radiance 2.0.0

Radiance becomes a multi-model engine: one process serves several models behind one port, loads
each when a request names it, parks it in host memory or restores it from its container, and
shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the
command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP).

Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an
int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block
FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such
weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5,
Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B,
the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0
serves all of them.

Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new
Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill
reworked, and a reworked adaptive draft window.

Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its
configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool
in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server,
each accelerator's memory by model, model states over time.

Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by
AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests
keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410);
eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d
large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi
(#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon
(#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and
multi-model serving as asked for in #367 and #109.

Plugin ABI 39: out-of-tree plugins need to be rebuilt.

Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
Deadcode committed 2026-11-14 22:32:28 +01:00
1 parent b4c04b6042
commit ddcb9c69bb
696 files changed
+120770 -56596

No files matched your search

+12 -9
View File
@@ -123,8 +123,6 @@ set(R4D_UNITS
"r4d_kda|"
# Mamba-2's selective state update (Nemotron-H), the KDA kernel's register layout.
"r4d_ssd|"
"r4d_moe_mxfp4|"
"r4d_fp8_f32scale|"
"r4d_ngram_ids|"
"r4d_ple_gate_bf16|"
"r4d_ple_conv_bf16|"
@@ -145,7 +143,6 @@ set(R4D_UNITS
"r4d_gemm_w4a16_nt_m64|"
"r4d_gemm_w5a16_nt_m64|"
"r4d_gemm_wpa8i8_tiled|"
"r4d_givens_dense|"
"r4d_gemm_w8a16_nt_m64|"
"r4d_gemm_w2a8_nt|"
"r4d_gemm_w4a8_nt_m64|"
@@ -157,19 +154,18 @@ set(R4D_UNITS
"r4d_gemm_mxfp4a8_tiled|"
"r4d_gemm_mxfp4a8_decode|"
"r4d_gemm_mxfp4a8_gemv|"
# M2XFP4 (arXiv 2601.19213 §4.4.2): the decode and tiled rows at the m2xfp4 encoding, one meta
# plane more. Same bands and fold as the OCP rows; the meta multipliers ride r4d_m2xfp4.h's table.
"r4d_gemm_m2xfp4a8_tiled|"
"r4d_gemm_m2xfp4a8_decode|"
# Block-scaled FP8 (the format Qwen3.8-27B-FP8 ships in). The 128x128 block is fixed by the
# checkpoint, and the entry points reject a mismatch.
"r4d_gemm_fp8a16_nt_m1|"
"r4d_gemm_fp8a8|"
"r4d_gemm_iqr|"
"r4d_gemm_iqr_p1|"
"r4d_gemm_iqr_p2|"
"r4d_gemm_iqr_p3|"
"r4d_moe_iqr|"
"r4d_iqr_embed|"
"r4d_logits_vocab|"
"r4d_quant_act_fp8|"
"r4d_givens_rotate|"
"r4d_fused_quant_fp8|"
"r4d_gram_accum_fp8|"
"r4d_qsa_block_key_bf16|"
@@ -216,6 +212,8 @@ set(R4D_UNITS
# Routed MoE: router, scatter, the grouped block-scaled fp8 GEMM and gather, in one unit because
# the other three only feed the GEMM.
"r4d_moe|"
# Blocks a row keeps for an output buffer, freed with the memory they serve (r4d_keyed.h).
"r4d_keyed|"
)
set(R4D_SRC "")
@@ -241,7 +239,12 @@ endforeach()
# descriptions and fusion claims. They are pure host C++ that includes neither r4d.h nor
# hip_runtime.h, so these tables compile and can be inspected without ROCm.
set(R4D_DECLARATION r4d_rows.cpp r4d_layout.cpp r4d_fp8_layout.cpp r4d_iqr_layout.cpp r4d_shapes.cpp
r4d_fuse.cpp)
r4d_fuse.cpp r4d_hsimd.cpp)
# The relayouts' hot loops, once per CPU level (r4d_hsimd.h); r4d_hsimd.cpp picks one at runtime.
include(${CMAKE_CURRENT_LIST_DIR}/../cmake/RadSimdLevels.cmake)
rad_simd_level_objects(r4d_hsimd ${CMAKE_CURRENT_SOURCE_DIR}/r4d_hsimd_kernels.cpp R4D_HSIMD_OBJS
DEFINE R4D_HSIMD_LEVEL INCLUDES ${CMAKE_CURRENT_SOURCE_DIR})
list(APPEND R4D_DECLARATION ${R4D_HSIMD_OBJS})
rad_add_plugin(libr4d kernels
SOURCES ${R4D_DECLARATION}
+10 -38
View File
@@ -14,8 +14,8 @@ r4d_<family>_<op>_<the geometry it is compiled for>
```
Every dimension in the name is a compile-time constant, and the entry point rejects a mismatch
instead of running. `attn_decode_h256_gqa6_fp8kv` serves head_dim 256 with 6 queries per KV head and
an fp8-e4m3 paged cache, and nothing else. A model with another head size needs a new
instead of running. `attn_decode_h256_gqa6_i8` serves head_dim 256 with 6 queries per KV head and
an int8 paged cache, and nothing else. A model with another head size needs a new
instantiation under its own name, so no existing name changes and no caller can pick up a kernel
that does not fit.
@@ -27,8 +27,8 @@ The table lists a selection; `r4d_rows.cpp` and `r4d.h` hold the full set.
| entry point | what it is |
| --- | --- |
| `attn_prefill_h256_gqa6_fp8kv` / `..._bf16kv` | paged causal attention, query-tiled; head_dim 256, 6 queries per KV head, fp8-e4m3 or bf16 KV cache |
| `attn_decode_h256_gqa6_fp8kv` / `..._bf16kv` | the same geometry, split-KV, `q_len * gqa` ≤ 64 |
| `attn_prefill_h256_gqa6_i8` / `..._bf16kv` | paged causal attention, query-tiled; head_dim 256, 6 queries per KV head, int8 or bf16 KV cache |
| `attn_decode_h256_gqa6_i8` / `..._bf16kv` | the same geometry, split-KV, `q_len * gqa` ≤ 64 |
| `attn_decode_h256_gqa6_scratch_bytes` / `attn_decode_h128_gqa4_scratch_bytes` | bytes of split-KV scratch a launch needs; ask before allocating, since the split count is chosen from the geometry |
| `attn_vit_h72_bf16` | dense non-causal vision-encoder attention, head_dim 72 native, varlen over images |
| `gdn_conv_prep_w4_h128_bf16` / `..._f32wgt` | the GDN prefill preamble in one kernel: causal conv (width 4, silu, with its state cache), q/k/v split, qk l2norm, gating and the per-chunk gate cumsum |
@@ -54,12 +54,10 @@ The table lists a selection; `r4d_rows.cpp` and `r4d.h` hold the full set.
| `gemm_mxfp4a8_nt_m64` | OCP-MXFP4 weight, fp8 activation, skinny |
| `gemm_mxfp4a8_gemv` | the same operands for one to eight rows: the weight streamed straight to registers, no LDS staging; WMMA when K is a multiple of 128, `v_dot4` otherwise, chosen from K alone so a row's bits do not depend on M |
| `gemm_mxfp4a8_gemv_wide` | its WMMA form at 9..64 rows: up to four 16-row tiles a wave over each weight word, two 16-column tiles a block on wide, deep weights |
| `gemm_mxfp4a8_gated_gemv` | `gemm_nt_q_gated_mx`: the gemv WMMA form over a gate_up weight with `gated_quant_fp8`'s pass (or GeGLU's `gelu_mul` and `quant_act_fp8`) in its epilogue, M ≤ 8; the [M, 2n] product is never written |
| `gemm_mxfp4a8_gated_gemv_wide` | the same fold at 9..64 rows over `gemv_wide`'s WMMA form: a block per gate/up tile pair, eight K waves each running both tiles, K ≥ 2688 |
| `gemm_mxfp4a8_decode` | the same operands for the decode band (M ≤ 128): split-K across workgroups with a last-arriver reduction, the partial in the op's scratch |
| `gemm_mxfp4a8_decode_shortk` | the decode kernel at 33..64 rows of a wide, short weight (N ≥ 8192, K ≤ 2560), above `gemm_mxfp4a8_gemv_wide`, which loses there |
| `gemm_mxfp4a8_tiled` | the prefill sibling: the activation re-tiled into fragment order in the op's scratch and read straight into registers, the weight unpacked once per K slab for a 256-row block |
| `attn_decode_h128_gqa4_fp8kv` / `..._bf16kv` | head_dim 128, 4 queries per KV head, sliding window: a block-diffusion drafter's geometry. Decode only; there is no prefill row at this geometry |
| `attn_decode_h128_gqa4_i8` / `..._bf16kv` | head_dim 128, 4 queries per KV head, sliding window: a block-diffusion drafter's geometry. Decode only; there is no prefill row at this geometry |
| `rowtopk_bf16` / `rowtopk_bf16_chunks` | exact per-row top-K over a bf16 matrix, two-stage |
| `dflash_conv_t2_g16_bf16` | the drafter's causal conv, two taps, 16 groups |
| `dflash_select_bf16` | the drafter's candidate selector: edge scores and the greedy path walk |
@@ -207,7 +205,7 @@ everywhere but this corner, where it lost by 7..30 %; there this row wins:
Narrower N stays with `gemv_wide` (5120 × 2176 at 40 rows 39.2 µs against 52.8), as do Qwen3.8-27B's
and TranslateGemma's two-rank shapes. It is a row rather than a rule inside the gemv entry so that
the choice stays a lookup over constraints, and `--debug-selection` names it.
the choice stays a lookup over constraints, and `debug-selection` names it.
**`gemm_mxfp4a8_decode`** (65..128 rows, and 9..64 where K is not a multiple of 128). Past 16 rows
each wave loads its weight words straight into registers, as `gemv` does (a fragment-order word is
@@ -229,33 +227,7 @@ rows their outputs differ from the decode row's in the last bf16 place on a few
thousand (within the selftest's bound). A greedy text can therefore differ from one produced
with the decode row at those rows. Within the family a row's bits do not depend on M, as above.
**`gemm_mxfp4a8_gated_gemv`** (`gemm_nt_q_gated_mx`, M ≤ 8, K a multiple of 128, N of 256, `act`
`silu`, or `gelu_tanh` without `out_bf16`). The `gemv` WMMA form over a gate_up weight, a block per
16-column tile pair of the gated output (eight K waves on the gate tile, eight on the up tile, in
`gemv`'s K order), the bf16 product and row amaxes in the op's scratch; the last of a 128-column
group's blocks to arrive (a counter keyed on the output) writes the group's codes and scales. Byte
for byte `gemm_mxfp4a8_gemv` followed by `gated_quant_fp8`, or by `gelu_mul` and `quant_act_fp8`
(`r4d_selftest`, M = 1..8, Qwen's and TranslateGemma's gate_up). It saves a launch: a dependent
kernel costs 3.5-6.4 µs in a replayed graph on gfx1201 however little it does, and a Qwen3.8-27B
TP2 decode step issues 631 a card. About +1.5 % at one to eight streams on Qwen3.8-27B, +4.5 % on
TranslateGemma 27B at speculation 7.
**`gemm_mxfp4a8_gated_gemv_wide`** (`gemm_nt_q_gated_mx`, 9 ≤ M ≤ 64, K a multiple of 128 and at
least 2688, N of 256, the same `act` rule). The fold over `gemv_wide`, the GEMM row of that band:
`gemv_wide`'s kernel at two column tiles a block with the tiles taken as one gate tile and its up
tile, so each of the eight K waves loads both tiles' weight words of its chunks and reads a chunk's
activation fragments once for both (the narrow row's sixteen waves, eight a tile, would be
`gemv_wide` at one tile a block, which at 32 and 64 rows took TranslateGemma's gate_up 39 % and 22 % longer).
Up to four 16-row tiles; the waves' partials meet through LDS one half at a time (32 KB at 64 rows),
then the narrow row's epilogue. Byte for byte `gemm_mxfp4a8_gemv_wide` followed by `gated_quant_fp8`,
or by `gelu_mul` and `quant_act_fp8` (`r4d_selftest`, M = 9..64). No spills: 101 / 137 / 166 / 196
VGPRs at one to four row tiles (per-(row, 128) activation scale), against `gemv_wide`'s 131 / 160 / 190
at two to four tiles and two columns. K from 2688 keeps it out of `decode_shortk`'s corner, where the
unfused GEMM sums 33..64 rows in the decode kernel's order. gemma3 declares the fold up to 64 rows
where K reaches it, which at two to eight TranslateGemma streams with speculation 7 is 2-5 % more
throughput than the unfused three past 8 rows.
**Tunables.** `gemv`, `gemv_wide` and `gated_gemv` have none, so a `RADIANCE_TUNE` pin on
**Tunables.** `gemv` and `gemv_wide` have none, so a `RADIANCE_TUNE` pin on
`gemm_nt_q` passes them by. `decode_shortk` shares the decode row's axes (`ks`, `bk`, `nt`; 0 the
rule), so a pin of those reaches both. A pin applies to every row serving the op, and an axis a
serving row lacks stops startup by name.
@@ -282,15 +254,15 @@ rank's weight at TP2 on an R9700, the row alone, clocks warmed; over 20 shapes,
`tn` (0 the rule, 2, 4) pins the TN choice through `RADIANCE_TUNE`.
## The fp8 and int8 heads past 64 rows
## The int8 head past 64 rows
**`logits_gemm_fp8`, `logits_gemm_i8`** took passes of 64 rows and read the head again for each.
**`logits_gemm_i8`** took passes of 64 rows and read the head again for each.
With `MH` = 2 a workgroup's eight waves split into two M halves of four 16-row tiles over 64 weight
rows that share one staged tile, so a pass takes 128 rows and reads the head once. Qwen3.8's
per-rank head (124160 × 5120) at 128 rows 3059 → 1984 µs, TranslateGemma's (131072 × 5376) 3242 →
2036; 65..128 rows -33..-39 %, 160..256 -26..-37 %, 64 and fewer unchanged; about 1 ms a step at 16
streams with speculation. Same scale blocks, WMMAs and K order per output: the same bytes (the
numeric cases at 65..150 rows for the fp8 head, 100 for the int8 head).
numeric cases at 100 rows).
## Notes on the kernels
+1 -1
View File
@@ -9,7 +9,7 @@ that report the geometry a kernel was launched with rather than every geometry i
BUILD=... ./dis.sh r4d_gemm_fp8a8 gemm_8a8_prefill_kernelILb0E
BUILD=... ./waterfall.sh # divergent VGPR indices, per kernel
./loop.sh # its K loop, classified
./trace.sh traces/dec -- ./bin/radiance ... # then: ./tsum.sh traces/dec/k_kernel_trace.csv
./trace.sh traces/dec -- ./bin/radiance --config radiance.yaml # then: ./tsum.sh traces/dec/k_kernel_trace.csv
./selftest.sh # the two parsers, on fixtures (ctest: isa_tools)
`res.sh` and `waterfall.sh` exit nonzero when they looked at nothing -- no `.hip.o`, an object whose
+32 -38
View File
@@ -8,8 +8,8 @@
// r4d_<family>_<op>_<geometry it is compiled for>
//
// Every dimension in the geometry suffix is a compile-time constant, and the entry point rejects a
// mismatch instead of running. `attn_decode_h256_gqa6_fp8kv` serves head_dim 256, 6 queries per KV
// head and an fp8-e4m3 paged cache, nothing else; another head size gets its own instantiation
// mismatch instead of running. `attn_decode_h256_gqa6_i8kv` serves head_dim 256, 6 queries per KV
// head and an int8 paged cache, nothing else; another head size gets its own instantiation
// beside it. Dimensions fixed for the whole library stay out of the names and are reported by
// r4d_*_dims() and the kernel registry: the paged block size (16), the query dtype (bf16
// everywhere, see r4d_attn_paged_h256_gqa6.hip) and the target architecture.
@@ -32,8 +32,9 @@
struct R4DArgs {
const void* q; // (num_seqs*q_len, q_heads, head_dim) bf16
const void* kv; // (num_blocks, kv_heads, block_size, 2*head_dim) fp8 e4m3 or bf16
// strides below are in elements of that dtype; K then V per slot
const void* kv; // (num_blocks, kv_heads, block_size, 2*head_dim) bf16, or the int8
// cache's 2*head_dim + 4 bytes; strides below are in elements of
// that dtype; K then V per slot
const int* block_table; // (num_seqs, max_blocks) int32
const int* seqused_k; // (num_seqs,) int32
void* out; // (total_q, q_heads, head_dim) bf16
@@ -101,17 +102,17 @@ extern "C" {
// kernel tiles the query; the decode kernel splits the KV and takes at most 64 query rows
// (q_len * gqa), the band a speculative-decode verify step falls in.
// Return 0 on success, negative on a shape this instantiation does not serve.
int r4d_attn_prefill_h256_gqa6_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_prefill_h256_gqa6_i8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_prefill_h256_gqa6_bf16kv(const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa6_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa6_i8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa6_bf16kv (const R4DArgs* a, hipStream_t stream);
// The DFlash2 drafter's geometry: head_dim 128, 4 queries per KV head, sliding window. Decode
// only (q_len * gqa <= 64).
int r4d_attn_decode_h128_gqa4_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa4_i8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa4_bf16kv (const R4DArgs* a, hipStream_t stream);
long r4d_attn_decode_h128_gqa4_scratch_bytes(const R4DArgs* a);
// ...with R4DArgs::kv_rep and q_ld read: a gqa of 4 * kv_rep over a cache of kv_heads / kv_rep.
int r4d_attn_decode_h128_gqa4_rep_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa4_rep_i8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa4_rep_bf16kv (const R4DArgs* a, hipStream_t stream);
// Bytes of split-KV partial buffer one decode launch of this shape needs. Independent of the cache
// dtype: the partials are f16 either way.
@@ -119,22 +120,22 @@ long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a);
// The Gemma 4 dense sliding-window geometry: head_dim 256, 2 queries per KV head. Both bands:
// decode (q_len*gqa <= 64, i.e. q_len <= 32) and windowed prefill, which is the h256/gqa6
// r4d_attn_prefill_kernel with the window bit on.
int r4d_attn_prefill_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_prefill_h256_gqa2_i8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_i8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_bf16kv (const R4DArgs* a, hipStream_t stream);
long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a);
/* Gemma 3 sliding window (r4d_attn_paged_h128_gqa2w.hip): head_dim 128, gqa 2, window >= 1. */
int r4d_attn_prefill_h128_gqa2w_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_prefill_h128_gqa2w_i8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_prefill_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa2w_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa2w_i8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa2w_bf16kv (const R4DArgs* a, hipStream_t stream);
long r4d_attn_decode_h128_gqa2w_scratch_bytes(const R4DArgs* a);
// ...with q at R4DArgs::q_ld (attn_paged_qrow).
int r4d_attn_decode_h256_gqa2_qld_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_qld_i8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_qld_bf16kv (const R4DArgs* a, hipStream_t stream);
// ...and a tree verify's mask from R4DArgs::spec_parent (attn_paged_qrow_tree).
int r4d_attn_decode_h256_gqa2_qld_tree_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_qld_tree_i8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_qld_tree_bf16kv (const R4DArgs* a, hipStream_t stream);
// The geometry the attention kernels above are compiled for, so a caller can check a model
// before the first launch.
@@ -301,11 +302,12 @@ void r4d_ar_host_free(long p);
// `stage`, the last argument of every 2-rank kernel below: 0, or a host-mailbox instance's mirror
// of its slots in this card's VRAM (same layout), which the reader's push check fills as it reads
// the slot so the reduce reads VRAM instead of the link a second time (r4d_ar_seq.h).
// Exact sum, fp32 accumulate, bf16 / fp16 / fp32 payload (dtype 0 / 1 / 2).
// Exact sum, fp32 accumulate, bf16 / fp16 / fp32 payload (dtype 0 / 1 / 2). `chain` launches the
// chained form (r4d_chain.h).
void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long inp, long out, long n_elem,
long dtype, long stream, long nblocks, long nthreads, long drain,
long acq, long stage = 0);
long acq, long stage = 0, long chain = 0);
// Same topology, with the wire payload Walsh-Hadamard rotated and quantised to 6 bits per element
// in groups of 64 (plus a bf16 scale per group). Lossy; bf16 / fp16 payload only. loc_pack is this
// rank's own packed copy, so the reduce folds exactly the bytes it sent.
@@ -318,11 +320,13 @@ void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_fla
// inj[r][c] * y[r][i] over the reduced y, byte-identical to all_reduce then hc_write. `irow` and
// `hrow` are the pitches of inj [M][hc] and h [M][hc*n] in elements; y is tight. A non-zero `gate`
// is the engine's link word, ended once the peer's push has landed (r4d_ar_link_landed);
// `gate_ctr` is its block counter. The gather form below takes the same pair.
// `gate_ctr` is its block counter. The gather form below takes the same pair. A non-zero `chain`
// launches the chained form (r4d_chain.h), which the gather form has at decode heights.
void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n,
long hc, long irow, long hrow, long stream, long nblocks, long nthreads,
long drain, long acq, long gate, long gate_ctr, long stage = 0, long chain = 0);
long drain, long acq, long gate, long gate_ctr, long stage = 0,
long chain = 0);
// The same with the MoE gather as its prologue: y is produced, not read, from the routed experts'
// rows `ye` [M*top_k][ye_ld] summed to token order by weights `ew` [M][ew_ld] and `sorted`
// [M*top_k], with the shared arm `sh` [M][sh_ld] and its gate `sg` folded when both are non-zero.
@@ -657,8 +661,6 @@ int r4d_gemm_fp8a16_nt_mt(long a, long wq, long ws, long c, int M, int K, int N
/* The lm_head at fp8, scales interleaved in each row's tail; see the .hip for why that layout. */
int r4d_logits_gemm_fp8(long a, long wq, long c, int M, int K, int N,
int a_ld, int c_ld, int w_ld, long stream);
int r4d_gemm_fp8a16_nt_m1_block(void);
int r4d_gemm_fp8a16_nt_m1_max_m(void);
// `a` is E4M3 [M][K] with `ascale` f32 [M][ceil(K/128)], r4d_quant_act_fp8's output. `scratch` is
// the split-K partial plane; 0 runs the launch unsplit (correct, slower). Size it with the query,
@@ -680,7 +682,8 @@ void r4d_gemm_fp8a8_pin_mw(int mw);
// Test hook: pins the waves the narrow tiles' K split aims for (fp8a8 and i8a8 128, the IQR narrow
// tile 512) for every subsequent call on every thread; 0 restores each caller's own. Not for
// serving; r4d_selftest holds it at the IQR tile's target around the i8a8 reference, so the two
// split K alike and their bytes compare.
// split K alike and their bytes compare. While it is set an int8 GEMM takes the narrow tile at
// every M, not the K-parallel tile, whose sums run in another order.
void r4d_gemm_i8a8_pin_split_waves(int waves);
// Test hook: pins the QSA score's form. 0 is the launcher's rule, 1 the scalar decode form, 2 the
// matrix form (which refuses a shape it is not built for). The two sum in different orders, so
@@ -756,25 +759,12 @@ void r4d_ar8_test_settings(const struct R4DAr8Settings* s);
// Refuses, without fallback, any shape the fold does not fit: M past the band, K not a multiple of
// 256, `nout` not a multiple of 128 (a block emits exactly one 128-column scale group), or a grid
// the split rule would widen.
int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws,
long q, long s, long y, int act,
int M, int K, int nout,
int a_ld, int sa_ld, int w_ld, int sw_ld,
int q_ld, int s_ld, int y_ld, long stream);
int r4d_gemm_fp8a8_gated_nt_m16_max_m(void);
// The same fold at any M (`gemm_nt_q_gated_wide`): past the narrow tile's 64 rows it takes the gated
// prefill tile, whose accumulators are the unfused prefill GEMM's, so its bytes are the pair's.
int r4d_gemm_fp8a8_gated_nt_wide(long a, long ascale, long wq, long ws,
long q, long s, long y, int act,
int M, int K, int nout,
int a_ld, int sa_ld, int w_ld, int sw_ld,
int q_ld, int s_ld, int y_ld, long stream);
// The narrow GEMM with a bias: `bias` bf16 [N], added to each output column's f32 accumulator before
// its one rounding, and C written at row pitch `c_ld` (0 = N), so C may be a column slice of a wider
// buffer. Never split. M up to r4d_gemm_fp8a8_nt_m16_max_m(); K a multiple of 128, N of 16.
int r4d_gemm_fp8a8_bias_nt_m16(long a, long ascale, long wq, long ws, long bias, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
int c_ld, long stream);
int r4d_gemm_fp8a8_tiled(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
long stream);
@@ -856,24 +846,28 @@ int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flag
long loc_pack, long loc_scale_off, long wp = 0, long stage = 0);
int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void);
// Its rotated int8 form, as r4d_rmsnorm_had_quant_i8g: the reduction and the norm unchanged, the
// norm's pass quantised by had_quant_act_i8g's rule. No post-norm.
// norm's pass quantised by had_quant_act_i8g's rule. No post-norm. `group` is the scale group, 128
// or IQ8R's 256 (`s` [M][n/group]). `chain` launches the chained form (r4d_chain.h) where the
// launch is 1024 threads wide, the decode heights.
int r4d_ar_rmsnorm_had_quant_i8g(long peer_scratch, long my_scratch, long peer_flags,
long my_flags, long seq_ctrs, long slot_stride16,
long x, long res, long w, long y, long q, long s,
int M, int n, float eps, float wadd, int w_f32,
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq, int wire,
long loc_pack, long loc_scale_off, long stage = 0);
long loc_pack, long loc_scale_off, long stage = 0,
int group = 128, int chain = 0);
// The same IPC with the sandwich-norm junction after it (r4d_rmsnorm_quant_i8.hip): post-norm of
// the reduced `x` (`wp`), the residual add, the [1] scalar (`sc`), the norm (`w`) and the w4a8
// GEMM's per-row int8 quantiser. Exact wire only; `x` is the message and takes no pitch. `grp`
// takes quant_act_i8g's quantiser instead (ar_rmsnorm_quant_i8g): `s` [M][n / 128], n % 128 == 0.
// `chain` launches the chained form (r4d_chain.h) where the launch is 1024 threads wide.
int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long x, long res, long w, long wp,
long sc, int sc_f32, long y, long q, long s, int M, int n, float eps,
float wadd, int w_f32, int r_ld, int y_ld, long stream, int nblocks,
int drain, int acq, int grp, long stage = 0);
int drain, int acq, int grp, long stage = 0, int chain = 0);
// ...and at four ranks, on the wide family's transport: r4d_ar_oneshot_4rank_exact's IPC
// arguments (peers in ascending rank, this rank's own, the counters, the slot stride), `pub`, the
// engine's link gate with the instance's landed counter (0 for none; r4d_ar_seq.h), and, with
@@ -1045,7 +1039,7 @@ int r4d_logits_gemm_bf16_cols(long a, long w, long c, int M, int K, int N, int a
// [.., head_dim + d], slot decomposing as block = slot / block_size, offset = slot % block_size.
int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim, int kv_heads,
int block_size, int n_blocks, int k_ld, int v_ld, long stream);
// The same scatter into an E4M3 cache, read by the fp8kv attention family. `k_scale` and `v_scale`
// The same scatter into an E4M3 cache, read by GLM-5.3's latent attention. `k_scale` and `v_scale`
// are the descales the reader multiplies by, so this divides by them; the read side has one per
// (sequence, head), hence a caller constant here. 1.0 is vLLM's default and what the attention
// kernels assume when their descale pointers are null. head_dim must be a multiple of 4.
+69 -43
View File
@@ -18,7 +18,6 @@
* with a 60-second timeout and a named error.
*/
#include "r4d_chain.h"
#include "r4d_args.h"
#include "r4d.h"
#include "r4d_ar_shards.h"
@@ -29,6 +28,8 @@
#include <cstdlib>
#include <cstring>
#include <exception>
#include <map>
#include <memory>
#include <mutex>
#include <vector>
#include <chrono>
@@ -76,22 +77,38 @@ struct Rendezvous {
int failed = 0;
};
Rendezvous g_rv;
/* One rendezvous per tensor-parallel group. Several engines may run in one process
* (docs/MULTIMODEL.md), each with its own ranks 0..world-1, so the ranks that meet are the ranks of
* one group: the core names it in init's `tp_group` parameter (absent, the one group 0). Entries
* live for the process; a group's id is reused only by a later engine with the same ranks. */
std::mutex g_rv_mu;
std::map<long long, std::unique_ptr<Rendezvous>> g_rvs;
Rendezvous& rv_for(long long group) {
std::lock_guard<std::mutex> lk(g_rv_mu);
std::unique_ptr<Rendezvous>& r = g_rvs[group];
if (!r) r.reset(new Rendezvous());
return *r;
}
/* Sense-reversing barrier on a monotone epoch, so a rank that wakes and re-enters for the next
* instance cannot be counted twice. The timeout is not recovery; it turns a startup deadlock into
* a named error instead of a silent hang. */
int rv_barrier(int world) {
std::unique_lock<std::mutex> lk(g_rv.m);
const int e = g_rv.epoch;
if (++g_rv.arrived == world) {
g_rv.arrived = 0;
g_rv.epoch++;
g_rv.cv.notify_all();
int rv_barrier(Rendezvous& rv, int world) {
std::unique_lock<std::mutex> lk(rv.m);
const int e = rv.epoch;
if (++rv.arrived == world) {
rv.arrived = 0;
rv.epoch++;
rv.cv.notify_all();
return RAD_OK;
}
const bool ok = g_rv.cv.wait_for(lk, std::chrono::seconds(60),
[&] { return g_rv.epoch != e; });
const bool ok = rv.cv.wait_for(lk, std::chrono::seconds(60),
[&] { return rv.epoch != e; });
/* A rank that gave up takes its arrival back: a peer that failed before arriving would
* otherwise leave it counted, and the group's next engine (its id is reused) would be released
* one rank early. */
if (!ok) --rv.arrived;
return ok ? RAD_OK : RAD_E_STATE;
}
@@ -99,6 +116,7 @@ int rv_barrier(int world) {
* ascending global rank with this rank removed (the order libr4d's wide entry points take). */
struct ArInst {
int rank = 0, world = 0;
long long group = 0; /* the tensor-parallel group it rendezvoused in (rv_for) */
long my_scratch = 0, my_flags = 0, my_seq = 0, locpack = 0;
/* A 2-rank host-mailbox instance's VRAM mirror of its slots, 0 otherwise (r4d_ar_seq.h). */
long my_stage = 0;
@@ -183,18 +201,19 @@ long long ar8_pieces_for(const ArInst* in, long numel, long long asked) {
* card's link, and after one barrier every rank derives the same weights from the same eight
* entries. */
int ar8_settle(ArInst* in, int rank, int world) {
Rendezvous& rv = rv_for(in->group);
static std::once_flag said_links, said_unknown, said_set;
const R4DAr8Settings set = ar8_settings();
R4DArLink own;
if (set.weights == R4D_AR8_WEIGHTS_AUTO && !ar8_own_link(&own)) own = R4DArLink();
{
std::lock_guard<std::mutex> lk(g_rv.m);
g_rv.ar8_link[rank] = own;
std::lock_guard<std::mutex> lk(rv.m);
rv.ar8_link[rank] = own;
}
const int rc = rv_barrier(world);
const int rc = rv_barrier(rv, world);
if (rc != RAD_OK) return rc;
const R4DArLink* all = g_rv.ar8_link;
const R4DArLink* all = rv.ar8_link;
in->pieces = set.pieces;
in->weights_min = set.weights_min;
in->pieces_min = set.pieces_min;
@@ -258,11 +277,13 @@ long kSeqWords(long nbw) { return 2L * nbw + 32; }
*
* Cost: at a 4096-token chunk on a 5120-wide residual, 40 MiB a slot and 80 MiB for the pair. One
* set serves every op with the same (rank, world, dtype, bound); see the cache below. */
int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, int host) {
int build(ArInst* in, long long group, int rank, int world, long long max_numel, int dtype_code,
int host) {
if (world < 2 || world > R4D_MAX_RANKS) return RAD_E_SHAPE;
if (rank < 0 || rank >= world) return RAD_E_INVAL;
if (max_numel <= 0) return RAD_E_INVAL;
in->group = group;
in->rank = rank;
in->world = world;
in->host = host;
@@ -382,14 +403,15 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
in->my_stage = stg;
in->gate_ctr = sq + 2L * maxb * 4; /* the word after the sequence counters (r4d_ar_seq.h) */
Rendezvous& rv = rv_for(group);
{
std::lock_guard<std::mutex> lk(g_rv.m);
g_rv.scratch[rank] = sc;
g_rv.flags[rank] = fl;
g_rv.seq[rank] = sq;
g_rv.dev[rank] = dev;
std::lock_guard<std::mutex> lk(rv.m);
rv.scratch[rank] = sc;
rv.flags[rank] = fl;
rv.seq[rank] = sq;
rv.dev[rank] = dev;
}
int rc = rv_barrier(world);
int rc = rv_barrier(rv, world);
if (rc != RAD_OK) return rc;
/* Peer access is per context, so each rank enables its own, after the publish barrier where
@@ -400,17 +422,17 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
int j = 0;
for (int r = 0; r < world; ++r) {
if (r == rank) continue;
if (!g_rv.scratch[r] || !g_rv.flags[r]) return RAD_E_STATE;
in->peer_scratch[j] = g_rv.scratch[r];
in->peer_flags[j] = g_rv.flags[r];
if (!rv.scratch[r] || !rv.flags[r]) return RAD_E_STATE;
in->peer_scratch[j] = rv.scratch[r];
in->peer_flags[j] = rv.flags[r];
++j;
if (!host && g_rv.dev[r] != dev)
R4D_TRY("ar_ipc_enable_peer", r4d_ar_ipc_enable_peer((long)g_rv.dev[r]));
if (!host && rv.dev[r] != dev)
R4D_TRY("ar_ipc_enable_peer", r4d_ar_ipc_enable_peer((long)rv.dev[r]));
}
/* Second barrier: no rank may launch until every rank has enabled peer access, or the first
* message would be pushed into a mapping the receiver has not opened. */
return rv_barrier(world);
return rv_barrier(rv, world);
}
/* ------------------------------------------------------------------ one world, shared
@@ -430,12 +452,13 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
* The rendezvous stays symmetric because every rank declares the same graph in the same order:
* the Nth all-reduce misses the cache on every rank or on none. */
struct CacheKey {
long long group; /* the tensor-parallel group: another engine's ranks never share */
int rank, world, dtype;
long long numel;
int host;
bool operator==(const CacheKey& o) const {
return rank == o.rank && world == o.world && dtype == o.dtype && numel == o.numel &&
host == o.host;
return group == o.group && rank == o.rank && world == o.world && dtype == o.dtype &&
numel == o.numel && host == o.host;
}
};
@@ -459,7 +482,7 @@ int acquire(const CacheKey& k, ArInst** out) {
* rank has one declare thread, so no two builders race for one key. */
ArInst* in = new (std::nothrow) ArInst();
if (!in) return RAD_E_NOMEM;
int rc = build(in, k.rank, k.world, k.numel, k.dtype, k.host);
int rc = build(in, k.group, k.rank, k.world, k.numel, k.dtype, k.host);
if (rc != RAD_OK) { delete in; return rc; }
{
std::lock_guard<std::mutex> lk(g_cache_mu);
@@ -515,7 +538,8 @@ static int ar_init(const RadParam* p, int n_p, int rank, int world, int host, vo
if (numel <= 0) return RAD_E_INVAL;
ArInst* in = nullptr;
int rc = acquire(CacheKey{ rank, world, dt, numel, host }, &in);
const long long group = pgeti_hi(p, n_p, "tp_group", 0);
int rc = acquire(CacheKey{ group, rank, world, dt, numel, host }, &in);
if (rc != RAD_OK) return rc;
*out = in;
return RAD_OK;
@@ -542,7 +566,8 @@ static int ar_mn_acquire(const RadParam* p, int n_p, int rank, int world, int ho
if (M <= 0 || K <= 0) return RAD_E_INVAL;
ArInst* in = nullptr;
int rc = acquire(CacheKey{ rank, world, 0 /* bf16 */, M * K, host }, &in);
const long long group = pgeti_hi(p, n_p, "tp_group", 0);
int rc = acquire(CacheKey{ group, rank, world, 0 /* bf16 */, M * K, host }, &in);
if (rc != RAD_OK) return rc;
*out = in;
return RAD_OK;
@@ -886,7 +911,7 @@ extern "C" int r4d_rad_ar_oneshot_2rank_exact(const RadArgs* a, RadStream s) {
c.in->peer_flags[0], c.in->my_flags, c.in->my_seq,
c.in->slot16, c.inp, c.out, c.numel, c.in->dtype,
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq,
c.in->my_stage));
c.in->my_stage, ar_chain(a, c.numel)));
return RAD_OK;
}
@@ -929,7 +954,7 @@ extern "C" int r4d_rad_ar_oneshot_2rank_wht6(const RadArgs* a, RadStream s) {
c.in->peer_flags[0], c.in->my_flags, c.in->my_seq,
c.in->slot16, c.inp, c.out, c.numel, c.in->dtype,
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq,
c.in->my_stage));
c.in->my_stage, ar_chain(a, c.numel)));
return RAD_OK;
}
@@ -1317,7 +1342,7 @@ extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) {
* size above --tp-wire-min-kb), and both ranks decide on the same T. A wire-6 chunk that would
* straddle a row is refused as a shape. */
/* `hi8`: ar_rmsnorm_had_quant_i8g, the same with had_quant_act_i8g's quantiser on the norm's pass
* (int8 codes, K whole 128s, no post-norm). */
* (int8 codes, K whole scale groups of 128 or IQ8R's 256, no post-norm). */
static int rad_ar_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) {
const ArInst* in = (const ArInst*)(a ? a->instance : nullptr);
if (!in) return RAD_E_STATE;
@@ -1349,9 +1374,10 @@ static int rad_ar_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) {
/* A row must be whole 16B words, since a block pushes its rows as words. */
if (K % 8) return RAD_E_SHAPE;
const long long grp = r4d_quant_act_fp8_group();
const long long g0 = r4d_quant_act_fp8_group();
const long long grp = r4d_geti_or(a, "group", g0);
if (grp != g0 && !(hi8 && grp == R4D_I8_GROUP_WIDE)) return RAD_E_SHAPE;
const long long nkb = (K + grp - 1) / grp;
if (r4d_geti_or(a, "group", grp) != grp) return RAD_E_SHAPE;
if (hi8 && K % grp) return RAD_E_SHAPE;
if (r4d_numel(w) != K) return RAD_E_SHAPE;
if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return RAD_E_DTYPE;
@@ -1422,7 +1448,8 @@ static int rad_ar_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) {
r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32,
(int)rp, (int)yp, (int)qp, (int)sp,
(long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire,
in->locpack, in->slot_bytes / 2, in->my_stage)
in->locpack, in->slot_bytes / 2, in->my_stage, (int)grp,
r4d_geti_or(a, "chain", 0) != 0 ? 1 : 0)
: r4d_ar_rmsnorm_quant_fp8(
in->peer_scratch[0], in->my_scratch,
in->peer_flags[0], in->my_flags, in->my_seq,
@@ -1510,7 +1537,7 @@ static int rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s, bool grp) {
v.sl ? (v.sl->dtype == RAD_F32) : 0, r4d_addr(v.ob), r4d_addr(v.q), r4d_addr(v.sc), (int)M,
(int)K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0),
v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (long)(uintptr_t)s, nblocks, cfgv.drain,
cfgv.acq, grp ? 1 : 0, in->my_stage);
cfgv.acq, grp ? 1 : 0, in->my_stage, r4d_geti_or(a, "chain", 0) != 0 ? 1 : 0);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
@@ -1716,8 +1743,7 @@ extern "C" int r4d_rad_ar_gather_hc_write(const RadArgs* a, RadStream s) {
sh ? r4d_addr(sh) : 0L, sh ? r4d_addr(sg) : 0L, (long)ye_ld, (long)ew_ld, (long)sh_ld,
(long)sg_ld, (long)top_k, (long)sig, (long)(uintptr_t)s, nblocks, cfgv.nthreads,
cfgv.drain, cfgv.acq, has_inv ? (long)(uintptr_t)a->scratch : 0L, early,
early ? in->gate_ctr : 0L, in->my_stage,
r4d_geti_or(a, "chain", 0) != 0 && r4d_chain_rows_ok(M) ? 1L : 0L);
early ? in->gate_ctr : 0L, in->my_stage, (long)r4d_geti_or(a, "chain", 0));
if (rc != 0) return RAD_E_SHAPE;
return early ? RAD_LINK_ENDED : RAD_OK;
}
@@ -1847,7 +1873,7 @@ extern "C" int r4d_rad_ar_hc_write(const RadArgs* a, RadStream s) {
(long)M, (long)n, (long)hc, (long)irow, (long)hrow, (long)(uintptr_t)s,
nblocks, cfgv.nthreads, cfgv.drain, cfgv.acq, early,
early ? in->gate_ctr : 0L, in->my_stage,
r4d_geti_or(a, "chain", 0) != 0 && r4d_chain_rows_ok(M) ? 1L : 0L));
(long)r4d_geti_or(a, "chain", 0)));
return early ? RAD_LINK_ENDED : RAD_OK;
}
+39 -64
View File
@@ -18,8 +18,8 @@
// * Fine-grained memory (hipDeviceMallocFinegrained) is uncached and posted straight to the
// fabric, so system-scope release/acquire skip the L2 writeback. The drain/acq fences are
// selectable (default drain=1/acq=0 on fine-grained).
#include "r4d_chain.h"
#include "r4d.h"
#include "r4d_chain.h"
#include "r4d_ar_seq.h"
#include "r4d_ar_hc.h" // the gather word and the hc write word, shared with the rotated wire
#include <hip/hip_fp16.h>
@@ -61,11 +61,13 @@ __device__ __forceinline__ int4 vadd(const int4& a, const int4& b) {
// Multi-block one-shot all-reduce. Each block owns words [start,end) of the 16B-word space and
// drives its own flag handshake; no cross-block sync.
template <typename T, int LANES>
// CH `r4dchain`: the chained form (r4d_chain.h); no block returns early.
template <typename T, int LANES, class CH>
__global__ void r4d_ar_oneshot_2rank_exact_kernel(
const int4* __restrict__ in4, int4* peer_base, const int4* my_base, int4* __restrict__ out4,
unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs,
int n16, int slot_stride16, int drain, int acq, unsigned int nbw, long stage) {
if (CH::on) r4d_chain_wait();
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
__shared__ unsigned int s_seq, s_slot;
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
@@ -138,6 +140,7 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel(
}
for (; k < end; k += nt) out4[k] = vadd<T, LANES>(in4[k], ms[k]);
}
if (CH::on) r4d_chain_done();
}
// The same all-reduce with the gated residual write as its epilogue. `y` is the message: each word
@@ -148,12 +151,15 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel(
//
// n is a multiple of eight, so a word never straddles a row and the block that reduces it owns
// every stream element behind it.
__device__ __forceinline__ void r4d_ar_hc_write_kernel_body(
// CH `r4dchain`: the chained form (r4d_chain.h); no block returns early.
template <class CH>
__global__ void r4d_ar_hc_write_kernel(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, int acq, unsigned int nbw, long long* gate,
unsigned int* gate_ctr, long stage) {
if (CH::on) r4d_chain_wait();
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
__shared__ unsigned int s_seq, s_slot;
const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid);
@@ -208,26 +214,7 @@ __device__ __forceinline__ void r4d_ar_hc_write_kernel_body(
r4d_ar_hc_write_word(inj, h, row, i0, n, hc, irow, hrow,
reinterpret_cast<const unsigned short*>(&r));
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
__global__ void r4d_ar_hc_write_kernel(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, int acq, unsigned int nbw, long long* gate,
unsigned int* gate_ctr, long stage) {
r4d_ar_hc_write_kernel_body(y4, peer_base, my_base, peer_flags, my_flags, seq_ctrs, inj, h, n16, n, hc, irow, hrow, slot_stride16, drain, acq, nbw, gate, gate_ctr, stage);
}
__global__ void r4dchain_ar_hc_write(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, int acq, unsigned int nbw, long long* gate,
unsigned int* gate_ctr, long stage) {
r4d_chain_wait();
r4d_ar_hc_write_kernel_body(y4, peer_base, my_base, peer_flags, my_flags, seq_ctrs, inj, h, n16, n, hc, irow, hrow, slot_stride16, drain, acq, nbw, gate, gate_ctr, stage);
r4d_chain_done();
if (CH::on) r4d_chain_done();
}
// The same write with the MoE gather as its prologue. The routed experts' rows go back to token
@@ -258,13 +245,15 @@ __global__ void r4d_ar_gather_inv_kernel(int* __restrict__ inv, const int* __res
}
}
template <bool INV>
__device__ __forceinline__ void r4d_ar_gather_hc_write_kernel_body(
// CH `r4dchain`: the chained form (r4d_chain.h); no block returns early.
template <bool INV, class CH>
__global__ void r4d_ar_gather_hc_write_kernel(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, int acq, unsigned int nbw, R4dArGather G,
const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr, long stage) {
if (CH::on) r4d_chain_wait();
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
__shared__ unsigned int s_seq, s_slot;
__shared__ int s_i[R4D_ARG_ROWS * R4D_ARG_SLOTS];
@@ -345,28 +334,7 @@ __device__ __forceinline__ void r4d_ar_gather_hc_write_kernel_body(
r4d_ar_hc_write_word(inj, h, row, i0, n, hc, irow, hrow,
reinterpret_cast<const unsigned short*>(&r));
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <bool INV>
__global__ void r4d_ar_gather_hc_write_kernel(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, int acq, unsigned int nbw, R4dArGather G,
const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr, long stage) {
r4d_ar_gather_hc_write_kernel_body<INV>(y4, peer_base, my_base, peer_flags, my_flags, seq_ctrs, inj, h, n16, n, hc, irow, hrow, slot_stride16, drain, acq, nbw, G, inv, gate, gate_ctr, stage);
}
template <bool INV>
__global__ void r4dchain_ar_gather_hc_write(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, int acq, unsigned int nbw, R4dArGather G,
const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr, long stage) {
r4d_chain_wait();
r4d_ar_gather_hc_write_kernel_body<INV>(y4, peer_base, my_base, peer_flags, my_flags, seq_ctrs, inj, h, n16, n, hc, irow, hrow, slot_stride16, drain, acq, nbw, G, inv, gate, gate_ctr, stage);
r4d_chain_done();
if (CH::on) r4d_chain_done();
}
// The IPC handle goes into a caller-owned buffer of R4D_AR_HANDLE_BYTES so this stays a C ABI.
@@ -479,11 +447,14 @@ void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long m
if (nt < 64) nt = 64;
if (nt > 1024) nt = 1024;
nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes
(chain ? r4dchain_ar_hc_write : r4d_ar_hc_write_kernel)<<<nb, nt, 0, st>>>(
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags,
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h,
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw,
(long long*)gate, (unsigned int*)gate_ctr, stage);
#define R4D_ARHW(CH_) \
r4d_ar_hc_write_kernel<CH_><<<nb, nt, 0, st>>>( \
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, \
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, \
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, \
(long long*)gate, (unsigned int*)gate_ctr, stage)
if (chain) R4D_ARHW(r4dchain); else R4D_ARHW(R4dUnchained);
#undef R4D_ARHW
}
int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
@@ -530,20 +501,22 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags,
G.sg = (const unsigned short*)sg;
G.ye_ld = ye_ld; G.ew_ld = ew_ld; G.sh_ld = sh_ld; G.sg_ld = sg_ld;
G.top_k = (int)top_k; G.T = (int)(M * top_k); G.sig = (int)sig;
/* The inverse table's two launches stay plain; the decode form's one has a chained form. */
#define R4D_ARGHW(INV_, CH_, inv_) \
r4d_ar_gather_hc_write_kernel<INV_, CH_><<<nb, nt, 0, st>>>( \
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, \
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, \
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G, \
inv_, (long long*)gate, (unsigned int*)gate_ctr, stage)
if (by_inv) {
r4d_ar_gather_inv_kernel<<<1, 1024, 0, st>>>((int*)inv, (const int*)sorted, G.T);
(chain ? r4dchain_ar_gather_hc_write<true> : r4d_ar_gather_hc_write_kernel<true>)<<<nb, nt, 0, st>>>(
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags,
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h,
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G,
(const int*)inv, (long long*)gate, (unsigned int*)gate_ctr, stage);
R4D_ARGHW(true, R4dUnchained, (const int*)inv);
} else if (chain) {
R4D_ARGHW(false, r4dchain, nullptr);
} else {
(chain ? r4dchain_ar_gather_hc_write<false> : r4d_ar_gather_hc_write_kernel<false>)<<<nb, nt, 0, st>>>(
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags,
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h,
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G,
nullptr, (long long*)gate, (unsigned int*)gate_ctr, stage);
R4D_ARGHW(false, R4dUnchained, nullptr);
}
#undef R4D_ARGHW
return (int)hipGetLastError();
}
@@ -597,7 +570,7 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl
long my_flags, long seq_ctrs, long slot_stride16,
long inp, long out, long n_elem, long dtype,
long stream_i, long nblocks, long nthreads,
long drain, long acq, long stage) {
long drain, long acq, long stage, long chain) {
hipStream_t st = (hipStream_t)stream_i;
const int esize = (dtype == 2) ? 4 : 2;
const long nbytes = (long)n_elem * esize;
@@ -619,14 +592,16 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl
// Tests only: every push lands after its flag (drain 4 above). Not in the tuning table, so no
// tuner can pick it.
if (g_ar_late_push) drain = 4;
#define L(T, LN) r4d_ar_oneshot_2rank_exact_kernel<T, LN><<<nb, nt, 0, st>>>( \
#define LK(T, LN, CH_) r4d_ar_oneshot_2rank_exact_kernel<T, LN, CH_><<<nb, nt, 0, st>>>( \
(const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out, \
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16, \
(int)slot_stride16, (int)drain, (int)acq, nbw, stage)
#define L(T, LN) do { if (chain) LK(T, LN, r4dchain); else LK(T, LN, R4dUnchained); } while (0)
if (dtype == 0) L(__hip_bfloat16, 8);
else if (dtype == 1) L(__half, 8);
else if (dtype == 2) L(float, 4);
else throw std::runtime_error("all_reduce: bad dtype");
#undef L
#undef LK
}
+21
View File
@@ -235,6 +235,10 @@ enum {
* cannot be static_asserted against `r4d_gemm_fp8a8_block()` (a function, not a macro), so
* r4d_gemm_fp8a8.hip checks it at launch. */
R4D_FP8_BLOCK = 128,
/* IQR's 8-bit format (IQ8R): int8 codes rotated 128 wide, one bf16 scale per row per 256 of K
* against an int8 activation with one f32 scale per (token, 256). Twice the int8 block, so a
* fold covers two 128-wide rotation blocks. */
R4D_I8_GROUP_WIDE = 256,
R4D_WAVE = 32,
R4D_NTILE = 16 /* output rows per WMMA n-tile */
};
@@ -274,6 +278,23 @@ static constexpr uint32_t kW4nlPerm[4] = { 0x504B4539u, 0x5B595653u, 0xD0CBC5B9
static constexpr float kW4nlTable[16] = { 1.125f, 3.25f, 5.5f, 8.0f, 11.0f, 14.0f, 18.0f, 22.0f,
-1.125f, -3.25f, -5.5f, -8.0f, -11.0f, -14.0f, -18.0f,
-22.0f };
/* w4nl's magnitudes as the int8 levels an int8 activation's WMMA multiplies, in units of
* kW4nlI8Unit: the integer set under 128 with the least squared distance from the table at one
* unit, and that unit, both over the code histogram of Qwen3.8-Flash-Next's GPTQ experts (19, 18,
* 17, 16, 12, 9, 5 and 4 percent by ascending magnitude), where the weight read this way is 2.4e-3
* of the stored one away in relative L2. w4nl_i8_dword packs entries 4d..4d+3 of the sixteen (the
* magnitudes, then their negatives) as kW4nlPerm packs its E4M3 bytes. */
static constexpr int8_t kW4nlI8[8] = { 6, 17, 29, 42, 58, 74, 95, 116 };
static constexpr float kW4nlI8Unit = 0.18965f;
static constexpr uint32_t w4nl_i8_dword(int d) {
uint32_t v = 0;
for (int i = 0; i < 4; ++i) {
const int e = 4 * d + i;
const int8_t l = (int8_t)(e < 8 ? kW4nlI8[e] : -kW4nlI8[e - 8]);
v |= (uint32_t)(uint8_t)l << (8 * i);
}
return v;
}
/* `w5nl64a8h` decodes libquant's `table=w5nl`: thirty-two levels, sixteen magnitudes ascending
* then their negatives, so a code's high bit is its sign and its low four bits index the
+72 -24
View File
@@ -14,7 +14,7 @@
#include "r4d.h"
#include "r4d_common.h"
#include "r4d_dt16.h"
#include "r4d_q8.h" // the gate quantiser's 8-bit codes: E4M3, or int8 (GQ == 2)
#include "r4d_q8.h" // the gate quantiser's 8-bit codes: E4M3, or int8 (GQ 2 and 3)
#include "r4d_chain.h"
#include <algorithm>
#include <type_traits>
@@ -54,9 +54,13 @@
// converted fragments and cost occupancy. Results are unchanged.
#define O_KRAW 16777216
// O_V4: the fp8_v4 cache (E4M3 K, int4 V in groups of 32 with an f16 scale), and with O_K6 the
// k6_v4 cache (int6 K, int4 V); a token's row layout is RadBuildCtx::kv_quant's (abi/rad_builder.h).
// k6_v4 cache (int6 K, int4 V). No row instantiates either without O_I8.
#define O_V4 33554432
#define O_K6 67108864
// O_I8 (with O_V4 | O_K6, whose staging it takes): the i8 cache, int8 K and V with one f16 scale
// each per token and head (a RAD_I8 group, abi/rad_builder.h). The codes are a byte wide and a key has
// one scale where k6_v4 has one per 32 dims; they widen to value * scale the same way.
#define O_I8 1073741824
// The two views of R4DArgs (r4d.h), compiled in only where a row asks for them, since the h256
// instances sit at the 256-VGPR bound and a runtime pitch and head map spill there:
// QLD q rows at R4DArgs::q_ld (attn_paged_qrow), not dense.
@@ -121,11 +125,13 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
constexpr int LDSB = (OPT & O_LDSB) ? 1 : 0;
constexpr int V4 = ((OPT & O_V4) && !KVP) ? 1 : 0;
constexpr int K6 = ((OPT & O_K6) && V4) ? 1 : 0;
constexpr int I8 = ((OPT & O_I8) && K6) ? 1 : 0;
// A token's row in a page, and where in it V's codes, V's scales and K's scales start.
constexpr int ROWB = K6 ? HEAD_DIM * 22 / 16 : V4 ? HEAD_DIM * 25 / 16 : 2 * HEAD_DIM;
constexpr int VOFF = K6 ? HEAD_DIM * 3 / 4 : HEAD_DIM;
constexpr int VSOFF = K6 ? HEAD_DIM * 21 / 16 : HEAD_DIM * 3 / 2;
constexpr int KSOFF = HEAD_DIM * 5 / 4;
constexpr int ROWB = I8 ? 2 * HEAD_DIM + 4
: K6 ? HEAD_DIM * 22 / 16 : V4 ? HEAD_DIM * 25 / 16 : 2 * HEAD_DIM;
constexpr int VOFF = I8 ? HEAD_DIM : K6 ? HEAD_DIM * 3 / 4 : HEAD_DIM;
constexpr int VSOFF = I8 ? 2 * HEAD_DIM + 2 : K6 ? HEAD_DIM * 21 / 16 : HEAD_DIM * 3 / 2;
constexpr int KSOFF = I8 ? 2 * HEAD_DIM : HEAD_DIM * 5 / 4;
constexpr int V8 = ((OPT & O_V8) && !KVP && !V4) ? 1 : 0;
static_assert(!V8 || (OPT & O_CONTIG), "the code tile is read in the contiguous layout");
constexpr int KRAW = ((OPT & O_KRAW) && !KLDS) ? 1 : 0;
@@ -288,7 +294,8 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
// The pair's two scales stay apart until storeV4 packs them: packed here, the fetch is waited on
// right after it is issued. fp8_v4 packs here, as the prefill kernel does.
constexpr int OLDV4 = V4 && !K6;
uint32_t v4c[U4][2], v4s[U4][2];
// i8: a key's 8 dims are two code words, so a pair's are four.
uint32_t v4c[U4][I8 ? 4 : 2], v4s[U4][2];
auto fetchV4 = [&](int k0, const int* blks) {
#pragma unroll
for (int r = 0; r < U4; ++r) {
@@ -307,8 +314,15 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
const int bk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS];
const uint8_t* base = (const uint8_t*)a.kv + (size_t)bk * a.kv_block_stride
+ (size_t)kvc * a.kv_head_stride + (size_t)(kk % BS) * ROWB;
v4c[r][j] = *(const uint32_t*)(base + VOFF + o * 4);
sc[j] = *(const uint16_t*)(base + VSOFF + (o >> 2) * 2);
if constexpr (I8) {
const uint2 cw = *(const uint2*)(base + VOFF + o * 8);
v4c[r][2 * j] = cw.x;
v4c[r][2 * j + 1] = cw.y;
sc[j] = *(const uint16_t*)(base + VSOFF);
} else {
v4c[r][j] = *(const uint32_t*)(base + VOFF + o * 4);
sc[j] = *(const uint16_t*)(base + VSOFF + (o >> 2) * 2);
}
}
if constexpr (OLDV4) { v4s[r][0] = sc[0] | (sc[1] << 16); v4s[r][1] = 0; }
else { v4s[r][0] = sc[0]; v4s[r][1] = sc[1]; }
@@ -326,13 +340,18 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
|| (NP4 % 32 == 0 ? __builtin_amdgcn_readfirstlane(warp) * 32 < NP4 - r * NTHR
: u < NP4)) : u < NP4)) {
const int kp = u % (TILE / 2), o = u / (TILE / 2);
// Two's complement nibbles; ^ 8 makes them offset binary (value + 8).
const uint32_t n0 = (v4c[r][0] & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t m0 = ((v4c[r][0] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t n1 = (v4c[r][1] & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t m1 = ((v4c[r][1] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
// Two's complement nibbles; ^ 8 makes them offset binary (value + 8). i8: bytes,
// ^ 0x80 (value + 128); `n` is a key's dims 0-3 of the octet and `m` its dims 4-7.
const uint32_t n0 = I8 ? v4c[r][0] ^ 0x80808080u
: (v4c[r][0] & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t m0 = I8 ? v4c[r][1] ^ 0x80808080u
: ((v4c[r][0] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t n1 = I8 ? v4c[r][I8 ? 2 : 1] ^ 0x80808080u
: (v4c[r][1] & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t m1 = I8 ? v4c[r][I8 ? 3 : 1] ^ 0x80808080u
: ((v4c[r][1] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
const h2 s2 = __builtin_bit_cast(h2, OLDV4 ? v4s[r][0] : (v4s[r][0] | (v4s[r][1] << 16)));
const h2 bias = { (_Float16)1032.0f, (_Float16)1032.0f };
const h2 bias = { (_Float16)(I8 ? 1152.0f : 1032.0f), (_Float16)(I8 ? 1152.0f : 1032.0f) };
uint16_t* dst = &sV16[(o * 8) * VSTR + 2 * kp
+ (VSK ? 16 * (o & 3) + 8 * ((o >> 2) & 1) + 128 * (o >> 2) : 0)];
#pragma unroll
@@ -342,8 +361,9 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
const uint32_t hi = __builtin_amdgcn_perm(m1, m0, sel) | 0x64006400u;
const h2 vl = (__builtin_bit_cast(h2, lo) - bias) * s2;
const h2 vh = (__builtin_bit_cast(h2, hi) - bias) * s2;
*(uint32_t*)(dst + (2 * b) * VSTR) = __builtin_bit_cast(uint32_t, vl);
*(uint32_t*)(dst + (2 * b + 1) * VSTR) = __builtin_bit_cast(uint32_t, vh);
// The octet's rows: nibbles interleave the dims (2b, 2b+1), bytes run b, 4+b.
*(uint32_t*)(dst + (I8 ? b : 2 * b) * VSTR) = __builtin_bit_cast(uint32_t, vl);
*(uint32_t*)(dst + (I8 ? 4 + b : 2 * b + 1) * VSTR) = __builtin_bit_cast(uint32_t, vh);
}
}
}
@@ -469,6 +489,8 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
+ (size_t)kvc * a.kv_head_stride + (size_t)(kk % BS) * ROWB)
* (KVP ? 2 : 1);
}
// i8: the key's one K scale, read once an m-tile.
const uint32_t ksb = I8 ? (uint32_t)*(const uint16_t*)(grow + KSOFF) : 0u;
// A fragment's raw K: 8 elements of 1 byte (fp8) or 2 (bf16).
typedef typename std::conditional<KVP != 0, uint4, uint2>::type kraw_t;
kraw_t kraw[KRAW ? NKS : 1];
@@ -505,6 +527,11 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
}
kb[j] = D::mk(make_uint2(D::from_bf16w(l0.x), D::from_bf16w(l0.y)),
make_uint2(D::from_bf16w(h0.x), D::from_bf16w(h0.y)));
} else if constexpr (I8) {
// i8: this lane's eight dims (16t + 8h ..) as bytes, times the key's scale.
uint32_t w4[4];
i8x8_to_f16x4w(*(const uint2*)(grow + 16 * t + 8 * h), ksb | (ksb << 16), w4);
kb[j] = D::mk(make_uint2(w4[0], w4[1]), make_uint2(w4[2], w4[3]));
} else if constexpr (K6) {
// k6_v4: this lane's eight dims (16t + 8h ..) from their low nibbles, the
// chunk's high-bit word and the group's scale.
@@ -671,12 +698,17 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
// multiply, product rounded, scale = group absmax / 448 (1 at zero), codes clamped to +-448, and
// the bf16 product stored to `out`. A padded slot merges to zeros and takes the same epilogue.
// GQ == 2 is the int8 form (scale amax / 127, round to nearest-even, r4d_q8.h).
// GQ == 3 (attn_paged_gate_had_quant) is the int8 form with the width-128 Hadamard between the
// bf16 product and the absmax, byte-identical to gate_had_quant_i8g: `out` keeps the unrotated
// product, and the stages run by ascending stride as r4d_fwht_wave's do, whose butterflies give
// the same bits under any thread map.
struct R4DGateQuant {
const uint16_t* g; // gate, row `job` at g + job * g_ld
uint8_t* q; // E4M3 (or int8, `i8`) codes, row `job` at q + job * q_ld
float* s; // one scale per 128 columns, row `job` at s + job * s_ld
unsigned g_ld, q_ld, s_ld;
int i8; // read by the launcher only: which combine to instantiate
int rot; // likewise: the rotated int8 form (GQ 3)
};
constexpr int kGqGroup = 128;
@@ -743,26 +775,28 @@ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DG
union { uint4 u4; uint2 u2; uint16_t w[DPL]; } gi, o_;
if (DPL == 8) gi.u4 = *(const uint4*)gp; else gi.u2 = *(const uint2*)gp;
float v[DPL];
float m = 0.0f;
#pragma unroll
for (int j = 0; j < DPL; ++j) {
o_.w[j] = r4d_gq_gate(gi.w[j], ob[j]);
v[j] = bf16_to_f32(o_.w[j]);
m = fmaxf(m, fabsf(v[j]));
}
if (DPL == 8) *(uint4*)outp = o_.u4; else *(uint2*)outp = o_.u2;
if constexpr (GQ == 3) r4d_fwht_part<DPL, LPG>(v, lane);
float m = 0.0f;
#pragma unroll
for (int j = 0; j < DPL; ++j) m = fmaxf(m, fabsf(v[j]));
if constexpr (LPG > 16) m = fmaxf(m, r4d_xor_lane<16>(m));
if constexpr (LPG > 8) m = fmaxf(m, r4d_xor_lane<8>(m));
m = fmaxf(m, r4d_xor_lane<4>(m));
m = fmaxf(m, r4d_xor_lane<2>(m));
m = fmaxf(m, r4d_xor_lane<1>(m));
const float sc = m > 0.0f ? m * (1.0f / q8_top<GQ == 2>()) : 1.0f;
const float sc = m > 0.0f ? m * (1.0f / q8_top<GQ >= 2>()) : 1.0f;
const float inv = 1.0f / sc;
if ((lane % LPG) == 0) gq.s[(size_t)job * gq.s_ld + (lane * DPL) / kGqGroup] = sc;
uint32_t pk[DPL / 4];
#pragma unroll
for (int w = 0; w < DPL / 4; ++w)
pk[w] = q8_pack4<GQ == 2>(v[4 * w + 0], v[4 * w + 1], v[4 * w + 2], v[4 * w + 3],
pk[w] = q8_pack4<GQ >= 2>(v[4 * w + 0], v[4 * w + 1], v[4 * w + 2], v[4 * w + 3],
inv);
uint8_t* qp = gq.q + (size_t)job * gq.q_ld + lane * DPL;
if (DPL == 8) *(uint2*)qp = make_uint2(pk[0], pk[DPL / 4 - 1]);
@@ -924,7 +958,21 @@ void splitkv_combine_body(const R4DArgs& a, int splits, int tile, const R4DGateQ
constexpr int WPG = kGqGroup / 32; // waves a scale group
const uint16_t h = r4d_gq_gate(gq.g[(size_t)job * gq.g_ld + d], ob);
*op = h;
const float v = bf16_to_f32(h);
float v = bf16_to_f32(h);
if constexpr (GQ == 3) {
/* Strides 1 to 16 pair lanes of the wave; 32 and 64 pair waves of the group, two
* exchanges through `red`, each read behind the barrier after its store and ahead
* of the next. */
r4d_fwht_part<1, 32>(&v, d & 31);
#pragma unroll
for (int hs = 32; hs < kGqGroup; hs <<= 1) {
red[d] = v;
__syncthreads();
const float o = red[d ^ hs];
v = __int_as_float(__float_as_int(v) ^ ((d & hs) ? 0x80000000u : 0u)) + o;
__syncthreads();
}
}
const float m = r4d_wave_max(fabsf(v));
if ((d & 31) == 0) red[d / 32] = m;
__syncthreads();
@@ -932,10 +980,10 @@ void splitkv_combine_body(const R4DArgs& a, int splits, int tile, const R4DGateQ
float gm = red[g0];
#pragma unroll
for (int w = 1; w < WPG; ++w) gm = fmaxf(gm, red[g0 + w]);
const float sc = gm > 0.0f ? gm * (1.0f / q8_top<GQ == 2>()) : 1.0f;
const float sc = gm > 0.0f ? gm * (1.0f / q8_top<GQ >= 2>()) : 1.0f;
const float inv = 1.0f / sc;
if ((d % kGqGroup) == 0) gq.s[(size_t)job * gq.s_ld + d / kGqGroup] = sc;
if constexpr (GQ == 2) {
if constexpr (GQ >= 2) {
gq.q[(size_t)job * gq.q_ld + d] =
(uint8_t)(int)rintf(fminf(fmaxf(v * inv, -127.0f), 127.0f));
} else {
+109 -93
View File
@@ -55,12 +55,6 @@ using std::max;
#ifndef R4D_ATTN_H256
#define R4D_ATTN_H256 1
#endif
/* The fp8_v4 and k6_v4 caches at head_dim 256 (RadBuildCtx::kv_quant), off unless the including
* unit serves a model whose plugin offers them: Qwen3.8-Flash-Next's QSA layers (gqa12, and gqa6
* at four ranks). The kernels are the h256/gqa6 templates' O_V4 / O_K6 forms. */
#ifndef R4D_ATTN_V4
#define R4D_ATTN_V4 0
#endif
#define GQ_JOIN_(a, b, c) a##b##c
#define GQ_JOIN(a, b, c) GQ_JOIN_(a, b, c)
#define GQ_SYM(pre, suf) GQ_JOIN(pre, R4D_ATTN_GQA, suf)
@@ -138,7 +132,7 @@ template <int HEAD_DIM, int KVP, int XOPT = 0>
/* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (184
* bytes) like any other kernel argument. Non-null `gq` adds the output gate and quantiser to the
* combine (attn_paged_gate_quant; R4DGateQuant in r4d_attn_decode_h256_gqa6.hip). `XOPT` adds
* option bits to the attention kernel's (O_V4, O_K6: the cache layout). */
* option bits to the attention kernel's (O_KVI8: the int8 cache). */
static int g8_decode_launch(const R4DArgs* a, RadStream stream,
const R4DGateQuant* gq = nullptr) {
int emit_rc = RAD_OK;
@@ -149,26 +143,28 @@ static int g8_decode_launch(const R4DArgs* a, RadStream stream,
const int nw = (rows + 15) / 16;
const int splits = r4d_decode_splits(a, G8_D_TILE);
#define G8_LAUNCH(NW) \
emit_rc = R4D_EMIT(stream, (r4d_attn_decode_kernel<NW, G8_D_TILE, HEAD_DIM, G8_GQA, \
G8_BLOCK_SIZE, KVP, G8_D_OPT | XOPT>), \
/* `a->chain`: the chained forms (r4d_chain.h) of the attention kernel and of the merge
* without a gate; the merge with a gate and quantiser has none. */
#define G8_LAUNCH_K(K_, NW, OPT_) \
emit_rc = R4D_EMIT(stream, (K_<NW, G8_D_TILE, HEAD_DIM, G8_GQA, G8_BLOCK_SIZE, KVP, \
G8_D_OPT | OPT_ | XOPT>), \
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, *a, splits)
/* One-wave workgroups stage V as codes (O_V8): same conversion count, half the LDS. A v4
* cache stages V widened (the kernel drops O_V8 under O_V4). */
if (nw == 1)
emit_rc = R4D_EMIT(stream, (r4d_attn_decode_kernel<1, G8_D_TILE, HEAD_DIM, G8_GQA,
G8_BLOCK_SIZE, KVP,
G8_D_OPT | O_V8 | XOPT>),
dim3(splits, a->kv_heads, a->num_seqs), dim3(32), 0, *a, splits);
else if (nw == 2) G8_LAUNCH(2);
else if (nw == 3) G8_LAUNCH(3);
#define G8_LAUNCH(NW, OPT_) \
do { if (a->chain) G8_LAUNCH_K(r4dchain_attn_decode, NW, OPT_); \
else G8_LAUNCH_K(r4d_attn_decode_kernel, NW, OPT_); } while (0)
/* One-wave workgroups stage V as codes (O_V8): same conversion count, half the LDS. The int8
* cache stages V widened (the kernel drops O_V8 under it). */
if (nw == 1) G8_LAUNCH(1, O_V8);
else if (nw == 2) G8_LAUNCH(2, 0);
else if (nw == 3) G8_LAUNCH(3, 0);
#if G8_MAX_DECODE_ROWS > 64
/* Five to eight waves take eight; a wave past the last query row computes a copy of it and
* stores nothing. */
else if (nw > 4) G8_LAUNCH(8);
else if (nw > 4) G8_LAUNCH(8, 0);
#endif
else G8_LAUNCH(4);
else G8_LAUNCH(4, 0);
#undef G8_LAUNCH
#undef G8_LAUNCH_K
if (emit_rc != RAD_OK) return -5;
CHK8();
@@ -176,7 +172,7 @@ static int g8_decode_launch(const R4DArgs* a, RadStream stream,
// segment count fits a wave, else the general LDS-tree form. Both give identical bytes.
const int jobs3 = r4d_q_total(*a) * a->q_heads;
if (gq) {
/* GQ 2: int8 codes, GQ 1: E4M3; see R4DGateQuant. */
/* GQ 3: rotated int8 codes, GQ 2: int8 codes, GQ 1: E4M3; see R4DGateQuant. */
#define G8_GQ_VEC(PF, GQV) \
R4D_EMIT(stream, \
(r4d_attn_splitkv_combine_vec_gq_kernel<HEAD_DIM, 4, PF, G8_D_JPB, 0, GQV>), \
@@ -186,35 +182,47 @@ static int g8_decode_launch(const R4DArgs* a, RadStream stream,
R4D_EMIT(stream, (r4d_attn_splitkv_combine_gq_kernel<HEAD_DIM, 4, PF, 0, GQV>), \
dim3(jobs3), dim3(HEAD_DIM), splits * sizeof(float), *a, splits, G8_D_TILE, \
*gq)
const bool i8 = gq->i8 != 0;
const bool i8 = gq->i8 != 0, rot = gq->rot != 0;
if (splits <= 64 && jobs3 >= G8_D_VECMIN) {
if (G8_D_OPT & 32) emit_rc = i8 ? G8_GQ_VEC(1, 2) : G8_GQ_VEC(1, 1);
else emit_rc = i8 ? G8_GQ_VEC(0, 2) : G8_GQ_VEC(0, 1);
if (G8_D_OPT & 32)
emit_rc = rot ? G8_GQ_VEC(1, 3) : i8 ? G8_GQ_VEC(1, 2) : G8_GQ_VEC(1, 1);
else
emit_rc = rot ? G8_GQ_VEC(0, 3) : i8 ? G8_GQ_VEC(0, 2) : G8_GQ_VEC(0, 1);
} else if (G8_D_OPT & 32) {
emit_rc = i8 ? G8_GQ_GEN(1, 2) : G8_GQ_GEN(1, 1);
emit_rc = rot ? G8_GQ_GEN(1, 3) : i8 ? G8_GQ_GEN(1, 2) : G8_GQ_GEN(1, 1);
} else {
emit_rc = i8 ? G8_GQ_GEN(0, 2) : G8_GQ_GEN(0, 1);
emit_rc = rot ? G8_GQ_GEN(0, 3) : i8 ? G8_GQ_GEN(0, 2) : G8_GQ_GEN(0, 1);
}
#undef G8_GQ_VEC
#undef G8_GQ_GEN
} else if (splits <= 64 && jobs3 >= G8_D_VECMIN) {
const int blocks = (jobs3 + G8_D_JPB - 1) / G8_D_JPB;
if (G8_D_OPT & 32)
emit_rc = R4D_EMIT(stream,
(r4d_attn_splitkv_combine_vec_kernel<HEAD_DIM, 4, 1, G8_D_JPB>),
dim3(blocks), dim3(32 * G8_D_JPB), 0, *a, splits, G8_D_TILE);
else
emit_rc = R4D_EMIT(stream,
(r4d_attn_splitkv_combine_vec_kernel<HEAD_DIM, 4, 0, G8_D_JPB>),
dim3(blocks), dim3(32 * G8_D_JPB), 0, *a, splits, G8_D_TILE);
} else if (G8_D_OPT & 32)
#define G8_VEC(K_, PF) \
emit_rc = R4D_EMIT(stream, (K_<HEAD_DIM, 4, PF, G8_D_JPB>), dim3(blocks), \
dim3(32 * G8_D_JPB), 0, *a, splits, G8_D_TILE)
if (G8_D_OPT & 32) {
if (a->chain) G8_VEC(r4dchain_attn_splitkv_combine_vec, 1);
else G8_VEC(r4d_attn_splitkv_combine_vec_kernel, 1);
} else {
if (a->chain) G8_VEC(r4dchain_attn_splitkv_combine_vec, 0);
else G8_VEC(r4d_attn_splitkv_combine_vec_kernel, 0);
}
#undef G8_VEC
} else {
/* Block of HEAD_DIM threads, not 256: the general combine is __launch_bounds__(HEAD_DIM),
* one thread per channel, and the runtime refuses a larger block. */
emit_rc = R4D_EMIT(stream, (r4d_attn_splitkv_combine_kernel<HEAD_DIM, 4, 1>), dim3(jobs3),
dim3(HEAD_DIM), splits * sizeof(float), *a, splits, G8_D_TILE);
else
emit_rc = R4D_EMIT(stream, (r4d_attn_splitkv_combine_kernel<HEAD_DIM, 4, 0>), dim3(jobs3),
dim3(HEAD_DIM), splits * sizeof(float), *a, splits, G8_D_TILE);
#define G8_GEN(K_, PF) \
emit_rc = R4D_EMIT(stream, (K_<HEAD_DIM, 4, PF>), dim3(jobs3), dim3(HEAD_DIM), \
splits * sizeof(float), *a, splits, G8_D_TILE)
if (G8_D_OPT & 32) {
if (a->chain) G8_GEN(r4dchain_attn_splitkv_combine, 1);
else G8_GEN(r4d_attn_splitkv_combine_kernel, 1);
} else {
if (a->chain) G8_GEN(r4dchain_attn_splitkv_combine, 0);
else G8_GEN(r4d_attn_splitkv_combine_kernel, 0);
}
#undef G8_GEN
}
if (emit_rc != RAD_OK) return -5;
CHK8();
return 0;
@@ -248,14 +256,6 @@ extern "C" int64_t GQ_SYM(r4d_rad_attn_prefill_h256_gqa, _scratch)(const RadArgs
return g8_prefill_scratch(a, 512);
}
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h256_gqa, _fp8)(const RadArgs* a, RadStream s) {
R4DArgs r;
const int rc = fill_paged(a, &r, 256);
if (rc != RAD_OK) return rc;
r.splits = r4d_prefill_splits(a, &r, G8_P_BQ, G8_P_TILE);
/* Absent descales mean 1.0, as on the gqa6 leg. */
return g8_prefill_launch<256, G8_P_OPT_256, 0>(&r, (hipStream_t)s);
}
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h256_gqa, _bf16)(const RadArgs* a, RadStream s) {
R4DArgs r;
const int rc = fill_paged(a, &r, 256);
@@ -265,12 +265,6 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h256_gqa, _bf16)(const RadArgs* a, Ra
}
#endif
#if R4D_ATTN_H128
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h128_gqa, _fp8)(const RadArgs* a, RadStream s) {
R4DArgs r;
const int rc = fill_paged(a, &r, 128);
if (rc != RAD_OK) return rc;
return g8_prefill_launch<128, G8_P_OPT_128, 0>(&r, (hipStream_t)s);
}
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h128_gqa, _bf16)(const RadArgs* a, RadStream s) {
R4DArgs r;
const int rc = fill_paged(a, &r, 128);
@@ -279,11 +273,12 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h128_gqa, _bf16)(const RadArgs* a, Ra
}
#endif
#if R4D_ATTN_H64
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _fp8)(const RadArgs* a, RadStream s) {
/* The int8 cache at this width: a token's row is 2 * 64 + 4 = 132 bytes. */
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _i8)(const RadArgs* a, RadStream s) {
R4DArgs r;
const int rc = fill_paged(a, &r, 64);
const int rc = fill_paged_row(a, &r, 64, 2 * 64 + 4);
if (rc != RAD_OK) return rc;
return g8_prefill_launch<64, G8_P_OPT_64, 0>(&r, (hipStream_t)s);
return g8_prefill_launch<64, G8_P_OPT_64 | O_KVI8, 0>(&r, (hipStream_t)s);
}
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _bf16)(const RadArgs* a, RadStream s) {
R4DArgs r;
@@ -300,7 +295,7 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _bf16)(const RadArgs* a, Rad
* split law's targets (r4d_decode_splits: 256 workgroups at q_len * gqa <= 32; above, 128 to 16384
* tokens deep and more past it) can give a shorter query more splits: at gqa 8 a 4-row step needs
* 1.6x the partials of the band bound 5. */
/* `row` is a token's bytes in a (block, head) page, 0 for the 16-bit and E4M3 caches' 2 * head_dim
/* `row` is a token's bytes in a (block, head) page, 0 for the bf16 cache's 2 * head_dim elements
* (fill_paged_row). */
static int64_t g8_decode_scratch(const RadArgs* a, int head_dim, long long row = 0) {
const int sp = split_of(a);
@@ -360,16 +355,9 @@ static int g8_decode_common(const RadArgs* a, R4DArgs* r, int head_dim, long lon
}
#if R4D_ATTN_H256
extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _fp8)(const RadArgs* a, RadStream stream) {
R4DArgs r;
const int rc = g8_decode_common(a, &r, 256);
if (rc != RAD_OK) return rc;
return g8_decode_launch<256, 0>(&r, stream);
}
/* ---- attn_paged_gate_quant: attn_paged's eight operands, then the gate, codes and scales.
* The gate is a [T, n_head, head_dim] column view of the [q|gate] projection; its (token, head)
* rows are one pitch apart only if the view narrowed the last axis alone. gq_row_pitch repeats
* gate_quant_fp8's tq_pitch test, which this unit cannot link. */
* rows are one pitch apart only if the view narrowed the last axis alone. */
enum { AP_GQ_G = AP_OUT + 1, AP_GQ_Q, AP_GQ_S };
static long long gq_row_pitch(const RadTensor* t, long long width) {
@@ -382,7 +370,9 @@ static long long gq_row_pitch(const RadTensor* t, long long width) {
return t->stride[t->rank - 2];
}
static int g8_gate_quant_args(const RadArgs* a, const R4DArgs& r, R4DGateQuant* gq) {
/* `rot`: attn_paged_gate_had_quant, whose codes are in the rotated domain. */
static int g8_gate_quant_args(const RadArgs* a, const R4DArgs& r, R4DGateQuant* gq,
bool rot = false) {
const RadTensor* g = r4d_opt(a, AP_GQ_G);
const RadTensor* q = r4d_opt(a, AP_GQ_Q);
const RadTensor* s = r4d_opt(a, AP_GQ_S);
@@ -391,6 +381,7 @@ static int g8_gate_quant_args(const RadArgs* a, const R4DArgs& r, R4DGateQuant*
if (g->dtype != RAD_BF16 || (q->dtype != RAD_F8E4M3 && q->dtype != RAD_I8) ||
s->dtype != RAD_F32)
return R4D_NO(RAD_E_DTYPE);
if (rot && q->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE);
const char* act = r4d_gets(a, "act");
if (!act || std::strcmp(act, "sigmoid")) return R4D_NO(RAD_E_UNSUPPORTED);
if (r4d_geti_or(a, "group", kGqGroup) != kGqGroup) return R4D_NO(RAD_E_SHAPE);
@@ -413,20 +404,12 @@ static int g8_gate_quant_args(const RadArgs* a, const R4DArgs& r, R4DGateQuant*
gq->q_ld = (unsigned)qp;
gq->s_ld = (unsigned)sp;
gq->i8 = q->dtype == RAD_I8 ? 1 : 0;
gq->rot = rot ? 1 : 0;
return RAD_OK;
}
extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _fp8)(const RadArgs* a, RadStream stream) {
R4DArgs r;
const int rc = g8_decode_common(a, &r, 256);
if (rc != RAD_OK) return rc;
R4DGateQuant gq{};
const int gc = g8_gate_quant_args(a, r, &gq);
if (gc != RAD_OK) return gc;
return g8_decode_launch<256, 0>(&r, stream, &gq);
}
/* bf16-cache decode, plain and gated: the fp8 pair at KVP 1. */
/* bf16-cache decode, plain and with the gate and quantiser in the merge (`_gq` E4M3 or int8 codes,
* `_ghq` rotated int8 codes for an out projection stored rotated). */
extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _bf16)(const RadArgs* a, RadStream stream) {
R4DArgs r;
const int rc = g8_decode_common(a, &r, 256);
@@ -442,14 +425,17 @@ extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _bf16)(const RadArgs* a,
if (gc != RAD_OK) return gc;
return g8_decode_launch<256, 1>(&r, stream, &gq);
}
extern "C" int GQ_SYM(r4d_rad_attn_decode_ghq_h256_gqa, _bf16)(const RadArgs* a, RadStream stream) {
R4DArgs r;
const int rc = g8_decode_common(a, &r, 256);
if (rc != RAD_OK) return rc;
R4DGateQuant gq{};
const int gc = g8_gate_quant_args(a, r, &gq, true);
if (gc != RAD_OK) return gc;
return g8_decode_launch<256, 1>(&r, stream, &gq);
}
#endif
#if R4D_ATTN_H128
extern "C" int GQ_SYM(r4d_rad_attn_decode_h128_gqa, _fp8)(const RadArgs* a, RadStream s) {
R4DArgs r;
const int rc = g8_decode_common(a, &r, 128);
if (rc != RAD_OK) return rc;
return g8_decode_launch<128, 0>(&r, s);
}
extern "C" int GQ_SYM(r4d_rad_attn_decode_h128_gqa, _bf16)(const RadArgs* a, RadStream s) {
R4DArgs r;
const int rc = g8_decode_common(a, &r, 128);
@@ -458,11 +444,32 @@ extern "C" int GQ_SYM(r4d_rad_attn_decode_h128_gqa, _bf16)(const RadArgs* a, Rad
}
#endif
#if R4D_ATTN_H256 && R4D_ATTN_V4
/* ---- the fp8_v4 cache (a token's row 25 * 256 / 16 = 400 bytes: E4M3 K, int4 V, f16 scales) and
* the k6_v4 cache (352 bytes: int6 K, int4 V), prefill, decode and decode with the gate and
* quantiser in the merge. */
#define G8_V4_ENTRIES(TAG, ROWB, XOPT) \
#if R4D_ATTN_H128
/* ---- the int8 cache at head_dim 128: a token's row is 2 * 128 + 4 = 260 bytes. Prefill (K staged
* eight dims a thread, having no wide fetch at this width), and the decode that also serves a
* drafter's non-causal block. */
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h128_gqa, _i8)(const RadArgs* a, RadStream s) {
R4DArgs r;
const int rc = fill_paged_row(a, &r, 128, 2 * 128 + 4);
if (rc != RAD_OK) return rc;
return g8_prefill_launch<128, G8_P_OPT_128 | O_KVI8, 0>(&r, (hipStream_t)s);
}
extern "C" int64_t GQ_SYM(r4d_rad_attn_decode_h128_gqa, _i8_scratch)(const RadArgs* a) {
return g8_decode_scratch(a, 128, 2 * 128 + 4);
}
extern "C" int GQ_SYM(r4d_rad_attn_decode_h128_gqa, _i8)(const RadArgs* a, RadStream stream) {
R4DArgs r;
const int rc = g8_decode_common(a, &r, 128, 2 * 128 + 4);
if (rc != RAD_OK) return rc;
return g8_decode_launch<128, 0, O_KVI8>(&r, stream);
}
#endif
#if R4D_ATTN_H256
/* ---- the int8 cache at head_dim 256 (a token's row 2 * 256 + 4 = 516 bytes): prefill, decode
* and decode with the gate and quantiser in the merge. `_ghq` is `_gq` with the rotated
* quantiser. */
#define G8_I8_ENTRIES(TAG, ROWB, XOPT) \
extern "C" int64_t GQ_SYM(r4d_rad_attn_prefill_h256_gqa, _##TAG##_scratch)(const RadArgs* a) { \
return g8_prefill_scratch(a, ROWB); \
} \
@@ -492,8 +499,17 @@ extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _##TAG)(const RadArgs* a,
const int gc = g8_gate_quant_args(a, r, &gq); \
if (gc != RAD_OK) return gc; \
return g8_decode_launch<256, 0, (XOPT)>(&r, stream, &gq); \
} \
extern "C" int GQ_SYM(r4d_rad_attn_decode_ghq_h256_gqa, _##TAG)(const RadArgs* a, \
RadStream stream) { \
R4DArgs r; \
const int rc = g8_decode_common(a, &r, 256, ROWB); \
if (rc != RAD_OK) return rc; \
R4DGateQuant gq{}; \
const int gc = g8_gate_quant_args(a, r, &gq, true); \
if (gc != RAD_OK) return gc; \
return g8_decode_launch<256, 0, (XOPT)>(&r, stream, &gq); \
}
G8_V4_ENTRIES(fp8v4, 400, O_V4)
G8_V4_ENTRIES(k6v4, 352, O_V4 | O_K6)
#undef G8_V4_ENTRIES
G8_I8_ENTRIES(i8, 516, O_KVI8)
#undef G8_I8_ENTRIES
#endif
+13 -11
View File
@@ -31,8 +31,10 @@ extern "C" long r4d_attn_decode_h128_gqa2w_scratch_bytes(const R4DArgs* a) {
return r4d_decode_scratch(a, r4d_decode_splits_win(a, B_TILE), B_OPT);
}
extern "C" int r4d_attn_decode_h128_gqa2w_fp8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 0>(a, s);
// The int8 cache: K is widened from the paged cache a fragment at a time, so without the one-round
// raw K loads.
extern "C" int r4d_attn_decode_h128_gqa2w_i8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, (B_OPT & ~O_KRAW) | O_KVI8, 0>(a, s);
}
extern "C" int r4d_attn_decode_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 1>(a, s);
@@ -46,33 +48,33 @@ extern "C" int r4d_attn_decode_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t s
#define P_TILE 48
#define P_OPT 3430923
template <int KVP>
template <int KVP, int XOPT = 0>
static int prefill_launch_h128_gqa2w(const R4DArgs* a, hipStream_t s) {
if (a->head_dim != B_HEAD_DIM || a->block_size != B_BLOCK_SIZE) return -1;
if (a->q_heads / a->kv_heads != B_GQA) return -2;
constexpr int BQ = (P_NWARPS * 16) / B_GQA;
dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs);
hipLaunchKernelGGL((r4d_attn_prefill_kernel<P_NWARPS, P_TILE, B_HEAD_DIM, B_GQA,
B_BLOCK_SIZE, KVP, P_OPT, 1>),
B_BLOCK_SIZE, KVP, P_OPT | XOPT, 1>),
grid, dim3(P_NWARPS * 32), 0, s, *a);
CHK4();
return 0;
}
extern "C" int r4d_attn_prefill_h128_gqa2w_fp8kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch_h128_gqa2w<0>(a, s);
extern "C" int r4d_attn_prefill_h128_gqa2w_i8kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch_h128_gqa2w<0, O_KVI8>(a, s);
}
extern "C" int r4d_attn_prefill_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch_h128_gqa2w<1>(a, s);
}
/* Prefill RadArgs wrappers. Absent descales mean 1.0 (fill_paged leaves them null). The decode
* wrappers are in r4d_attn_paged_h256_gqa6.hip beside decode_common. */
extern "C" int r4d_rad_attn_prefill_h128_gqa2w_fp8(const RadArgs* a, RadStream s) {
/* Prefill RadArgs wrappers; the int8 cache's token row is 2 * 128 + 4 bytes. The decode wrappers
* are in r4d_attn_paged_h256_gqa6.hip beside decode_common. */
extern "C" int r4d_rad_attn_prefill_h128_gqa2w_i8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = fill_paged(a, &r, B_HEAD_DIM);
int rc = fill_paged_row(a, &r, B_HEAD_DIM, 2 * B_HEAD_DIM + 4);
if (rc != RAD_OK) return rc;
return r4d_attn_prefill_h128_gqa2w_fp8kv(&r, (hipStream_t)s);
return r4d_attn_prefill_h128_gqa2w_i8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_prefill_h128_gqa2w_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
+8 -5
View File
@@ -31,16 +31,19 @@ extern "C" long r4d_attn_decode_h128_gqa4_scratch_bytes(const R4DArgs* a) {
return r4d_decode_scratch(a, r4d_decode_splits_win(a, B_TILE), B_OPT);
}
extern "C" int r4d_attn_decode_h128_gqa4_fp8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 0>(a, s);
}
extern "C" int r4d_attn_decode_h128_gqa4_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 1>(a, s);
}
// The int8 cache (int8 K and V, an f16 scale each per token and head): K is widened from the paged
// cache a fragment at a time, so without the one-round raw K loads.
extern "C" int r4d_attn_decode_h128_gqa4_i8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, (B_OPT & ~O_KRAW) | O_KVI8, 0>(a, s);
}
// The same over a cache holding each kv head once for kv_rep query groups (O_KVREP), q at
// R4DArgs::q_ld (O_QLD): gqa 8 on this gqa-4 kernel, under attn_paged_qrow.
extern "C" int r4d_attn_decode_h128_gqa4_rep_fp8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD | O_KVREP, 0>(a, s);
extern "C" int r4d_attn_decode_h128_gqa4_rep_i8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, (B_OPT & ~O_KRAW) | O_KVI8 | O_QLD | O_KVREP,
0>(a, s);
}
extern "C" int r4d_attn_decode_h128_gqa4_rep_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD | O_KVREP, 1>(a, s);
-2
View File
@@ -17,7 +17,5 @@
// pages at 4 (RadKVGroupDecl takes the block size from the resolved kernel). A row saying 16 here
// would refuse at issue rather than at declare.
#define G8_BLOCK_SIZE 4
// The fp8_v4 and k6_v4 caches (--kv-cache-dtype), which qwen4exp_fp8 offers for these layers.
#define R4D_ATTN_V4 1
#include "r4d_attn_paged_gqa8.hip"
+23 -19
View File
@@ -31,23 +31,24 @@ extern "C" long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a) {
return r4d_decode_scratch(a, r4d_decode_splits_win(a, B_TILE), B_OPT);
}
extern "C" int r4d_attn_decode_h256_gqa2_fp8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 0>(a, s);
extern "C" int r4d_attn_decode_h256_gqa2_i8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, (B_OPT & ~O_KRAW) | O_KVI8, 0>(a, s);
}
extern "C" int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 1>(a, s);
}
// The same with q at R4DArgs::q_ld (O_QLD), for attn_paged_qrow; its own instances, so the dense
// ones above keep their registers.
extern "C" int r4d_attn_decode_h256_gqa2_qld_fp8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD, 0>(a, s);
extern "C" int r4d_attn_decode_h256_gqa2_qld_i8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, (B_OPT & ~O_KRAW) | O_KVI8 | O_QLD, 0>(a, s);
}
extern "C" int r4d_attn_decode_h256_gqa2_qld_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD, 1>(a, s);
}
// ...and a tree verify's mask (O_TREE, attn_paged_qrow_tree), again its own instances.
extern "C" int r4d_attn_decode_h256_gqa2_qld_tree_fp8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD | O_TREE, 0>(a, s);
extern "C" int r4d_attn_decode_h256_gqa2_qld_tree_i8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, (B_OPT & ~O_KRAW) | O_KVI8 | O_QLD | O_TREE,
0>(a, s);
}
extern "C" int r4d_attn_decode_h256_gqa2_qld_tree_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD | O_TREE, 1>(a, s);
@@ -81,7 +82,7 @@ extern "C" int r4d_attn_prefill_h256_gqa2_last_splits(void) { return g_prefill_l
// a->splits > 1 with a->scratch set and no window is the split form: segments in the scratch, then
// the merge. Anything else is the plain (windowed) form, unchanged.
template <int KVP>
template <int KVP, int XOPT = 0>
static int prefill_launch_h256_gqa2(const R4DArgs* a, hipStream_t s) {
if (a->head_dim != B_HEAD_DIM || a->block_size != B_BLOCK_SIZE) return -1;
if (a->q_heads / a->kv_heads != B_GQA) return -2;
@@ -92,7 +93,7 @@ static int prefill_launch_h256_gqa2(const R4DArgs* a, hipStream_t s) {
dim3 grid((a->q_len + BQ - 1) / BQ * splits, a->kv_heads, a->num_seqs);
if (splits > 1) {
hipLaunchKernelGGL((r4d_attn_prefill_kernel<P_NWARPS, P_TILE, B_HEAD_DIM, B_GQA,
B_BLOCK_SIZE, KVP, P_OPT | O_PSPLIT, 0>),
B_BLOCK_SIZE, KVP, P_OPT | XOPT | O_PSPLIT, 0>),
grid, dim3(P_NWARPS * 32), 0, s, *a);
CHK4();
// The full-attention legs' merge constants, as r4d_decode_launch_win takes them: two rows
@@ -100,7 +101,7 @@ static int prefill_launch_h256_gqa2(const R4DArgs* a, hipStream_t s) {
return r4d_prefill_combine<B_HEAD_DIM, 2, 256>(a, splits, P_TILE, s);
}
hipLaunchKernelGGL((r4d_attn_prefill_kernel<P_NWARPS, P_TILE, B_HEAD_DIM, B_GQA,
B_BLOCK_SIZE, KVP, P_OPT, 1>),
B_BLOCK_SIZE, KVP, P_OPT | XOPT, 1>),
grid, dim3(P_NWARPS * 32), 0, s, *a);
CHK4();
return 0;
@@ -109,29 +110,32 @@ static int prefill_launch_h256_gqa2(const R4DArgs* a, hipStream_t s) {
/* The split's f32 partials at declare (r4d_prefill_scratch). None for a windowed layer: `window`
* is the op's parameter, the same at declare and at every launch, and a windowed launch never
* splits. */
static int64_t prefill_scratch_h256_gqa2(const RadArgs* a) {
static int64_t prefill_scratch_h256_gqa2(const RadArgs* a, long long row) {
if (r4d_geti_or(a, "window", 0) > 0) return 0;
return r4d_prefill_scratch(a, B_HEAD_DIM, 2LL * B_HEAD_DIM, P_BQ, P_TILE);
return r4d_prefill_scratch(a, B_HEAD_DIM, row, P_BQ, P_TILE);
}
extern "C" int64_t r4d_rad_attn_prefill_h256_gqa2_scratch(const RadArgs* a) {
return prefill_scratch_h256_gqa2(a);
return prefill_scratch_h256_gqa2(a, 2LL * B_HEAD_DIM);
}
extern "C" int64_t r4d_rad_attn_prefill_h256_gqa2_i8_scratch(const RadArgs* a) {
return prefill_scratch_h256_gqa2(a, 2LL * B_HEAD_DIM + 4);
}
extern "C" int r4d_attn_prefill_h256_gqa2_fp8kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch_h256_gqa2<0>(a, s);
extern "C" int r4d_attn_prefill_h256_gqa2_i8kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch_h256_gqa2<0, O_KVI8>(a, s);
}
extern "C" int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch_h256_gqa2<1>(a, s);
}
/* Prefill RadArgs wrappers, defined in this unit rather than the h256 dispatch. Absent descales
* mean 1.0 (fill_paged leaves them null). */
extern "C" int r4d_rad_attn_prefill_h256_gqa2_fp8(const RadArgs* a, RadStream s) {
/* Prefill RadArgs wrappers, defined in this unit rather than the h256 dispatch; the int8 cache's
* token row is 2 * 256 + 4 bytes. */
extern "C" int r4d_rad_attn_prefill_h256_gqa2_i8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = fill_paged(a, &r, B_HEAD_DIM);
int rc = fill_paged_row(a, &r, B_HEAD_DIM, 2 * B_HEAD_DIM + 4);
if (rc != RAD_OK) return rc;
if (prefill_h256_gqa2_can_split(&r)) r.splits = r4d_prefill_splits(a, &r, P_BQ, P_TILE);
return r4d_attn_prefill_h256_gqa2_fp8kv(&r, (hipStream_t)s);
return r4d_attn_prefill_h256_gqa2_i8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_prefill_h256_gqa2_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
+75 -168
View File
@@ -2,12 +2,9 @@
// KV-dtype variants are template instantiations of one device code. The geometry is a hard gate:
// anything else is rejected.
//
// The query is bf16 in every exact variant. A single-term 8-bit query is ~10x less accurate
// against an fp32 reference (2.58e-02 vs ~2.3e-03 relative), and the two-term e4m3 form that
// reaches f16 accuracy is 4-10% slower end to end. Two families ship, differing in KV dtype: bf16
// and 8-bit (fp8, the production configuration, and the fp8_v4 and k6_v4 caches). Over the 8-bit
// caches the prefill also has lossy rows that run Q.K^T, P.V or both as e4m3 WMMA (O_QK8, O_PV8),
// taken only when the caller's `prefill_fp8` asks for them.
// The query is bf16 in every variant. A single-term 8-bit query is ~10x less accurate against an
// fp32 reference (2.58e-02 vs ~2.3e-03 relative). Two families ship, differing in KV dtype: bf16
// and the int8 cache (int8 K and V, an f16 scale each per token and head).
//
// `opt` is a bitmask of optimisation steps:
// prefill 3954187 | KLATE = f16 operands | mask skip | folded query scale | contiguous-k fragments
@@ -69,7 +66,7 @@ extern "C" int r4d_attn_prefill_h256_gqa6_last_splits(void) { return g_prefill_l
static int prefill_combine(const R4DArgs* a, int splits, hipStream_t s);
// KVP: 0 = an 8-bit cache (XOPT names fp8_v4 or k6_v4 and the e4m3 legs), 1 = bf16 cache.
// KVP: 0 = the int8 cache (XOPT carries its option bits), 1 = bf16 cache.
// a->splits > 1 with a->scratch set (the plugin entries below, prefill_splits) is the split form:
// segments in the scratch, then the merge. Anything else is the plain form, unchanged.
template <int KVP, int XOPT = 0>
@@ -77,9 +74,7 @@ static int prefill_launch(const R4DArgs* a, hipStream_t s) {
if (a->head_dim != A_HEAD_DIM || a->block_size != A_BLOCK_SIZE) return -1;
if (a->q_heads / a->kv_heads != A_GQA) return -2;
constexpr int BQ = (P_NWARPS * 16) / A_GQA;
// The split form serves the f16 operand legs; the lossy e4m3 legs (O_QK8, O_PV8 rows) stay unsplit
// rather than double their instances.
constexpr bool CAN_SPLIT = !(XOPT & (O_QK8 | O_PV8));
constexpr bool CAN_SPLIT = true;
const int splits = (CAN_SPLIT && a->scratch && a->splits > 1) ? a->splits : 1;
g_prefill_last_splits = splits;
dim3 grid((a->q_len + BQ - 1) / BQ * splits, a->kv_heads, a->num_seqs);
@@ -99,28 +94,12 @@ static int prefill_launch(const R4DArgs* a, hipStream_t s) {
return 0;
}
extern "C" int r4d_attn_prefill_h256_gqa6_fp8kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch<0>(a, s);
}
extern "C" int r4d_attn_prefill_h256_gqa6_bf16kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch<1>(a, s);
}
extern "C" int r4d_attn_prefill_h256_gqa6_fp8v4kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch<0, O_V4>(a, s);
extern "C" int r4d_attn_prefill_h256_gqa6_i8kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch<0, O_V4 | O_K6 | O_I8>(a, s);
}
extern "C" int r4d_attn_prefill_h256_gqa6_k6v4kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch<0, O_V4 | O_K6>(a, s);
}
// The e4m3 product legs over an 8-bit cache (XOPT 0 fp8, O_V4 fp8_v4, O_V4 | O_K6 k6_v4). `legs`
// is 1 Q.K^T, 2 P.V, 3 both. Lossy, so reached only through the rows a caller's attn_paged
// `prefill_fp8` selects.
template <int XOPT>
static int prefill_legs_launch(const R4DArgs* a, hipStream_t s, int legs) {
if (legs == 1) return prefill_launch<0, XOPT | O_QK8>(a, s);
if (legs == 2) return prefill_launch<0, XOPT | O_PV8>(a, s);
return prefill_launch<0, XOPT | O_QK8 | O_PV8>(a, s);
}
// ---- decode ----------------------------------------------------------------------------------
#define D_TILE 16
// Decode prefetches two K fragments per WMMA group, not four. Four costs 8 more VGPRs at the peak
@@ -155,50 +134,49 @@ static int decode_launch(const R4DArgs* a, hipStream_t s) {
const int nw = (rows + 15) / 16; // gqa-aligned height; no dead m-tiles issued
const int splits = r4d_decode_splits(a, D_TILE);
#define D_LAUNCH(NW) \
hipLaunchKernelGGL((r4d_attn_decode_kernel<NW, D_TILE, A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, \
KVP, D_OPT | XOPT>), \
/* `a->chain`: the chained forms (r4d_chain.h) of the attention kernel and of its merge. */
#define D_LAUNCH_K(K_, NW) \
hipLaunchKernelGGL((K_<NW, D_TILE, A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, KVP, D_OPT | XOPT>), \
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits)
#define D_LAUNCH(NW) \
do { if (a->chain) D_LAUNCH_K(r4dchain_attn_decode, NW); \
else D_LAUNCH_K(r4d_attn_decode_kernel, NW); } while (0)
if (nw == 1) D_LAUNCH(1);
else if (nw == 2) D_LAUNCH(2);
else if (nw == 3) D_LAUNCH(3);
else D_LAUNCH(4);
#undef D_LAUNCH
#undef D_LAUNCH_K
CHK();
// The vectorised merge's wave sum reproduces the general LDS tree only while splits <= 64.
// Above that (only when kv_heads * num_seqs is 1, giving 128 splits) use the general form.
// Both produce identical bytes; the choice is speed only.
const int jobs3 = r4d_q_total(*a) * a->q_heads;
constexpr int PF16 = (D_OPT & 32) ? 1 : 0;
if (splits <= 64 && jobs3 >= D_VECMIN) {
const int blocks = (jobs3 + D_JPB - 1) / D_JPB;
if (D_OPT & 32)
hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel<A_HEAD_DIM, 4, 1, D_JPB>),
if (a->chain)
hipLaunchKernelGGL((r4dchain_attn_splitkv_combine_vec<A_HEAD_DIM, 4, PF16, D_JPB>),
dim3(blocks), dim3(32 * D_JPB), 0, s, *a, splits, D_TILE);
else
hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel<A_HEAD_DIM, 4, 0, D_JPB>),
hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel<A_HEAD_DIM, 4, PF16, D_JPB>),
dim3(blocks), dim3(32 * D_JPB), 0, s, *a, splits, D_TILE);
} else if (D_OPT & 32)
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<A_HEAD_DIM, 4, 1>), dim3(jobs3),
} else if (a->chain)
hipLaunchKernelGGL((r4dchain_attn_splitkv_combine<A_HEAD_DIM, 4, PF16>), dim3(jobs3),
dim3(256), splits * sizeof(float), s, *a, splits, D_TILE);
else
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<A_HEAD_DIM, 4, 0>), dim3(jobs3),
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<A_HEAD_DIM, 4, PF16>), dim3(jobs3),
dim3(256), splits * sizeof(float), s, *a, splits, D_TILE);
CHK();
return 0;
}
extern "C" int r4d_attn_decode_h256_gqa6_fp8kv(const R4DArgs* a, hipStream_t s) {
return decode_launch<0>(a, s);
}
extern "C" int r4d_attn_decode_h256_gqa6_bf16kv(const R4DArgs* a, hipStream_t s) {
return decode_launch<1>(a, s);
}
extern "C" int r4d_attn_decode_h256_gqa6_fp8v4kv(const R4DArgs* a, hipStream_t s) {
return decode_launch<0, O_V4>(a, s);
}
extern "C" int r4d_attn_decode_h256_gqa6_k6v4kv(const R4DArgs* a, hipStream_t s) {
return decode_launch<0, O_V4 | O_K6>(a, s);
extern "C" int r4d_attn_decode_h256_gqa6_i8kv(const R4DArgs* a, hipStream_t s) {
return decode_launch<0, O_V4 | O_K6 | O_I8>(a, s);
}
// ============================================================== the plugin ABI entry points
@@ -216,71 +194,16 @@ static int prefill_splits(const RadArgs* a, const R4DArgs* r) {
}
/* The split's f32 partials at declare (r4d_prefill_scratch: 23.8 MB is reached at this geometry,
* at 384 rows x 5 and 640 x 3), by the cache's token row: fp8 and bf16 (2 * head_dim), fp8_v4 (400
* bytes), k6_v4 (352). */
* at 384 rows x 5 and 640 x 3), by the cache's token row: bf16 (2 * head_dim elements) or int8
* (2 * head_dim + 4 bytes). */
static int64_t prefill_scratch(const RadArgs* a, long long row) {
return r4d_prefill_scratch(a, A_HEAD_DIM, row, P_BQ, P_TILE);
}
extern "C" int64_t r4d_rad_attn_prefill_h256_scratch(const RadArgs* a) {
return prefill_scratch(a, 512);
}
extern "C" int64_t r4d_rad_attn_prefill_h256_v4_scratch(const RadArgs* a) {
return prefill_scratch(a, 400);
}
extern "C" int64_t r4d_rad_attn_prefill_h256_k6_scratch(const RadArgs* a) {
return prefill_scratch(a, 352);
}
extern "C" int r4d_rad_attn_prefill_h256_fp8(const RadArgs* a, RadStream s) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
int rc = fill_paged(a, &r, 256);
if (rc != RAD_OK) return rc;
r.splits = prefill_splits(a, &r);
/* Absent descales mean 1.0, not an error: the kernels read them that way, vLLM defaults both
* scales to 1.0, and kv_store_fp8 at its default scale needs no descale plane. The operands
* are optional in the schema and the kernel, so they are optional here too. A calibrated pair
* is used when passed. */
return r4d_attn_prefill_h256_gqa6_fp8kv(&r, (hipStream_t)s);
}
/* The 8-bit caches with e4m3 products. `legs` is the row's `prefill_fp8`, which its constraint has
* matched: 1 Q.K^T, 2 P.V, 3 both. `row` is a token's bytes in a (block, head) page: 512 for fp8,
* 400 for fp8_v4, 352 for k6_v4. */
template <int XOPT>
static int prefill_h256_legs(const RadArgs* a, RadStream s, long long row, int legs) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
int rc = fill_paged_row(a, &r, 256, row);
if (rc != RAD_OK) return rc;
return prefill_legs_launch<XOPT>(&r, (hipStream_t)s, legs);
}
extern "C" int r4d_rad_attn_prefill_h256_fp8_qk8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<0>(a, s, 512, 1);
}
extern "C" int r4d_rad_attn_prefill_h256_fp8_pv8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<0>(a, s, 512, 2);
}
extern "C" int r4d_rad_attn_prefill_h256_fp8_qk8pv8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<0>(a, s, 512, 3);
}
extern "C" int r4d_rad_attn_prefill_h256_fp8v4_qk8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<O_V4>(a, s, 400, 1);
}
extern "C" int r4d_rad_attn_prefill_h256_fp8v4_pv8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<O_V4>(a, s, 400, 2);
}
extern "C" int r4d_rad_attn_prefill_h256_fp8v4_qk8pv8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<O_V4>(a, s, 400, 3);
}
extern "C" int r4d_rad_attn_prefill_h256_k6v4_qk8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<O_V4 | O_K6>(a, s, 352, 1);
}
extern "C" int r4d_rad_attn_prefill_h256_k6v4_pv8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<O_V4 | O_K6>(a, s, 352, 2);
}
extern "C" int r4d_rad_attn_prefill_h256_k6v4_qk8pv8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<O_V4 | O_K6>(a, s, 352, 3);
extern "C" int64_t r4d_rad_attn_prefill_h256_i8_scratch(const RadArgs* a) {
return prefill_scratch(a, 516);
}
extern "C" int r4d_rad_attn_prefill_h256_bf16(const RadArgs* a, RadStream s) {
@@ -387,57 +310,26 @@ static int decode_common(const RadArgs* a, R4DArgs* r, int head_dim, int which,
return RAD_OK;
}
extern "C" int r4d_rad_attn_decode_h256_fp8(const RadArgs* a, RadStream s) {
/* The i8 cache: a token's row is 2 * 256 + 4 = 516 bytes (int8 K and V, an f16 scale each). */
extern "C" int r4d_rad_attn_prefill_h256_i8(const RadArgs* a, RadStream s) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
int rc = decode_common(a, &r, 256, 0);
if (rc != RAD_OK) return rc;
/* Absent descales mean 1.0; see the prefill twin above. */
return r4d_attn_decode_h256_gqa6_fp8kv(&r, (hipStream_t)s);
}
/* The fp8_v4 cache: a token's row is 25 * 256 / 16 = 400 bytes (E4M3 K, int4 V, f16 scales). */
extern "C" int r4d_rad_attn_prefill_h256_fp8v4(const RadArgs* a, RadStream s) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
int rc = fill_paged_row(a, &r, 256, 400);
int rc = fill_paged_row(a, &r, 256, 516);
if (rc != RAD_OK) return rc;
r.splits = prefill_splits(a, &r);
return r4d_attn_prefill_h256_gqa6_fp8v4kv(&r, (hipStream_t)s);
return r4d_attn_prefill_h256_gqa6_i8kv(&r, (hipStream_t)s);
}
extern "C" int64_t r4d_rad_attn_decode_h256_v4_scratch(const RadArgs* a) {
return decode_scratch(a, 256, 0, 400);
extern "C" int64_t r4d_rad_attn_decode_h256_i8_scratch(const RadArgs* a) {
return decode_scratch(a, 256, 0, 516);
}
extern "C" int r4d_rad_attn_decode_h256_fp8v4(const RadArgs* a, RadStream s) {
extern "C" int r4d_rad_attn_decode_h256_i8(const RadArgs* a, RadStream s) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
int rc = decode_common(a, &r, 256, 0, 400);
int rc = decode_common(a, &r, 256, 0, 516);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa6_fp8v4kv(&r, (hipStream_t)s);
}
/* The k6_v4 cache: a token's row is 22 * 256 / 16 = 352 bytes (int6 K, int4 V, f16 scales). */
extern "C" int r4d_rad_attn_prefill_h256_k6v4(const RadArgs* a, RadStream s) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
int rc = fill_paged_row(a, &r, 256, 352);
if (rc != RAD_OK) return rc;
r.splits = prefill_splits(a, &r);
return r4d_attn_prefill_h256_gqa6_k6v4kv(&r, (hipStream_t)s);
}
extern "C" int64_t r4d_rad_attn_decode_h256_k6_scratch(const RadArgs* a) {
return decode_scratch(a, 256, 0, 352);
}
extern "C" int r4d_rad_attn_decode_h256_k6v4(const RadArgs* a, RadStream s) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
int rc = decode_common(a, &r, 256, 0, 352);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa6_k6v4kv(&r, (hipStream_t)s);
return r4d_attn_decode_h256_gqa6_i8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_decode_h256_bf16(const RadArgs* a, RadStream s) {
@@ -448,14 +340,6 @@ extern "C" int r4d_rad_attn_decode_h256_bf16(const RadArgs* a, RadStream s) {
return r4d_attn_decode_h256_gqa6_bf16kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_decode_h128_fp8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 128, 1);
if (rc != RAD_OK) return rc;
/* Absent descales mean 1.0; see the prefill twin above. */
return r4d_attn_decode_h128_gqa4_fp8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_decode_h128_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 128, 1);
@@ -463,6 +347,18 @@ extern "C" int r4d_rad_attn_decode_h128_bf16(const RadArgs* a, RadStream s) {
return r4d_attn_decode_h128_gqa4_bf16kv(&r, (hipStream_t)s);
}
/* The i8 cache at this geometry: a token's row is 2 * 128 + 4 = 260 bytes. */
extern "C" int64_t r4d_rad_attn_decode_h128_i8_scratch(const RadArgs* a) {
return decode_scratch(a, 128, 1, 260);
}
extern "C" int r4d_rad_attn_decode_h128_i8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 128, 1, 260);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h128_gqa4_i8kv(&r, (hipStream_t)s);
}
/* Gemma 4 dense sliding window (head_dim 256, gqa 2, window 1024) decode; its prefill entry points
* are in r4d_attn_paged_h256_gqa2.hip. No check_dims_once: this is not the geometry that reports
* dims. */
@@ -470,12 +366,14 @@ extern "C" int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs* a) {
return decode_scratch(a, 256, 2);
}
extern "C" int r4d_rad_attn_decode_h256_gqa2_fp8(const RadArgs* a, RadStream s) {
extern "C" int64_t r4d_rad_attn_decode_h256_gqa2_i8_scratch(const RadArgs* a) {
return decode_scratch(a, 256, 2, 516);
}
extern "C" int r4d_rad_attn_decode_h256_gqa2_i8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 256, 2);
int rc = decode_common(a, &r, 256, 2, 516);
if (rc != RAD_OK) return rc;
/* Absent descales mean 1.0; see the prefill twin above. */
return r4d_attn_decode_h256_gqa2_fp8kv(&r, (hipStream_t)s);
return r4d_attn_decode_h256_gqa2_i8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) {
@@ -491,11 +389,14 @@ extern "C" int64_t r4d_rad_attn_decode_h128_gqa2w_scratch(const RadArgs* a) {
return decode_scratch(a, 128, 3);
}
extern "C" int r4d_rad_attn_decode_h128_gqa2w_fp8(const RadArgs* a, RadStream s) {
extern "C" int64_t r4d_rad_attn_decode_h128_gqa2w_i8_scratch(const RadArgs* a) {
return decode_scratch(a, 128, 3, 260);
}
extern "C" int r4d_rad_attn_decode_h128_gqa2w_i8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 128, 3);
int rc = decode_common(a, &r, 128, 3, 260);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h128_gqa2w_fp8kv(&r, (hipStream_t)s);
return r4d_attn_decode_h128_gqa2w_i8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_decode_h128_gqa2w_bf16(const RadArgs* a, RadStream s) {
@@ -510,11 +411,14 @@ extern "C" int r4d_rad_attn_decode_h128_gqa2w_bf16(const RadArgs* a, RadStream s
extern "C" int64_t r4d_rad_attn_qrow_decode_h256_gqa2_scratch(const RadArgs* a) {
return decode_scratch(a, 256, 2, 0, 1, true);
}
extern "C" int r4d_rad_attn_qrow_decode_h256_gqa2_fp8(const RadArgs* a, RadStream s) {
extern "C" int64_t r4d_rad_attn_qrow_decode_h256_gqa2_i8_scratch(const RadArgs* a) {
return decode_scratch(a, 256, 2, 516, 1, true);
}
extern "C" int r4d_rad_attn_qrow_decode_h256_gqa2_i8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 256, 2, 0, 1, true);
int rc = decode_common(a, &r, 256, 2, 516, 1, true);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa2_qld_fp8kv(&r, (hipStream_t)s);
return r4d_attn_decode_h256_gqa2_qld_i8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_qrow_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
@@ -534,12 +438,12 @@ static int tree_operand(const RadArgs* a, R4DArgs* r) {
r->spec_parent = (const int*)tp->data;
return RAD_OK;
}
extern "C" int r4d_rad_attn_qrow_tree_decode_h256_gqa2_fp8(const RadArgs* a, RadStream s) {
extern "C" int r4d_rad_attn_qrow_tree_decode_h256_gqa2_i8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 256, 2, 0, 1, true);
int rc = decode_common(a, &r, 256, 2, 516, 1, true);
if (rc == RAD_OK) rc = tree_operand(a, &r);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa2_qld_tree_fp8kv(&r, (hipStream_t)s);
return r4d_attn_decode_h256_gqa2_qld_tree_i8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_qrow_tree_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
@@ -557,11 +461,14 @@ extern "C" int r4d_rad_attn_qrow_tree_decode_h256_gqa2_bf16(const RadArgs* a, Ra
extern "C" int64_t r4d_rad_attn_qrow_h128_gqa8_scratch(const RadArgs* a) {
return decode_scratch(a, 128, 1, 0, 2, true);
}
extern "C" int r4d_rad_attn_qrow_h128_gqa8_fp8(const RadArgs* a, RadStream s) {
extern "C" int64_t r4d_rad_attn_qrow_h128_gqa8_i8_scratch(const RadArgs* a) {
return decode_scratch(a, 128, 1, 260, 2, true);
}
extern "C" int r4d_rad_attn_qrow_h128_gqa8_i8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 128, 1, 0, 2, true);
int rc = decode_common(a, &r, 128, 1, 260, 2, true);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h128_gqa4_rep_fp8kv(&r, (hipStream_t)s);
return r4d_attn_decode_h128_gqa4_rep_i8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_qrow_h128_gqa8_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
-2
View File
@@ -19,7 +19,5 @@
// the pages at 4 (RadKVGroupDecl takes the block size from the resolved kernel). A row saying 16
// here would refuse at issue rather than at declare.
#define G8_BLOCK_SIZE 4
// The fp8_v4 and k6_v4 caches (--kv-cache-dtype), which qwen4exp_fp8 offers for these layers.
#define R4D_ATTN_V4 1
#include "r4d_attn_paged_gqa8.hip"
+119 -51
View File
@@ -1,5 +1,5 @@
/* r4d_attn_paged_window.hip -- paged attention at head_dim 128, 256 and 512, 1/2/4/8 queries per
* KV head (16 at 512), any sliding window, causal or not, bf16 or fp8-e4m3 cache, q at any row
* KV head (16 at 512), any sliding window, causal or not, bf16 or int8 cache, q at any row
* pitch.
*
* head_dim 128 is Unlimited-OCR's decoder (10 query heads over 10 KV heads): the plain MHA case,
@@ -35,7 +35,9 @@
*
* Paged layout: kv_cache[n_blocks, kv_heads, 16, 2*head_dim], K then V per slot, so one block of
* one KV head is a contiguous run of 16 * 2 * head_dim elements; a key tile is one or two runs,
* fetched as 16-byte loads.
* fetched as 16-byte loads. The int8 cache (KV8 2, --kv-cache-dtype i8) appends four bytes to a
* slot, the token's f16 scales of K and of V (kv_store_i8): a key's score is its integer codes'
* dot times its K scale, and its row of V enters the sum at its probability times its V scale.
*
* Split-KV: with few (tile, kv head) pairs (decode, short verify) each tile's key range is cut into
* `n_split` pieces, each writing an unnormalised partial (acc, max, sum) to scratch, merged by a
@@ -160,10 +162,28 @@ __device__ __forceinline__ unsigned bf16_rtne(float f) {
}
__device__ __forceinline__ unsigned pack2(float a, float b) { return bf16_rtne(a) | (bf16_rtne(b) << 16); }
/* Four int8 codes as their values. */
__device__ __forceinline__ void i8x4(unsigned w, float (&f)[4]) {
f[0] = (float)(signed char)(w & 0xffu);
f[1] = (float)(signed char)((w >> 8) & 0xffu);
f[2] = (float)(signed char)((w >> 16) & 0xffu);
f[3] = (float)(signed char)(w >> 24);
}
/* Four bytes of an 8-bit cache: E4M3 (KV8 1) or int8 codes (KV8 2). */
template <int KV8>
__device__ __forceinline__ void kv8x4(unsigned w, float (&f)[4]) {
if constexpr (KV8 == 2) i8x4(w, f);
else fp8x4(w, f);
}
/* An f16 at `p` as a float: one of the int8 cache's scales. */
__device__ __forceinline__ float f16_at(const unsigned char* p) {
return (float)__builtin_bit_cast(_Float16, *(const unsigned short*)p);
}
/* Four elements of one slot row, at element offset `e`, out of the LDS tile. */
template <bool KV8>
template <int KV8>
__device__ __forceinline__ void lds4(const unsigned char* row, int e, float (&f)[4]) {
if constexpr (KV8) fp8x4(*(const unsigned*)(row + e), f);
if constexpr (KV8) kv8x4<KV8>(*(const unsigned*)(row + e), f);
else bf16x4(*(const uint2*)(row + 2 * e), f);
}
@@ -254,21 +274,25 @@ __device__ void find_tile(const int* cu, int n_seq, int tile, int* s_scan, int*
/* ------------------------------------------------------------------ the attention kernel */
/* The body; attn_kernel and its chained form r4dchain_attn_window (r4d_chain.h) wrap it below,
* since its blocks return early. */
template <int HD, int GQA, bool KV8, bool TREE = false>
template <int HD, int GQA, int KV8, bool TREE = false>
__device__ __forceinline__ void attn_body(AttnArgs A) {
constexpr int R = Geo<HD>::R, BK = Geo<HD>::BK, RW = R / kWaves, BQ = R / GQA;
constexpr int NC = HD / 128; /* 4-element chunks a lane holds of a row */
constexpr int ESZ = KV8 ? 1 : 2;
constexpr int KEY_BYTES = 2 * HD * ESZ; /* one slot: K then V */
constexpr int TAIL = KV8 == 2 ? 4 : 0; /* the int8 cache's two f16 scales */
constexpr int KEY_BYTES = 2 * HD * ESZ + TAIL; /* one slot: K then V (then the scales) */
constexpr int TILE_U4 = BK * KEY_BYTES / 16;
constexpr int NPT = TILE_U4 / kThreads; /* 16-byte loads a thread, per tile */
/* 16-byte loads a thread, per tile. With the scales a tile is not whole threads: the last
* round is short, and a block's loads are found by division. */
constexpr int NPT = (TILE_U4 + kThreads - 1) / kThreads;
constexpr int BLK_U4 = 16 * KEY_BYTES / 16; /* one paged block of one kv head */
constexpr int NB = BK / 16; /* paged blocks a key tile spans */
static_assert(R % kWaves == 0 && R % GQA == 0, "rows must split over waves and heads");
static_assert(TILE_U4 % kThreads == 0 && BLK_U4 % kThreads == 0, "tile must split over threads");
static_assert(TAIL != 0 || (TILE_U4 % kThreads == 0 && BLK_U4 % kThreads == 0),
"tile must split over threads");
static_assert(BK == 32 || BK == 16, "the reduce-scatter is written for 16 or 32 keys");
__shared__ uint4 s_kv[TILE_U4];
__shared__ uint4 s_kv[NPT * kThreads];
__shared__ int s_scan[kWaves];
__shared__ int s_res[2];
@@ -399,10 +423,18 @@ __device__ __forceinline__ void attn_body(AttnArgs A) {
}
#pragma unroll
for (int i = 0; i < NPT; ++i) {
const int b = (i * kThreads) / BLK_U4; /* constant: BLK_U4 is a multiple of 256 */
const int off = tid + i * kThreads - b * BLK_U4;
if (pre_ok[b]) pre[i] = ((const uint4*)src[b])[off];
else pre[i] = make_uint4(0u, 0u, 0u, 0u);
if constexpr (TAIL) {
const int gi = tid + i * kThreads;
const int b = gi >= BLK_U4 ? NB - 1 : 0;
const int off = gi - b * BLK_U4;
pre[i] = make_uint4(0u, 0u, 0u, 0u);
if (gi < TILE_U4 && pre_ok[b]) pre[i] = ((const uint4*)src[b])[off];
} else {
const int b = (i * kThreads) / BLK_U4; /* constant: BLK_U4 is a multiple of 256 */
const int off = tid + i * kThreads - b * BLK_U4;
if (pre_ok[b]) pre[i] = ((const uint4*)src[b])[off];
else pre[i] = make_uint4(0u, 0u, 0u, 0u);
}
}
};
@@ -436,6 +468,7 @@ __device__ __forceinline__ void attn_body(AttnArgs A) {
#pragma unroll
for (int e = 0; e < 4; ++e) acc = __builtin_fmaf(qf[i][c][e], k[e], acc);
}
if constexpr (KV8 == 2) acc *= f16_at(row + 2 * HD);
sc[j] = acc;
}
if constexpr (BK == 32) {
@@ -469,12 +502,13 @@ __device__ __forceinline__ void attn_body(AttnArgs A) {
const float pj = readlane(p, j); /* uniform; a masked key's V is never read */
if (pj != 0.0f) {
const unsigned char* row = sb + j * KEY_BYTES;
const float pv = KV8 == 2 ? pj * f16_at(row + 2 * HD + 2) : pj;
#pragma unroll
for (int c = 0; c < NC; ++c) {
float v[4];
lds4<KV8>(row, HD + c * 128 + lane * 4, v);
#pragma unroll
for (int e = 0; e < 4; ++e) o[i][c][e] = __builtin_fmaf(pj, v[e], o[i][c][e]);
for (int e = 0; e < 4; ++e) o[i][c][e] = __builtin_fmaf(pv, v[e], o[i][c][e]);
}
}
}
@@ -601,24 +635,28 @@ __device__ __forceinline__ void bf16x8_f16(const uint4 w, unsigned (&h)[8]) {
h[2 * q + 1] = f16_bits(__uint_as_float(in[q] & 0xffff0000u));
}
}
/* fp8 e4m3 -> bf16 bits (the K tile), exact: the f32 a byte widens to has nothing below bit 16 */
__device__ __forceinline__ void fp8x16_bf16(const uint4 w, unsigned (&h)[16]) {
/* fp8 e4m3 or int8 -> bf16 bits (the K tile), exact: the f32 a byte widens to has nothing below
* bit 16 */
template <int KV8>
__device__ __forceinline__ void kv8x16_bf16(const uint4 w, unsigned (&h)[16]) {
const unsigned in[4] = {w.x, w.y, w.z, w.w};
#pragma unroll
for (int q = 0; q < 4; ++q) {
float f[4];
fp8x4(in[q], f);
kv8x4<KV8>(in[q], f);
#pragma unroll
for (int e = 0; e < 4; ++e) h[q * 4 + e] = __float_as_uint(f[e]) >> 16;
}
}
template <int HD, int GQA, bool KV8>
template <int HD, int GQA, int KV8>
__global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
using G = WGeo<HD>;
constexpr int NS = G::NS, R = G::R, BQ = R / GQA, KS = G::KS, VS = G::VS;
constexpr int ESZ = KV8 ? 1 : 2;
constexpr int SLOT = 2 * HD * ESZ; /* bytes of one key's slot: K then V */
/* bytes of one key's slot: K then V, and at KV8 2 the token's two f16 scales, which make a
* slot's 16-byte loads start on a 4-byte boundary */
constexpr int SLOT = 2 * HD * ESZ + (KV8 == 2 ? 4 : 0);
constexpr int CW = 16 / ESZ; /* cache elements one 16-byte load carries */
constexpr int NCH = HD / CW; /* such chunks a head */
constexpr int NKI = 16 * NCH; /* K items a tile: (key, chunk) */
@@ -631,6 +669,7 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
__shared__ uint4 s_k[16 * KS / 16];
__shared__ uint4 s_vt[HD * VS / 16];
__shared__ float4 s_x[kWWaves * 32 * 2];
__shared__ unsigned s_sc[KV8 == 2 ? 16 : 1]; /* a key's scales: K's f16 low, V's high */
__shared__ int s_scan[kWWaves];
__shared__ int s_res[2];
@@ -697,6 +736,7 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
/* ---- the key tiles, one paged block each, prefetched one ahead through registers */
uint4 pk[KPT], pv[VPT][2];
unsigned psc = 0u;
bool pre_ok = false;
auto fetch = [&](int kt) __attribute__((always_inline)) {
const int k0 = lo_a + kt * 16, lb = k0 >> 4;
@@ -715,6 +755,10 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
pk[j] = *(const uint4*)(base + key * SLOT + ch * 16);
}
}
if constexpr (KV8 == 2) {
psc = 0u;
if (pre_ok && tid < 16) psc = *(const unsigned*)(base + tid * SLOT + 2 * HD);
}
#pragma unroll
for (int j = 0; j < VPT; ++j) {
const int idx = tid + j * kWThreads;
@@ -747,7 +791,7 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
const uint4 w = keep ? pk[j] : make_uint4(0u, 0u, 0u, 0u);
if constexpr (KV8) {
unsigned hb[16];
fp8x16_bf16(w, hb);
kv8x16_bf16<KV8>(w, hb);
uint4* dst = (uint4*)(kb + key * KS + ch * 32);
dst[0] = make_uint4(hb[0] | hb[1] << 16, hb[2] | hb[3] << 16, hb[4] | hb[5] << 16, hb[6] | hb[7] << 16);
dst[1] = make_uint4(hb[8] | hb[9] << 16, hb[10] | hb[11] << 16, hb[12] | hb[13] << 16, hb[14] | hb[15] << 16);
@@ -756,6 +800,9 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
}
}
}
if constexpr (KV8 == 2) {
if (tid < 16) s_sc[tid] = psc;
}
/* ---- V: [dim][key] as f16, two keys a dword; the row order rotated by 2 per 8-lane
* group, so the four groups of a wave write four different rows mod 8 -- 32 banks */
#pragma unroll
@@ -768,14 +815,15 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
const uint4 wb = (tok && kb1 >= lo && kb1 < hi) ? pv[j][1] : make_uint4(0u, 0u, 0u, 0u);
unsigned d[CW]; /* f16 pairs: key 2kp low, 2kp + 1 high */
if constexpr (KV8) {
/* every e4m3 value is exact in f16 (|v| <= 448, subnormals 2^-9 up), so the
* pack's round-toward-zero and f16_bits' clamp leave the same bits */
/* every e4m3 value is exact in f16 (|v| <= 448, subnormals 2^-9 up), and so
* is an int8 code, so the pack's round-toward-zero and f16_bits' clamp leave
* the same bits */
const unsigned ia[4] = {wa.x, wa.y, wa.z, wa.w}, ib[4] = {wb.x, wb.y, wb.z, wb.w};
#pragma unroll
for (int q = 0; q < 4; ++q) {
float fa[4], fb[4];
fp8x4(ia[q], fa);
fp8x4(ib[q], fb);
kv8x4<KV8>(ia[q], fa);
kv8x4<KV8>(ib[q], fb);
#pragma unroll
for (int e = 0; e < 4; ++e) d[q * 4 + e] = f16x2_exact(fa[e], fb[e]);
}
@@ -835,6 +883,12 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
for (int e = 0; e < 8; ++e) tot[e] = j == 0 ? v[e] : tot[e] + v[e];
}
/* The int8 cache: a key's dot is over its codes, times its K scale. */
if constexpr (KV8 == 2) {
#pragma unroll
for (int e = 0; e < 8; ++e)
tot[e] *= (float)__builtin_bit_cast(_Float16, (unsigned short)(s_sc[8 * h + e] & 0xffffu));
}
/* ---- online softmax, row n: eight keys here, eight in lane ^ 16 */
float sv[8], mx = -__builtin_inff();
/* A tile wholly inside [lo, hi) and, causal, at or before the block's first position
@@ -872,6 +926,16 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
}
l = l * corr + ps;
m = mn;
/* The int8 cache: a key's row of V codes enters at its probability times its V scale. */
if constexpr (KV8 == 2) {
#pragma unroll
for (int e = 0; e < 8; ++e) {
/* a masked key's scale is whatever its slot holds: its zero stays zero */
const float pe = (float)pf[e];
const float vs = (float)__builtin_bit_cast(_Float16, (unsigned short)(s_sc[8 * h + e] >> 16));
pf[e] = pe != 0.0f ? (_Float16)(pe * vs) : (_Float16)0.0f;
}
}
/* ---- O^T += V^T * P^T in f16: A = V^T rows (dim n of the chunk), keys 8h .. 8h + 7 */
const unsigned char* va = vb + (sl * kDQ + n) * VS + h * 16;
@@ -1054,11 +1118,11 @@ static constexpr int64_t scratch_need() {
/* The plain kernels and their chained forms (r4dchain*, RadKernelChainFn): the chained ones wait
* for the kernels before them on the queue in their prologue and count themselves in at the end. */
template <int HD, int GQA, bool KV8, bool TREE = false>
template <int HD, int GQA, int KV8, bool TREE = false>
__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) {
attn_body<HD, GQA, KV8, TREE>(A);
}
template <int HD, int GQA, bool KV8, bool TREE = false>
template <int HD, int GQA, int KV8, bool TREE = false>
__global__ __launch_bounds__(kThreads) void r4dchain_attn_window(AttnArgs A) {
r4d_chain_wait();
attn_body<HD, GQA, KV8, TREE>(A);
@@ -1073,9 +1137,12 @@ __global__ __launch_bounds__(kThreads) void r4dchain_merge_window(AttnArgs A) {
r4d_chain_done();
}
template <int HD, int GQA, bool KV8, bool TREE = false, bool SHARED = false, bool FWD = false>
template <int HD, int GQA, int KV8, bool TREE = false, bool SHARED = false, bool FWD = false>
static int launch_attn(const RadArgs* a, RadStream stream, bool sink = false) {
constexpr int R = Geo<HD>::R, BK = Geo<HD>::BK, BQ = R / GQA, ESZ = KV8 ? 1 : 2;
/* A slot's elements: K then V, and for the int8 cache its four bytes of scales
* (abi/rad_builder.h, rad_kv_row_elems). */
constexpr int SLOT_E = 2 * HD + (KV8 == 2 ? 4 : 0);
if (!a || a->n_t < (TREE || sink ? 9 : 8)) return RAD_E_INVAL;
/* attn_paged_sink keeps its output where the tree operand would be: never both. */
if (TREE && sink) return RAD_E_INVAL;
@@ -1106,14 +1173,14 @@ static int launch_attn(const RadArgs* a, RadStream stream, bool sink = false) {
if (FWD && (causal != 0 || window == 0)) return RAD_E_SHAPE;
if (q->dtype != RAD_BF16 || o->dtype != RAD_BF16) return RAD_E_DTYPE;
if (kv->dtype != (uint32_t)(KV8 ? RAD_F8E4M3 : RAD_BF16)) return RAD_E_DTYPE;
if (kv->dtype != (uint32_t)(KV8 ? RAD_I8 : RAD_BF16)) return RAD_E_DTYPE;
if (bt->dtype != RAD_I32 || su->dtype != RAD_I32 || (cu && cu->dtype != RAD_I32)) return RAD_E_DTYPE;
if ((kd && kd->dtype != RAD_F32) || (vd && vd->dtype != RAD_F32)) return RAD_E_DTYPE;
if (sk && sk->dtype != RAD_F32) return RAD_E_DTYPE;
/* the cache: [n_blocks, kv_heads, 16, 2 * head_dim], slots dense */
if (kv->rank != 4 || kv->shape[2] != 16 || kv->shape[3] != 2 * HD) return RAD_E_SHAPE;
if (kv->stride[3] != 1 || kv->stride[2] != 2 * HD) return RAD_E_STRIDE;
/* the cache: [n_blocks, kv_heads, 16, 2 * head_dim (+ 4)], slots dense */
if (kv->rank != 4 || kv->shape[2] != 16 || kv->shape[3] != SLOT_E) return RAD_E_SHAPE;
if (kv->stride[3] != 1 || kv->stride[2] != SLOT_E) return RAD_E_STRIDE;
const int64_t kvh = kv->shape[1];
if (kvh <= 0 || kvh > 65535) return RAD_E_SHAPE;
const int64_t qh = kvh * GQA;
@@ -1290,12 +1357,13 @@ static int launch_attn(const RadArgs* a, RadStream stream, bool sink = false) {
/* ------------------------------------------------------------------ the exported entry points */
extern "C" {
/* Each geometry at the bf16 cache and at the int8 one (kv_store_i8's layout, KV8 2). */
#define R4D_WIN_DEF(HD, G) \
int r4d_rad_attn_window_h##HD##_gqa##G##_bf16(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, false>(a, s); \
} \
int r4d_rad_attn_window_h##HD##_gqa##G##_fp8(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, true>(a, s); \
int r4d_rad_attn_window_h##HD##_gqa##G##_bf16(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, 0>(a, s); \
} \
int r4d_rad_attn_window_h##HD##_gqa##G##_i8(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, 2>(a, s); \
}
R4D_WIN_DEF(128, 1)
R4D_WIN_DEF(256, 1) R4D_WIN_DEF(256, 2) R4D_WIN_DEF(256, 4) R4D_WIN_DEF(256, 8)
@@ -1306,10 +1374,10 @@ R4D_WIN_DEF(512, 1) R4D_WIN_DEF(512, 2) R4D_WIN_DEF(512, 4) R4D_WIN_DEF(512, 8)
* (FWD), the sliding layers' mask over a picture's rows (docs/OPS.md). */
#define R4D_WIN_AHEAD_DEF(HD, G) \
int r4d_rad_attn_window_ahead_h##HD##_gqa##G##_bf16(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, false, false, false, true>(a, s); \
} \
int r4d_rad_attn_window_ahead_h##HD##_gqa##G##_fp8(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, true, false, false, true>(a, s); \
return r4d_win::launch_attn<HD, G, 0, false, false, true>(a, s); \
} \
int r4d_rad_attn_window_ahead_h##HD##_gqa##G##_i8(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, 2, false, false, true>(a, s); \
}
R4D_WIN_AHEAD_DEF(256, 1) R4D_WIN_AHEAD_DEF(256, 2) R4D_WIN_AHEAD_DEF(256, 4) R4D_WIN_AHEAD_DEF(256, 8)
#undef R4D_WIN_AHEAD_DEF
@@ -1317,10 +1385,10 @@ R4D_WIN_AHEAD_DEF(256, 1) R4D_WIN_AHEAD_DEF(256, 2) R4D_WIN_AHEAD_DEF(256, 4) R4
/* attn_paged_qrow_tree: the scalar kernel with a tree verify's mask (TREE). */
#define R4D_WIN_TREE_DEF(HD, G) \
int r4d_rad_attn_window_tree_h##HD##_gqa##G##_bf16(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, false, true>(a, s); \
} \
int r4d_rad_attn_window_tree_h##HD##_gqa##G##_fp8(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, true, true>(a, s); \
return r4d_win::launch_attn<HD, G, 0, true>(a, s); \
} \
int r4d_rad_attn_window_tree_h##HD##_gqa##G##_i8(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, 2, true>(a, s); \
}
R4D_WIN_TREE_DEF(256, 1) R4D_WIN_TREE_DEF(256, 2) R4D_WIN_TREE_DEF(256, 4) R4D_WIN_TREE_DEF(256, 8)
R4D_WIN_TREE_DEF(512, 1) R4D_WIN_TREE_DEF(512, 2) R4D_WIN_TREE_DEF(512, 4) R4D_WIN_TREE_DEF(512, 8)
@@ -1330,10 +1398,10 @@ R4D_WIN_TREE_DEF(512, 1) R4D_WIN_TREE_DEF(512, 2) R4D_WIN_TREE_DEF(512, 4) R4D_W
* This is a distinct op name so a library without this semantic cannot silently resolve it. */
#define R4D_WIN_ANCHOR_DEF(HD, G) \
int r4d_rad_attn_anchor_window_h##HD##_gqa##G##_bf16kv(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, false, false, true>(a, s); \
} \
int r4d_rad_attn_anchor_window_h##HD##_gqa##G##_fp8kv(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, true, false, true>(a, s); \
return r4d_win::launch_attn<HD, G, 0, false, true>(a, s); \
} \
int r4d_rad_attn_anchor_window_h##HD##_gqa##G##_i8kv(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, 2, false, true>(a, s); \
}
R4D_WIN_ANCHOR_DEF(128, 1)
R4D_WIN_ANCHOR_DEF(256, 1) R4D_WIN_ANCHOR_DEF(256, 2) R4D_WIN_ANCHOR_DEF(256, 4) R4D_WIN_ANCHOR_DEF(256, 8)
@@ -1345,10 +1413,10 @@ R4D_WIN_ANCHOR_DEF(512, 1) R4D_WIN_ANCHOR_DEF(512, 2) R4D_WIN_ANCHOR_DEF(512, 4)
* block, a 1024-token window. */
#define R4D_WINSINK_DEF(HD, G) \
int r4d_rad_attn_window_sink_h##HD##_gqa##G##_bf16(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, false>(a, s, true); \
return r4d_win::launch_attn<HD, G, 0>(a, s, true); \
} \
int r4d_rad_attn_window_sink_h##HD##_gqa##G##_fp8(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, true>(a, s, true); \
int r4d_rad_attn_window_sink_h##HD##_gqa##G##_i8(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, 2>(a, s, true); \
}
R4D_WINSINK_DEF(128, 8) R4D_WINSINK_DEF(128, 16)
#undef R4D_WINSINK_DEF
+55 -17
View File
@@ -77,6 +77,10 @@
// O_V4: the fp8_v4 cache, O_V4 | O_K6 the k6_v4 cache (see r4d_attn_decode_h256_gqa6.hip).
#define O_V4 33554432
#define O_K6 67108864
// O_I8 (with O_V4 | O_K6): the i8 cache (see r4d_attn_decode_h256_gqa6.hip).
#define O_I8 1073741824
// The int8 cache's bits together, for a launcher's option set.
#define O_KVI8 (O_V4 | O_K6 | O_I8)
// O_PSPLIT: a KV split for launches with too few workgroups to fill the card (r4d_prefill_splits
// in r4d_attn_prefill_split.h). blockIdx.x is qtile * a.splits + split, and the workgroup walks
// only its segment of the sequence's tiles, cut as r4d_attn_tps cuts them (the partition the
@@ -147,11 +151,14 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
constexpr int BTS = (OPT & O_BTS) ? 1 : 0;
constexpr int V4 = ((OPT & O_V4) && !KVP) ? 1 : 0;
constexpr int K6 = ((OPT & O_K6) && V4) ? 1 : 0;
constexpr int I8 = ((OPT & O_I8) && K6) ? 1 : 0;
static_assert(!I8 || !(OPT & (O_QK8 | O_PV8)), "the i8 cache has no e4m3 legs");
// A token's row in a page, and where in it V's codes, V's scales and K's scales start.
constexpr int ROWB = K6 ? HEAD_DIM * 22 / 16 : V4 ? HEAD_DIM * 25 / 16 : 2 * HEAD_DIM;
constexpr int VOFF = K6 ? HEAD_DIM * 3 / 4 : HEAD_DIM;
constexpr int VSOFF = K6 ? HEAD_DIM * 21 / 16 : HEAD_DIM * 3 / 2;
constexpr int KSOFF = HEAD_DIM * 5 / 4;
constexpr int ROWB = I8 ? 2 * HEAD_DIM + 4
: K6 ? HEAD_DIM * 22 / 16 : V4 ? HEAD_DIM * 25 / 16 : 2 * HEAD_DIM;
constexpr int VOFF = I8 ? HEAD_DIM : K6 ? HEAD_DIM * 3 / 4 : HEAD_DIM;
constexpr int VSOFF = I8 ? 2 * HEAD_DIM + 2 : K6 ? HEAD_DIM * 21 / 16 : HEAD_DIM * 3 / 2;
constexpr int KSOFF = I8 ? 2 * HEAD_DIM : HEAD_DIM * 5 / 4;
constexpr int GPREV = ((OPT & O_GPREV) && !V4) ? 1 : 0;
constexpr int LDSB = (OPT & O_LDSB) ? 1 : 0;
constexpr int KWIDE = (OPT & O_KWIDE) ? 1 : 0;
@@ -186,7 +193,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
constexpr float PSHIFT = D::SHIFT;
constexpr float PGROW = PV8 ? 8.0f : D::GROW; // e4m3 max is 448 = 2^8.8
static_assert(!KWIDE || KPASS == 1, "the wide K fetch is one straight-line pass");
static_assert(!K6 || KWIDE, "k6_v4 K is staged sixteen dims a thread");
static_assert(!K6 || I8 || KWIDE, "k6_v4 K is staged sixteen dims a thread");
static_assert((!QK8 && !PV8) || CTG, "the 8-bit fragment maps are written for CONTIG");
constexpr int KSTR8 = HEAD_DIM + 8, VSTR8 = TILE + 8;
@@ -294,6 +301,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
// The split lets GPREV move the fetch out from between the barriers.
const int vg = lane >> 3, vj = lane & 7;
uint4 kreg[KREGS], vreg[VREGS];
// i8: the K scale of the key a pass stages.
uint32_t ksc8[I8 ? KPASS : 1];
// ---- fp8_v4 / k6_v4: V is int4 in groups of 32 with an f16 scale (absmax / 7): 16 bytes of
// codes a group at VOFF (dim d at bits 4*(d%8) of word d/8), the group scales at VSOFF. A thread stages one key pair's 8 dims: two code words and the pair's scale,
@@ -307,7 +316,9 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
constexpr int U4 = V4 ? (NP4 + NTHR - 1) / NTHR : 1;
// The pair's two scales stay apart until storeV4 packs them: packed here, the prefetch a tile
// ahead would be waited on right after it is issued (fp8_v4 packs here, see KLATE).
uint32_t v4c[U4][2], v4s[U4][2];
// i8: V's codes are bytes, two words a key's 8 dims, and a key has one scale; the rest is the
// same with u = code ^ 0x80 and (x - 1152) * s.
uint32_t v4c[U4][I8 ? 4 : 2], v4s[U4][2];
auto fetchV4 = [&](int k0, const int* blks) {
#pragma unroll
for (int r = 0; r < U4; ++r) {
@@ -321,8 +332,15 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
const int bk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS];
const uint8_t* base = (const uint8_t*)a.kv + (size_t)bk * a.kv_block_stride
+ (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB;
v4c[r][j] = *(const uint32_t*)(base + VOFF + o * 4);
sc[j] = *(const uint16_t*)(base + VSOFF + (o >> 2) * 2);
if constexpr (I8) {
const uint2 cw = *(const uint2*)(base + VOFF + o * 8);
v4c[r][2 * j] = cw.x;
v4c[r][2 * j + 1] = cw.y;
sc[j] = *(const uint16_t*)(base + VSOFF);
} else {
v4c[r][j] = *(const uint32_t*)(base + VOFF + o * 4);
sc[j] = *(const uint16_t*)(base + VSOFF + (o >> 2) * 2);
}
}
if constexpr (OLDV4) { v4s[r][0] = sc[0] | (sc[1] << 16); v4s[r][1] = 0; }
else { v4s[r][0] = sc[0]; v4s[r][1] = sc[1]; }
@@ -336,13 +354,18 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
const int u = tid + r * NTHR;
if (NP4 % NTHR == 0 || u < NP4) {
const int kp = u % (TILE / 2), o = u / (TILE / 2);
// Codes are two's complement nibbles; ^ 8 makes them offset binary (value + 8).
const uint32_t n0 = (v4c[r][0] & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t m0 = ((v4c[r][0] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t n1 = (v4c[r][1] & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t m1 = ((v4c[r][1] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
// Codes are two's complement nibbles; ^ 8 makes them offset binary (value + 8). i8:
// bytes, ^ 0x80; `n` is a key's dims 0-3 of the octet and `m` its dims 4-7.
const uint32_t n0 = I8 ? v4c[r][0] ^ 0x80808080u
: (v4c[r][0] & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t m0 = I8 ? v4c[r][1] ^ 0x80808080u
: ((v4c[r][0] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t n1 = I8 ? v4c[r][I8 ? 2 : 1] ^ 0x80808080u
: (v4c[r][1] & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t m1 = I8 ? v4c[r][I8 ? 3 : 1] ^ 0x80808080u
: ((v4c[r][1] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
const h2 s2 = __builtin_bit_cast(h2, OLDV4 ? v4s[r][0] : (v4s[r][0] | (v4s[r][1] << 16)));
const h2 bias = { (_Float16)1032.0f, (_Float16)1032.0f };
const h2 bias = { (_Float16)(I8 ? 1152.0f : 1032.0f), (_Float16)(I8 ? 1152.0f : 1032.0f) };
uint16_t* dst = &sV16[(o * 8) * VSTR + 2 * kp];
uint8_t* dst8 = &sV8[(o * 8) * VSTR8 + 2 * kp];
#pragma unroll
@@ -361,8 +384,9 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
*(uint16_t*)(dst8 + (2 * b + 1) * VSTR8) = (uint16_t)pk_fp8x2_h(__builtin_bit_cast(uint32_t, vh));
continue;
}
*(uint32_t*)(dst + (2 * b) * VSTR) = __builtin_bit_cast(uint32_t, vl);
*(uint32_t*)(dst + (2 * b + 1) * VSTR) = __builtin_bit_cast(uint32_t, vh);
// The octet's rows: nibbles interleave the dims (2b, 2b+1), bytes run b, 4+b.
*(uint32_t*)(dst + (I8 ? b : 2 * b) * VSTR) = __builtin_bit_cast(uint32_t, vl);
*(uint32_t*)(dst + (I8 ? 4 + b : 2 * b + 1) * VSTR) = __builtin_bit_cast(uint32_t, vh);
}
}
}
@@ -385,6 +409,17 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
#pragma unroll
for (int q = 0; q < (KVP ? (KEL / 8) : 1); ++q)
kreg[p * (KEL / 8) + q] = *(const uint4*)(g + 8 * q);
} else if (I8) {
// i8: the chunk's codes (sixteen, or eight without the wide fetch) and the
// key's scale.
const uint8_t* rp = (const uint8_t*)a.kv + o;
if constexpr (KWIDE) {
kreg[p] = *(const uint4*)(rp + ch * 16);
} else {
const uint2 r = *(const uint2*)(rp + ch * 8);
kreg[p] = make_uint4(r.x, r.y, 0, 0);
}
ksc8[p] = *(const uint16_t*)(rp + KSOFF);
} else if (K6) {
// k6_v4: the chunk's sixteen low nibbles, its high-bit word, its group's scale.
const uint8_t* rp = (const uint8_t*)a.kv + o;
@@ -454,7 +489,10 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
w4[2] = D::from_bf16w(r.z); w4[3] = D::from_bf16w(r.w);
} else {
const uint4 r = kreg[p];
if constexpr (K6) k6x8_to_f16x4w(q ? r.y : r.x, r.z, q, r.w | (r.w << 16), w4);
if constexpr (I8)
i8x8_to_f16x4w(q ? make_uint2(r.z, r.w) : make_uint2(r.x, r.y),
ksc8[p] | (ksc8[p] << 16), w4);
else if constexpr (K6) k6x8_to_f16x4w(q ? r.y : r.x, r.z, q, r.w | (r.w << 16), w4);
else fp8x8_to_16x4w<D>(q ? make_uint2(r.z, r.w) : make_uint2(r.x, r.y), w4);
}
*(uint2*)(kd + 8 * q) = make_uint2(w4[0], w4[1]);
+2 -2
View File
@@ -64,8 +64,8 @@ static inline int r4d_prefill_splits_law(int bq, int tile, int q_len, int total_
static int g_prefill_last_splits = 0;
/* RadArgs::kv_used_max_h is the host maximum of the launch's seqused operand (Ctx::issue_body),
* -1 where it cannot be proven, which uses max_ctx below. In a recorded pass of a plugin with no
* pass-key callback (decode, verify, draft) it is the step's keyed context bound instead. Never
* -1 where it cannot be proven, which uses max_ctx below. In a decode, verify or draft pass, which is
* recorded, it is the step's keyed context bound instead. Never
* synchronously copy device seqused from a HIP queue independent of the AQL upload queue. */
/* The KV split's count before the scratch bound: the case's `splits` parameter when it names one
+6 -15
View File
@@ -14,6 +14,12 @@
#include <hip/hip_runtime.h>
#include "rad_abi.h"
/* A kernel template's chain parameter, for a kernel that brackets its own body: `r4dchain`
* instantiates the chained form and puts the name the backend knows a chained kernel by into the
* instantiation's symbol, R4dUnchained the plain form. */
struct r4dchain { static constexpr bool on = true; };
struct R4dUnchained { static constexpr bool on = false; };
#if !defined(__HIP__)
/* The host SIMT emulator (tests/r4d_emu) compiles some of these sources as C++: no engine record
* ever reaches a launch there, so a chained form is its plain form. */
@@ -83,18 +89,3 @@ __device__ __forceinline__ void r4d_chain_done() {
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
}
#endif /* __HIP__ */
/* The launchers given a chained form here take it only at steps of up to 32 token rows: above that
* the waiting blocks hold room a wide predecessor needs. Flash-Next on 2x R9700 at MTP depth 5 with
* the adaptive window, sampled: 32 against 64 rows 214/349/494/654/890 -> 218/355/494/662/893 tok/s
* at 1/2/4/8/16 streams. */
constexpr long long kR4dChainMaxRows = 32;
inline bool r4d_chain_rows_ok(long long rows) { return rows <= kR4dChainMaxRows; }
/* A launcher that takes no RadArgs reads its row's `chain` here; the plugin
* ABI entry sets it around the launch only, so a direct C call never chains. */
inline thread_local bool g_r4d_chain_arg = false;
struct R4dChainArg {
explicit R4dChainArg(bool on) { g_r4d_chain_arg = on; }
~R4dChainArg() { g_r4d_chain_arg = false; }
};
+26
View File
@@ -183,6 +183,32 @@ __device__ __forceinline__ float r4d_wave_sum(float v) {
return v;
}
// Sixteen values a lane, each summed over the wave: after a level's exchange both lanes of a pair
// hold the same sums, so one keeps the first half of them and the other the second, and the next
// level adds half as many. 47 instructions where sixteen r4d_wave_sum take 96; lane l ends with the
// wave's sum of value red16_row(l). The levels run from offset 1 up, so a sum's rounding differs
// from r4d_wave_sum's.
// `x` where `c`, else `y`, by value: a conditional over two elements of one array is an lvalue, which
// the compiler turns into one indexed read and then into a compare and select per element.
__device__ __forceinline__ float r4d_pick(bool c, float x, float y) { return c ? x : y; }
__device__ __forceinline__ float red16(float (&a)[16], uint32_t lane) {
const bool l1 = lane & 1u, l2 = lane & 2u, l4 = lane & 4u, l8 = lane & 8u;
float b[8], c[4], d[2];
#pragma unroll
for (uint32_t q = 0; q < 16; ++q) a[q] = r4d_dpp_xor_add<0x161>(a[q]);
#pragma unroll
for (uint32_t j = 0; j < 8; ++j) b[j] = r4d_dpp_xor_add<0x162>(r4d_pick(l1, a[8 + j], a[j]));
#pragma unroll
for (uint32_t j = 0; j < 4; ++j) c[j] = r4d_dpp_xor_add<0x164>(r4d_pick(l2, b[4 + j], b[j]));
#pragma unroll
for (uint32_t j = 0; j < 2; ++j) d[j] = r4d_dpp_xor_add<0x168>(r4d_pick(l4, c[2 + j], c[j]));
const float v = r4d_pick(l8, d[1], d[0]);
return v + swap16(v);
}
__device__ __forceinline__ uint32_t red16_row(uint32_t lane) {
return (lane & 1u) << 3 | (lane & 2u) << 1 | (lane & 4u) >> 1 | (lane & 8u) >> 3;
}
// The same butterfly over a group of W lanes (W a power of two up to the wave): the exchanges of
// `for (o = W / 2; o; o >>= 1) v = op(v, __shfl_xor(v, o))`, in its order, so bit-identical to
// that loop.
+19
View File
@@ -92,6 +92,25 @@ __device__ __forceinline__ void k6x8_to_f16x4w(uint32_t lo, uint32_t hb, int hal
}
}
// Eight int8 codes (two dwords, element order) as four f16 dwords, dims (2i, 2i+1) in dword i,
// each the code times the scale `s2` (the f16 in both halves): the i8 cache's K and V
// (a RAD_I8 group). ^ 0x80 makes a code offset binary u, 0x6400 | u is the f16 1024 + u, and
// (x - 1152) * s is the value times the scale, rounded once.
__device__ __forceinline__ void i8x8_to_f16x4w(uint2 raw, uint32_t s2, uint32_t* w4) {
typedef _Float16 h2 __attribute__((ext_vector_type(2)));
const uint32_t lo = raw.x ^ 0x80808080u, hi = raw.y ^ 0x80808080u;
const h2 s = __builtin_bit_cast(h2, s2);
const h2 bias = { (_Float16)1152.0f, (_Float16)1152.0f };
#pragma unroll
for (int b = 0; b < 4; ++b) {
// Bytes 2b and 2b+1 of the eight, each into the low byte of a half; perm takes bytes 0-3
// from its second operand, 4-7 from its first, and 0x0c is a zero byte.
const uint32_t sel = (uint32_t)(2 * b) | 0x0c00u | ((uint32_t)(2 * b + 1) << 16) | 0x0c000000u;
const uint32_t x = __builtin_amdgcn_perm(hi, lo, sel) | 0x64006400u;
w4[b] = __builtin_bit_cast(uint32_t, (__builtin_bit_cast(h2, x) - bias) * s);
}
}
template<class D>
__device__ __forceinline__ void fp8x8_to_16x4w(uint2 raw, uint32_t* w4) {
#pragma unroll
+7 -1
View File
@@ -23,6 +23,9 @@ enum { SC_LOGITS = 0, SC_QUERY = 1, SC_U = 2, SC_DRAW = 3 };
struct Fp8Ops {
const RadTensor *a, *ascale, *b, *bscale, *y;
long long M, N, K, nkb;
/* The scale group along K: R4D_FP8_BLOCK, or R4D_I8_GROUP_WIDE for an int8 row-scale weight
* whose op says `group` 256 (IQ8R). Both scale planes have K / group columns. */
long long group;
long a_ld, sa_ld, w_ld, sw_ld; /* a_ld / w_ld in elements here; see the note at each use */
};
@@ -61,7 +64,10 @@ static inline int fp8_ops(const RadArgs* a, Fp8Ops* g, int want_ascale,
* a mismatch would be a silently wrong scale grid. */
const long long blk = r4d_gemm_fp8a8_block();
if (blk != R4D_FP8_BLOCK) return R4D_NO(RAD_E_SHAPE);
g->nkb = (g->K + blk - 1) / blk;
g->group = wscale == FP8_OPS_ROW_SCALE ? r4d_geti_or(a, "group", blk) : blk;
if (g->group != blk && g->group != R4D_I8_GROUP_WIDE) return R4D_NO(RAD_E_SHAPE);
if (g->group != blk && g->K % g->group) return R4D_NO(RAD_E_SHAPE);
g->nkb = (g->K + g->group - 1) / g->group;
/* Check the scale plane's extents: a wrong grid still reads plausible numbers. A trellis
* weight's two-level scale (E4M3 per row per 128 K under a second level) is a view of two
* planes, declared at the weight's logical extents [N][K] (which no one-level scale is); its
-723
View File
@@ -1,723 +0,0 @@
/* Canonical E4M3 weights with exact F32 block scales: native FP8 WMMA and F32 scale folding, no
* checkpoint scale narrowing. The legacy dense form computes one 16x64 output tile a block; the
* dense decode and prefill forms below it produce the same bytes faster, and the grouped form runs
* expert-major over the same per-element sequence. */
#include <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "r4d_fp8_wmma.h"
#include "r4d_launch.h"
#include <climits>
#include <cstdint>
#include <cstring>
namespace {
struct Meta {
long ar, asr, yr, wr, sr, wstep[2], sstep[2];
int T, N, K, experts, topk, sorted_a;
};
__device__ const uint8_t* entry(const void* p, long step, int e) {
return step ? (const uint8_t*)p + step * e : ((const uint8_t* const*)p)[e];
}
/* The legacy dense form: a block per 16 rows by 64 columns, the operands staged through LDS a
* dword at a time, so it serves any row pitch and alignment. */
__global__ void fp8_f32scale(const uint8_t* a, const float* as, const uint8_t* w, const float* ws,
uint16_t* y, Meta m) {
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, n0 = blockIdx.x * 64;
__shared__ uint8_t qa[16 * 136], wb[64 * 136];
__shared__ int source[16];
const int first = (int)blockIdx.y * 16, end = min(first + 16, m.T);
if (tid < 16) {
const int r = first + tid;
source[tid] = r < end ? r : -1;
}
__syncthreads();
auto acc = r4d_fp8::acc_zero();
for (int k0 = 0; k0 < m.K; k0 += 128) {
for (int j = tid; j < 16 * 32; j += 128) {
const int r = j / 32, c = (j % 32) * 4, src = source[r];
uint32_t v = 0;
if (src >= 0) {
const auto* p = a + (long)src * m.ar + k0 + c;
v = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) |
((uint32_t)p[3] << 24);
}
*(uint32_t*)(qa + r * 136 + c) = v;
}
for (int j = tid; j < 64 * 32; j += 128) {
const int r = j / 32, c = (j % 32) * 4;
const auto* p = w + (long)(n0 + r) * m.wr + k0 + c;
*(uint32_t*)(wb + r * 136 + c) = (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
__syncthreads();
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int k = 0; k < 128; k += 16)
raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, 0, k, lane),
r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw);
const float weight_scale = ws[(long)(n0 / 128) * m.sr + k0 / 128];
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int src = source[(lane >> 4) * 8 + j];
const float scale = src >= 0 ? as[(long)src * m.asr + k0 / 128] * weight_scale : 0;
acc[j] += raw[j] * scale;
}
__syncthreads();
}
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = first + (lane >> 4) * 8 + j, c = n0 + wave * 16 + (lane & 15);
if (r < end) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]);
}
}
/* The grouped form expert-major: a block per (column span, expert) takes every row of its
* expert in 16-row tiles, so an expert slice is read from memory once however its rows fall in
* the sorted order (16-row tiles of the sorted order read it once per tile its run spans). Each
* element keeps the sequence above: per 128 of K in order a fresh chain of eight WMMAs, folded as
* raw * (activation scale * weight scale). A block walks ColTiles column tiles of 64, each over K
* in stages of StageK, as one stage sequence with the next stage loaded into registers while the
* current one computes from LDS. Block row `experts` zeroes the dropped rows past
* offsets[experts]. */
typedef unsigned f8_u4 __attribute__((ext_vector_type(4)));
template <int StageK>
struct F8Stage {
static constexpr int KB = StageK / 128;
f8_u4 a[StageK / 128], w[StageK / 32];
float wsc[KB], sa;
};
template <int StageK, int ColTiles>
__global__ __launch_bounds__(128) void fp8_f32scale_experts(const uint8_t* a, const float* as,
const void* w0, const void* s0,
const void* w1, const void* s1,
const int* sorted, const int* offsets,
uint16_t* y, Meta m) {
using St = F8Stage<StageK>;
constexpr int KB = St::KB, P = StageK + 8;
__shared__ __align__(16) uint8_t qa[16 * P], wb[64 * P];
__shared__ float sa[16 * KB];
__shared__ int source[16];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, e = blockIdx.y,
colb = blockIdx.x * 64 * ColTiles;
if (e == m.experts) {
const int r0 = offsets[m.experts];
for (long i = tid; i < (long)(m.T - r0) * 64 * ColTiles; i += 128) {
const int c = colb + (int)(i % (64 * ColTiles));
if (c < m.N) y[(long)(r0 + i / (64 * ColTiles)) * m.yr + c] = 0;
}
return;
}
const int lo = offsets[e], hi = offsets[e + 1];
if (lo >= hi) return;
const int parity = e & 1;
const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e / 2);
const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e / 2);
const int ksn = (m.K + StageK - 1) / StageK, tiles = min(ColTiles, (m.N - colb + 63) / 64),
S = tiles * ksn;
const int rowbase = (lane >> 4) * 8;
for (int r0 = lo; r0 < hi; r0 += 16) {
__syncthreads();
if (tid < 16) {
const int r = r0 + tid, flat = r < hi ? sorted[r] : -1;
source[tid] = r < hi && flat >= 0 ? (m.sorted_a ? r : flat / m.topk) : -1;
}
__syncthreads();
bool rv[8];
#pragma unroll
for (int j = 0; j < 8; ++j) rv[j] = source[rowbase + j] >= 0;
auto load = [&](int s, St& R) {
const int col0 = colb + (s / ksn) * 64, k0 = (s % ksn) * StageK;
#pragma unroll
for (int i = 0; i < StageK / 128; ++i) {
const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16,
src = source[r];
R.a[i] = f8_u4{ 0, 0, 0, 0 };
if (src >= 0 && k0 + c < m.K)
__builtin_memcpy(&R.a[i], a + (long)src * m.ar + k0 + c, 16);
}
#pragma unroll
for (int i = 0; i < StageK / 32; ++i) {
const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
R.w[i] = f8_u4{ 0, 0, 0, 0 };
if (k0 + c < m.K)
__builtin_memcpy(&R.w[i], w + (long)(col0 + r) * m.wr + k0 + c, 16);
}
#pragma unroll
for (int kb = 0; kb < KB; ++kb)
R.wsc[kb] =
k0 + kb * 128 < m.K ? ws[(long)(col0 / 128) * m.sr + (k0 + kb * 128) / 128] : 0;
if (tid < 16 * KB) {
const int src = source[tid / KB], kb = k0 + (tid % KB) * 128;
R.sa = src >= 0 && kb < m.K ? as[(long)src * m.asr + kb / 128] : 0;
}
};
auto store = [&](const St& R) {
#pragma unroll
for (int i = 0; i < StageK / 128; ++i) {
const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
*reinterpret_cast<f8_u4*>(qa + r * P + c) = R.a[i];
}
#pragma unroll
for (int i = 0; i < StageK / 32; ++i) {
const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
*reinterpret_cast<f8_u4*>(wb + r * P + c) = R.w[i];
}
if (tid < 16 * KB) sa[tid] = R.sa;
};
auto acc = r4d_fp8::acc_zero();
St R;
load(0, R);
for (int s = 0; s < S; ++s) {
store(R);
float wsc[KB];
#pragma unroll
for (int kb = 0; kb < KB; ++kb) wsc[kb] = R.wsc[kb];
__syncthreads();
if (s + 1 < S) load(s + 1, R);
const int k0 = (s % ksn) * StageK;
#pragma unroll
for (int kb = 0; kb < KB; ++kb) {
if (k0 + kb * 128 >= m.K) break;
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int k = kb * 128; k < (kb + 1) * 128; k += 16)
raw = r4d_fp8::mma(r4d_fp8::frag<StageK>(qa, 0, k, lane),
r4d_fp8::frag<StageK>(wb, wave * 16, k, lane), raw);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const float scale = rv[j] ? sa[(rowbase + j) * KB + kb] * wsc[kb] : 0;
acc[j] += raw[j] * scale;
}
}
if (s % ksn == ksn - 1) {
const int c = colb + (s / ksn) * 64 + wave * 16 + (lane & 15);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = r0 + rowbase + j;
if (r < hi) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]);
}
acc = r4d_fp8::acc_zero();
}
__syncthreads();
}
}
}
/* The small-M grouped form at GLM's MTP gate_up slice, with fp8_f32scale_experts' per-element
* sequence and so its bytes. A draft pass routes one token to eight experts, and the four column
* tiles a block of the form above leave sixteen blocks, each a chain of 64 stages of 256 K. Here a
* block takes one column tile of the y-th touched expert (the grid has min(experts, rows) + 1
* rows, as at the MXFP4 small-M form), in stages of 512 K, with loads unconditional from clamped
* addresses and masked at the store, barriers that order LDS only, and a 128 of K's eight fragment
* pairs loaded before its WMMA chain. */
typedef unsigned f8_g16 __attribute__((ext_vector_type(4), aligned(1)));
__device__ __forceinline__ f8_u4 f8_ldg16(const uint8_t* p) {
return *(const __attribute__((address_space(1))) f8_g16*)p;
}
__device__ __forceinline__ float f8_ldgf(const float* p) {
return *(const __attribute__((address_space(1))) float*)p;
}
template <int StageK>
struct F8Small {
static constexpr int Threads = 128, KB = StageK / 128, P = StageK + 8;
static constexpr int AChunks = StageK / Threads, WChunks = 64 * StageK / 16 / Threads;
f8_u4 a[AChunks], w[WChunks];
float wsc[KB], sa;
uint32_t ok;
};
template <int StageK>
__global__ __launch_bounds__(128) void fp8_f32scale_small(const uint8_t* a, const float* as,
const void* w0, const void* s0,
const void* w1, const void* s1,
const int* sorted, const int* offsets,
uint16_t* y, Meta m) {
using St = F8Small<StageK>;
constexpr int KB = St::KB, P = St::P, Threads = St::Threads;
static_assert(St::AChunks <= 8 && St::WChunks <= 16 && KB <= 4 && 16 * KB <= Threads &&
64 * P >= 4 * 513,
"stage chunks must fit the load mask and the offsets the weight tile");
__shared__ __align__(16) uint8_t qa[16 * P], wb[64 * P];
__shared__ float sa[16 * KB];
__shared__ int source[16];
__shared__ int pick;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, col0 = blockIdx.x * 64;
if ((int)blockIdx.y == (int)gridDim.y - 1) {
const int r0 = offsets[m.experts];
for (long i = tid; i < (long)(m.T - r0) * 64; i += Threads) {
const int c = col0 + (int)(i % 64);
if (c < m.N) y[(long)(r0 + i / 64) * m.yr + c] = 0;
}
return;
}
{
// The offsets in the weight tile, whose bytes are free until the first stage.
int* offs = reinterpret_cast<int*>(wb);
#pragma unroll
for (int q = 0; q < 5; ++q) {
const int x = tid + q * Threads;
if (x <= m.experts) offs[x] = offsets[x];
}
lds_barrier();
if (wave == 0) {
int want = blockIdx.y, found = -1;
for (int base = 0; base < m.experts; base += 32) {
const int x = base + lane;
const bool live = x < m.experts && offs[x + 1] > offs[x];
const uint32_t mask = __builtin_amdgcn_ballot_w32(live);
const int n = __builtin_popcount(mask);
if (want < n) {
const uint32_t below = mask & ((1u << lane) - 1u);
found = base + __builtin_ctz(__builtin_amdgcn_ballot_w32(
live && __builtin_popcount(below) == want));
break;
}
want -= n;
}
if (lane == 0) pick = found;
}
lds_barrier();
}
const int e = pick;
if (e < 0) return;
const int lo = offsets[e], hi = offsets[e + 1];
const int parity = e & 1;
const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e / 2);
const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e / 2);
const int S = (m.K + StageK - 1) / StageK, rowbase = (lane >> 4) * 8;
for (int r0 = lo; r0 < hi; r0 += 16) {
lds_barrier();
if (tid < 16) {
const int r = r0 + tid, flat = r < hi ? sorted[r] : -1;
source[tid] = flat >= 0 ? (m.sorted_a ? r : flat / m.topk) : -1;
}
lds_barrier();
bool rv[8];
#pragma unroll
for (int j = 0; j < 8; ++j) rv[j] = source[rowbase + j] >= 0;
auto load = [&](int s, St& L) {
const int k0 = s * StageK;
uint32_t ok = 0;
#pragma unroll
for (int i = 0; i < St::AChunks; ++i) {
const int j = tid + i * Threads, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16,
src = source[r];
const bool v = src >= 0 && k0 + c < m.K;
__builtin_memcpy(&L.a[i], a + (v ? (long)src * m.ar + k0 + c : 0), 16);
ok |= (uint32_t)v << i;
}
#pragma unroll
for (int i = 0; i < St::WChunks; ++i) {
const int j = tid + i * Threads, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
const bool v = k0 + c < m.K;
L.w[i] = f8_ldg16(w + (v ? (long)(col0 + r) * m.wr + k0 + c : 0));
ok |= (uint32_t)v << (8 + i);
}
#pragma unroll
for (int kb = 0; kb < KB; ++kb) {
const bool v = k0 + kb * 128 < m.K;
L.wsc[kb] =
f8_ldgf(ws + (v ? (long)(col0 / 128) * m.sr + (k0 + kb * 128) / 128 : 0));
ok |= (uint32_t)v << (24 + kb);
}
{
const int src = source[(tid / KB) & 15], kb = k0 + (tid % KB) * 128;
const bool v = tid < 16 * KB && src >= 0 && kb < m.K;
L.sa = as[v ? (long)src * m.asr + kb / 128 : 0];
ok |= (uint32_t)v << 28;
}
L.ok = ok;
};
auto store = [&](const St& L) {
#pragma unroll
for (int i = 0; i < St::AChunks; ++i) {
const int j = tid + i * Threads, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
*reinterpret_cast<f8_u4*>(qa + r * P + c) =
(L.ok >> i) & 1u ? L.a[i] : f8_u4{ 0, 0, 0, 0 };
}
#pragma unroll
for (int i = 0; i < St::WChunks; ++i) {
const int j = tid + i * Threads, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
*reinterpret_cast<f8_u4*>(wb + r * P + c) =
(L.ok >> (8 + i)) & 1u ? L.w[i] : f8_u4{ 0, 0, 0, 0 };
}
if (tid < 16 * KB) sa[(tid % KB) * 16 + tid / KB] = (L.ok >> 28) & 1u ? L.sa : 0.f;
};
auto acc = r4d_fp8::acc_zero();
St L;
load(0, L);
for (int s = 0; s < S; ++s) {
store(L);
float wsc[KB];
#pragma unroll
for (int kb = 0; kb < KB; ++kb) wsc[kb] = (L.ok >> (24 + kb)) & 1u ? L.wsc[kb] : 0.f;
lds_barrier();
if (s + 1 < S) load(s + 1, L);
const int k0 = s * StageK;
#pragma unroll
for (int kb = 0; kb < KB; ++kb) {
if (k0 + kb * 128 >= m.K) break;
r4d_fp8::i2v fa[8], fb[8];
#pragma unroll
for (int t = 0; t < 8; ++t) {
fa[t] = r4d_fp8::frag<StageK>(qa, 0, kb * 128 + 16 * t, lane);
fb[t] = r4d_fp8::frag<StageK>(wb, wave * 16, kb * 128 + 16 * t, lane);
}
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int t = 0; t < 8; ++t) raw = r4d_fp8::mma(fa[t], fb[t], raw);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const float scale = rv[j] ? sa[kb * 16 + rowbase + j] * wsc[kb] : 0;
acc[j] += raw[j] * scale;
}
}
lds_barrier();
}
const int c = col0 + wave * 16 + (lane & 15);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = r0 + rowbase + j;
if (r < hi) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]);
}
}
}
// Both forms below keep fp8_f32scale's arithmetic for every output: per 128-K block the same
// eight-mma chain from zero over the same fragments (the bytes at k + 8*(lane/16) of the block's
// row segment, which the legacy form copies through LDS unchanged), then acc += raw * (a_scale *
// w_scale) in ascending block order. A WMMA output depends only on its own A row, B column and
// C, so which rows and columns share a tile does not change it.
// Decode: one wave C adjacent 16-column tiles, S waves of a block on S consecutive K blocks at
// once, the fragments loaded straight from global memory; R row tiles share each weight fragment
// and C column tiles each activation fragment. Each wave scales its own partial products (the
// a_scale x w_scale product and the multiply are the legacy fold's own two roundings) into LDS;
// then every wave folds a share of the outputs, adding the round's products in block order to the
// output's running sum, which lives in LDS between rounds. The block's activation scales are
// staged in LDS when they fit (`stage`).
template <int R, int C>
__global__ void fp8_f32scale_decode(const uint8_t* a, const float* as, const uint8_t* w,
const float* ws, uint16_t* y, Meta m, int stage) {
constexpr int SL = R * C * 8;
R4D_DYN_LDS(float, lds);
const int lane = threadIdx.x & 31, s = threadIdx.x >> 5, S = blockDim.x >> 5, h = lane >> 4;
const int c0 = blockIdx.x * 16 * C, first = (int)blockIdx.y * R * 16, KB = m.K / 128;
float* part = lds;
float* sums = part + S * SL * 32;
float* scales = sums + SL * 32;
if (stage)
for (int i = threadIdx.x; i < R * 16 * KB; i += blockDim.x) {
const int r = first + i / KB;
scales[i] = r < m.T ? as[(long)r * m.asr + i % KB] : 0;
}
for (int i = threadIdx.x; i < SL * 32; i += blockDim.x) sums[i] = 0;
const uint8_t* arow[R];
bool alive[R];
#pragma unroll
for (int t = 0; t < R; ++t) {
const int r = first + t * 16 + (lane & 15);
alive[t] = r < m.T;
arow[t] = a + (long)(alive[t] ? r : 0) * m.ar + h * 8;
}
__syncthreads();
for (int k0 = 0; k0 < KB; k0 += S) {
const int kb = k0 + s;
if (kb < KB) {
r4d_fp8::i2v b[C][8];
float weight_scale[C];
#pragma unroll
for (int c = 0; c < C; ++c) {
const uint8_t* wrow =
w + (long)(c0 + c * 16 + (lane & 15)) * m.wr + h * 8 + (long)kb * 128;
#pragma unroll
for (int q = 0; q < 8; ++q) {
const uint2 v = *(const uint2*)(wrow + q * 16);
b[c][q][0] = (int)v.x;
b[c][q][1] = (int)v.y;
}
weight_scale[c] = ws[(long)((c0 + c * 16) / 128) * m.sr + kb];
}
#pragma unroll
for (int t = 0; t < R; ++t) {
r4d_fp8::i2v f[8];
#pragma unroll
for (int q = 0; q < 8; ++q) {
uint2 v = make_uint2(0, 0);
if (alive[t]) v = *(const uint2*)(arow[t] + (long)kb * 128 + q * 16);
f[q][0] = (int)v.x;
f[q][1] = (int)v.y;
}
float act[8];
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int rr = t * 16 + h * 8 + j, r = first + rr;
act[j] =
stage ? scales[rr * KB + kb] : (r < m.T ? as[(long)r * m.asr + kb] : 0);
}
#pragma unroll
for (int c = 0; c < C; ++c) {
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int q = 0; q < 8; ++q) raw = r4d_fp8::mma(f[q], b[c][q], raw);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = first + t * 16 + h * 8 + j;
const float scale = r < m.T ? act[j] * weight_scale[c] : 0;
part[((long)s * SL + (t * C + c) * 8 + j) * 32 + lane] = raw[j] * scale;
}
}
}
}
__syncthreads();
for (int slot = s; slot < SL; slot += S) {
float acc = sums[slot * 32 + lane];
for (int q = 0; q < S && k0 + q < KB; ++q)
acc += part[((long)q * SL + slot) * 32 + lane];
sums[slot * 32 + lane] = acc;
}
__syncthreads();
}
for (int slot = s; slot < SL; slot += S) {
const int t = slot / (C * 8), c = slot / 8 % C, j = slot % 8,
r = first + t * 16 + h * 8 + j;
if (r < m.T)
y[(long)r * m.yr + c0 + c * 16 + (lane & 15)] = f32_to_bf16(sums[slot * 32 + lane]);
}
}
// Prefill: the legacy form's 64-column block and LDS layout over R row tiles, so a staged weight
// block serves R*16 rows instead of 16, staged with 16-byte loads and the next K block loaded
// into registers while the current one is multiplied.
template <int R>
__global__ void __launch_bounds__(128)
fp8_f32scale_rows(const uint8_t* a, const float* as, const uint8_t* w, const float* ws,
uint16_t* y, Meta m) {
constexpr int P = 136, AV = R * 16 * 8 / 128, WV = 64 * 8 / 128;
__shared__ uint8_t qa[R * 16 * P], wb[64 * P];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, h = lane >> 4,
n0 = blockIdx.x * 64;
const int first = (int)blockIdx.y * R * 16, KB = m.K / 128;
uint4 av[AV], wv[WV];
auto load = [&](int kb) {
#pragma unroll
for (int i = 0; i < AV; ++i) {
const int j = tid + i * 128, r = j / 8, c = (j % 8) * 16;
av[i] = first + r < m.T
? *(const uint4*)(a + (long)(first + r) * m.ar + (long)kb * 128 + c)
: make_uint4(0, 0, 0, 0);
}
#pragma unroll
for (int i = 0; i < WV; ++i) {
const int j = tid + i * 128, r = j / 8, c = (j % 8) * 16;
wv[i] = *(const uint4*)(w + (long)(n0 + r) * m.wr + (long)kb * 128 + c);
}
};
r4d_fp8::f8v acc[R];
#pragma unroll
for (int t = 0; t < R; ++t) acc[t] = r4d_fp8::acc_zero();
load(0);
for (int kb = 0; kb < KB; ++kb) {
// The 136-byte pitch keeps 8-byte alignment only, so each 16 bytes go in as two halves.
auto put = [](uint8_t* p, const uint4& v) {
((uint2*)p)[0] = make_uint2(v.x, v.y);
((uint2*)p)[1] = make_uint2(v.z, v.w);
};
#pragma unroll
for (int i = 0; i < AV; ++i) {
const int j = tid + i * 128;
put(qa + (j / 8) * P + (j % 8) * 16, av[i]);
}
#pragma unroll
for (int i = 0; i < WV; ++i) {
const int j = tid + i * 128;
put(wb + (j / 8) * P + (j % 8) * 16, wv[i]);
}
__syncthreads();
if (kb + 1 < KB) load(kb + 1);
const float weight_scale = ws[(long)(n0 / 128) * m.sr + kb];
#pragma unroll
for (int t = 0; t < R; ++t) {
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int k = 0; k < 128; k += 16)
raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, t * 16, k, lane),
r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = first + t * 16 + h * 8 + j;
const float scale = r < m.T ? as[(long)r * m.asr + kb] * weight_scale : 0;
acc[t][j] += raw[j] * scale;
}
}
__syncthreads();
}
#pragma unroll
for (int t = 0; t < R; ++t)
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = first + t * 16 + h * 8 + j, c = n0 + wave * 16 + (lane & 15);
if (r < m.T) y[(long)r * m.yr + c] = f32_to_bf16(acc[t][j]);
}
}
// The dense form: a decode form (`decode`, C column tiles a wave, S waves a block) or the row
// tiles (R of 16 rows a block), by the rule at the end of dense_form. The forms are
// byte-identical; the choice is speed only.
struct Form {
bool decode = false;
int r = 1, s = 1, c = 1;
};
constexpr int kLdsCap = 64 * 1024;
long decode_lds(int R, int S, int C, long KB, bool stage) {
return ((long)S * R * C * 8 * 32 + (long)R * C * 8 * 32 + (stage ? (long)R * 16 * KB : 0)) * 4;
}
Form dense_form(long N, long K, long T) {
// Measured on gfx1201 (r4d_selftest --perfq, cold) at GLM's six shapes: decode1x8 up to 16
// rows; from 17 to 64 two column tiles a wave (decode1x8x2) lead by 5 to 15 %, except at N 512
// (too few column tiles, 1x8 stays) and N 4096 over K 1536, where the 16-row tile wins; from 65
// to 128 rows decode1x8 holds at K 4096 and the row tiles win at K 2048 and below. Among the
// row tiles (and past 128 rows) the 16-row tile beats the 64-row tile by a quarter; the 32-row
// tile wins at N 4096.
const long kb = K / 128;
Form f;
const bool rows =
T > 128 || (T > 64 && K <= 2048) || (T > 16 && T <= 64 && K <= 1536 && N >= 4096);
if (!rows) {
f.decode = true;
f.c = T > 16 && T <= 64 && N > 512 ? 2 : 1;
f.s = 8;
while (f.s > 1 && f.s > kb) f.s /= 2;
return f;
}
f.r = T > 64 && N >= 4096 ? 2 : 1;
return f;
}
template <int R>
int emit_rows(RadStream stream, const uint8_t* xa, const float* xsa, const uint8_t* wa,
const float* wsa, uint16_t* ya, const Meta& m) {
return R4D_EMIT(stream, fp8_f32scale_rows<R>,
dim3(m.N / 64, (unsigned)((m.T + R * 16 - 1) / (R * 16))), dim3(128), 0, xa,
xsa, wa, wsa, ya, m);
}
int dense_fast(RadStream stream, const RadTensor& x, const RadTensor& xs, const RadTensor& w,
const RadTensor& ws, const RadTensor& y, const Meta& m, bool* done) {
*done = false;
const Form f = dense_form(m.N, m.K, m.T);
if (m.wr % 16 || m.ar % 16 ||
(reinterpret_cast<uintptr_t>(x.data) | reinterpret_cast<uintptr_t>(w.data)) % 16)
return RAD_OK;
const uint8_t *xa = (const uint8_t*)x.data, *wa = (const uint8_t*)w.data;
const float *xsa = (const float*)xs.data, *wsa = (const float*)ws.data;
uint16_t* ya = (uint16_t*)y.data;
if (f.decode) {
const long kb = m.K / 128;
const int stage = decode_lds(1, f.s, f.c, kb, true) <= kLdsCap;
const long lds = decode_lds(1, f.s, f.c, kb, stage);
if (lds > kLdsCap || m.N % (16 * f.c)) return RAD_OK;
*done = true;
const dim3 grid(m.N / (16 * f.c), (unsigned)((m.T + 15) / 16)), block(32 * f.s);
if (f.c == 2)
return R4D_EMIT(stream, (fp8_f32scale_decode<1, 2>), grid, block, (uint32_t)lds, xa,
xsa, wa, wsa, ya, m, stage);
return R4D_EMIT(stream, (fp8_f32scale_decode<1, 1>), grid, block, (uint32_t)lds, xa, xsa,
wa, wsa, ya, m, stage);
}
*done = true;
if (f.r == 2) return emit_rows<2>(stream, xa, xsa, wa, wsa, ya, m);
return emit_rows<1>(stream, xa, xsa, wa, wsa, ya, m);
}
int body(const RadArgs* a, RadStream stream, bool grouped) {
if (!a || !a->t || a->n_t < (grouped ? 9 : 5)) return RAD_E_INVAL;
const auto &x = a->t[0], &xs = a->t[1], &w = a->t[2], &ws = a->t[3], &y = a->t[grouped ? 8 : 4];
const int64_t N = r4d_geti_or(a, "N", 0), K = r4d_geti_or(a, "K", 0);
if (N < 128 || N % 128 || K < 128 || K % 128 || N > INT_MAX || K > INT_MAX ||
r4d_geti_or(a, "group", 0) != 128 || r4d_geti_or(a, "pb1", 0) > 0)
return RAD_E_SHAPE;
if (x.dtype != RAD_F8E4M3 || xs.dtype != RAD_F32 || w.dtype != RAD_F8E4M3 ||
ws.dtype != RAD_F32 || y.dtype != RAD_BF16)
return RAD_E_DTYPE;
if (!x.data || !xs.data || !w.data || !ws.data || !y.data || x.rank != 2 || xs.rank != 2 ||
y.rank != 2 || x.shape[1] != K || xs.shape[0] != x.shape[0] || xs.shape[1] != K / 128 ||
y.shape[1] != N || x.stride[1] != 1 || xs.stride[1] != 1 || y.stride[1] != 1 ||
y.shape[0] < 1 || y.shape[0] > INT_MAX)
return RAD_E_SHAPE;
const uint32_t rank = grouped ? 3 : 2;
if (w.rank != rank || ws.rank != rank || w.shape[rank - 2] != N || w.shape[rank - 1] != K ||
ws.shape[rank - 2] != N / 128 || ws.shape[rank - 1] != K / 128 || w.stride[rank - 1] != 1 ||
ws.stride[rank - 1] != 1)
return RAD_E_SHAPE;
Meta m{};
m.ar = x.stride[0];
m.asr = xs.stride[0];
m.yr = y.stride[0];
m.wr = w.stride[rank - 2];
m.sr = ws.stride[rank - 2];
m.T = (int)y.shape[0];
m.N = N;
m.K = K;
if (!grouped) {
if (x.shape[0] != m.T) return RAD_E_SHAPE;
bool done = false;
const int rc = dense_fast(stream, x, xs, w, ws, y, m, &done);
if (done || rc < 0) return rc;
return R4D_EMIT(stream, fp8_f32scale, dim3(N / 64, (m.T + 15) / 16), dim3(128), 0,
(const uint8_t*)x.data, (const float*)xs.data, (const uint8_t*)w.data,
(const float*)ws.data, (uint16_t*)y.data, m);
}
m.experts = r4d_geti_or(a, "n_expert", 0);
m.topk = r4d_geti_or(a, "top_k", 0);
const char* order = r4d_gets(a, "a_order");
m.sorted_a = order && !std::strcmp(order, "sorted");
const auto &wo = a->t[6], &so = a->t[7], &st = a->t[4], &off = a->t[5];
if (m.experts < 2 || m.topk < 1 || r4d_geti_or(a, "N_odd", N) != N ||
r4d_geti_or(a, "K_odd", K) != K || wo.dtype != RAD_F8E4M3 || so.dtype != RAD_F32 ||
wo.rank != 3 || so.rank != 3 || wo.shape[1] != N || wo.shape[2] != K ||
so.shape[1] != N / 128 || so.shape[2] != K / 128 || wo.stride[1] != m.wr ||
so.stride[1] != m.sr || wo.stride[2] != 1 || so.stride[2] != 1 || st.dtype != RAD_I32 ||
off.dtype != RAD_I32 || st.rank != 1 || off.rank != 1 || st.stride[0] != 1 ||
off.stride[0] != 1 || st.shape[0] < m.T || off.shape[0] < m.experts + 1 || !wo.data ||
!so.data || !st.data || !off.data)
return RAD_E_SHAPE;
m.wstep[0] = w.stride[0];
m.wstep[1] = wo.stride[0];
m.sstep[0] = ws.stride[0] * 4;
m.sstep[1] = so.stride[0] * 4;
if (w.shape[0] < (m.experts + 1) / 2 || wo.shape[0] < m.experts / 2) return RAD_E_SHAPE;
/* The small-M form at the MTP layer's gate_up slice up to 384 routed rows: a draft pass routes
* one token, a verify pass a few. On gfx1201 (perfmxf8, cold) it halves the expert-major time
* at one token and gains 3 to 21 % from 2 to 16. Down's K of 256 gains nothing from it (within
* a few percent, a quarter slower at three tokens). */
if (m.experts == 288 && m.topk == 8 && N == 512 && K == 4096 && m.T <= 384)
return R4D_EMIT(stream, fp8_f32scale_small<512>,
dim3(N / 64, (m.T < m.experts ? m.T : m.experts) + 1), dim3(128), 0,
(const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, wo.data,
so.data, (const int*)st.data, (const int*)off.data, (uint16_t*)y.data, m);
/* The expert-major form at every routed-row count. Measured at GLM's TP8 slices: a long K
* (gate_up's 4096) wants the 256 stage, 25 to 40 % ahead of 128, and under 128 routed rows
* four tiles a block on top; at down's K of 256 every variant reads within a few percent of
* the bandwidth, so it keeps 128 over four tiles. */
#define F8_EXPERTS(SK, C) \
R4D_EMIT(stream, (fp8_f32scale_experts<SK, C>), \
dim3((N + 64 * C - 1) / (64 * C), m.experts + 1), dim3(128), 0, \
(const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, wo.data, so.data, \
(const int*)st.data, (const int*)off.data, (uint16_t*)y.data, m)
if (K > 256) return m.T < 128 ? F8_EXPERTS(256, 4) : F8_EXPERTS(256, 1);
return F8_EXPERTS(128, 4);
#undef F8_EXPERTS
}
int dense(const RadArgs* a, RadStream stream) { return body(a, stream, false); }
int grouped(const RadArgs* a, RadStream stream) { return body(a, stream, true); }
}
extern "C" int r4d_rad_fp8_f32scale(const RadArgs* a, RadStream stream) { return dense(a, stream); }
extern "C" int r4d_rad_moe_fp8_f32scale(const RadArgs* a, RadStream stream) {
return grouped(a, stream);
}
extern "C" int r4d_layout_fp8_f32scale(const RadParam*, int, int operand, const RadEncoding* e,
const int* sel, const RadTensor*, int n, RadLayout*) {
if (operand != 2 && operand != 3 && operand != 6 && operand != 7) return RAD_E_UNSUPPORTED;
if (!e || !sel || n != 1 || !rad_enc_is(e, "affine") || e->n_planes != 2 ||
e->plane[0].dtype != RAD_F8E4M3 || e->plane[1].dtype != RAD_F32 ||
e->plane[1].block[0] != 128 || e->plane[1].block[1] != 128 ||
sel[0] != (operand == 3 || operand == 7 ? 1 : 0))
return RAD_E_DTYPE;
return RAD_E_UNSUPPORTED; // Both canonical planes are read without a relayout.
}
+89 -126
View File
@@ -39,6 +39,7 @@
#include "r4d_fp8_lm.h"
#include "r4d_hc_fp8.h"
#include "r4d_enc.h"
#include "r4d_hsimd.h"
#include <algorithm>
#include <cmath>
@@ -75,6 +76,15 @@ void frag_walk(long long N, long long K, Move move) {
}
}
/* frag_walk's forward direction a 16-row tile at a time (r4d_hsimd, by CPU level): the load
* path of every block-FP8 and int8 GEMM weight. */
void frag_tiles(const uint8_t* s, long long N, long long K, uint8_t* d) {
const long long ksuper = K / r4d_fp8::kSuperK;
for (long long rt = 0; rt < N / r4d_fp8::kFragRows; ++rt)
r4d_hsimd::fp8_frag_tile(s + rt * r4d_fp8::kFragRows * K, K, ksuper,
d + rt * r4d_fp8::kFragRows * K);
}
struct FGeom { long long N, K, sn, sk; };
int fgeom(const RadParam* p, int n_p, FGeom* g) {
@@ -158,71 +168,8 @@ bool fp8_block_enc(const RadEncoding* e) {
return r4d_enc::affine(e, RAD_F8E4M3, RAD_BF16, R4D_FP8_BLOCK, R4D_FP8_BLOCK);
}
int fp8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* pl, int n, RadLayout* out, bool frag) {
if (!out || !pl) return RAD_E_INVAL;
FGeom g;
const int rc = fgeom(p, n_p, &g);
if (rc != RAD_OK) return rc;
if (operand != FL_B && operand != FL_BSCALE) return RAD_E_UNSUPPORTED;
if (!fp8_block_enc(enc)) return RAD_E_DTYPE;
if (operand == FL_BSCALE) {
if (!r4d_enc::selects(enc, sel, n, "scale") || !r4d_enc::dims(pl[0], g.sn, g.sk))
return RAD_E_SHAPE;
return RAD_E_UNSUPPORTED; /* the checkpoint's own bf16 plane */
}
if (!r4d_enc::selects(enc, sel, n, "codes") || !r4d_enc::dims(pl[0], g.N, g.K))
return RAD_E_SHAPE;
if (!frag) return RAD_E_UNSUPPORTED; /* row-major, as the matvec reads it */
if (g.K % R4D_FP8_SUPER_K || g.N % r4d_fp8::kFragRows) return RAD_E_SHAPE;
ffill(out, "r4d.fp8.w.frag64", RAD_F8E4M3, g.N, g.K, r4d_fp8::frag_bytes(g.N, g.K));
return RAD_OK;
}
} /* namespace */
extern "C" int r4d_rad_layout_fp8_block(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
return fp8_enc_layout(p, n_p, operand, enc, sel, pl, n, out, true);
}
extern "C" int r4d_rad_layout_fp8_rowmajor(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
return fp8_enc_layout(p, n_p, operand, enc, sel, pl, n, out, false);
}
extern "C" int r4d_rad_relayout_fp8_block(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) {
RadLayout L;
const int rc = fp8_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, true);
if (rc != RAD_OK) return rc;
if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
const uint8_t* s = (const uint8_t*)pl[0].data;
uint8_t* d = (uint8_t*)dst;
frag_walk(pl[0].shape[0], pl[0].shape[1],
[&](int64_t at, int64_t from) { std::memcpy(d + at, s + from, 8); });
return RAD_OK;
}
extern "C" int r4d_rad_unrelayout_fp8_block(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const void* src, int64_t src_bytes,
const RadTensor* pl, int n) {
RadLayout L;
const int rc = fp8_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, true);
if (rc != RAD_OK) return rc;
if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
const uint8_t* s = (const uint8_t*)src;
uint8_t* d = (uint8_t*)pl[0].data;
frag_walk(pl[0].shape[0], pl[0].shape[1],
[&](int64_t at, int64_t from) { std::memcpy(d + from, s + at, 8); });
return RAD_OK;
}
/* ---- the int8 twin: i8 codes in the same fragment order as E4M3, with a bf16 scale per row per
* 128 K.
*
@@ -250,20 +197,49 @@ bool i8_codes(const RadEncoding* enc, const char* tr) {
return r4d_enc::affine(enc, RAD_I8, RAD_BF16, 1, R4D_FP8_BLOCK, RAD_DT_INVALID, tr);
}
/* IQ8R: int8 codes rotated 128 wide, a u8 scale per (row, 256) under one bf16 scale a row
* (libquant's `codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128`). A weight
* element is code * scale * scale.1. */
bool iq8r_codes(const RadEncoding* enc) {
if (!enc || !rad_enc_is(enc, "affine") || enc->n_planes != 3 ||
std::strncmp(enc->transform, "fwht128", RAD_ENC_STR) != 0)
return false;
if (enc->plane[0].dtype != RAD_I8 || enc->plane[0].block[1] != 1) return false;
const int s = rad_enc_find(enc, "scale"), s2 = rad_enc_find(enc, "scale.1");
return s >= 0 && enc->plane[s].dtype == RAD_U8 && enc->plane[s].kind == RAD_PLANE_TILED &&
enc->plane[s].block[0] == 1 && enc->plane[s].block[1] == R4D_I8_GROUP_WIDE &&
s2 >= 0 && enc->plane[s2].dtype == RAD_BF16 && enc->plane[s2].kind == RAD_PLANE_TILED &&
enc->plane[s2].block[0] == 1 && enc->plane[s2].block[1] == 0;
}
/* The scale group is 128, or 256 for IQ8R (the rotation stays 128 wide). The kernels take it as a
* template argument, so no other width has a layout. Either way the kernels read one bf16 scale
* per (row, group), tile-major: IQ8R's is the product of its two stored levels, rounded once. */
int i8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
if (!out || !pl) return RAD_E_INVAL;
FGeom g;
const int rc = fgeom(p, n_p, &g);
if (rc != RAD_OK) return rc;
g.N = r4d_pgeti_or(p, n_p, "N", 0);
g.K = r4d_pgeti_or(p, n_p, "K", 0);
const long long group = r4d_pgeti_or(p, n_p, "group", R4D_FP8_BLOCK);
if (g.N <= 0 || g.K <= 0 || (group != R4D_FP8_BLOCK && group != R4D_I8_GROUP_WIDE))
return RAD_E_SHAPE;
g.sn = (g.N + R4D_FP8_BLOCK - 1) / R4D_FP8_BLOCK;
g.sk = (g.K + group - 1) / group;
if (operand != FL_B && operand != FL_BSCALE) return RAD_E_UNSUPPORTED;
const bool rot = i8_rotated(p, n_p);
if (!i8_codes(enc, rot ? "fwht128" : "")) return RAD_E_DTYPE;
const bool wide = group == R4D_I8_GROUP_WIDE;
if (wide ? !(rot && iq8r_codes(enc)) : !i8_codes(enc, rot ? "fwht128" : "")) return RAD_E_DTYPE;
if (operand == FL_BSCALE) {
if (!r4d_enc::selects(enc, sel, n, "scale") || !r4d_enc::dims(pl[0], g.N, g.sk))
if (wide) {
if (!r4d_enc::selects(enc, sel, n, "scale", "scale.1") ||
!r4d_enc::dims(pl[0], g.N, g.sk) || !r4d_enc::dims(pl[1], g.N, 1))
return RAD_E_SHAPE;
} else if (!r4d_enc::selects(enc, sel, n, "scale") || !r4d_enc::dims(pl[0], g.N, g.sk)) {
return RAD_E_SHAPE;
}
if (g.N % r4d_fp8::kFragRows) return RAD_E_SHAPE;
ffill(out, "r4d.i8.s.t16", RAD_BF16, g.N, g.sk, g.N * g.sk * 2);
ffill(out, wide ? "r4d.iq8r.s.t16" : "r4d.i8.s.t16", RAD_BF16, g.N, g.sk, g.N * g.sk * 2);
return RAD_OK;
}
if (!r4d_enc::selects(enc, sel, n, "codes") || !r4d_enc::dims(pl[0], g.N, g.K))
@@ -281,6 +257,25 @@ extern "C" int r4d_rad_layout_i8_block(const RadParam* p, int n_p, int operand,
return i8_enc_layout(p, n_p, operand, enc, sel, pl, n, out);
}
/* The same int8 weight at one scale per (row, 128 of K), both planes row-major as stored: what
* the grouped expert GEMM reads, which stages a run's rows through LDS and gains nothing from a
* permutation. An expert then goes from the container or a host pool to the kernel unchanged. */
extern "C" int r4d_rad_layout_i8_rowmajor(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout*) {
if (!pl) return RAD_E_INVAL;
FGeom g;
const int rc = fgeom(p, n_p, &g);
if (rc != RAD_OK) return rc;
if (operand != FL_B && operand != FL_BSCALE) return RAD_E_UNSUPPORTED;
if (!i8_codes(enc, i8_rotated(p, n_p) ? "fwht128" : "")) return RAD_E_DTYPE;
if (operand == FL_BSCALE
? !r4d_enc::selects(enc, sel, n, "scale") || !r4d_enc::dims(pl[0], g.N, g.sk)
: !r4d_enc::selects(enc, sel, n, "codes") || !r4d_enc::dims(pl[0], g.N, g.K))
return RAD_E_SHAPE;
return RAD_E_UNSUPPORTED; /* the stored plane, as it is */
}
extern "C" int r4d_rad_relayout_i8_block(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, void* dst,
@@ -291,17 +286,26 @@ extern "C" int r4d_rad_relayout_i8_block(const RadParam* p, int n_p, int operand
if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
if (operand == FL_BSCALE) {
const long long N = pl[0].shape[0], nkb = pl[0].shape[1];
const uint16_t* s = (const uint16_t*)pl[0].data;
uint16_t* d = (uint16_t*)dst;
if (n == 2) {
/* IQ8R: the two levels' product, the one bf16 the fold multiplies by. */
if (!pl[1].data) return RAD_E_SHAPE;
for (long long r = 0; r < N; ++r) {
const uint8_t* s1 = r4d_enc::row(pl[0], r);
const float s2 = rad_load_f32(pl[1].data, RAD_BF16, r);
for (long long kb = 0; kb < nkb; ++kb)
rad_store_f32(d, RAD_BF16, ((r / 16) * nkb + kb) * 16 + r % 16,
(float)s1[kb] * s2);
}
return RAD_OK;
}
const uint16_t* s = (const uint16_t*)pl[0].data;
for (long long r = 0; r < N; ++r)
for (long long kb = 0; kb < nkb; ++kb)
d[((r / 16) * nkb + kb) * 16 + r % 16] = s[r * nkb + kb];
return RAD_OK;
}
const uint8_t* s = (const uint8_t*)pl[0].data;
uint8_t* d = (uint8_t*)dst;
frag_walk(pl[0].shape[0], pl[0].shape[1],
[&](int64_t at, int64_t from) { std::memcpy(d + at, s + from, 8); });
frag_tiles((const uint8_t*)pl[0].data, pl[0].shape[0], pl[0].shape[1], (uint8_t*)dst);
return RAD_OK;
}
@@ -314,6 +318,8 @@ extern "C" int r4d_rad_unrelayout_i8_block(const RadParam* p, int n_p, int opera
if (rc != RAD_OK) return rc;
if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
if (operand == FL_BSCALE) {
/* IQ8R's product does not come apart into its two stored levels. */
if (n == 2) return RAD_E_UNSUPPORTED;
const long long N = pl[0].shape[0], nkb = pl[0].shape[1];
const uint16_t* s = (const uint16_t*)src;
uint16_t* d = (uint16_t*)pl[0].data;
@@ -360,55 +366,6 @@ int lm_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
}
} /* namespace */
extern "C" int r4d_rad_layout_fp8_logits(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
return lm_enc_layout(p, n_p, operand, enc, sel, pl, n, out, nullptr);
}
extern "C" int r4d_rad_relayout_fp8_logits(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, void* dst,
int64_t dst_bytes) {
RadLayout L;
FGeom g;
const int rc = lm_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g);
if (rc != RAD_OK) return rc;
if (dst_bytes != L.bytes || !pl[0].data || !pl[1].data) return RAD_E_SHAPE;
const long long stride = r4d_fp8::lm_row_bytes(g.K);
const uint8_t* codes = (const uint8_t*)pl[0].data;
const uint16_t* sc = (const uint16_t*)pl[1].data;
uint8_t* d = (uint8_t*)dst;
std::memset(d, 0, (size_t)dst_bytes);
for (long long r = 0; r < g.N; ++r) {
uint8_t* row = d + r * stride;
std::memcpy(row, codes + r * g.K, (size_t)g.K);
std::memcpy(row + g.K, sc + (r / R4D_FP8_BLOCK) * g.sk, (size_t)(2 * g.sk));
}
return RAD_OK;
}
extern "C" int r4d_rad_unrelayout_fp8_logits(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const void* src, int64_t src_bytes,
const RadTensor* pl, int n) {
RadLayout L;
FGeom g;
const int rc = lm_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g);
if (rc != RAD_OK) return rc;
if (src_bytes != L.bytes || !pl[0].data || !pl[1].data) return RAD_E_SHAPE;
const long long stride = r4d_fp8::lm_row_bytes(g.K);
const uint8_t* s = (const uint8_t*)src;
uint8_t* codes = (uint8_t*)pl[0].data;
uint16_t* sc = (uint16_t*)pl[1].data;
for (long long r = 0; r < g.N; ++r) {
std::memcpy(codes + r * g.K, s + r * stride, (size_t)g.K);
if (r % R4D_FP8_BLOCK == 0)
std::memcpy(sc + (r / R4D_FP8_BLOCK) * g.sk, s + r * stride + g.K, (size_t)(2 * g.sk));
}
return RAD_OK;
}
extern "C" int r4d_rad_layout_i8_logits(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
@@ -428,12 +385,15 @@ extern "C" int r4d_rad_relayout_i8_logits(const RadParam* p, int n_p, int operan
const uint8_t* codes = (const uint8_t*)pl[0].data;
const uint16_t* sc = (const uint16_t*)pl[1].data;
uint8_t* d = (uint8_t*)dst;
std::memset(d, 0, (size_t)dst_bytes);
/* Each row written once: its codes, its scales, then the padding cleared. */
const long long used = g.K + 2 * g.sk;
for (long long r = 0; r < g.N; ++r) {
uint8_t* row = d + r * stride;
std::memcpy(row, codes + r * g.K, (size_t)g.K);
std::memcpy(row + g.K, sc + r * g.sk, (size_t)(2 * g.sk));
if (stride > used) std::memset(row + used, 0, (size_t)(stride - used));
}
if (dst_bytes > g.N * stride) std::memset(d + g.N * stride, 0, (size_t)(dst_bytes - g.N * stride));
return RAD_OK;
}
@@ -478,10 +438,13 @@ int hcrows_relayout(const HGeom& g, const RadTensor* pl, void* dst, int64_t dst_
const uint8_t* codes = (const uint8_t*)pl[0].data;
const float* sc = (const float*)pl[1].data;
uint8_t* d = (uint8_t*)dst;
std::memset(d, 0, (size_t)dst_bytes);
/* Each row written once: its codes, its scales, then the padding cleared. */
const long long used = g.K + 4 * ng;
for (long long r = 0; r < g.rows; ++r) {
std::memcpy(d + r * stride, codes + r * g.K, (size_t)g.K);
std::memcpy(d + r * stride + g.K, sc + r * ng, (size_t)(4 * ng));
uint8_t* row = d + r * stride;
std::memcpy(row, codes + r * g.K, (size_t)g.K);
std::memcpy(row + g.K, sc + r * ng, (size_t)(4 * ng));
if (stride > used) std::memset(row + used, 0, (size_t)(stride - used));
}
return RAD_OK;
}
+12 -159
View File
@@ -316,39 +316,6 @@ extern "C" int r4d_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t pre
}
}
/* ==========================================================================================
* swiglu_clamped_quant_fp8 -- GLM's clipped SwiGLU and the fp8 quantiser in one pass.
* (kernel: libr4d/r4d_glm.hip, swiglu_clamped_quant_kernel)
*
* Operands: [0] gate_up [1] q [2] scale [3] out_bf16?
*
* Each element is `swiglu_clamped_bf16`'s expression, rounded to bf16 once, and the codes are
* quant_act_fp8's over that rounded value, so the chain is the two rows with the product between.
*/
extern "C" int r4d_fuse_swiglu_clamped_quant_fp8(const RadParam* p, int n_p, uint64_t present,
int step, RadFuseStep* out) {
if (!out) return RAD_E_INVAL;
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED;
const int16_t mid = RAD_FUSE_HAS(present, 3) ? (int16_t)3 : RAD_FUSE_TMP(0);
switch (step) {
case 0: {
Step s(out, "swiglu_clamped");
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "limit").mirror(p, n_p, "dtype");
return s.wire({ 0, mid }); /* gate_up, y */
}
case 1: {
Step s(out, "quant_act_fp8");
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "group").mirror(p, n_p, "dtype");
return s.wire({ mid, 1, 2 }); /* x, q, scale */
}
default:
return RAD_E_NOTFOUND;
}
}
/* ==========================================================================================
* router_sigmoid_topk_scatter -- GLM's selection, the sort over its ids and the shared gate's fill.
* (kernel: libr4d/r4d_glm.hip, router_sigmoid_scatter_kernel)
@@ -471,129 +438,6 @@ extern "C" int r4d_fuse_gate_quant_fp8(const RadParam* p, int n_p, uint64_t pres
}
}
/* ==========================================================================================
* gemm_nt_q_gated -- the narrow fp8 GEMM with the SwiGLU and the quantiser in its epilogue.
* (row: gemm_fp8a8_gated_nt_m16; shim: r4d_gemm_fp8a8.hip)
*
* Operands: [0] a [1] a_scale [2] b [3] b_scale [4] q [5] scale [6] out_bf16?
*
* Byte-identical to gemm_nt_q followed by gated_quant_fp8: the accumulator is rounded to bf16
* before the gate and the multiply, and the amax is an fmaxf reduction, exact under any regrouping
* across waves. Both steps are libr4d rows.
*
* TMP(0) is the [M, N] bf16 plane between the GEMM and the quantiser, which the fusion never
* writes. Its extents come from step 0's `opd_shape` (the ABI rule for temporaries):
* r4d_shape_gemm_nt_q gives [M, N] for operand 4 and r4d_shape_gated_quant_fp8 gives [M, 2n] for
* operand 0, the same plane since `n` = N/2.
*
* Two parameters are not copies:
*
* `n` is N/2. The fused `N` is the weight's rows, gate then up, twice the output width
* (hence a schema of its own rather than a flag on `gemm_nt_q`).
*
* `dtype` is "fp8a8" on the GEMM step and "bf16" on the quantiser step. For a GEMM it names the
* operand combination, for an activation op the width of its input: cGemmNtQGatedFp8
* has `C_IN("dtype", "fp8a8")`, cGatedQuantFp8 `C_IN("dtype", "bf16")`. Copying the
* fused value fails to resolve only because no other row declares that combination.
*
* `a_sum` (asymmetric integer grids) and `b_ref` (mxfp4) follow `gemm_nt_q`'s `y`; an fp8 grid has
* neither, and r4d_shape_gemm_nt_q describes both as absent. They are wired RAD_FUSE_NONE, not
* omitted, to keep one entry per schema operand.
*/
extern "C" int r4d_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t present, int step,
RadFuseStep* out) {
if (!out) return RAD_E_INVAL;
const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K");
const char* dt = r4d_pgets(p, n_p, "dtype");
if (M <= 0 || N <= 0 || K <= 0 || N % 2) return RAD_E_UNSUPPORTED;
if (pi(p, n_p, "group", R4D_FP8_BLOCK) != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED;
if (!dt || std::strcmp(dt, "fp8a8")) return RAD_E_UNSUPPORTED;
/* Required on this op, unlike on the quantiser, because only silu is compiled; an optional
* parameter would let the row resolve for a gate it cannot serve. */
if (!act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED;
switch (step) {
case 0: {
/* The GEMM over the whole [N, K] gate_up weight, into the temporary plane. */
Step s(out, "gemm_nt_q");
s.mirror(p, n_p, "M").mirror(p, n_p, "N").mirror(p, n_p, "K")
.mirror(p, n_p, "group").mirror(p, n_p, "dtype");
/* a, a_scale, b, b_scale, y, a_sum, b_ref */
return s.wire({ 0, 1, 2, 3, RAD_FUSE_TMP(0), RAD_FUSE_NONE, RAD_FUSE_NONE });
}
case 1: {
/* Gate, multiply and codes over the accumulator plane, at half its width. */
Step s(out, "gated_quant_fp8");
s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).mirror(p, n_p, "group")
.pstr("dtype", "bf16").mirror(p, n_p, "act");
return s.wire({ RAD_FUSE_TMP(0), 4, 5, 6 }); /* gate_up, q, scale, out_bf16 */
}
default:
return RAD_E_NOTFOUND;
}
}
/* ==========================================================================================
* gemm_nt_q_gated_mx -- the same fold over an OCP-MXFP4 weight.
* (rows: gemm_mxfp4a8_gated_gemv, M <= 8, and gemm_mxfp4a8_gated_gemv_wide, 9..64; kernels:
* libr4d/r4d_gemm_mxfp4a8_gemv.hip, the gated forms. The chain's gemm_nt_q resolves to gemv and
* gemv_wide in those bands, the rows each form is byte-identical to.)
*
* Operands: [0] a [1] a_scale [2] b [3] b_scale [4] b_ref [5] q [6] scale [7] out_bf16
*
* The GEMM step is gemm_nt_q at dtype mxfp4a8 with `b_ref` in its last operand. `group` is the
* weight's 32 on the GEMM and the activation's 128 on the quantiser, so the quantiser's is set, not
* mirrored. At act gelu_tanh the chain is three steps, gelu_mul into a second temporary and
* quant_act_fp8 over it; that form refuses `out_bf16` (the shim), so operand 7 is not wired.
*/
extern "C" int r4d_fuse_gemm_nt_q_gated_mx(const RadParam* p, int n_p, uint64_t present, int step,
RadFuseStep* out) {
if (!out) return RAD_E_INVAL;
const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K");
const char* dt = r4d_pgets(p, n_p, "dtype");
if (M <= 0 || N <= 0 || K <= 0 || N % 2) return RAD_E_UNSUPPORTED;
if (pi(p, n_p, "group", 32) != 32) return RAD_E_UNSUPPORTED;
if (!dt || std::strcmp(dt, "mxfp4a8")) return RAD_E_UNSUPPORTED;
const bool gelu = act_is(p, n_p, "silu", "gelu_tanh");
if (!gelu && !act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED;
/* The GeGLU chain leaves its bf16 plane in a temporary, so a caller asking for out_bf16 there
* has no chain (the shim refuses the operand too). */
if (gelu && RAD_FUSE_HAS(present, 7)) return RAD_E_UNSUPPORTED;
if (step == 0) {
Step s(out, "gemm_nt_q");
s.mirror(p, n_p, "M").mirror(p, n_p, "N").mirror(p, n_p, "K")
.mirror(p, n_p, "group").mirror(p, n_p, "dtype");
/* a, a_scale, b, b_scale, y, a_sum, b_ref */
return s.wire({ 0, 1, 2, 3, RAD_FUSE_TMP(0), RAD_FUSE_NONE, 4 });
}
if (gelu) {
if (step == 1) {
Step s(out, "gelu_mul");
s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pstr("dtype", "bf16");
return s.wire({ RAD_FUSE_TMP(0), RAD_FUSE_TMP(1) }); /* gate_up, y */
}
if (step == 2) {
Step s(out, "quant_act_fp8");
s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pint("group", 128)
.pstr("dtype", "bf16");
return s.wire({ RAD_FUSE_TMP(1), 5, 6 }); /* x, q, scale */
}
return RAD_E_NOTFOUND;
}
switch (step) {
case 1: {
Step s(out, "gated_quant_fp8");
s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pint("group", 128)
.pstr("dtype", "bf16").mirror(p, n_p, "act");
return s.wire({ RAD_FUSE_TMP(0), 5, 6, 7 }); /* gate_up, q, scale, out_bf16 */
}
default:
return RAD_E_NOTFOUND;
}
}
/* ==========================================================================================
* gemm_nt_q_gated at i8a8h -- the same fold over an IQR gate_up weight (r4d_iqr.h) under the
* rotated int8 trunk. (row: gemm_iqr_gated, M <= 16; kernel: libr4d/r4d_gemm_iqr.hip, the gated
@@ -824,8 +668,8 @@ extern "C" int r4d_fuse_add_rmsnorm(const RadParam* p, int n_p, uint64_t present
* in-place pair the fold replaces. Its rows are attn_paged's (token, head) pairs, so its `M` is the
* band's query rows times the head count (a bound, which is how its shim reads it) and its `n` is
* `head_dim`. */
extern "C" int r4d_fuse_attn_paged_gate_quant(const RadParam* p, int n_p, uint64_t present,
int step, RadFuseStep* out) {
static int fuse_attn_paged_gate(const RadParam* p, int n_p, uint64_t present, int step,
RadFuseStep* out, const char* gate_op) {
if (!out) return RAD_E_INVAL;
auto opt = [present](int i) { return opt_opd(present, i); };
const int64_t q_len = pi(p, n_p, "q_len"), nh = pi(p, n_p, "n_head");
@@ -842,7 +686,7 @@ extern "C" int r4d_fuse_attn_paged_gate_quant(const RadParam* p, int n_p, uint64
return s.wire({ 0, 1, 2, 3, opt(4), opt(5), opt(6), 7 });
}
case 1: {
Step s(out, "gate_quant_fp8");
Step s(out, gate_op);
s.pint("M", (long long)(seqs * q_len * nh)).pint("n", (long long)hd)
.mirror(p, n_p, "group").pstr("dtype", "bf16").mirror(p, n_p, "act");
return s.wire({ 8, 7, 9, 10, 7 }); /* gate, x, q, scale, out_bf16 */
@@ -851,6 +695,15 @@ extern "C" int r4d_fuse_attn_paged_gate_quant(const RadParam* p, int n_p, uint64
return RAD_E_NOTFOUND;
}
}
extern "C" int r4d_fuse_attn_paged_gate_quant(const RadParam* p, int n_p, uint64_t present,
int step, RadFuseStep* out) {
return fuse_attn_paged_gate(p, n_p, present, step, out, "gate_quant_fp8");
}
/* attn_paged_gate_had_quant -- the same two steps with gate_had_quant_i8g as the second. */
extern "C" int r4d_fuse_attn_paged_gate_had_quant(const RadParam* p, int n_p, uint64_t present,
int step, RadFuseStep* out) {
return fuse_attn_paged_gate(p, n_p, present, step, out, "gate_had_quant_i8g");
}
/* ==========================================================================================
* ar_gather_hc_write -- moe_gather, then ar_hc_write.
+295 -190
View File
@@ -36,7 +36,7 @@
#include "r4d_ar_seq.h" // the all-reduce sequence step the fused all-reduce + norm takes
#include "r4d_fp8_args.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_chain.h" // the chained forms of the rotated int8 producers
#include "r4d_common.h" // r4d_act_threads: the workgroup width, shared with the int8 path
#include "r4d_fwht.h" // the in-register rotation the `_had_` forms put before the absmax
#include "r4d_q8.h" // the 8-bit codes: E4M3, or int8 for an int8 trunk linear
@@ -106,6 +106,34 @@ __device__ __forceinline__ void quant_group(const float v[4], float* __restrict_
if (c0 < n) *(uint32_t*)(q + c0) = pk;
}
// One scale group of SUB 128-column blocks (SUB 2: IQ8R's 256-wide group, int8 only): `v[h]` are
// the lane's four values of block h, already rotated where the form rotates (the rotation stays 128
// wide). One amax over the whole group, one scale, then each block's codes at its own `c0[h]`.
template <bool I8, uint32_t SUB>
__device__ __forceinline__ void quant_groups(const float (&v)[SUB][4], float* __restrict__ s,
uint8_t* __restrict__ q, size_t s_at,
const uint32_t (&c0)[SUB], uint32_t n, uint32_t lane) {
static_assert(SUB == 1 || (SUB == 2 && I8), "a 256 group is the int8 quantiser's");
if constexpr (SUB == 1) {
quant_group<I8>(v[0], s, q, s_at, c0[0], n, lane);
} else {
float m = 0.0f;
#pragma unroll
for (uint32_t h = 0; h < SUB; ++h)
m = fmaxf(m, fmaxf(fmaxf(fabsf(v[h][0]), fabsf(v[h][1])),
fmaxf(fabsf(v[h][2]), fabsf(v[h][3]))));
m = wave_max(m);
const float sc = m > 0.0f ? m * (1.0f / q8_top<I8>()) : 1.0f;
if (lane == 0) s[s_at] = sc;
const float inv = 1.0f / sc;
#pragma unroll
for (uint32_t h = 0; h < SUB; ++h) {
const uint32_t pk = q8_pack4<I8>(v[h][0], v[h][1], v[h][2], v[h][3], inv);
if (c0[h] < n) *(uint32_t*)(q + c0[h]) = pk;
}
}
}
// Pass two of every norm kernel here: each wave takes a 128-column group and each lane four
// consecutive columns, so the group's amax is a wave reduction and the store a single dword. `nr`
// is the row the norm is taken of, already in memory (see the bit-identity note above). Shared so
@@ -116,46 +144,58 @@ __device__ __forceinline__ void quant_group(const float v[4], float* __restrict_
// together. r4d_quant_act_fp8's kernel has the same mapping, rotation and rounding, so the codes
// are the norm + had_quant_act_i8g pair's bytes. `y` still receives the unrotated norm output.
// The launchers require n % 128 == 0, so no rotated group contains padding.
template <bool WF32, uint32_t THR, bool HI8 = false>
// SUB 2 (with HI8) is IQ8R's group: a wave takes both 128-column blocks of a 256-wide group and
// `nkb` counts groups.
template <bool WF32, uint32_t THR, bool HI8 = false, uint32_t SUB = 1>
__device__ __forceinline__ void norm_quant_row(
const uint16_t* __restrict__ nr, const void* __restrict__ w, uint16_t* __restrict__ yr,
uint8_t* __restrict__ qr, float* __restrict__ s, size_t s_row, uint32_t n, uint32_t nkb,
float rs, float wadd) {
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
for (uint32_t kb = wave; kb < nkb; kb += THR / kWave) {
const uint32_t c0 = kb * kGroup + lane * 4u;
float v[4] = {0.0f, 0.0f, 0.0f, 0.0f};
// One branch for all four columns: every launcher requires n % 4 == 0, so a lane's columns
// are all in or all out. Per-column guards would serialise the loads.
if (c0 < n) {
float g[4];
uint16_t x[4];
float v[SUB][4];
uint32_t c0[SUB];
#pragma unroll
for (int j = 0; j < 4; ++j) {
g[j] = WF32 ? ((const float*)w)[c0 + j] : bf2f(((const uint16_t*)w)[c0 + j]);
x[j] = nr[c0 + j];
}
for (uint32_t b = 0; b < SUB; ++b) {
c0[b] = (kb * SUB + b) * kGroup + lane * 4u;
#pragma unroll
for (int j = 0; j < 4; ++j) {
// The bf16 round trip is deliberate: the unfused quantiser reads these bytes.
const uint16_t h = f2bf(bf2f(x[j]) * rs * (g[j] + wadd));
if (yr) yr[c0 + j] = h;
v[j] = bf2f(h);
for (int j = 0; j < 4; ++j) v[b][j] = 0.0f;
// One branch for all four columns: every launcher requires n % 4 == 0, so a lane's
// columns are all in or all out. Per-column guards would serialise the loads.
if (c0[b] < n) {
float g[4];
uint16_t x[4];
#pragma unroll
for (int j = 0; j < 4; ++j) {
g[j] = WF32 ? ((const float*)w)[c0[b] + j]
: bf2f(((const uint16_t*)w)[c0[b] + j]);
x[j] = nr[c0[b] + j];
}
#pragma unroll
for (int j = 0; j < 4; ++j) {
// The bf16 round trip is deliberate: the unfused quantiser reads these bytes.
const uint16_t h = f2bf(bf2f(x[j]) * rs * (g[j] + wadd));
if (yr) yr[c0[b] + j] = h;
v[b][j] = bf2f(h);
}
}
if constexpr (HI8) r4d_fwht_wave<(int)kGroup>(v[b], (int)lane);
}
if constexpr (HI8) r4d_fwht_wave<(int)kGroup>(v, (int)lane);
quant_group<HI8>(v, s, qr, s_row + kb, c0, n, lane);
quant_groups<HI8, SUB>(v, s, qr, s_row + kb, c0, n, lane);
}
}
// ---------------------------------------------------------------------------- rmsnorm -> quant
// One block per row. Pass one is the block-wide sum of squares; pass two is norm_quant_row.
template <bool WF32, bool RES, uint32_t THR, bool HI8 = false>
__global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
uint16_t* __restrict__ y, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n,
uint32_t nkb, float eps, float wadd, uint32_t x_ld, uint32_t r_ld, uint32_t y_ld,
uint32_t q_ld, uint32_t s_ld) {
// One block per row. Pass one is the block-wide sum of squares; pass two is norm_quant_row. The
// body of rmsnorm_quant_fp8_kernel and of its chained form r4dchain_rmsnorm_quant (r4d_chain.h); no
// block returns early.
#define R4D_RQ_PARAMS const uint16_t* __restrict__ x, uint16_t* __restrict__ res, \
const void* __restrict__ w, uint16_t* __restrict__ y, uint8_t* __restrict__ q, \
float* __restrict__ s, uint32_t n, uint32_t nkb, float eps, float wadd, uint32_t x_ld, \
uint32_t r_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld
#define R4D_RQ_ARGS x, res, w, y, q, s, n, nkb, eps, wadd, x_ld, r_ld, y_ld, q_ld, s_ld
template <bool WF32, bool RES, uint32_t THR, bool HI8 = false, uint32_t SUB = 1>
__device__ __forceinline__ void rmsnorm_quant_fp8_body(R4D_RQ_PARAMS) {
__shared__ float lds[THR / kWave];
const uint32_t row = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)row * x_ld;
@@ -200,9 +240,22 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
}
const float rs = rsqrtf(block_sum<THR / kWave>(ss, lds) / (float)n + eps);
norm_quant_row<WF32, THR, HI8>(nr, w, y ? y + (size_t)row * y_ld : nullptr,
q + (size_t)row * q_ld, s, (size_t)row * s_ld, n, nkb, rs, wadd);
norm_quant_row<WF32, THR, HI8, SUB>(nr, w, y ? y + (size_t)row * y_ld : nullptr,
q + (size_t)row * q_ld, s, (size_t)row * s_ld, n, nkb, rs,
wadd);
}
template <bool WF32, bool RES, uint32_t THR, bool HI8 = false, uint32_t SUB = 1>
__global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(R4D_RQ_PARAMS) {
rmsnorm_quant_fp8_body<WF32, RES, THR, HI8, SUB>(R4D_RQ_ARGS);
}
template <bool WF32, bool RES, uint32_t THR, bool HI8 = false, uint32_t SUB = 1>
__global__ __launch_bounds__(THR) void r4dchain_rmsnorm_quant(R4D_RQ_PARAMS) {
r4d_chain_wait();
rmsnorm_quant_fp8_body<WF32, RES, THR, HI8, SUB>(R4D_RQ_ARGS);
r4d_chain_done();
}
#undef R4D_RQ_ARGS
#undef R4D_RQ_PARAMS
// ---------------------------------------------------------------------------- gate -> quant
// silu(gate) * up or sigmoid(gate) * up, then the same quantiser. No row reduction, so no first
@@ -215,11 +268,14 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
//
// The launcher sizes the workgroup to the row's groups (capped at r4d_act_threads' width) and the
// kernel reads the width from blockDim, so a narrow row does not leave most waves idle.
template <int ACT, bool ROT = false, bool I8 = false>
__device__ __forceinline__ void gated_quant_fp8_kernel_body(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q,
float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t gu_ld, uint32_t y_ld,
uint32_t q_ld, uint32_t s_ld) {
// SUB 2 (rotated int8 only) is IQ8R's 256-wide group, as in norm_quant_row.
// The body of gated_quant_fp8_kernel and of its chained form r4dchain_gated_quant; no block returns
// early.
#define R4D_GQ_PARAMS const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, \
uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t gu_ld, \
uint32_t y_ld, uint32_t q_ld, uint32_t s_ld
template <int ACT, bool ROT = false, bool I8 = false, uint32_t SUB = 1>
__device__ __forceinline__ void gated_quant_fp8_body(R4D_GQ_PARAMS) {
const uint32_t row = blockIdx.x;
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
const uint16_t* __restrict__ gr = gu + (size_t)row * gu_ld;
@@ -227,48 +283,47 @@ __device__ __forceinline__ void gated_quant_fp8_kernel_body(
uint8_t* __restrict__ qr = q + (size_t)row * q_ld;
for (uint32_t kb = wave; kb < nkb; kb += blockDim.x / kWave) {
const uint32_t c0 = kb * kGroup + lane * 4u;
float v[4] = {0.0f, 0.0f, 0.0f, 0.0f};
// One branch for all four columns; see norm_quant_row.
if (c0 < n) {
uint16_t gb[4], ub[4];
float v[SUB][4];
uint32_t c0[SUB];
#pragma unroll
for (int j = 0; j < 4; ++j) {
gb[j] = gr[c0 + j];
ub[j] = gr[n + c0 + j];
}
for (uint32_t b = 0; b < SUB; ++b) {
c0[b] = (kb * SUB + b) * kGroup + lane * 4u;
#pragma unroll
for (int j = 0; j < 4; ++j) {
const float g = bf2f(gb[j]);
const float a = ACT == 0 ? g / (1.0f + expf(-g)) : 1.0f / (1.0f + expf(-g));
const uint16_t h = f2bf(a * bf2f(ub[j]));
if (yr) yr[c0 + j] = h;
v[j] = bf2f(h);
for (int j = 0; j < 4; ++j) v[b][j] = 0.0f;
// One branch for all four columns; see norm_quant_row.
if (c0[b] < n) {
uint16_t gb[4], ub[4];
#pragma unroll
for (int j = 0; j < 4; ++j) {
gb[j] = gr[c0[b] + j];
ub[j] = gr[n + c0[b] + j];
}
#pragma unroll
for (int j = 0; j < 4; ++j) {
const float g = bf2f(gb[j]);
const float a = ACT == 0 ? g / (1.0f + expf(-g)) : 1.0f / (1.0f + expf(-g));
const uint16_t h = f2bf(a * bf2f(ub[j]));
if (yr) yr[c0[b] + j] = h;
v[b][j] = bf2f(h);
}
}
// The rotated launcher requires n % 128 == 0, so no rotated group contains padding.
if constexpr (ROT) r4d_fwht_wave<(int)kGroup>(v[b], (int)lane);
}
// The rotated launcher requires n % 128 == 0, so no rotated group contains padding.
if constexpr (ROT) r4d_fwht_wave<(int)kGroup>(v, (int)lane);
quant_group<I8>(v, s, qr, (size_t)row * s_ld + kb, c0, n, lane);
quant_groups<I8, SUB>(v, s, qr, (size_t)row * s_ld + kb, c0, n, lane);
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <int ACT, bool ROT = false, bool I8 = false>
__global__ __launch_bounds__(1024) void gated_quant_fp8_kernel(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q,
float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t gu_ld, uint32_t y_ld,
uint32_t q_ld, uint32_t s_ld) {
gated_quant_fp8_kernel_body<ACT, ROT, I8>(gu, y, q, s, n, nkb, gu_ld, y_ld, q_ld, s_ld);
template <int ACT, bool ROT = false, bool I8 = false, uint32_t SUB = 1>
__global__ __launch_bounds__(1024) void gated_quant_fp8_kernel(R4D_GQ_PARAMS) {
gated_quant_fp8_body<ACT, ROT, I8, SUB>(gu, y, q, s, n, nkb, gu_ld, y_ld, q_ld, s_ld);
}
template <int ACT, bool ROT = false, bool I8 = false>
__global__ __launch_bounds__(1024) void r4dchain_gated_quant_fp8(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q,
float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t gu_ld, uint32_t y_ld,
uint32_t q_ld, uint32_t s_ld) {
template <int ACT, bool ROT = false, bool I8 = false, uint32_t SUB = 1>
__global__ __launch_bounds__(1024) void r4dchain_gated_quant(R4D_GQ_PARAMS) {
r4d_chain_wait();
gated_quant_fp8_kernel_body<ACT, ROT, I8>(gu, y, q, s, n, nkb, gu_ld, y_ld, q_ld, s_ld);
gated_quant_fp8_body<ACT, ROT, I8, SUB>(gu, y, q, s, n, nkb, gu_ld, y_ld, q_ld, s_ld);
r4d_chain_done();
}
#undef R4D_GQ_PARAMS
// -------------------------------------------------- gate . x -> quant, two source buffers
//
@@ -285,11 +340,15 @@ __global__ __launch_bounds__(1024) void r4dchain_gated_quant_fp8(
// ROT (with I8: gate_had_quant_i8g) puts the width-128 Hadamard between the bf16-rounded product
// and the absmax, as gated_quant_fp8_kernel's ROT, for an out projection stored rotated: the codes
// are had_quant_act_i8g's over `y`.
template <int ACT, bool I8 = false, bool ROT = false>
__device__ __forceinline__ void gate_quant_fp8_kernel_body(
const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t g_ld,
uint32_t x_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld) {
// SUB 2 (rotated int8 only) is IQ8R's 256-wide group, as in norm_quant_row; a row (one head) is
// then whole 256s.
// The body of gate_quant_fp8_kernel and of its chained form r4dchain_gate_quant; no block returns
// early.
#define R4D_GTQ_PARAMS const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, \
uint16_t* __restrict__ y, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, \
uint32_t nkb, uint32_t g_ld, uint32_t x_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld
template <int ACT, bool I8 = false, bool ROT = false, uint32_t SUB = 1>
__device__ __forceinline__ void gate_quant_fp8_body(R4D_GTQ_PARAMS) {
const uint32_t row = blockIdx.x;
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
const uint16_t* __restrict__ gr = g + (size_t)row * g_ld;
@@ -298,57 +357,57 @@ __device__ __forceinline__ void gate_quant_fp8_kernel_body(
uint8_t* __restrict__ qr = q + (size_t)row * q_ld;
for (uint32_t kb = wave; kb < nkb; kb += blockDim.x / kWave) {
const uint32_t c0 = kb * kGroup + lane * 4u;
float v[4] = {0.0f, 0.0f, 0.0f, 0.0f};
// One branch for all four columns; see norm_quant_row.
if (c0 < n) {
uint16_t gb[4], xb[4];
float v[SUB][4];
uint32_t c0[SUB];
#pragma unroll
for (int j = 0; j < 4; ++j) {
gb[j] = gr[c0 + j];
xb[j] = xr[c0 + j];
}
for (uint32_t b = 0; b < SUB; ++b) {
c0[b] = (kb * SUB + b) * kGroup + lane * 4u;
#pragma unroll
for (int j = 0; j < 4; ++j) {
uint16_t h;
if (ACT == 2) {
h = f2bf(bf2f(gb[j]) * bf2f(xb[j]));
} else {
const float gv = bf2f(gb[j]);
// The activation is rounded to bf16 before the multiply, unlike gated_quant_fp8:
// the unfused reference here is `sigmoid` then `mul` with a bf16 buffer between
// them (silu_mul_bf16 keeps f32). Skipping the round trip changes the output.
const uint16_t ab =
f2bf(ACT == 0 ? gv / (1.0f + expf(-gv)) : 1.0f / (1.0f + expf(-gv)));
h = f2bf(bf2f(ab) * bf2f(xb[j]));
for (int j = 0; j < 4; ++j) v[b][j] = 0.0f;
// One branch for all four columns; see norm_quant_row.
if (c0[b] < n) {
uint16_t gb[4], xb[4];
#pragma unroll
for (int j = 0; j < 4; ++j) {
gb[j] = gr[c0[b] + j];
xb[j] = xr[c0[b] + j];
}
#pragma unroll
for (int j = 0; j < 4; ++j) {
uint16_t h;
if (ACT == 2) {
h = f2bf(bf2f(gb[j]) * bf2f(xb[j]));
} else {
const float gv = bf2f(gb[j]);
// The activation is rounded to bf16 before the multiply, unlike
// gated_quant_fp8: the unfused reference here is `sigmoid` then `mul` with
// a bf16 buffer between them (silu_mul_bf16 keeps f32). Skipping the round
// trip changes the output.
const uint16_t ab =
f2bf(ACT == 0 ? gv / (1.0f + expf(-gv)) : 1.0f / (1.0f + expf(-gv)));
h = f2bf(bf2f(ab) * bf2f(xb[j]));
}
if (yr) yr[c0[b] + j] = h;
v[b][j] = bf2f(h);
}
if (yr) yr[c0 + j] = h;
v[j] = bf2f(h);
}
// The rotated launcher requires n % 128 == 0, so no rotated group contains padding.
if constexpr (ROT) r4d_fwht_wave<(int)kGroup>(v[b], (int)lane);
}
// The rotated launcher requires n % 128 == 0, so no rotated group contains padding.
if constexpr (ROT) r4d_fwht_wave<(int)kGroup>(v, (int)lane);
quant_group<I8>(v, s, qr, (size_t)row * s_ld + kb, c0, n, lane);
quant_groups<I8, SUB>(v, s, qr, (size_t)row * s_ld + kb, c0, n, lane);
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <int ACT, bool I8 = false, bool ROT = false>
__global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t g_ld,
uint32_t x_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld) {
gate_quant_fp8_kernel_body<ACT, I8, ROT>(g, x, y, q, s, n, nkb, g_ld, x_ld, y_ld, q_ld, s_ld);
template <int ACT, bool I8 = false, bool ROT = false, uint32_t SUB = 1>
__global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(R4D_GTQ_PARAMS) {
gate_quant_fp8_body<ACT, I8, ROT, SUB>(g, x, y, q, s, n, nkb, g_ld, x_ld, y_ld, q_ld, s_ld);
}
template <int ACT, bool I8 = false, bool ROT = false>
__global__ __launch_bounds__(1024) void r4dchain_gate_quant_fp8(
const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t g_ld,
uint32_t x_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld) {
template <int ACT, bool I8 = false, bool ROT = false, uint32_t SUB = 1>
__global__ __launch_bounds__(1024) void r4dchain_gate_quant(R4D_GTQ_PARAMS) {
r4d_chain_wait();
gate_quant_fp8_kernel_body<ACT, I8, ROT>(g, x, y, q, s, n, nkb, g_ld, x_ld, y_ld, q_ld, s_ld);
gate_quant_fp8_body<ACT, I8, ROT, SUB>(g, x, y, q, s, n, nkb, g_ld, x_ld, y_ld, q_ld, s_ld);
r4d_chain_done();
}
#undef R4D_GTQ_PARAMS
// -------------------------------------------------------- all-reduce -> rmsnorm -> quant
//
@@ -445,12 +504,14 @@ __device__ __forceinline__ unsigned int arq_load_acq(const unsigned int* p) {
// stored the sum into `x`); a residual only.
//
// HI8: ar_rmsnorm_had_quant_i8g, pass two in norm_quant_row's rotated int8 form. The reduction and
// the norm are untouched, so `x`, the residual and `y` are ar_rmsnorm_quant_fp8's bytes.
// the norm are untouched, so `x`, the residual and `y` are ar_rmsnorm_quant_fp8's bytes. SUB 2
// (with HI8) is IQ8R's 256-wide scale group, as norm_quant_row's; `nkb` then counts groups.
// PAD (wire 6 only): the row is whole 64-element groups but not whole chunks, so its last chunk is
// padded and a chunk's elements are found by (row, chunk in row). Without it, for a row of whole
// chunks, the flat chunk index gives the element offset.
// CH `r4dchain`: the chained form (r4d_chain.h); no block returns early.
template <bool WF32, bool RES, uint32_t THR, int WIRE, bool POST = false, bool HI8 = false,
bool PAD = false>
bool PAD = false, uint32_t SUB = 1, class CH = R4dUnchained>
__global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp,
@@ -459,6 +520,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
unsigned int* seq_ctrs, char* loc_pack, long loc_scale_off, int M, uint32_t n, uint32_t nkb,
float eps, float wadd, uint32_t r_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld,
int slot_stride16, int drain, int acq, unsigned int nbw, long stage) {
if (CH::on) r4d_chain_wait();
__shared__ float lds[THR / kWave];
__shared__ unsigned int s_seq, s_slot;
const int b = (int)blockIdx.x, nb = (int)gridDim.x;
@@ -749,13 +811,14 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
if constexpr (THR != kR4dSumLanes) { __syncthreads(); ss = lanes_sumsq(nr, n); }
/* block_sum's barrier is also what publishes pass one's stores to pass two's reads. */
const float rs = rsqrtf(block_sum<THR / kWave>(ss, lds) / (float)n + eps);
norm_quant_row<WF32, THR, HI8>(nr, w, y ? y + (size_t)row * y_ld : nullptr,
q + (size_t)row * q_ld, s, (size_t)row * s_ld, n, nkb, rs,
wadd);
norm_quant_row<WF32, THR, HI8, SUB>(nr, w, y ? y + (size_t)row * y_ld : nullptr,
q + (size_t)row * q_ld, s, (size_t)row * s_ld, n, nkb,
rs, wadd);
/* lds is reused by this block's next row; without the barrier a thread still reading it
* would race the next row's write. */
__syncthreads();
}
if (CH::on) r4d_chain_done();
}
} // namespace
@@ -776,33 +839,45 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
// up to 4
// s [M][ceil(n/128)] f32, `s_ld` elements a row (0 = ceil(n/128))
//
// `hi8` additionally requires n % 128 == 0, as gated_quant_fp8_launch's `rot`.
// `hi8` additionally requires n % 128 == 0, as gated_quant_fp8_launch's `rot`. `wide` (with
// `hi8`) is IQ8R's group: one scale per 256 columns, n % 256 == 0, `s` [M][n/256]. `chain` (with
// `hi8`) takes the chained form at decode heights, where the row resolved with it.
static int rmsnorm_quant_launch(long x, long res, long w, long y, long q, long s, int M, int n,
float eps, float wadd, int w_f32, int x_ld, int r_ld, int y_ld,
int q_ld, int s_ld, long stream, bool hi8) {
int q_ld, int s_ld, long stream, bool hi8, bool wide = false,
bool chain = false) {
if (!x || !w || !q || !s) return -1;
if (M <= 0 || n <= 0) return -2;
if (n % 4) return -3; // a lane owns four columns; see the kernel
if (hi8 && (n % (int)kGroup)) return -6;
if (wide && (!hi8 || n % (2 * (int)kGroup))) return -6;
if (!x_ld) x_ld = n;
if (!r_ld) r_ld = n;
if (!y_ld) y_ld = n;
if (!q_ld) q_ld = n;
const int nkb = (n + (int)kGroup - 1) / (int)kGroup;
const int grp = wide ? 2 * (int)kGroup : (int)kGroup;
const int nkb = (n + grp - 1) / grp;
if (!s_ld) s_ld = nkb;
// One workgroup per row, so a decode batch is 8-72 workgroups and the kernel is latency bound;
// the workgroup width is the parallelism knob (crossover table in r4d_act_threads). The sum of
// squares is folded in kR4dSumLanes' partition at every width, as rmsnorm_bf16 folds it.
const int thr = r4d_act_threads(M, n);
#define R4D_RQ_H(wf, rs, T, H) \
hipLaunchKernelGGL((rmsnorm_quant_fp8_kernel<wf, rs, T, H>), dim3((uint32_t)M), dim3(T), 0, \
const bool ch = chain && hi8 && M <= 64;
#define R4D_RQ_K(K_) \
hipLaunchKernelGGL((K_), dim3((uint32_t)M), dim3((uint32_t)thr), 0, \
(hipStream_t)stream, (const uint16_t*)x, (uint16_t*)res, (const void*)w, \
(uint16_t*)y, (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)nkb, eps, \
wadd, (uint32_t)x_ld, (uint32_t)r_ld, (uint32_t)y_ld, (uint32_t)q_ld, \
(uint32_t)s_ld)
#define R4D_RQ_H(wf, rs, T, H, SUB) R4D_RQ_K((rmsnorm_quant_fp8_kernel<wf, rs, T, H, SUB>))
/* The rotated int8 forms, plain or chained. */
#define R4D_RQ_C(wf, rs, T, SUB) \
do { if (ch) R4D_RQ_K((r4dchain_rmsnorm_quant<wf, rs, T, true, SUB>)); \
else R4D_RQ_H(wf, rs, T, true, SUB); } while (0)
#define R4D_RQ_T(wf, rs, T) \
do { if (hi8) R4D_RQ_H(wf, rs, T, true); else R4D_RQ_H(wf, rs, T, false); } while (0)
do { if (wide) R4D_RQ_C(wf, rs, T, 2u); \
else if (hi8) R4D_RQ_C(wf, rs, T, 1u); else R4D_RQ_H(wf, rs, T, false, 1u); } while (0)
#define R4D_RQ(wf, rs) \
do { if (thr == 1024) R4D_RQ_T(wf, rs, 1024); \
else if (thr == 512) R4D_RQ_T(wf, rs, 512); \
@@ -811,7 +886,9 @@ static int rmsnorm_quant_launch(long x, long res, long w, long y, long q, long s
else { if (res) R4D_RQ(false, true); else R4D_RQ(false, false); }
#undef R4D_RQ
#undef R4D_RQ_T
#undef R4D_RQ_C
#undef R4D_RQ_H
#undef R4D_RQ_K
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -843,38 +920,52 @@ extern "C" int r4d_rmsnorm_had_quant_i8g(long x, long res, long w, long y, long
// masked by the GEMM) but a butterfly mixing real values with padding has no matching weight block.
// `rot` with `i8` is had_quant_act_i8g's form (gated_had_quant_i8g), for a rotated int8 down
// projection; `rot` alone pairs with a rotated four-bit expert, which reads E4M3.
// `wide` (with `rot` and `i8`): IQ8R's group, one scale per 256 columns, n % 256 == 0. `chain`
// (with `rot`) takes the chained form at decode heights: to 64 rows at IQ8R's group, to 1024 at
// the 128 group, whose rows are a routed layer's (token, expert) slots.
static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n, int mode,
int gu_ld, int y_ld, int q_ld, int s_ld, RadStream stream,
bool rot, bool i8 = false, bool chain = false) {
bool rot, bool i8 = false, bool wide = false,
bool chain = false) {
int emit_rc = RAD_OK;
if (!gu || !q || !s) return -1;
if (M <= 0 || n <= 0) return -2;
if (n % 4) return -3;
if (mode != 0 && mode != 1) return -5;
if (rot && (n % (int)kGroup)) return -6;
if (wide && (!rot || !i8 || n % (2 * (int)kGroup))) return -6;
if (!gu_ld) gu_ld = 2 * n;
if (!y_ld) y_ld = n;
if (!q_ld) q_ld = n;
const int nkb = (n + (int)kGroup - 1) / (int)kGroup;
const int grp = wide ? 2 * (int)kGroup : (int)kGroup;
const int nkb = (n + grp - 1) / grp;
if (!s_ld) s_ld = nkb;
// One wave per group, capped at r4d_act_threads' width. The width does not affect the numerics:
// there is no cross-row reduction and the rotation is wave-local (r4d_fwht.h).
const int thr = std::min(nkb, r4d_act_threads(M, n) / (int)kWave) * (int)kWave;
#define R4D_GQ_R(a, R, I) \
emit_rc = R4D_EMIT(stream, (chain ? &r4dchain_gated_quant_fp8<a, R, I> \
: &gated_quant_fp8_kernel<a, R, I>), dim3((uint32_t)M), dim3(thr), \
const bool ch = chain && rot && M <= (wide ? 64 : 64 * 16);
#define R4D_GQ_K(K_) \
emit_rc = R4D_EMIT(stream, K_, dim3((uint32_t)M), dim3(thr), \
0, (const uint16_t*)gu, (uint16_t*)y, (uint8_t*)q, \
(float*)s, (uint32_t)n, (uint32_t)nkb, (uint32_t)gu_ld, (uint32_t)y_ld, \
(uint32_t)q_ld, (uint32_t)s_ld)
#define R4D_GQ_R(a, R, I, SUB) R4D_GQ_K((gated_quant_fp8_kernel<a, R, I, SUB>))
/* The rotated forms (int8 codes or E4M3), plain or chained. */
#define R4D_GQ_C(a, I, SUB) \
do { if (ch) R4D_GQ_K((r4dchain_gated_quant<a, true, I, SUB>)); \
else R4D_GQ_R(a, true, I, SUB); } while (0)
#define R4D_GQ(a) \
do { if (rot && i8) R4D_GQ_R(a, true, true); \
else if (rot) R4D_GQ_R(a, true, false); \
else if (i8) R4D_GQ_R(a, false, true); \
else R4D_GQ_R(a, false, false); } while (0)
do { if (wide) R4D_GQ_C(a, true, 2u); \
else if (rot && i8) R4D_GQ_C(a, true, 1u); \
else if (rot) R4D_GQ_C(a, false, 1u); \
else if (i8) R4D_GQ_R(a, false, true, 1u); \
else R4D_GQ_R(a, false, false, 1u); } while (0)
if (mode == 0) R4D_GQ(0);
else R4D_GQ(1);
#undef R4D_GQ
#undef R4D_GQ_C
#undef R4D_GQ_R
#undef R4D_GQ_K
if (emit_rc != RAD_OK) return -4;
return (hipGetLastError() != hipSuccess) ? -4 : 0;
}
@@ -885,12 +976,6 @@ extern "C" int r4d_gated_quant_fp8(long gu, long y, long q, long s, int M, int n
(RadStream)(uintptr_t)stream, false);
}
extern "C" int r4d_gated_had_quant_fp8(long gu, long y, long q, long s, int M, int n, int mode,
int gu_ld, int y_ld, int q_ld, int s_ld, long stream) {
return gated_quant_fp8_launch(gu, y, q, s, M, n, mode, gu_ld, y_ld, q_ld, s_ld,
(RadStream)(uintptr_t)stream, true);
}
// The same product with had_quant_act_i8g's quantiser: `q` is int8.
extern "C" int r4d_gated_had_quant_i8g(long gu, long y, long q, long s, int M, int n, int mode,
int gu_ld, int y_ld, int q_ld, int s_ld, long stream) {
@@ -908,43 +993,49 @@ extern "C" int r4d_gated_had_quant_i8g(long gu, long y, long q, long s, int M, i
// y [M][n] bf16, `y_ld` elements a row (0 = n), optional
// q [M][n] E4M3 (int8 when `i8`), `q_ld` bytes a row (0 = n), rounded up to 4
// s [M][ceil(n/128)] f32, `s_ld` elements a row (0 = ceil(n/128))
// `wide` (with `rot`): IQ8R's group, one scale per 256 columns of a row, n % 256 == 0. `chain`
// (with `rot`) takes the chained form at decode heights.
static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, int n, int mode,
int g_ld, int x_ld, int y_ld, int q_ld, int s_ld,
RadStream stream, bool i8 = false, bool rot = false) {
RadStream stream, bool i8 = false, bool rot = false,
bool wide = false, bool chain = false) {
int emit_rc = RAD_OK;
if (!g || !x || !q || !s) return -1;
if (M <= 0 || n <= 0) return -2;
if (n % 4) return -3;
if (rot && (!i8 || n % (int)kGroup)) return -3;
if (wide && (!rot || n % (2 * (int)kGroup))) return -3;
if (mode < 0 || mode > 2) return -5;
if (!g_ld) g_ld = n;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
if (!q_ld) q_ld = n;
const int nkb = (n + (int)kGroup - 1) / (int)kGroup;
const int grp = wide ? 2 * (int)kGroup : (int)kGroup;
const int nkb = (n + grp - 1) / grp;
if (!s_ld) s_ld = nkb;
// A wave a group, capped at r4d_act_threads' width, as gated_quant_fp8 above.
const int thr = std::min(nkb, r4d_act_threads(M, n) / (int)kWave) * (int)kWave;
/* A row is a (token, head) pair: decode heights are 64 tokens of up to 32 heads. */
const bool ch = chain && rot && M <= 64 * 32;
#define R4D_GTQ_K(K_) \
R4D_EMIT(stream, K_, dim3((uint32_t)M), dim3(thr), 0, (const uint16_t*)g, \
(const uint16_t*)x, (uint16_t*)y, (uint8_t*)q, (float*)s, (uint32_t)n, \
(uint32_t)nkb, (uint32_t)g_ld, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)q_ld, \
(uint32_t)s_ld)
/* The rotated int8 forms (128, or IQ8R's 256), plain or chained; else the E4M3 or plain int8 one. */
#define R4D_GTQ_I(a, I) \
emit_rc = rot ? R4D_EMIT(stream, (g_r4d_chain_arg ? &r4dchain_gate_quant_fp8<a, true, true> \
: &gate_quant_fp8_kernel<a, true, true>), \
dim3((uint32_t)M), dim3(thr), 0, (const uint16_t*)g, \
(const uint16_t*)x, (uint16_t*)y, (uint8_t*)q, (float*)s, \
(uint32_t)n, (uint32_t)nkb, (uint32_t)g_ld, (uint32_t)x_ld, \
(uint32_t)y_ld, (uint32_t)q_ld, (uint32_t)s_ld) \
: R4D_EMIT(stream, (g_r4d_chain_arg ? &r4dchain_gate_quant_fp8<a, I> \
: &gate_quant_fp8_kernel<a, I>), dim3((uint32_t)M), \
dim3(thr), 0, \
(const uint16_t*)g, (const uint16_t*)x, \
(uint16_t*)y, (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)nkb, \
(uint32_t)g_ld, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)q_ld, \
(uint32_t)s_ld)
emit_rc = wide ? (ch ? R4D_GTQ_K((r4dchain_gate_quant<a, true, true, 2u>)) \
: R4D_GTQ_K((gate_quant_fp8_kernel<a, true, true, 2u>))) \
: rot ? (ch ? R4D_GTQ_K((r4dchain_gate_quant<a, true, true>)) \
: R4D_GTQ_K((gate_quant_fp8_kernel<a, true, true>))) \
: R4D_GTQ_K((gate_quant_fp8_kernel<a, I>))
#define R4D_GTQ(a) do { if (i8) R4D_GTQ_I(a, true); else R4D_GTQ_I(a, false); } while (0)
if (mode == 0) R4D_GTQ(0);
else if (mode == 1) R4D_GTQ(1);
else R4D_GTQ(2);
#undef R4D_GTQ
#undef R4D_GTQ_I
#undef R4D_GTQ_K
if (emit_rc != RAD_OK) return -4;
return (hipGetLastError() != hipSuccess) ? -4 : 0;
}
@@ -967,7 +1058,9 @@ extern "C" int r4d_gate_quant_fp8(long g, long x, long y, long q, long s, int M,
extern "C" int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void) { return ARQ_CE; }
// `hi8` is the rotated int8 form (ar_rmsnorm_had_quant_i8g): `q` is int8, n % 128 == 0, and there
// is no post-norm.
// is no post-norm. `wide` (with `hi8`) is IQ8R's group: one scale per 256 columns, n % 256 == 0,
// `s` [M][n/256]. `chain` takes the chained form (r4d_chain.h), which the rotated int8 form has at
// the decode width of 1024 threads; any other launch stays plain.
static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer_flags,
long my_flags, long seq_ctrs, long slot_stride16,
long x, long res, long w, long y, long q, long s,
@@ -975,11 +1068,12 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq, int wire,
long loc_pack, long loc_scale_off, long wp, bool hi8,
long stage) {
long stage, bool wide = false, bool chain = false) {
if (!x || !w || !q || !s) return -1;
if (wp && !res) return -10; // a post-norm needs the stream
if (hi8 && wp) return -11;
if (hi8 && (n % (int)kGroup)) return -12;
if (wide && (!hi8 || n % (2 * (int)kGroup))) return -12;
if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1;
if (M <= 0 || n <= 0) return -2;
// n % 8: n bf16 is a whole number of 16B words (see the push), which also gives every lane its
@@ -993,7 +1087,8 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
if (!r_ld) r_ld = n;
if (!y_ld) y_ld = n;
if (!q_ld) q_ld = n;
const int nkb = (n + (int)kGroup - 1) / (int)kGroup;
const int grp = wide ? 2 * (int)kGroup : (int)kGroup;
const int nkb = (n + grp - 1) / grp;
if (!s_ld) s_ld = nkb;
int nb = nblocks < 1 ? 1 : nblocks;
@@ -1004,8 +1099,10 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
const int thr = nthreads ? nthreads : r4d_act_threads(M, n);
if (thr != 256 && thr != 512 && thr != 1024) return -6;
const bool pad = wire == 6 && (n % ARQ_CE) != 0;
#define R4D_ARQ_HP(wf, rs, T, W, PO, H, PD) \
hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel<wf, rs, T, W, PO, H, PD>), dim3((uint32_t)nb), \
const bool ch = chain && hi8 && thr == 1024;
#define R4D_ARQ_HP(wf, rs, T, W, PO, H, PD, SUB, CH) \
hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel<wf, rs, T, W, PO, H, PD, SUB, CH>), \
dim3((uint32_t)nb), \
dim3(T), 0, \
(hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, (const void*)w, \
(const void*)wp, \
@@ -1015,22 +1112,24 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
(long)loc_scale_off, M, (uint32_t)n, \
(uint32_t)nkb, eps, wadd, (uint32_t)r_ld, (uint32_t)y_ld, (uint32_t)q_ld, \
(uint32_t)s_ld, (int)slot_stride16, drain, acq, (unsigned)nbw, stage)
#define R4D_ARQ_H(wf, rs, T, W, PO, H) \
do { if (pad) R4D_ARQ_HP(wf, rs, T, W, PO, H, (W == 6)); \
else R4D_ARQ_HP(wf, rs, T, W, PO, H, false); } while (0)
#define R4D_ARQ_P(wf, rs, T, W, PO) R4D_ARQ_H(wf, rs, T, W, PO, false)
#define R4D_ARQ_T(wf, rs, T, W) \
do { if (hi8) R4D_ARQ_H(wf, rs, T, W, false, true); \
#define R4D_ARQ_H(wf, rs, T, W, PO, H, SUB, CH) \
do { if (pad) R4D_ARQ_HP(wf, rs, T, W, PO, H, (W == 6), SUB, CH); \
else R4D_ARQ_HP(wf, rs, T, W, PO, H, false, SUB, CH); } while (0)
#define R4D_ARQ_P(wf, rs, T, W, PO) R4D_ARQ_H(wf, rs, T, W, PO, false, 1u, R4dUnchained)
#define R4D_ARQ_T(wf, rs, T, W, CH) \
do { if (wide) R4D_ARQ_H(wf, rs, T, W, false, true, 2u, CH); \
else if (hi8) R4D_ARQ_H(wf, rs, T, W, false, true, 1u, CH); \
else R4D_ARQ_P(wf, rs, T, W, false); } while (0)
#define R4D_ARQ_W(wf, rs, T) \
#define R4D_ARQ_W(wf, rs, T, CH) \
do { if (wire == 6 && rs && wp) R4D_ARQ_P(wf, rs, T, 6, true); \
else if (wire == 6) R4D_ARQ_T(wf, rs, T, 6); \
else if (wire == 6) R4D_ARQ_T(wf, rs, T, 6, CH); \
else if (rs && wp) R4D_ARQ_P(wf, rs, T, 0, true); \
else R4D_ARQ_T(wf, rs, T, 0); } while (0)
else R4D_ARQ_T(wf, rs, T, 0, CH); } while (0)
#define R4D_ARQ(wf, rs) \
do { if (thr == 1024) R4D_ARQ_W(wf, rs, 1024); \
else if (thr == 512) R4D_ARQ_W(wf, rs, 512); \
else R4D_ARQ_W(wf, rs, 256); } while (0)
do { if (ch) R4D_ARQ_W(wf, rs, 1024, r4dchain); \
else if (thr == 1024) R4D_ARQ_W(wf, rs, 1024, R4dUnchained); \
else if (thr == 512) R4D_ARQ_W(wf, rs, 512, R4dUnchained); \
else R4D_ARQ_W(wf, rs, 256, R4dUnchained); } while (0)
if (w_f32) { if (res) R4D_ARQ(true, true); else R4D_ARQ(true, false); }
else { if (res) R4D_ARQ(false, true); else R4D_ARQ(false, false); }
#undef R4D_ARQ
@@ -1055,7 +1154,8 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long
wire, loc_pack, loc_scale_off, wp, false, stage);
}
// The same with had_quant_act_i8g's quantiser on the norm's pass (no post-norm).
// The same with had_quant_act_i8g's quantiser on the norm's pass (no post-norm). `group` is the
// scale group: 128, or IQ8R's 256. `chain`: the chained form at the decode width.
extern "C" int r4d_ar_rmsnorm_had_quant_i8g(long peer_scratch, long my_scratch, long peer_flags,
long my_flags, long seq_ctrs, long slot_stride16,
long x, long res, long w, long y, long q, long s,
@@ -1063,11 +1163,13 @@ extern "C" int r4d_ar_rmsnorm_had_quant_i8g(long peer_scratch, long my_scratch,
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq,
int wire, long loc_pack, long loc_scale_off,
long stage) {
long stage, int group, int chain) {
if (group != (int)kGroup && group != 2 * (int)kGroup) return -12;
return ar_rmsnorm_quant_launch(peer_scratch, my_scratch, peer_flags, my_flags, seq_ctrs,
slot_stride16, x, res, w, y, q, s, M, n, eps, wadd, w_f32,
r_ld, y_ld, q_ld, s_ld, stream, nblocks, nthreads, drain, acq,
wire, loc_pack, loc_scale_off, 0, true, stage);
wire, loc_pack, loc_scale_off, 0, true, stage,
group == 2 * (int)kGroup, chain != 0);
}
// ============================================================== the plugin ABI entry points
@@ -1094,9 +1196,12 @@ static int rad_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) {
if (x->rank != 2 || q->rank != 2 || sc->rank != 2) return R4D_NO(RAD_E_SHAPE);
if (y && y->rank != 2) return R4D_NO(RAD_E_SHAPE);
const long long M = x->shape[0], K = x->shape[1];
const long long grp = r4d_quant_act_fp8_group();
/* 128, or IQ8R's 256 for the rotated int8 form. */
const long long g0 = r4d_quant_act_fp8_group();
const long long grp = r4d_geti_or(a, "group", g0);
const bool wide = hi8 && grp == R4D_I8_GROUP_WIDE;
if (grp != g0 && !wide) return R4D_NO(RAD_E_SHAPE);
const long long nkb = (K + grp - 1) / grp;
if (r4d_geti_or(a, "group", grp) != grp) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(w) != K) return R4D_NO(RAD_E_SHAPE);
if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
if (q->shape[0] != M || q->shape[1] != K) return R4D_NO(RAD_E_SHAPE);
@@ -1114,7 +1219,8 @@ static int rad_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) {
(int)M, (int)K,
(float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0),
w->dtype == RAD_F32, (int)xp, (int)rp, (int)yp, (int)qp,
(int)sp, (long)(uintptr_t)s, hi8);
(int)sp, (long)(uintptr_t)s, hi8, wide,
r4d_geti_or(a, "chain", 0) != 0);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
@@ -1151,9 +1257,12 @@ static int rad_gated_quant_fp8(const RadArgs* a, RadStream stream, bool rot, boo
if (gu->rank != 2 || q->rank != 2 || sc->rank != 2) return R4D_NO(RAD_E_SHAPE);
if (y && y->rank != 2) return R4D_NO(RAD_E_SHAPE);
const long long M = gu->shape[0], K = q->shape[1];
const long long grp = r4d_quant_act_fp8_group();
/* 128, or IQ8R's 256 for the rotated int8 form. */
const long long g0 = r4d_quant_act_fp8_group();
const long long grp = r4d_geti_or(a, "group", g0);
const bool wide = rot && hi8 && grp == R4D_I8_GROUP_WIDE;
if (grp != g0 && !wide) return R4D_NO(RAD_E_SHAPE);
const long long nkb = (K + grp - 1) / grp;
if (r4d_geti_or(a, "group", grp) != grp) return R4D_NO(RAD_E_SHAPE);
/* The gated operand is [M][2K], gate then up, as the fused gate_up projection writes it. */
if (gu->shape[1] != 2 * K) return R4D_NO(RAD_E_SHAPE);
if (q->shape[0] != M) return R4D_NO(RAD_E_SHAPE);
@@ -1166,9 +1275,8 @@ static int rad_gated_quant_fp8(const RadArgs* a, RadStream stream, bool rot, boo
if (mode < 0) return R4D_NO(RAD_E_UNSUPPORTED);
const int e = gated_quant_fp8_launch(r4d_addr(gu), y ? r4d_addr(y) : 0, r4d_addr(q),
r4d_addr(sc), (int)M, (int)K, mode, (int)gp, (int)yp,
(int)qp, (int)sp, stream, rot, q->dtype == RAD_I8,
/* decode heights: its rows are tokens or routed slots */
r4d_geti_or(a, "chain", 0) != 0 && M <= 1024);
(int)qp, (int)sp, stream, rot, q->dtype == RAD_I8, wide,
r4d_geti_or(a, "chain", 0) != 0);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
@@ -1176,12 +1284,6 @@ extern "C" int r4d_rad_gated_quant_fp8(const RadArgs* a, RadStream stream) {
return rad_gated_quant_fp8(a, stream, false);
}
/* The rotated form is a separate op for the same reason as had_quant_act_fp8 (different codes in
* the same shape). It pairs only with a down-projection weight stored at dtype w4a8h. */
extern "C" int r4d_rad_gated_had_quant_fp8(const RadArgs* a, RadStream stream) {
return rad_gated_quant_fp8(a, stream, true);
}
/* Its int8 twin, had_quant_act_i8g's codes: pairs only with a weight stored at dtype i8a8h. */
extern "C" int r4d_rad_gated_had_quant_i8g(const RadArgs* a, RadStream stream) {
return rad_gated_quant_fp8(a, stream, true, true);
@@ -1219,12 +1321,15 @@ static int rad_gate_quant(const RadArgs* a, RadStream stream, bool rot) {
/* M is numel(x) / n. The `M` parameter is the band's declared maximum, not this issue's, and
* shape[0] counts tokens while a row here is a (token, head) pair. */
const long long K = r4d_geti_or(a, "n", 0);
const long long grp = r4d_quant_act_fp8_group();
/* 128, or IQ8R's 256 for the rotated form. */
const long long g0 = r4d_quant_act_fp8_group();
const long long grp = r4d_geti_or(a, "group", g0);
const bool wide = rot && grp == R4D_I8_GROUP_WIDE;
if (grp != g0 && !wide) return R4D_NO(RAD_E_SHAPE);
if (K <= 0 || r4d_numel(x) % K) return R4D_NO(RAD_E_SHAPE);
const long long M = r4d_numel(x) / K;
if (M <= 0) return R4D_NO(RAD_E_SHAPE);
const long long nkb = (K + grp - 1) / grp;
if (r4d_geti_or(a, "group", grp) != grp) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(g) < M * K) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(q) < M * K || r4d_numel(sc) < M * nkb) return R4D_NO(RAD_E_SHAPE);
if (y && r4d_numel(y) < M * K) return R4D_NO(RAD_E_SHAPE);
@@ -1234,11 +1339,11 @@ static int rad_gate_quant(const RadArgs* a, RadStream stream, bool rot) {
if (gp < 0 || xp < 0 || qp < 0 || sp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE);
const int mode = act_mode(a, 1); /* sigmoid: gated attention */
if (mode < 0) return R4D_NO(RAD_E_UNSUPPORTED);
const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0 && M <= 1024);
const int e = gate_quant_fp8_emit(r4d_addr(g), r4d_addr(x), y ? r4d_addr(y) : 0,
r4d_addr(q), r4d_addr(sc), (int)M, (int)K, mode,
(int)gp, (int)xp, (int)yp, (int)qp, (int)sp, stream,
q->dtype == RAD_I8, rot);
q->dtype == RAD_I8, rot, wide,
r4d_geti_or(a, "chain", 0) != 0);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
+25
View File
@@ -54,3 +54,28 @@ __device__ __forceinline__ void r4d_fwht_wave(float* v, int lane) {
r4d_fwht_xstage<VPL, 8>(v, lane);
r4d_fwht_xstage<VPL, 16>(v, lane);
}
// The same transform of a block a part of the wave holds: VPL contiguous values per lane and LPG
// adjacent lanes (a power of two, the block HAD = VPL * LPG wide, lane-major from a lane that is a
// multiple of LPG). Stages run by ascending stride as in r4d_fwht_wave, and a butterfly's two
// results do not depend on which lane holds which index, so any (VPL, LPG) with the same product
// gives the same bits: r4d_fwht_part<8, 16> over sixteen lanes is r4d_fwht_wave<128> over a wave.
template <int VPL, int LPG>
__device__ __forceinline__ void r4d_fwht_part(float* v, int lane) {
#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;
}
}
}
if constexpr (LPG > 1) r4d_fwht_xstage<VPL, 1>(v, lane);
if constexpr (LPG > 2) r4d_fwht_xstage<VPL, 2>(v, lane);
if constexpr (LPG > 4) r4d_fwht_xstage<VPL, 4>(v, lane);
if constexpr (LPG > 8) r4d_fwht_xstage<VPL, 8>(v, lane);
if constexpr (LPG > 16) r4d_fwht_xstage<VPL, 16>(v, lane);
}
@@ -27,12 +27,13 @@
// attention page size (e.g. 421888 elements per slot vs 393216 from the shape), so a shape-derived
// stride would read every slot but the first at the wrong offset there.
#include <hip/hip_runtime.h>
#include "r4d_keyed.h"
#include "r4d.h"
#include "r4d_gdn_args.h"
#include "r4d_gdn_wmma.h"
#include "r4d_common.h"
#include "r4d_gdn_conv_tap.h"
#include "r4d_chain.h"
#include "r4d_gdn_conv_tap.h"
#include "r4d_q8.h" // the 8-bit codes the folded quantiser writes: E4M3 or int8
#include "r4d_fwht.h" // NORM 3: had_quant_act_i8g's rotation before the int8 codes
#include <cstdlib>
@@ -201,6 +202,9 @@ struct RuConv {
const int* cidx; long ci_stride; // conv state slot per sequence; negative is padding
unsigned int* ctr; // one arrival counter per (sequence, key head)
};
// NORM 4's arrival counters, one per (sequence, pair of value heads), are the same block's from
// here on: the key heads' take the entries below it.
constexpr unsigned kRuPairCtr = 2048;
// Max tokens per sequence for the folded convolution (preloaded into registers, static indices).
#define RU_CVT 8
@@ -217,35 +221,29 @@ __device__ __forceinline__ void ru_conv_rewrite(unsigned short* sp, const unsign
if (t < T) sp[(size_t)(t + NH) * cs_tok] = xs[t];
}
#define RU_PARAMS \
const unsigned short* __restrict__ q, const unsigned short* __restrict__ k, const \
unsigned short* __restrict__ v, const void* __restrict__ av, const void* __restrict__ \
bv, long ab_stride, const float* __restrict__ A_log, const float* __restrict__ dt_bias, \
typename ru_state<SDT>::T* __restrict__ state, long st_slot, long st_head, unsigned \
short* __restrict__ o, unsigned char* __restrict__ oq, float* __restrict__ os, long \
oq_pitch, long os_ld, const int* __restrict__ cu, const int* __restrict__ sidx, long \
sidx_stride, const int* __restrict__ naccept, const unsigned short* __restrict__ zg, \
long zg_pitch, const float* __restrict__ nw, float neps, int nact, int H, int Hg, float \
scale, float sp_thr, const RuConv cv
template <int ABF16, int NORM, int VS, int NT, int ANC, int STG = 0, int SDT = 0,
int CV = 0>
__device__ __forceinline__ void r4d_gdn_recurrent_update_kernel_body(const unsigned short* __restrict__ q,
const unsigned short* __restrict__ k,
const unsigned short* __restrict__ v,
const void* __restrict__ av,
const void* __restrict__ bv, long ab_stride,
const float* __restrict__ A_log,
const float* __restrict__ dt_bias,
typename ru_state<SDT>::T* __restrict__ state,
long st_slot, long st_head,
unsigned short* __restrict__ o,
unsigned char* __restrict__ oq,
float* __restrict__ os, long oq_pitch,
long os_ld,
const int* __restrict__ cu,
const int* __restrict__ sidx, long sidx_stride,
const int* __restrict__ naccept,
const unsigned short* __restrict__ zg,
long zg_pitch,
const float* __restrict__ nw, float neps, int nact,
int H, int Hg, float scale, float sp_thr,
const RuConv cv) {
__device__ __forceinline__ void ru_update_body(RU_PARAMS)
{
using ST = typename ru_state<SDT>::T;
constexpr int NR = RU_V / VS; // v rows this workgroup owns
constexpr int THR = NR * 2;
static_assert(!(NORM && VS > 1), "the fused row norm needs the whole 128-wide row");
static_assert(NORM != 4 || CV, "the pair's arrival counter is the folded convolution's block");
__shared__ float wsum[THR / 32];
__shared__ float srot[NORM == 3 ? RU_V : 1]; // NORM 3: the row's bf16 output, for the rotation
// NORM 3: a block of tokens' bf16 output rows, for the rotation (one token a wave afterwards)
constexpr int RB = THR / 32;
__shared__ __attribute__((aligned(8))) unsigned short srot[NORM == 3 ? RB * RU_V : 1];
__shared__ float spart[STG ? RU_TMAX * 4 : 1]; // per (token, half): sum q^2, sum k^2
__shared__ float sscl [STG ? RU_TMAX * 2 : 1]; // per token: the two closed scales
const int n = blockIdx.x, hv = blockIdx.y;
@@ -646,27 +644,34 @@ __device__ __forceinline__ void r4d_gdn_recurrent_update_kernel_body(const unsig
// NORM == 3 writes had_quant_act_i8g's codes: the row's 128 stored bf16 values through
// r4d_fwht_wave<128> in one wave (a lane four consecutive channels, that function's mapping),
// then its amax / 127 scale and round-to-nearest-even, so the bytes are that quantiser's over
// `o`.
// `o`. Nothing in the token loop reads the codes, so the rows wait in LDS and every RB tokens
// (and after the last) each wave takes one token's: the rotation leaves the serial chain of
// the state update, which otherwise pays a barrier pair and one wave's work a token.
if (NORM == 3 && oq) {
if (half == 0) srot[row] = bf2f(ob);
__syncthreads();
if (tid < 32) {
float rv[4];
const int tb = t % RB;
if (half == 0) srot[tb * RU_V + row] = ob;
if (tb == RB - 1 || t == T - 1) {
__syncthreads();
const int rw = tid >> 5, rl = tid & 31;
if (rw <= tb) {
const int rtok = tok - tb + rw;
const uint2 rr = *(const uint2*)(srot + rw * RU_V + 4 * rl);
float rv[4] = { bf2f((unsigned short)(rr.x & 0xFFFFu)), bf2f((unsigned short)(rr.x >> 16)),
bf2f((unsigned short)(rr.y & 0xFFFFu)), bf2f((unsigned short)(rr.y >> 16)) };
r4d_fwht_wave<128>(rv, rl);
float m = fmaxf(fmaxf(fabsf(rv[0]), fabsf(rv[1])), fmaxf(fabsf(rv[2]), fabsf(rv[3])));
m = r4d_wave_max(m);
const float qs = m > 0.0f ? m * (1.0f / 127.0f) : 1.0f;
if (rl == 0) os[(size_t)rtok * os_ld + hv] = qs;
const float inv = 1.0f / qs;
uint32_t pk = 0;
#pragma unroll
for (int j = 0; j < 4; ++j) rv[j] = srot[4 * tid + j];
r4d_fwht_wave<128>(rv, tid);
float m = fmaxf(fmaxf(fabsf(rv[0]), fabsf(rv[1])), fmaxf(fabsf(rv[2]), fabsf(rv[3])));
m = r4d_wave_max(m);
const float qs = m > 0.0f ? m * (1.0f / 127.0f) : 1.0f;
if (tid == 0) os[(size_t)tok * os_ld + hv] = qs;
const float inv = 1.0f / qs;
uint32_t pk = 0;
#pragma unroll
for (int j = 0; j < 4; ++j)
pk |= ((uint32_t)(int)rintf(fminf(fmaxf(rv[j] * inv, -127.0f), 127.0f)) & 0xFFu) << (8 * j);
*(uint32_t*)(oq + (size_t)tok * oq_pitch + (size_t)hv * RU_V + 4 * tid) = pk;
for (int j = 0; j < 4; ++j)
pk |= ((uint32_t)(int)rintf(fminf(fmaxf(rv[j] * inv, -127.0f), 127.0f)) & 0xFFu) << (8 * j);
*(uint32_t*)(oq + (size_t)rtok * oq_pitch + (size_t)hv * RU_V + 4 * rl) = pk;
}
__syncthreads(); // srot is reused by the next block of tokens
}
__syncthreads(); // srot is reused by the next token
}
if ((NORM == 1 || NORM == 2) && oq) {
const float ov = bf2f(ob);
@@ -707,6 +712,58 @@ __device__ __forceinline__ void r4d_gdn_recurrent_update_kernel_body(const unsig
}
}
// NORM 4: had_quant_act_i8g's codes at IQ8R's group, one scale per 256 columns of `o`: two value
// heads' rows. A workgroup owns one head, so the second of a pair to arrive quantises both heads'
// rows for every token of the sequence, from the stored bf16 `o`: each head's 128 values through
// r4d_fwht_wave<128> in one wave (wave 0 the even head, wave 1 the odd), the amax over the pair,
// then that quantiser's amax / 127 scale and round-to-nearest-even, so the bytes are its over
// `o`. The arrival is router_gemm_topk_scatter_kernel's idiom: every store made visible
// device-wide before the arrival is published, and the workgroup completing the count resets
// it for the next launch and acquires its partner's rows. Every workgroup of a sequence takes
// the same early returns above, so a pair's two arrive or neither does.
if constexpr (NORM == 4) {
if (oq) {
__shared__ unsigned int s_pair;
__threadfence();
__syncthreads();
unsigned int* const pc = cv.ctr + kRuPairCtr + (size_t)n * (H / 2) + (hv >> 1);
if (tid == 0)
s_pair = __hip_atomic_fetch_add(pc, 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT);
__syncthreads();
if (s_pair == 1u) {
if (tid == 0) __hip_atomic_store(pc, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
__threadfence();
const int hp = hv & ~1, pw = tid >> 5, pl = tid & 31;
for (int t = 0; t < T; ++t) {
const int tok = bos + t;
float rv[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
if (tid < 64) {
const unsigned short* src = o + ((size_t)tok * H + hp + pw) * RU_V + 4 * pl;
#pragma unroll
for (int j = 0; j < 4; ++j) rv[j] = bf2f(src[j]);
r4d_fwht_wave<128>(rv, pl);
float m = fmaxf(fmaxf(fabsf(rv[0]), fabsf(rv[1])), fmaxf(fabsf(rv[2]), fabsf(rv[3])));
m = r4d_wave_max(m);
if (pl == 0) wsum[pw] = m;
}
__syncthreads();
if (tid < 64) {
const float m = fmaxf(wsum[0], wsum[1]);
const float qs = m > 0.0f ? m * (1.0f / 127.0f) : 1.0f;
if (tid == 0) os[(size_t)tok * os_ld + (hp >> 1)] = qs;
const float inv = 1.0f / qs;
uint32_t pk = 0;
#pragma unroll
for (int j = 0; j < 4; ++j)
pk |= ((uint32_t)(int)rintf(fminf(fmaxf(rv[j] * inv, -127.0f), 127.0f)) & 0xFFu) << (8 * j);
*(uint32_t*)(oq + (size_t)tok * oq_pitch + (size_t)(hp + pw) * RU_V + 4 * pl) = pk;
}
__syncthreads(); // wsum is reused by the next token
}
}
}
}
if constexpr (CV) {
// The last arriving reader rewrites the key head's q and k channels. The count was taken
// before the token loop, hiding its latency.
@@ -731,61 +788,21 @@ __device__ __forceinline__ void r4d_gdn_recurrent_update_kernel_body(const unsig
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <int ABF16, int NORM, int VS, int NT, int ANC, int STG = 0, int SDT = 0,
int CV = 0>
// The kernel around the body, whose workgroups return where their work ends: CH `r4dchain` is the
// chained form (r4d_chain.h), every workgroup waiting before its first read and adding once after
// its last write.
template <int ABF16, int NORM, int VS, int NT, int ANC, int STG, int SDT, int CV, class CH>
__global__ __launch_bounds__(RU_V / VS * 2)
void r4d_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 ab_stride,
const float* __restrict__ A_log,
const float* __restrict__ dt_bias,
typename ru_state<SDT>::T* __restrict__ state,
long st_slot, long st_head,
unsigned short* __restrict__ o,
unsigned char* __restrict__ oq,
float* __restrict__ os, long oq_pitch,
long os_ld,
const int* __restrict__ cu,
const int* __restrict__ sidx, long sidx_stride,
const int* __restrict__ naccept,
const unsigned short* __restrict__ zg,
long zg_pitch,
const float* __restrict__ nw, float neps, int nact,
int H, int Hg, float scale, float sp_thr,
const RuConv cv) {
r4d_gdn_recurrent_update_kernel_body<ABF16, NORM, VS, NT, ANC, STG, SDT, CV>(q, k, v, av, bv, ab_stride, A_log, dt_bias, state, st_slot, st_head, o, oq, os, oq_pitch, os_ld, cu, sidx, sidx_stride, naccept, zg, zg_pitch, nw, neps, nact, H, Hg, scale, sp_thr, cv);
}
template <int ABF16, int NORM, int VS, int NT, int ANC, int STG = 0, int SDT = 0,
int CV = 0>
__global__ __launch_bounds__(RU_V / VS * 2)
void r4dchain_gdn_recurrent_update(const unsigned short* __restrict__ q,
const unsigned short* __restrict__ k,
const unsigned short* __restrict__ v,
const void* __restrict__ av,
const void* __restrict__ bv, long ab_stride,
const float* __restrict__ A_log,
const float* __restrict__ dt_bias,
typename ru_state<SDT>::T* __restrict__ state,
long st_slot, long st_head,
unsigned short* __restrict__ o,
unsigned char* __restrict__ oq,
float* __restrict__ os, long oq_pitch,
long os_ld,
const int* __restrict__ cu,
const int* __restrict__ sidx, long sidx_stride,
const int* __restrict__ naccept,
const unsigned short* __restrict__ zg,
long zg_pitch,
const float* __restrict__ nw, float neps, int nact,
int H, int Hg, float scale, float sp_thr,
const RuConv cv) {
r4d_chain_wait();
r4d_gdn_recurrent_update_kernel_body<ABF16, NORM, VS, NT, ANC, STG, SDT, CV>(q, k, v, av, bv, ab_stride, A_log, dt_bias, state, st_slot, st_head, o, oq, os, oq_pitch, os_ld, cu, sidx, sidx_stride, naccept, zg, zg_pitch, nw, neps, nact, H, Hg, scale, sp_thr, cv);
r4d_chain_done();
void r4d_gdn_recurrent_update_kernel(RU_PARAMS)
{
if (CH::on) r4d_chain_wait();
ru_update_body<ABF16, NORM, VS, NT, ANC, STG, SDT, CV>(
q, k, v, av, bv, ab_stride, A_log, dt_bias, state, st_slot, st_head, o, oq, os, oq_pitch,
os_ld, cu, sidx, sidx_stride, naccept, zg, zg_pitch, nw, neps, nact, H, Hg, scale, sp_thr,
cv);
if (CH::on) r4d_chain_done();
}
#undef RU_PARAMS
// Non-temporal hint on the state load and store (TH_LOAD_NT / TH_STORE_NT): no result changes;
// chosen per launch because its cost and saving land in different kernels. In isolation it makes
@@ -818,14 +835,6 @@ static bool ru_anchor() {
#define RU_NT_MB 16
// `oq_i8` picks the folded quantiser's codes: E4M3 (0) or int8 (1); see the kernel's epilogue.
/* The chained form (r4d_chain.h) for this thread's launch: set by the plugin ABI entries below from
* the row's `chain`, around their launch only, so the C entry point never chains. */
static thread_local bool g_ru_chain = false;
struct RuChainScope {
explicit RuChainScope(bool on) { g_ru_chain = on; }
~RuChainScope() { g_ru_chain = false; }
};
static int ru_update_launch(
const void* q, const void* k, const void* v, const void* a, const void* b,
long ab_stride, int ab_is_bf16, const void* A_log, const void* dt_bias, void* state,
@@ -851,8 +860,8 @@ static int ru_update_launch(
dim3 grid(N, H, vs), blk(RU_V / vs * 2);
// Every switch is a template parameter; the nested pick macros enumerate the instantiations.
#define RU_LAUNCH(AB, NM, VSC, NTC, ANCC, STGC, SDTC) \
hipLaunchKernelGGL((g_ru_chain ? &r4dchain_gdn_recurrent_update<AB, NM, VSC, NTC, ANCC, STGC, SDTC> \
: &r4d_gdn_recurrent_update_kernel<AB, NM, VSC, NTC, ANCC, STGC, SDTC>), \
hipLaunchKernelGGL((r4d_gdn_recurrent_update_kernel<AB, NM, VSC, NTC, ANCC, STGC, SDTC, 0, \
R4dUnchained>), \
grid, blk, 0, (hipStream_t)stream, \
(const unsigned short*)q, (const unsigned short*)k, \
(const unsigned short*)v, a, b, ab_stride, \
@@ -937,41 +946,18 @@ extern "C" int r4d_gdn_recurrent_update_k128_v128_bf16_fp32state(
// sharing a block must not overlap: different streams get different blocks, and launches on one
// stream sharing an output are ordered by their dependency.
constexpr unsigned kMaxConvCtr = 4096;
static_assert(kRuPairCtr * 2 == kMaxConvCtr, "the pairs' counters are the block's upper half");
static unsigned int* ru_conv_ctr(RadStream s, const void* out) {
static std::mutex m;
static std::map<std::pair<RadStream, const void*>, unsigned int*> blocks;
const auto key = std::make_pair(s, out);
{
// Not held while the block is made, as in split_ctr: the zeroing waits for the card.
std::lock_guard<std::mutex> lk(m);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
}
void* p = nullptr;
if (hipMalloc(&p, (size_t)kMaxConvCtr * sizeof(unsigned int)) != hipSuccess) return nullptr;
// Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has finished
// when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it runs on the
// null stream, which a non-blocking stream does not wait for, so wait here.
if (hipMemset(p, 0, (size_t)kMaxConvCtr * sizeof(unsigned int)) != hipSuccess ||
hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return nullptr;
}
unsigned int* kept = nullptr;
{
std::lock_guard<std::mutex> lk(m);
const auto [it, fresh] = blocks.emplace(key, (unsigned int*)p);
if (fresh) return it->second;
kept = it->second;
}
(void)hipFree(p); // another thread made this key's block in the meantime
return kept;
return r4d::keyed_block(r4d::Keyed::GdnConv, s, out,
(size_t)kMaxConvCtr * sizeof(unsigned int));
}
// The recurrent update with gdn_conv_update folded in, decode shape only (bf16 a/b, fused row
// norm, one workgroup per (sequence, value head)). State contract, non-temporal choice and
// factor-block bounds are as in ru_update_launch. `w_f32` is the conv weight's type. `oq_i8`:
// E4M3 codes (0), int8 (1), or had_quant_act_i8g's rotated int8 (2).
// E4M3 codes (0), int8 (1), had_quant_act_i8g's rotated int8 (2), or those at IQ8R's one scale
// per 256 columns (3). `chain`: the chained form (r4d_chain.h); the launch is the op's only one.
static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void* b, long ab_stride,
const void* A_log, const void* dt_bias, void* state,
long st_slot, long st_head, void* o, void* oq, void* os,
@@ -979,7 +965,8 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void*
long sidx_stride, const void* nacc, const void* z,
long z_pitch, const void* nw, float neps, int nact, int N,
int H, int Hg, float scale, float thr, int state_fp16,
RadStream stream, int oq_i8, bool anc, bool w_f32) {
RadStream stream, int oq_i8, bool anc, bool w_f32,
bool chain) {
if (anc && sidx_stride < 6) return RAD_E_SHAPE;
if (anc && sidx_stride * RU_FSTR > st_head) return RAD_E_SHAPE;
const int sdt = state_fp16 ? 1 : 0;
@@ -988,12 +975,15 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void*
const bool nt = flood <= (long)RU_NT_MB * 1024 * 1024;
const dim3 grid(N, H, 1), blk(RU_V * 2);
#define RC_LAUNCH(NTC, ANCC, SDTC, CVC) \
do { if (oq_i8 == 2) RC_LAUNCH_NM(3, NTC, ANCC, SDTC, CVC); \
do { if (oq_i8 == 3) RC_LAUNCH_NM(4, NTC, ANCC, SDTC, CVC); \
else if (oq_i8 == 2) RC_LAUNCH_NM(3, NTC, ANCC, SDTC, CVC); \
else if (oq_i8) RC_LAUNCH_NM(2, NTC, ANCC, SDTC, CVC); \
else RC_LAUNCH_NM(1, NTC, ANCC, SDTC, CVC); } while (0)
#define RC_LAUNCH_NM(NM, NTC, ANCC, SDTC, CVC) \
hipLaunchKernelGGL((g_ru_chain ? &r4dchain_gdn_recurrent_update<1, NM, 1, NTC, ANCC, 0, SDTC, CVC> \
: &r4d_gdn_recurrent_update_kernel<1, NM, 1, NTC, ANCC, 0, SDTC, CVC>), \
do { if (chain) RC_LAUNCH_CH(NM, NTC, ANCC, SDTC, CVC, r4dchain); \
else RC_LAUNCH_CH(NM, NTC, ANCC, SDTC, CVC, R4dUnchained); } while (0)
#define RC_LAUNCH_CH(NM, NTC, ANCC, SDTC, CVC, CH_) \
hipLaunchKernelGGL((r4d_gdn_recurrent_update_kernel<1, NM, 1, NTC, ANCC, 0, SDTC, CVC, CH_>), \
grid, blk, 0, (hipStream_t)stream, nullptr, nullptr, nullptr, a, b, \
ab_stride, (const float*)A_log, (const float*)dt_bias, \
(ru_state<SDTC>::T*)state, st_slot, st_head, (unsigned short*)o, \
@@ -1013,6 +1003,7 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void*
#undef RC_PICKNT
#undef RC_LAUNCH
#undef RC_LAUNCH_NM
#undef RC_LAUNCH_CH
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
@@ -1116,7 +1107,6 @@ extern "C" int r4d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s) {
/* Slot and head strides come from the tensor, so a cache with padded slots is served too
* (see the header); the engine's own state cache is dense ([n_states, H, V, K] per layer). */
const RuChainScope chain_scope(r4d_geti_or(a, "chain", 0) != 0);
return R4D_RAW(ru_update_launch(
q->data, k->data, v->data, ta->data, tb->data, (long)ab_stride, ab_is_bf16,
alog->data, dtb->data, state->data,
@@ -1190,6 +1180,14 @@ static int gdn_conv_recurrent_entry(const RadArgs* a, RadStream s, bool had) {
const long long nhv = r4d_geti_or(a, "n_head_v", 0);
if (nhv > 0 && nhv != H) return R4D_NO(RAD_E_SHAPE);
if ((long long)N * Hg > (long long)kMaxConvCtr) return R4D_NO(RAD_E_SHAPE);
/* `group` 256 (the `_had` op alone): one scale per two value heads, whose arrival counters
* share the block with the key heads'. */
const long long qgrp = r4d_geti_or(a, "group", RU_V);
const bool wide = had && qgrp == 2 * RU_V;
if (qgrp != RU_V && !wide) return R4D_NO(RAD_E_UNSUPPORTED);
if (wide && (H % 2 || (long long)N * Hg > (long long)kRuPairCtr ||
(long long)N * (H / 2) > (long long)kRuPairCtr))
return R4D_NO(RAD_E_SHAPE);
const long long xpitch = r4d_row_pitch(x);
if (xpitch < 0) return R4D_NO(RAD_E_STRIDE);
@@ -1237,7 +1235,6 @@ static int gdn_conv_recurrent_entry(const RadArgs* a, RadStream s, bool had) {
cv.ctr = ru_conv_ctr(s, o->data);
if (!cv.ctr) return R4D_NO(RAD_E_NOMEM);
const RuChainScope chain_scope(r4d_geti_or(a, "chain", 0) != 0);
return ru_conv_recurrent_launch(
cv, ta->data, tb->data, (long)ab_stride, alog->data, dtb->data, state->data,
(long)state->stride[0], (long)state->stride[1], o->data, oq ? oq->data : nullptr,
@@ -1245,7 +1242,9 @@ static int gdn_conv_recurrent_entry(const RadArgs* a, RadStream s, bool had) {
os ? (long)r4d_row_pitch(os) : 0, cu->data, sidx->data, (long)sidx->stride[0],
nacc ? nacc->data : nullptr, z->data, (long)z_row, nw->data, neps, nact, N, (int)H,
(int)Hg, scale, thr, state->dtype == RAD_F16 ? 1 : 0, s,
had ? 2 : oq && oq->dtype == RAD_I8 ? 1 : 0, anc != 0, cw->dtype == RAD_F32);
wide ? 3 : had ? 2 : oq && oq->dtype == RAD_I8 ? 1 : 0, anc != 0,
cw->dtype == RAD_F32,
r4d_geti_or(a, "chain", 0) != 0);
}
extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s) {
+17 -7
View File
@@ -94,13 +94,19 @@ struct PrefillPlain {
/* ROWF (RB 32): the weight's scale is one f32 a row times one f32 a 128-K block for all rows (an
* IQR weight under kRowF32): the block's factor `Cf[kb]` is the fold's wave-uniform scale, as RB
* 32's, and each row's `Rs[n]` scales its outputs at the store. */
template <bool I8, int RB, class Pre, bool ROWF = false>
/* SB (I8, RB 0): the K extent of one scale on both sides, 128 or IQ8R's 256. A block of SB
* columns is SB / kPFK staged tiles; the int32 sums run over all of them before the one fold
* (|sum| <= 256 * 127 * 127 < 2^24, exact in the f32 conversion), so at 256 the tile folds half as
* often. */
template <bool I8, int RB, class Pre, bool ROWF = false, uint32_t SB = kBlock>
__device__ __forceinline__ void gemm_8a8_prefill_body(
const uint8_t* __restrict__ A, const float* __restrict__ Sa, const uint8_t* __restrict__ W,
const uint16_t* __restrict__ Sw, uint16_t* __restrict__ C, uint32_t M, uint32_t K, uint32_t N,
uint32_t a_ld, uint32_t sa_ld, uint32_t sw_ld, const Pre& pre,
const float* __restrict__ Rs = nullptr, const float* __restrict__ Cf = nullptr) {
static_assert(!ROWF || RB == 32, "a row's scale and a block's factor fold as RB 32's one scale");
static_assert(SB == kBlock || (I8 && RB == 0 && SB == 256u), "a 256 group is the per-row int8 tile's");
constexpr uint32_t kTPB = SB / kPFK; // staged tiles a scale block
constexpr uint32_t P = lds_pitch<kPFK>();
static_assert(kPBM * 2u == kPWaves * kWave, "two threads stage an activation row");
// Double-buffered: one barrier a staged tile, which publishes it.
@@ -129,7 +135,7 @@ __device__ __forceinline__ void gemm_8a8_prefill_body(
bn = r / gm;
}
const uint32_t m0 = bm * kPBM, n0 = bn * kPBN;
const uint32_t ksuper = K / kSuperK, nkb = K / kBlock;
const uint32_t ksuper = K / kSuperK, nkb = K / SB;
pre.begin(bm, bn, &s_a[0][0]);
// Staging: two threads a row, 32 bytes each. Rows past M re-read row M-1, and every load is
@@ -176,20 +182,20 @@ __device__ __forceinline__ void gemm_8a8_prefill_body(
* k steps from `cur`. The first k step of a block starts from a zero accumulator, so `raw` needs
* no clearing after the fold. */
auto tile = [&](uint32_t kb, uint32_t half, Stage8 (&cur)[kPTW], Stage8 (&nxt)[kPTW]) {
stage8_store<kPFK>(s_a[half], sr, sc, pa);
if (half == 1u) s_as[(kb + 1u) % 2u][tid % kPBM] = scn;
stage8_store<kPFK>(s_a[half % 2u], sr, sc, pa);
if (half == kTPB - 1u) s_as[(kb + 1u) % 2u][tid % kPBM] = scn;
lds_barrier();
const uint32_t c1 = min(kb * kBlock + (half + 1u) * kPFK, K - kPFK);
const uint32_t c1 = min(kb * SB + (half + 1u) * kPFK, K - kPFK);
pa = stage8_load(asrc + c1, true);
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
nxt[i] = stage8_load(wsrc + ((size_t)i * ksuper + c1 / kSuperK) * kTileBytes, true);
if (half == 1u) scn = ssrc[min(kb + 2u, nkb - 1u)];
if (half == kTPB - 1u) scn = ssrc[min(kb + 2u, nkb - 1u)];
#pragma unroll
for (uint32_t ks = 0; ks < kPFK / kK; ++ks) {
i2v bf[kPTA];
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j) bf[j] = frag<kPFK>(s_a[half], arow + j * 16u, ks * kK, lane);
for (uint32_t j = 0; j < kPTA; ++j) bf[j] = frag<kPFK>(s_a[half % 2u], arow + j * 16u, ks * kK, lane);
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i) {
const i2v af = frag_of(cur[i], ks);
@@ -226,6 +232,10 @@ __device__ __forceinline__ void gemm_8a8_prefill_body(
}
tile(kb, 0u, w0, w1);
tile(kb, 1u, w1, w0);
if constexpr (kTPB == 4u) {
tile(kb, 2u, w0, w1);
tile(kb, 3u, w1, w0);
}
if constexpr (RB != 0) {
if (kb % kRbFlush == 0u && kb) { // the last kRbFlush blocks' bias, before this fold
#pragma unroll
+4
View File
@@ -155,6 +155,10 @@ static inline int cfg_for(const RadArgs* a, long long K, long long M, long long
out->npw = 4;
sk_pin = 8;
}
/* W2A8 at one row tile is bound by the weight stream (a vocabulary head of 80 to 170 MB), and
* its N tiles already fill the card, so a deep split only adds reduction work: the ladder's
* answer of 20 at K = 2560 runs the 124160-row head in 144 us where a split of 2 takes 133. */
if (br == BR_W2A8 && c->mb <= 0 && out->mb == 1) sk_pin = 2;
const int bound = block_bound(br, out->mb, out->npw);
if (sk_pin && (out->wv * sk_pin * 32 > bound ||
(unit > 0 && (K % ((long long)sk_pin * unit)))))
-32
View File
@@ -714,9 +714,6 @@ __global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void r4
#undef R4D_LMW_PARAMS
} // namespace
extern "C" int r4d_gemm_fp8a16_nt_m1_block(void) { return (int)kBlock; }
extern "C" int r4d_gemm_fp8a16_nt_m1_max_m(void) { return (int)kMaxMt; }
// C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T for M <= kMaxMt, one weight read for all M rows.
//
// a [M][K] bf16, `a_ld` elements a row (0 = K)
@@ -983,10 +980,6 @@ static int rad_logits_gemm_8(const RadArgs* a, RadStream s, bool i8) {
(int)x_ld, (int)y_ld, (int)stride, (long)(uintptr_t)s, ch) == 0 ? RAD_OK : RAD_E_DEVICE;
}
extern "C" int r4d_rad_logits_gemm_fp8(const RadArgs* a, RadStream s) {
return rad_logits_gemm_8(a, s, false);
}
/* The int8 head: the same operands and stored row, i8 codes (r4d_rad_layout_i8_logits). */
extern "C" int r4d_rad_logits_gemm_i8(const RadArgs* a, RadStream s) {
return rad_logits_gemm_8(a, s, true);
@@ -1030,28 +1023,3 @@ extern "C" int r4d_rad_logits_gemm_iqr(const RadArgs* a, RadStream s) {
// The shared operand reader is r4d_fp8_args.h; see libr4d/r4d_args.h.
/* ================================================================== the fp8 GEMMs */
extern "C" int r4d_rad_gemm_fp8a16_m1(const RadArgs* a, RadStream s) {
Fp8Ops g;
int rc = fp8_ops(a, &g, 0);
if (rc != RAD_OK) return rc;
if (g.M > r4d_gemm_fp8a16_nt_m1_max_m()) return R4D_NO(RAD_E_SHAPE);
/* This kernel reads bf16 directly; refuse an activation scale rather than silently drop it. */
if (g.ascale) return R4D_NO(RAD_E_INVAL);
/* M = 1 keeps the one-row kernel (its own RB tuning; every non-speculative decode step), so a
* deployment that never speculates runs exactly that arithmetic. Above one row, the multi-row
* form reads the weight once for all M rows. */
if (g.M == 1) {
R4dMvCfg mv;
r4d_cfg_mv(a, &mv);
const int e = r4d_gemm_fp8a16_nt_m1(r4d_addr(g.a), r4d_addr(g.b), r4d_addr(g.bscale),
r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N,
(int)g.w_ld, (int)g.sw_ld, mv.rb, (long)(uintptr_t)s);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
/* `c_ld` is 0 because fp8_ops has already refused any output whose row pitch is not N. */
const int e = r4d_gemm_fp8a16_nt_mt(r4d_addr(g.a), r4d_addr(g.b), r4d_addr(g.bscale),
r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N,
(int)g.a_ld, 0, (int)g.w_ld, (int)g.sw_ld,
(long)(uintptr_t)s);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
+258 -561
View File
File diff suppressed because it is too large. Load diff
+314 -92
View File
@@ -11,13 +11,15 @@
// caller's scratch, which the tile's blocks decode as they arrive, each value
// once.
//
// The narrow tile above 16 tokens and the prefill tile compute what the int8 tiles compute over the
// same int8 values (their split, staging, accumulation order and fold), so a weight decoded here
// and the same weight's int8 values in the int8 kernels give the same output bytes. The GEMV and
// The narrow tile above 16 tokens and the prefill tile compute what the int8 narrow and prefill
// tiles compute over the same int8 values (their split, staging, accumulation order and fold), so
// a weight decoded here and the same weight's int8 values in those tiles give the same output
// bytes (the int8 rows' K-parallel tile, r4d_gemm_fp8a8.hip, sums in another order). The GEMV and
// the 16-token tile sum per wave and then across waves: the product within f32 rounding.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_chain.h"
#include "r4d_emit.h"
#include "r4d_fp8_wmma.h"
#include "r4d_iqr.h"
@@ -50,6 +52,29 @@ constexpr uint32_t kWave = 32, kBlock = 128, kFK = 256;
* the outputs (K = 3072) 29 -> 24 / 25 / 30 us; 1024 and more lose on the outputs. */
constexpr uint32_t kIqrSplitWaves = 512;
/* The forms are built in kIqrParts units, each this file under its own R4D_IQR_PART (the
* r4d_gemm_iqr_p<k>.hip wrappers; this unit is part 0), so their kernels compile in parallel. A
* form's part is its place in R4D_IQR_FORMS modulo the count, which spreads every family over all
* parts. Part 0 alone defines the rows' entry points and hands each call to its form's part. */
#ifndef R4D_IQR_PART
#define R4D_IQR_PART 0
#endif
constexpr int kIqrParts = 4;
#define R4D_IQR_W(k, b, lv, l, lrb, sc) FormT<k, b, lv, l, lrb, sc>::word(),
constexpr uint32_t kIqrWords[] = { R4D_IQR_FORMS(R4D_IQR_W) };
#undef R4D_IQR_W
/* The part building the form with kernel word `kw`; 0 for a word that is no form, whose call part 0
* then refuses as before. */
constexpr int iqr_part(uint32_t kw) {
for (size_t i = 0; i < sizeof(kIqrWords) / sizeof(kIqrWords[0]); ++i)
if (kIqrWords[i] == kw) return (int)(i % kIqrParts);
return 0;
}
template <class F>
constexpr bool in_part() { return iqr_part(F::word()) == R4D_IQR_PART; }
#include "r4d_gemm_8a8_prefill.h"
/* ---- the gated fold (gemm_nt_q_gated at i8a8h) ----------------------------------------------
@@ -124,11 +149,12 @@ __device__ __forceinline__ void gated_tail(const GatedOut& go, uint32_t M, uint3
*
* The fold order differs from the WMMA tile's (per lane, then across lanes and waves), so the
* output is the product within f32 rounding rather than the int8 tile's bytes. */
template <class F, uint32_t MT, uint32_t KW, bool GATED = false>
template <class F, uint32_t MT, uint32_t KW, bool GATED, class CH>
__global__ __launch_bounds__((GATED ? 2u : 1u) * KW * kWave) R4D_WAVES(6)
void iqr_gemv_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restrict__ XS,
uint16_t* __restrict__ Y, uint32_t N, uint32_t x_ld, uint32_t xs_ld,
GatedOut go) {
if (CH::on) r4d_chain_wait();
using D = Dec<F, true>;
constexpr uint32_t NW = (GATED ? 2u : 1u) * KW;
__shared__ __attribute__((aligned(16))) int8_t s_tab[D::kTab];
@@ -263,21 +289,24 @@ void iqr_gemv_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restri
}
cur = nxt;
}
/* every lane's rows carry 12582912 times the factors once for each of its blocks */
/* every lane's rows carry 12582912 times the factors once for each of its blocks; a token's
* sixteen rows are summed over the wave together (red16), lane l left with row red16_row(l) */
float rv[MT];
#pragma unroll
for (uint32_t q = 0; q < 16; ++q)
for (uint32_t m = 0; m < MT; ++m) {
float a16[16];
#pragma unroll
for (uint32_t m = 0; m < MT; ++m) acc[q][m] = r4d_wave_sum(fmaf(-kRbBiasF, fsum[m], acc[q][m]));
if (lane == 0) {
for (uint32_t q = 0; q < 16; ++q) a16[q] = fmaf(-kRbBiasF, fsum[m], acc[q][m]);
rv[m] = red16(a16, lane);
}
if (lane < 16u) {
#pragma unroll
for (uint32_t q = 0; q < 16; ++q)
#pragma unroll
for (uint32_t m = 0; m < MT; ++m) s_red[wave0][q * MT + m] = acc[q][m];
for (uint32_t m = 0; m < MT; ++m) s_red[wave0][lane * MT + m] = rv[m];
}
__syncthreads();
if constexpr (GATED) {
if (tid < 16u * MT) {
const uint32_t q = tid / MT, m = tid % MT;
const uint32_t q = red16_row(tid / MT), m = tid % MT;
float vg = 0.0f, vu = 0.0f;
#pragma unroll
for (uint32_t w = 0; w < KW; ++w) vg += s_red[w][tid];
@@ -290,7 +319,7 @@ void iqr_gemv_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restri
gated_tail(go, MT, NW);
} else {
if (tid < 16u * MT) {
const uint32_t q = tid / MT, m = tid % MT;
const uint32_t q = red16_row(tid / MT), m = tid % MT;
float v = 0.0f;
#pragma unroll
for (uint32_t w = 0; w < KW; ++w) v += s_red[w][tid];
@@ -299,6 +328,7 @@ void iqr_gemv_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restri
Y[(size_t)m * N + rt * 16u + q] = f32_to_bf16(v);
}
}
if (CH::on) r4d_chain_done();
}
/* ---- the narrow tile at M <= 16 -------------------------------------------------------------
@@ -308,26 +338,37 @@ void iqr_gemv_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restri
* fragment order through its own LDS tile (frag), then runs the unit's eight WMMA steps against
* the activation's fragments read straight from global memory, where the M x K activation sits
* in L2, so the loop has no block barrier and no shared staging. Rows of the token tile past M
* read token M - 1; their outputs are not stored.
* read token M - 1; their outputs are not stored. NT token tiles a block (to 64 tokens): a unit
* is decoded and transposed once and multiplied against each tile in turn, the further tiles'
* fragments asked for a tile ahead. Measured cold against the narrow tile at the trunk's per-rank
* shapes, 6 bits, us a launch: 6144 x 2560 at 32 tokens 38.8 -> 30.4 and at 64 53.8 -> 34.6;
* 2560 x 3072 at 32 tokens 31.1 -> 20.4 and at 64 47.4 -> 24.6; 8192 x 2560 level (36.2 / 37.2
* at 32, 42.0 / 42.5 at 64).
*
* Under one f32 scale a row each unit's int32 sums start at 0x4B400000, so a slot read as an f32
* is 12582912 plus its sum and one fma folds it (the prefill tile's RB 32 fold), flushed every
* kRbFlush units; other scale forms fold the converted sum with their (row, block) scales. The
* waves' partials are summed through LDS in ascending wave order, so the output is the product
* within f32 rounding, not the int8 tile's bytes. */
template <class F, uint32_t KW, bool GATED = false>
template <class F, uint32_t KW, bool GATED, uint32_t NT, class CH>
__global__ __launch_bounds__((GATED ? 2u : 1u) * KW * kWave) R4D_WAVES(6)
void iqr_m16_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restrict__ XS,
uint16_t* __restrict__ Y, uint32_t N, uint32_t M, uint32_t x_ld, uint32_t xs_ld,
GatedOut go) {
if (CH::on) r4d_chain_wait();
using D = Dec<F>;
static_assert(!GATED || NT == 1u, "the gated form serves one token tile");
constexpr bool BIAS = F::SC == kRowF32;
constexpr uint32_t NW = (GATED ? 2u : 1u) * KW;
__shared__ __attribute__((aligned(16))) int8_t s_tab[D::kTab];
/* the waves' transpose tiles, then their partials (8 x 32 floats a wave, in its own tile) */
/* the waves' transpose tiles, then their partials (8 x 32 floats a wave): one token tile's
* in the wave's own transpose tile, several tiles' in s_nt */
__shared__ __attribute__((aligned(16))) uint8_t s_tr[NW * kTrBytes];
__shared__ float s_nt[NT > 1u ? NW : 1u][NT > 1u ? NT : 1u][NT > 1u ? 8u * kWave : 1u];
static_assert(8u * kWave * 4u <= kTrBytes, "a wave's partials in its transpose tile");
auto red = [&](uint32_t w) { return (float*)(s_tr + w * kTrBytes); };
auto red = [&](uint32_t w, uint32_t j) {
return NT > 1u ? &s_nt[w][j][0] : (float*)(s_tr + w * kTrBytes);
};
const uint32_t tid = threadIdx.x, lane = tid & (kWave - 1);
const uint32_t wave0 = __builtin_amdgcn_readfirstlane(tid / kWave);
Ctx c = c0;
@@ -339,52 +380,49 @@ void iqr_m16_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restric
/* Gated, waves KW and up take the up rows' tile, n rows below the gate rows'. */
const uint32_t half = GATED ? wave0 / KW : 0u, wave = GATED ? wave0 % KW : wave0;
const uint32_t rt = blockIdx.x + half * (N / 32u), row0 = rt * 16u;
const uint32_t tok = min(frag_c(lane), M - 1u);
const int8_t* const xrow = X + (size_t)tok * x_ld + frag_k0(lane);
/* Token tile j is tokens 16 j .. 16 j + 15; a column past M reads token M - 1. */
uint32_t tok[NT];
const int8_t* xrow[NT];
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
tok[j] = min(j * 16u + frag_c(lane), M - 1u);
xrow[j] = X + (size_t)tok[j] * x_ld + frag_k0(lane);
}
f8v out = acc_zero();
float corr = 0.0f; /* BIAS: the units' fold factors since the last flush */
f8v out[NT];
float corr[NT]; /* BIAS: the units' fold factors since the last flush */
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
out[j] = acc_zero();
corr[j] = 0.0f;
}
uint32_t nflush = 0;
auto bload = [&](uint32_t kb, i2v (&b)[8], bool live) {
auto bload = [&](uint32_t j, uint32_t kb, i2v (&b)[8], bool live) {
#pragma unroll
for (uint32_t ks = 0; ks < 8; ++ks) {
const uint2 v = live ? *(const uint2*)(xrow + kb * kBlock + ks * kK) : make_uint2(0u, 0u);
const uint2 v = live ? *(const uint2*)(xrow[j] + kb * kBlock + ks * kK)
: make_uint2(0u, 0u);
b[ks][0] = (int)v.x;
b[ks][1] = (int)v.y;
}
};
/* The weight and the first token tile are asked for a unit ahead of their WMMA steps, each
* further tile's fragments a tile ahead (gemm_i8_kpar_kernel's order). */
typename D::Raw cur = D::fetch(c, rt, wave, lane, wave < c.nkb), nxt;
i2v bc[8], bn[8];
bload(wave, bc, wave < c.nkb);
i2v bc[8], bn[8], bq[2][8];
bload(0u, wave, bc, wave < c.nkb);
for (uint32_t kb = wave; kb < c.nkb; kb += KW) {
if (kb + KW < c.nkb) {
nxt = D::fetch(c, rt, kb + KW, lane, true);
bload(kb + KW, bn, true);
bload(0u, kb + KW, bn, true);
}
uint32_t w[16];
D::rows(cur, c, rb_ratio<F>(c, row0 + (lane & 15u), kb), w);
D::unzero(c, rt, kb, w);
Stage8 a8[2];
frag(w, tr, lane, a8);
/* two chains of four steps, so a step does not wait on the one before it */
f8v raw = rb_first<BIAS ? 32 : 0>();
#pragma unroll
for (uint32_t ks = 0; ks < kBlock / kK; ++ks)
raw = mma8<true>(frag_of(a8[ks / 4u], ks % 4u), bc[ks], raw);
const float as = XS[(size_t)tok * xs_ld + kb];
if constexpr (BIAS) {
const float sb = fold_f32<F>(c, row0, kb) * as;
corr += sb;
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) out[t] = __builtin_fmaf(raw[t], sb, out[t]);
if (++nflush == kRbFlush) {
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) out[t] = __builtin_fmaf(-kRbBiasF, corr, out[t]);
corr = 0.0f;
nflush = 0;
}
} else {
float wsr[8];
float wsr[8]; /* the lane's eight rows' (row, block) scales, where the form has them */
if constexpr (!BIAS) {
if constexpr (F::SC == kBf16 && F::LRB == 0) {
/* A bf16 scale a (row, 128): the lane's eight rows are consecutive in the tile's
* scale run (own_scale's order), 16 aligned bytes, one load. */
@@ -400,9 +438,42 @@ void iqr_m16_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restric
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) wsr[t] = fold_f32<F>(c, row0 + acc_row(lane, t), kb);
}
}
float sbw = 0.0f; /* BIAS: the unit's fold factor before the token's scale */
if constexpr (BIAS) sbw = fold_f32<F>(c, row0, kb);
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
out[t] = __builtin_fmaf(acc_val<true>(raw[t]), wsr[t] * as, out[t]);
for (uint32_t ks = 0; ks < 8; ++ks) bq[0][ks] = bc[ks];
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
if (j + 1u < NT) bload(j + 1u, kb, bq[(j + 1u) & 1u], true);
/* two chains of four steps, so a step does not wait on the one before it */
f8v raw = rb_first<BIAS ? 32 : 0>();
#pragma unroll
for (uint32_t ks = 0; ks < kBlock / kK; ++ks)
raw = mma8<true>(frag_of(a8[ks / 4u], ks % 4u), bq[j & 1u][ks], raw);
const float as = XS[(size_t)tok[j] * xs_ld + kb];
if constexpr (BIAS) {
const float sb = sbw * as;
corr[j] += sb;
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) out[j][t] = __builtin_fmaf(raw[t], sb, out[j][t]);
} else {
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
out[j][t] = __builtin_fmaf(acc_val<true>(raw[t]), wsr[t] * as, out[j][t]);
}
}
if constexpr (BIAS) {
if (++nflush == kRbFlush) {
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
out[j][t] = __builtin_fmaf(-kRbBiasF, corr[j], out[j][t]);
corr[j] = 0.0f;
}
nflush = 0;
}
}
cur = nxt;
#pragma unroll
@@ -412,7 +483,11 @@ void iqr_m16_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restric
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront", "local");
__builtin_amdgcn_wave_barrier();
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) red(wave0)[t * kWave + lane] = BIAS ? __builtin_fmaf(-kRbBiasF, corr, out[t]) : out[t];
for (uint32_t j = 0; j < NT; ++j)
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
red(wave0, j)[t * kWave + lane] =
BIAS ? __builtin_fmaf(-kRbBiasF, corr[j], out[j][t]) : out[j][t];
__syncthreads();
if constexpr (GATED) {
if (wave0 == 0) {
@@ -422,9 +497,9 @@ void iqr_m16_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restric
for (uint32_t t = 0; t < 8; ++t) {
float ag = 0.0f, au = 0.0f;
#pragma unroll
for (uint32_t w = 0; w < KW; ++w) ag += red(w)[t * kWave + lane];
for (uint32_t w = 0; w < KW; ++w) ag += red(w, 0u)[t * kWave + lane];
#pragma unroll
for (uint32_t w = 0; w < KW; ++w) au += red(KW + w)[t * kWave + lane];
for (uint32_t w = 0; w < KW; ++w) au += red(KW + w, 0u)[t * kWave + lane];
ag *= row_scale<F>(c, blockIdx.x * 16u + r0 + t);
au *= row_scale<F>(c, (blockIdx.x + N / 32u) * 16u + r0 + t);
if (col < M) gated_put(go, col, blockIdx.x * 16u + r0 + t, ag, au);
@@ -432,20 +507,28 @@ void iqr_m16_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restric
}
gated_tail(go, M, NW);
} else if (wave == 0) {
const uint32_t col = frag_c(lane);
const uint32_t r0 = row0 + acc_row(lane, 0);
float v[8];
float rs[8];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
float a = 0.0f;
for (uint32_t t = 0; t < 8; ++t) rs[t] = row_scale<F>(c, r0 + t);
#pragma unroll
for (uint32_t w = 0; w < KW; ++w) a += red(w)[t * kWave + lane];
v[t] = a * row_scale<F>(c, r0 + t);
for (uint32_t j = 0; j < NT; ++j) {
const uint32_t col = j * 16u + frag_c(lane);
float v[8];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
float a = 0.0f;
#pragma unroll
for (uint32_t w = 0; w < KW; ++w) a += red(w, j)[t * kWave + lane];
v[t] = a * rs[t];
}
if (col < M)
*(uint4*)(Y + (size_t)col * N + r0) =
make_uint4(bf16x2_rne(v[0], v[1]), bf16x2_rne(v[2], v[3]),
bf16x2_rne(v[4], v[5]), bf16x2_rne(v[6], v[7]));
}
if (col < M)
*(uint4*)(Y + (size_t)col * N + r0) = make_uint4(bf16x2_rne(v[0], v[1]), bf16x2_rne(v[2], v[3]),
bf16x2_rne(v[4], v[5]), bf16x2_rne(v[6], v[7]));
}
if (CH::on) r4d_chain_done();
}
/* ---- the narrow tile: 16 < M <= 64 -----------------------------------------------------------
@@ -455,12 +538,12 @@ void iqr_m16_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restric
* last z block reducing. Only the weight operand's source differs: each 128-K block's unit is
* decoded and transposed into fragment order through the wave's LDS tile (r4d_iqr_dec.h), its two
* supertiles just before their eight WMMA steps. The int8 tile's arithmetic, so its bytes. */
#define R4D_IQR_M64_PARAMS \
Ctx c0, const uint8_t* __restrict__ Bp, const float* __restrict__ Sb, void* __restrict__ Y, \
uint16_t* __restrict__ C, unsigned int* __restrict__ Ctr, uint32_t rows, uint32_t cols, \
uint32_t nb, uint32_t b_ld, uint32_t sb_ld, uint32_t ck
template <class F, uint32_t NT, uint32_t MW>
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(MW >= 8u ? 4u : 6u)
void iqr_m64_kernel(Ctx c0, const uint8_t* __restrict__ Bp, const float* __restrict__ Sb,
void* __restrict__ Y, uint16_t* __restrict__ C, unsigned int* __restrict__ Ctr,
uint32_t rows, uint32_t cols, uint32_t nb, uint32_t b_ld, uint32_t sb_ld,
uint32_t ck) {
__device__ __forceinline__ void iqr_m64_body(R4D_IQR_M64_PARAMS) {
using D = Dec<F>;
constexpr uint32_t FK = kFK, FN = NT * 16, FM = MW * 16, kU = FK / kBlock;
__shared__ uint8_t s_b[FN * lds_pitch<FK>()];
@@ -657,6 +740,17 @@ void iqr_m64_kernel(Ctx c0, const uint8_t* __restrict__ Bp, const float* __restr
}
}
/* The kernel around the body, whose blocks past the split's K return at once: CH `r4dchain` is
* the chained form (r4d_chain.h). */
template <class F, uint32_t NT, uint32_t MW, class CH>
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(MW >= 8u ? 4u : 6u)
void iqr_m64_kernel(R4D_IQR_M64_PARAMS) {
if (CH::on) r4d_chain_wait();
iqr_m64_body<F, NT, MW>(c0, Bp, Sb, Y, C, Ctr, rows, cols, nb, b_ld, sb_ld, ck);
if (CH::on) r4d_chain_done();
}
#undef R4D_IQR_M64_PARAMS
/* The split's separate reduce, for a split with no counter block (r4d_gemm_fp8a8.hip's). */
__global__ void iqr_splitk_reduce(const float* __restrict__ ws, uint16_t* __restrict__ y,
uint32_t n_out, uint32_t ksplit) {
@@ -792,14 +886,25 @@ struct Operands {
const RadTensor *a, *as, *b, *bs, *y;
long long M, N, K, nkb, a_ld, sa_ld;
uint32_t word;
bool chain; /* the row's `chain` parameter: the chained forms (r4d_chain.h) */
};
/* The forms whose GEMV and 16-token tile have chained instantiations: the computed trellises, and
* the plain 4-bit table a DFlash2 drafter's linears are held in. Every other form's launch stays
* plain, which keeps the instantiations to the forms a decode step meets. */
template <class F>
constexpr bool chained_form() {
return F::KIND == kTrellisMad ||
(F::KIND == kTable && F::B == 4 && F::LV == 0 && F::L == 0 && F::LRB == 0 && F::SC == 0);
}
int operands(const RadArgs* a, Operands* g) {
g->a = r4d_opt(a, 0);
g->as = r4d_opt(a, 1);
g->b = r4d_opt(a, 2);
g->bs = r4d_opt(a, 3);
g->y = r4d_opt(a, 4);
g->chain = r4d_geti_or(a, "chain", 0) != 0;
if (!g->a || !g->as || !g->b || !g->bs || !g->y) return R4D_NO(RAD_E_INVAL);
if (!is_weight_dtype(g->b->dtype) || !is_scale_dtype(g->bs->dtype)) return R4D_NO(RAD_E_DTYPE);
g->word = g->b->dtype & kWordMask;
@@ -850,13 +955,20 @@ int gemv_launch(const Operands& g, RadStream stream, const GatedOut* go = nullpt
const GatedOut gz = go ? *go : GatedOut{};
uint16_t* const y = go ? nullptr : (uint16_t*)g.y->data;
int rc = RAD_E_SHAPE;
#define R4D_IQR_GV(mt_, kw_) \
rc = go ? R4D_EMIT(stream, (iqr_gemv_kernel<F, mt_, kw_, true>), dim3(N / 32u), \
#define R4D_IQR_GV_E(mt_, kw_, ch_) \
rc = go ? R4D_EMIT(stream, (iqr_gemv_kernel<F, mt_, kw_, true, ch_>), dim3(N / 32u), \
dim3(2u * kw_ * kWave), 0, c, (const int8_t*)g.a->data, \
(const float*)g.as->data, y, N, (uint32_t)g.a_ld, (uint32_t)g.sa_ld, gz) \
: R4D_EMIT(stream, (iqr_gemv_kernel<F, mt_, kw_>), dim3(N / 16u), dim3(kw_ * kWave), \
0, c, (const int8_t*)g.a->data, (const float*)g.as->data, y, N, \
(uint32_t)g.a_ld, (uint32_t)g.sa_ld, gz)
: R4D_EMIT(stream, (iqr_gemv_kernel<F, mt_, kw_, false, ch_>), dim3(N / 16u), \
dim3(kw_ * kWave), 0, c, (const int8_t*)g.a->data, \
(const float*)g.as->data, y, N, (uint32_t)g.a_ld, (uint32_t)g.sa_ld, gz)
#define R4D_IQR_GV(mt_, kw_) \
do { if constexpr (chained_form<F>()) { \
if (g.chain) R4D_IQR_GV_E(mt_, kw_, r4dchain); \
else R4D_IQR_GV_E(mt_, kw_, R4dUnchained); \
} else { \
R4D_IQR_GV_E(mt_, kw_, R4dUnchained); \
} } while (0)
#define R4D_IQR_GVK(mt_) do { if (kw == 4u) R4D_IQR_GV(mt_, 4u); else R4D_IQR_GV(mt_, 8u); } while (0)
switch (M) {
case 1u: R4D_IQR_GVK(1u); break;
@@ -871,27 +983,57 @@ int gemv_launch(const Operands& g, RadStream stream, const GatedOut* go = nullpt
}
#undef R4D_IQR_GVK
#undef R4D_IQR_GV
#undef R4D_IQR_GV_E
return rc == RAD_OK && hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
/* The 16-token tile, plain into `g.y` or gated as gemv_launch. */
/* The forms whose 16-token tile also serves two to four token tiles a block: the computed
* trellis under one f32 scale a row or a bf16 scale a (row, 128), the trunk's two. */
template <class F>
constexpr bool tiles_form() {
return F::KIND == kTrellisMad && F::LRB == 0 && (F::SC == kRowF32 || F::SC == kBf16);
}
/* The 16-token tile, plain into `g.y` or gated as gemv_launch; plain, a tiles_form serves up to 64
* tokens with it, a block multiplying its decoded weight tile against each token tile in turn. */
template <class F>
int m16_launch(const Operands& g, RadStream stream, const GatedOut* go = nullptr) {
const uint32_t N = (uint32_t)g.N, M = (uint32_t)g.M;
const Ctx c = ctx_of(g);
const GatedOut gz = go ? *go : GatedOut{};
uint16_t* const y = go ? nullptr : (uint16_t*)g.y->data;
int rc;
const uint32_t nt = (M + 15u) / 16u;
if (nt > (go || !tiles_form<F>() ? 1u : 4u)) return R4D_NO(RAD_E_SHAPE);
int rc = RAD_E_SHAPE;
#define R4D_IQR_M16_G(kw_, ch_) \
rc = R4D_EMIT(stream, (iqr_m16_kernel<F, kw_, true, 1u, ch_>), dim3(N / 32u), \
dim3(2u * kw_ * kWave), 0, c, (const int8_t*)g.a->data, \
(const float*)g.as->data, y, N, M, (uint32_t)g.a_ld, (uint32_t)g.sa_ld, gz)
#define R4D_IQR_M16_P(kw_, nt_, ch_) \
rc = R4D_EMIT(stream, (iqr_m16_kernel<F, kw_, false, nt_, ch_>), dim3(N / 16u), \
dim3(kw_ * kWave), 0, c, (const int8_t*)g.a->data, \
(const float*)g.as->data, y, N, M, (uint32_t)g.a_ld, (uint32_t)g.sa_ld, gz)
#define R4D_IQR_M16_E(kw_, ch_) \
do { if (go) R4D_IQR_M16_G(kw_, ch_); \
else if (nt == 1u) R4D_IQR_M16_P(kw_, 1u, ch_); \
else if constexpr (tiles_form<F>()) { \
if (nt == 2u) R4D_IQR_M16_P(kw_, 2u, ch_); \
else if (nt == 3u) R4D_IQR_M16_P(kw_, 3u, ch_); \
else R4D_IQR_M16_P(kw_, 4u, ch_); \
} } while (0)
#define R4D_IQR_M16(kw_) \
rc = go ? R4D_EMIT(stream, (iqr_m16_kernel<F, kw_, true>), dim3(N / 32u), \
dim3(2u * kw_ * kWave), 0, c, (const int8_t*)g.a->data, \
(const float*)g.as->data, y, N, M, (uint32_t)g.a_ld, (uint32_t)g.sa_ld, gz) \
: R4D_EMIT(stream, (iqr_m16_kernel<F, kw_>), dim3(N / 16u), dim3(kw_ * kWave), 0, c, \
(const int8_t*)g.a->data, (const float*)g.as->data, y, N, M, \
(uint32_t)g.a_ld, (uint32_t)g.sa_ld, gz)
do { if constexpr (chained_form<F>()) { \
if (g.chain) R4D_IQR_M16_E(kw_, r4dchain); \
else R4D_IQR_M16_E(kw_, R4dUnchained); \
} else { \
R4D_IQR_M16_E(kw_, R4dUnchained); \
} } while (0)
if (N >= 4096u) R4D_IQR_M16(4u);
else R4D_IQR_M16(8u);
#undef R4D_IQR_M16
#undef R4D_IQR_M16_E
#undef R4D_IQR_M16_P
#undef R4D_IQR_M16_G
return rc == RAD_OK && hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
@@ -911,7 +1053,8 @@ int m64_launch(const Operands& g, void* scratch, long long scratch_bytes, int sp
RadStream stream) {
const uint32_t N = (uint32_t)g.N, K = (uint32_t)g.K, M = (uint32_t)g.M;
if (M <= gemv_max<F>()) return gemv_launch<F>(g, stream);
if (M <= 16u && ((uintptr_t)g.y->data & 15u) == 0u) return m16_launch<F>(g, stream);
if (M <= (tiles_form<F>() ? 64u : 16u) && ((uintptr_t)g.y->data & 15u) == 0u)
return m16_launch<F>(g, stream);
/* At most eight waves a block: each has its own transpose tile in LDS. The wave count changes
* no output bit (r4d_gemm_fp8a8.hip's narrow_mw). */
const uint32_t mw = std::min(r4d_8a8_narrow_mw(N, M), 8u);
@@ -928,10 +1071,17 @@ int m64_launch(const Operands& g, void* scratch, long long scratch_bytes, int sp
const Ctx c = ctx_of(g);
const dim3 grid(gx, 1, ksplit);
int rc = RAD_E_SHAPE;
#define R4D_IQR_M64(mw_, nt_) \
rc = R4D_EMIT(stream, (iqr_m64_kernel<F, nt_, mw_>), grid, dim3(mw_ * kWave), 0, c, \
#define R4D_IQR_M64_E(mw_, nt_, ch_) \
rc = R4D_EMIT(stream, (iqr_m64_kernel<F, nt_, mw_, ch_>), grid, dim3(mw_ * kWave), 0, c, \
(const uint8_t*)g.a->data, (const float*)g.as->data, dst, (uint16_t*)g.y->data, \
ctr, N, K, M, (uint32_t)g.a_ld, (uint32_t)g.sa_ld, ck)
#define R4D_IQR_M64(mw_, nt_) \
do { if constexpr (chained_form<F>()) { \
if (g.chain) R4D_IQR_M64_E(mw_, nt_, r4dchain); \
else R4D_IQR_M64_E(mw_, nt_, R4dUnchained); \
} else { \
R4D_IQR_M64_E(mw_, nt_, R4dUnchained); \
} } while (0)
#define R4D_IQR_M64_NT(mw_) \
do { if (nt == 4u) R4D_IQR_M64(mw_, 4u); else if (nt == 3u) R4D_IQR_M64(mw_, 3u); \
else if (nt == 2u) R4D_IQR_M64(mw_, 2u); else R4D_IQR_M64(mw_, 1u); } while (0)
@@ -940,6 +1090,7 @@ int m64_launch(const Operands& g, void* scratch, long long scratch_bytes, int sp
else return R4D_NO(RAD_E_SHAPE);
#undef R4D_IQR_M64_NT
#undef R4D_IQR_M64
#undef R4D_IQR_M64_E
if (rc != RAD_OK || hipGetLastError() != hipSuccess) return R4D_NO(RAD_E_DEVICE);
if (ksplit > 1 && !ctr) {
const uint32_t n = M * N;
@@ -980,8 +1131,9 @@ int tiled_launch(const Operands& g, void* scratch, long long scratch_bytes, RadS
(const uint8_t*)g.a->data, (const float*)g.as->data, (const uint8_t*)pre.fragp, \
ws, (uint16_t*)g.y->data, (uint32_t)g.M, (uint32_t)g.K, (uint32_t)g.N, \
(uint32_t)g.a_ld, (uint32_t)g.sa_ld, (uint32_t)g.nkb)
if (f.lrb >= 5) R4D_IQR_PF(32);
else if (f.lrb >= 3) R4D_IQR_PF(8);
/* F's own lrb is the word's (kernel_word keeps it), so one tile form is built a form. */
if constexpr (F::LRB >= 5) R4D_IQR_PF(32);
else if constexpr (F::LRB >= 3) R4D_IQR_PF(8);
else R4D_IQR_PF(0);
#undef R4D_IQR_PF
return rc == RAD_OK && hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
@@ -989,6 +1141,7 @@ int tiled_launch(const Operands& g, void* scratch, long long scratch_bytes, RadS
} // namespace
#if R4D_IQR_PART == 0
extern "C" int64_t r4d_rad_gemm_iqr_m64_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0),
K = r4d_geti_or(a, "K", 0), sn = r4d_geti_or(a, "split_n", 0);
@@ -998,8 +1151,24 @@ extern "C" int64_t r4d_rad_gemm_iqr_m64_scratch(const RadArgs* a) {
(uint32_t)M, &ck, kIqrSplitWaves);
return k2 > 1 ? (int64_t)k2 * M * N * 4 : 0;
}
#endif
extern "C" int r4d_rad_gemm_iqr_m64(const RadArgs* a, RadStream s) {
#define R4D_IQR_CAT2(a, b) a##b
#define R4D_IQR_CAT(a, b) R4D_IQR_CAT2(a, b)
namespace {
/* A form's launch where this part builds it, else a refusal no call reaches: iqr_part sends each
* word to the one part whose chain holds it. */
template <class F>
int m64_part(const Operands& g, void* scratch, long long scratch_bytes, int split_n, RadStream s) {
if constexpr (in_part<F>()) return m64_launch<F>(g, scratch, scratch_bytes, split_n, s);
else return R4D_NO(RAD_E_UNSUPPORTED);
}
} // namespace
extern "C" int R4D_IQR_CAT(r4d_iqr_m64_p, R4D_IQR_PART)(const RadArgs* a, RadStream s) {
Operands g;
const int rc = operands(a, &g);
if (rc != RAD_OK) return rc;
@@ -1007,8 +1176,8 @@ extern "C" int r4d_rad_gemm_iqr_m64(const RadArgs* a, RadStream s) {
const uint32_t kw = kernel_word(g.word);
const int sn = (int)r4d_geti_or(a, "split_n", 0);
#define R4D_IQR_GO(...) \
if (kw == R4D_IQR_T(__VA_ARGS__)::word()) \
return m64_launch<R4D_IQR_T(__VA_ARGS__)>(g, a->scratch, (long long)a->scratch_bytes, sn, s);
if (in_part<R4D_IQR_T(__VA_ARGS__)>() && kw == R4D_IQR_T(__VA_ARGS__)::word()) \
return m64_part<R4D_IQR_T(__VA_ARGS__)>(g, a->scratch, (long long)a->scratch_bytes, sn, s);
R4D_IQR_FORMS(R4D_IQR_GO)
#undef R4D_IQR_GO
return R4D_NO(RAD_E_UNSUPPORTED);
@@ -1067,19 +1236,31 @@ int gated_operands(const RadArgs* a, Operands* g, GatedOut* go) {
template <class F>
int gated_launch(const Operands& g, const GatedOut& go, RadStream stream) {
if (g.M <= gemv_max<F>()) return gemv_launch<F>(g, stream, &go);
return m16_launch<F>(g, stream, &go);
if constexpr (in_part<F>()) {
if (g.M <= gemv_max<F>()) return gemv_launch<F>(g, stream, &go);
return m16_launch<F>(g, stream, &go);
} else {
return R4D_NO(RAD_E_UNSUPPORTED);
}
}
template <class F>
int tiled_part(const Operands& g, void* scratch, long long scratch_bytes, RadStream s) {
if constexpr (in_part<F>()) return tiled_launch<F>(g, scratch, scratch_bytes, s);
else return R4D_NO(RAD_E_UNSUPPORTED);
}
} // namespace
#if R4D_IQR_PART == 0
extern "C" int64_t r4d_rad_gemm_iqr_gated_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0);
if (M < 1 || N < 2) return 0;
return (int64_t)align256(M * (N / 2) * 2);
}
#endif
extern "C" int r4d_rad_gemm_iqr_gated(const RadArgs* a, RadStream s) {
extern "C" int R4D_IQR_CAT(r4d_iqr_gated_p, R4D_IQR_PART)(const RadArgs* a, RadStream s) {
Operands g;
GatedOut go;
const int rc = gated_operands(a, &g, &go);
@@ -1091,12 +1272,14 @@ extern "C" int r4d_rad_gemm_iqr_gated(const RadArgs* a, RadStream s) {
if (!go.cnt || go.n / 128u > 8192u) return R4D_NO(RAD_E_DEVICE);
const uint32_t kw = kernel_word(g.word);
#define R4D_IQR_GO(...) \
if (kw == R4D_IQR_T(__VA_ARGS__)::word()) return gated_launch<R4D_IQR_T(__VA_ARGS__)>(g, go, s);
if (in_part<R4D_IQR_T(__VA_ARGS__)>() && kw == R4D_IQR_T(__VA_ARGS__)::word()) \
return gated_launch<R4D_IQR_T(__VA_ARGS__)>(g, go, s);
R4D_IQR_FORMS(R4D_IQR_GO)
#undef R4D_IQR_GO
return R4D_NO(RAD_E_UNSUPPORTED);
}
#if R4D_IQR_PART == 0
extern "C" int64_t r4d_rad_gemm_iqr_tiled_scratch(const RadArgs* a) {
const long long N = r4d_geti_or(a, "N", 0), K = r4d_geti_or(a, "K", 0);
if (N < 1 || K < 1) return 0;
@@ -1105,17 +1288,56 @@ extern "C" int64_t r4d_rad_gemm_iqr_tiled_scratch(const RadArgs* a) {
f.scale = kE4m3Tensor;
return (int64_t)tiled_scratch(f, N, K);
}
#endif
extern "C" int r4d_rad_gemm_iqr_tiled(const RadArgs* a, RadStream s) {
extern "C" int R4D_IQR_CAT(r4d_iqr_tiled_p, R4D_IQR_PART)(const RadArgs* a, RadStream s) {
Operands g;
const int rc = operands(a, &g);
if (rc != RAD_OK) return rc;
if (g.N % kBlock) return R4D_NO(RAD_E_SHAPE);
const uint32_t kw = kernel_word(g.word);
#define R4D_IQR_GO(...) \
if (kw == R4D_IQR_T(__VA_ARGS__)::word()) \
return tiled_launch<R4D_IQR_T(__VA_ARGS__)>(g, a->scratch, (long long)a->scratch_bytes, s);
if (in_part<R4D_IQR_T(__VA_ARGS__)>() && kw == R4D_IQR_T(__VA_ARGS__)::word()) \
return tiled_part<R4D_IQR_T(__VA_ARGS__)>(g, a->scratch, (long long)a->scratch_bytes, s);
R4D_IQR_FORMS(R4D_IQR_GO)
#undef R4D_IQR_GO
return R4D_NO(RAD_E_UNSUPPORTED);
}
#if R4D_IQR_PART == 0
/* The rows' entry points: each call goes to the part that builds its weight's form, which parses
* and checks the operands itself. */
using IqrPartFn = int (*)(const RadArgs*, RadStream);
#define R4D_IQR_PARTS_OF(row) \
extern "C" int row##1(const RadArgs*, RadStream); \
extern "C" int row##2(const RadArgs*, RadStream); \
extern "C" int row##3(const RadArgs*, RadStream);
R4D_IQR_PARTS_OF(r4d_iqr_m64_p)
R4D_IQR_PARTS_OF(r4d_iqr_gated_p)
R4D_IQR_PARTS_OF(r4d_iqr_tiled_p)
#undef R4D_IQR_PARTS_OF
static_assert(kIqrParts == 4, "the entry points below name every part");
static int iqr_by_part(const IqrPartFn (&fn)[kIqrParts], const RadArgs* a, RadStream s) {
const RadTensor* b = r4d_opt(a, 2);
return fn[b ? iqr_part(kernel_word(b->dtype & kWordMask)) : 0](a, s);
}
extern "C" int r4d_rad_gemm_iqr_m64(const RadArgs* a, RadStream s) {
static constexpr IqrPartFn fn[] = { r4d_iqr_m64_p0, r4d_iqr_m64_p1, r4d_iqr_m64_p2,
r4d_iqr_m64_p3 };
return iqr_by_part(fn, a, s);
}
extern "C" int r4d_rad_gemm_iqr_gated(const RadArgs* a, RadStream s) {
static constexpr IqrPartFn fn[] = { r4d_iqr_gated_p0, r4d_iqr_gated_p1, r4d_iqr_gated_p2,
r4d_iqr_gated_p3 };
return iqr_by_part(fn, a, s);
}
extern "C" int r4d_rad_gemm_iqr_tiled(const RadArgs* a, RadStream s) {
static constexpr IqrPartFn fn[] = { r4d_iqr_tiled_p0, r4d_iqr_tiled_p1, r4d_iqr_tiled_p2,
r4d_iqr_tiled_p3 };
return iqr_by_part(fn, a, s);
}
#endif
+5
View File
@@ -0,0 +1,5 @@
// gemm_iqr's forms in part 1 of r4d_gemm_iqr.hip's kIqrParts: that unit's kernels and launches for
// the forms whose place in R4D_IQR_FORMS is 1 modulo the count, compiled beside the other parts.
#define R4D_IQR_PART 1
#include "r4d_gemm_iqr.hip"
+5
View File
@@ -0,0 +1,5 @@
// gemm_iqr's forms in part 2 of r4d_gemm_iqr.hip's kIqrParts: that unit's kernels and launches for
// the forms whose place in R4D_IQR_FORMS is 2 modulo the count, compiled beside the other parts.
#define R4D_IQR_PART 2
#include "r4d_gemm_iqr.hip"
+5
View File
@@ -0,0 +1,5 @@
// gemm_iqr's forms in part 3 of r4d_gemm_iqr.hip's kIqrParts: that unit's kernels and launches for
// the forms whose place in R4D_IQR_FORMS is 3 modulo the count, compiled beside the other parts.
#define R4D_IQR_PART 3
#include "r4d_gemm_iqr.hip"
-680
View File
@@ -1,680 +0,0 @@
// r4d_gemm_m2xfp4a8_decode.hip - r4d_gemm_m2xfp4a8_decode: the M2XFP4 x fp8 GEMM for the decode
// band, M <= 128, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the operands, weight layout,
// fold and split-K of r4d_gemm_mxfp4a8_decode, and the paper's weight-side Sg-EM (arXiv 2601.19213
// §4.4.2) on top: per group of 32 K the weight carries, beside its E8M0 exponent (whose adaptive
// bias is already folded in), one meta byte of four two-bit subgroup multipliers k_s. The exact
// weight is e2m1mag[c&7] * sign(c) * 2^(scale-127) * (1 + k_s/4); r4d_m2xfp4.h folds the
// (1 + k_s/4) * 2^-d into the e4m3 byte through a second table index, so the WMMA sees the same
// bytes it would for MXFP4, and the Wref epilogue, the activation scale grids and the split-K
// reduction (fp32 partials, last arriver) are the mxfp4 kernel's; the split and slab rule is
// m2d_plan's own.
//
// The meta byte is staged beside the exponent byte: one byte per (row, 32 of K), in the scale
// plane's [K/32][N] order and row pitch, in the tail of the same stored weight (the relayout
// appends it after the fragment-order codes, r4d_layout.cpp), so the staging reads it with the
// codes' and exponents' own geometry and the weight stream grows by one byte per sixteen.
//
// The fold's bound: Wref[n] is the row's largest exponent byte as for MXFP4, so d >= 0 holds for
// every block, and the largest element any table cell then holds is 6 * 1.75 * 2^-d = 10.5 * 2^-d
// -- an e4m3 normal at every d >= 0 (r4d_m2xfp4.h).
//
// Tile: DWN = 8 waves over 128 output columns and DTM 16-row M fragments; each K slab stages A and
// the 128 weight rows, unpacked to e4m3, in LDS. DKS blocks split the K slabs, each writing an fp32
// partial [DKS][M][N] to the op's scratch, and the last to arrive on a column block sums them. The
// arrival counters are this row's own, one block per output buffer (m2d_out_ctr), zero at entry
// and reset by the reducer, as mxd_out_ctr is for the mxfp4 row; so the row is concurrent
// (rad_kernel_concurrent) on the same terms. A scratch shorter than the split needs is refused.
#include "r4d.h"
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_m2xfp4.h"
// bf16 output as uint16 pairs, the emulator-compatible spelling the MoE units use: the OCP rows
// read __hip_bfloat16 from hip_bf16.h, which the emulator's shim does not carry, and the bytes are
// the same -- bf16x2_rne_nan and f32_to_bf16 round as it does (r4d_common.h).
#include <cstdint>
#include <map>
#include <mutex>
#include <stdexcept>
#define R4D_M2D_DWN 8 // waves per block; the N tile is DWN*16 = 128 wide
#define R4D_M2D_MTILE 16
#define R4D_M2D_MAX_TM 8 // M <= 128
#define R4D_M2D_PAD 8
#define R4D_M2D_MAX_KS 16
#define R4D_M2D_MAX_N 36864 // the counter block's width; a 27B gate_up at TP=1 is 34816
typedef int m2d_v2i __attribute__((ext_vector_type(2)));
typedef unsigned m2d_u2 __attribute__((ext_vector_type(2)));
typedef unsigned m2d_u4 __attribute__((ext_vector_type(4)));
typedef float m2d_f4 __attribute__((ext_vector_type(4)));
template <bool NT, typename T>
static __device__ __forceinline__ T m2d_ld(const T* p) {
if constexpr (NT) return __builtin_nontemporal_load(p);
else return *p;
}
// ---- shared by both kernels: the scale grid at a 128 boundary, and the epilogue.
//
// The accumulator is C transposed: the WMMA takes the weight fragment as A and the activation as B
// (same register layout), so a lane's accumulator for M fragment i holds one row, m = 16i + col,
// and eight consecutive columns n0 + 16*wave + kb8 + e. A lane needs one activation scale per row,
// and writes its eight outputs as one 16-byte store (one 32-byte store of partials).
// The (row, 128) scale grid: thread t < ROWS owns row t, loads the next boundary's two scales a
// boundary early and writes s_prev / s_next to LDS at the boundary (published by the staging
// barrier). A zero next block keeps the carried scale; after a zero block the carried scale is
// looked up from the grid.
static __device__ __forceinline__ float m2d_ratio(float ns, float np, const float* __restrict__ row,
int kb) {
return ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(row, kb - 2)) / ns : 1.f;
}
template <int DTM>
static __device__ __forceinline__ void m2d_rescale(v8f (&acc)[DTM], const float* sR, int col) {
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const float r = sR[i * 16 + col];
#pragma unroll
for (int e = 0; e < 8; ++e) acc[i][e] *= r;
}
}
// The split's result: written to C when the accumulator covers all of K, else as an fp32 partial
// that the last block to arrive on this column block sums. `kb_end` is the block the split's last
// slab ends in (ABLK: the scale the accumulators are carried in).
template <int DTM, int DKS, bool ABLK>
static __device__ __forceinline__ void m2d_epilogue(
const v8f (&acc)[DTM], const float* __restrict__ As, int as_rs,
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
uint16_t* __restrict__ C, int M, int N, int ldc, int n0, int wave, int col, int kb8,
int ks, int kb_end, unsigned* s_last, float* sR) {
constexpr int NTHR = R4D_M2D_DWN * 32, BND = R4D_M2D_DWN * 16;
constexpr int ROWS = R4D_M2D_MTILE * DTM;
const int tid = threadIdx.x;
const int nb = n0 + wave * 16 + kb8; // this lane's eight columns; N % 16 == 0 keeps all or none
// Each row's final scale: the one the split's accumulators end in (ABLK), or the row's own. The
// K loop's closing barrier retired the last ratio reads.
if (tid < ROWS) {
const int m = tid < M ? tid : M - 1;
sR[tid] = ABLK ? r4d_mxfp4_carried(As + (size_t)m * as_rs, kb_end) : As[(size_t)m * as_rs];
}
__syncthreads();
float sc[DTM];
#pragma unroll
for (int i = 0; i < DTM; ++i) sc[i] = sR[i * 16 + col];
if constexpr (DKS == 1) {
if (nb < N) {
const m2d_u2 rb = *(const m2d_u2*)(Wref + nb);
float rf[8];
#pragma unroll
for (int e = 0; e < 8; ++e) rf[e] = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23);
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const int m = i * 16 + col;
if (m < M) {
// rounded as the bf16 store rounds, packed in whole registers (see bf16x2_rne_nan)
float v[8];
#pragma unroll
for (int e = 0; e < 8; ++e)
v[e] = ABLK ? acc[i][e] * sc[i] * rf[e] : acc[i][e] * rf[e] * sc[i];
m2d_u4 o;
o.x = bf16x2_rne_nan(v[0], v[1]);
o.y = bf16x2_rne_nan(v[2], v[3]);
o.z = bf16x2_rne_nan(v[4], v[5]);
o.w = bf16x2_rne_nan(v[6], v[7]);
*(m2d_u4*)(C + (size_t)m * ldc + nb) = o;
}
}
}
return;
}
if (nb < N) {
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const int m = i * 16 + col;
if (m < M) {
m2d_f4 lo, hi;
#pragma unroll
for (int e = 0; e < 4; ++e) {
lo[e] = ABLK ? acc[i][e] * sc[i] : acc[i][e];
hi[e] = ABLK ? acc[i][e + 4] * sc[i] : acc[i][e + 4];
}
m2d_f4* dst = (m2d_f4*)(P + ((size_t)ks * M + m) * N + nb);
dst[0] = lo;
dst[1] = hi;
}
}
}
// Every thread's partial stores are ordered before the counter; then the last arriver reduces.
__threadfence();
__syncthreads();
if (tid == 0)
*s_last = __hip_atomic_fetch_add(&cnt[blockIdx.x], 1u, __ATOMIC_ACQ_REL,
__HIP_MEMORY_SCOPE_AGENT);
__syncthreads();
if (*s_last != (unsigned)(DKS - 1)) return;
if (tid == 0) cnt[blockIdx.x] = 0u; // reset for the next launch
__threadfence(); // acquire, before reading the other partials
const int nhi = min(n0 + BND, N);
for (int nn = n0 + tid; nn < nhi; nn += NTHR) {
const float rf = __int_as_float((int)Wref[nn] << 23);
for (int m = 0; m < M; ++m) {
float sum = 0.f;
#pragma unroll
for (int k = 0; k < DKS; ++k) sum += P[((size_t)k * M + m) * N + nn];
C[(size_t)m * ldc + nn] = f32_to_bf16(sum * rf * (ABLK ? 1.f : As[(size_t)m * as_rs]));
}
}
}
/* Waves per SIMD for each tile shape (R4D_WAVES), by K block, M fragments and scale form: pins
* the register budget the tile was tuned at so a compiler release cannot change occupancy (LLVM 24
* would drop the DBK 64, three-fragment form from 16 waves to 12). Where a shape spilled at 256
* VGPRs, the budget is the one it reaches without spilling. The meta adds one global byte per
* staged pair to the fold's inputs and no register to the WMMA chain, so the budgets are the
* mxfp4 decode kernel's; the fold is a second table index, not a multiply. */
constexpr int m2d_waves(int dbk, int dtm, bool ablk) {
if (dbk == 64)
return dtm <= 3 ? 16 : dtm == 4 ? 12 : dtm == 5 ? 10 : dtm == 6 ? (ablk ? 9 : 10)
: dtm == 7 ? 9 : (ablk ? 8 : 9);
return dtm <= 3 ? 10 : dtm == 4 ? 8 : dtm == 5 ? (ablk ? 8 : 7) : dtm == 6 ? (ablk ? 8 : 6)
: 6;
}
template <int DBK, int DKS, int DTM, bool NT, bool ABLK>
__global__ __launch_bounds__(R4D_M2D_DWN * 32) R4D_WAVES(m2d_waves(DBK, DTM, ABLK))
void r4d_gemm_m2xfp4a8_decode_kernel(
const unsigned char* __restrict__ A, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wm, const unsigned char* __restrict__ Wref,
float* __restrict__ P, unsigned* __restrict__ cnt, uint16_t* __restrict__ C,
int M, int K, int N, int as_rs, int lda, int ldws, int ldc) {
constexpr int DWN = R4D_M2D_DWN, BND = DWN * 16, NTHR = DWN * 32;
constexpr int ROWS = R4D_M2D_MTILE * DTM;
constexpr int STR = DBK + R4D_M2D_PAD;
__shared__ unsigned char sA[ROWS * STR];
__shared__ unsigned char sW[BND * STR];
__shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
__shared__ unsigned s_last;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int n0 = blockIdx.x * BND;
const int ks = blockIdx.z;
const int slabs = (K + DBK - 1) / DBK;
const int spb = (slabs + DKS - 1) / DKS;
const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb);
const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K);
v8f acc[DTM];
#pragma unroll
for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f);
const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs;
float ns = 0.f, np = 0.f;
if constexpr (ABLK) {
// a split that starts mid-block meets its first boundary one slab in
const int kb = ((s_lo * DBK) >> 7) + 1;
if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; }
}
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
const int ksteps_g = K / 16;
for (int s = s_lo; s < s_hi; ++s) {
const int k0 = s * DBK;
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
if constexpr (ABLK) {
if (bnd && tid < ROWS) sR[tid] = m2d_ratio(ns, np, asrow, k0 >> 7);
}
// ---- A: ROWS x DBK bytes, clamped rows, 16 B a thread
#pragma unroll
for (int off = 0; off < ROWS * DBK; off += NTHR * 16) {
const int idx = off + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
const int rc = r < M - 1 ? r : M - 1; // clamp, never predicate
*(m2d_u4*)(&sA[r * STR + c]) = *(const m2d_u4*)(A + (size_t)rc * lda + k0 + c);
}
}
// ---- W: fragment-order slots, two adjacent rows a thread (an 8 B request), folded to e4m3.
// The k offset of the eight elements a lane stages is a multiple of 8 and DBK of 32, so one
// meta byte's two-bit field per row covers it whole (r4d_m2xfp4.h).
{
constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16;
const int kstep0 = k0 / 16;
#pragma unroll
for (int off = 0; off < NTILES_T * KSTEPS_T * 32; off += NTHR * 2) {
const int sl = off + tid * 2;
const int lane_ = sl & 31, rest = sl >> 5;
const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T;
const int r = ntl * 16 + (lane_ & 15), kloc = kst * 16 + (lane_ >> 4) * 8;
const int ksh = r4d_m2xfp4_kshift(kloc);
const int gn = n0 + r;
// gn is even and N % 16 == 0, so clamping to N - 2 keeps the 8 B read aligned and gc + 1 in
// bounds; the slot address is recomputed from the clamped row.
const int gc = gn < N - 2 ? gn : N - 2;
const int lanec = (lane_ & 16) | (gc & 15);
const m2d_u2 wv =
m2d_ld<NT>((const m2d_u2*)&Wp[((size_t)(gc >> 4) * ksteps_g + kstep0 + kst) * 32 +
lanec]);
const int blk = (k0 + kst * 16) / R4D_MXFP4_GROUP;
#pragma unroll
for (int q = 0; q < 2; ++q) {
const int d = r4d_mxfp4_fold_d(Wref[gc + q], Ws[(size_t)blk * ldws + gc + q]);
const int k = (Wm[(size_t)blk * ldws + gc + q] >> ksh) & 3;
unsigned int lo, hi;
r4d_m2xfp4_unpack8(q ? wv[1] : wv[0], d, k, &lo, &hi);
*(m2d_u2*)(&sW[(r + q) * STR + kloc]) = m2d_u2{lo, hi};
}
}
}
__syncthreads();
if constexpr (ABLK) {
if (bnd) m2d_rescale(acc, sR, col);
if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) {
ns = asrow[(k0 >> 7) + 1];
np = asrow[k0 >> 7];
}
}
#pragma unroll
for (int step = 0; step < DBK / 16; ++step) {
const int kk = step * 16 + kb8;
m2d_v2i af[DTM], wf;
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const unsigned char* pa = &sA[(i * 16 + col) * STR + kk];
af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4);
}
const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk];
wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4);
#pragma unroll
for (int i = 0; i < DTM; ++i)
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]);
}
__syncthreads();
}
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
m2d_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, ldc, n0, wave, col, kb8, ks,
kb_end, &s_last, sR);
}
// The one-fragment form (M <= 16), every single-sequence verify step. Same tile, fold and split as
// above, plus: the next slab's A, codes, exponents and meta bytes are loaded into registers while
// this slab computes, keeping loads in flight across barriers; a thread takes four adjacent slots
// (one 16 B load); and each row's reference exponent is read once. Bit-identical to the kernel
// above.
template <int DBK, int DKS, bool NT, bool ABLK>
__global__ __launch_bounds__(R4D_M2D_DWN * 32) R4D_WAVES(DBK == 64 ? 16 : 12)
void r4d_gemm_m2xfp4a8_decode1_kernel(
const unsigned char* __restrict__ A, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wm, const unsigned char* __restrict__ Wref,
float* __restrict__ P, unsigned* __restrict__ cnt, uint16_t* __restrict__ C,
int M, int K, int N, int as_rs, int lda, int ldws, int ldc) {
constexpr int DTM = 1, VEC = 4;
constexpr int DWN = R4D_M2D_DWN, BND = DWN * 16, NTHR = DWN * 32;
constexpr int ROWS = R4D_M2D_MTILE * DTM;
constexpr int STR = DBK + R4D_M2D_PAD;
constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16;
constexpr int W_IT = NTILES_T * KSTEPS_T * 32 / (NTHR * VEC);
constexpr int A_IT = (ROWS * DBK + NTHR * 16 - 1) / (NTHR * 16);
__shared__ unsigned char sA[ROWS * STR];
__shared__ unsigned char sW[BND * STR];
__shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
__shared__ unsigned s_last;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int n0 = blockIdx.x * BND;
const int ks = blockIdx.z;
const int slabs = (K + DBK - 1) / DBK;
const int spb = (slabs + DKS - 1) / DKS;
const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb);
const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K);
v8f acc[DTM];
#pragma unroll
for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f);
const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs;
float ns = 0.f, np = 0.f;
if constexpr (ABLK) {
const int kb = ((s_lo * DBK) >> 7) + 1;
if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; }
}
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
const int ksteps_g = K / 16;
// per-thread slot geometry, fixed across slabs; the meta shift with it, since an eight-element
// slot's offset inside its 32-column group does not move
int s_r[W_IT], s_kst[W_IT], s_kloc[W_IT], s_gc[W_IT], s_lanec[W_IT], s_ksh[W_IT][VEC];
int s_ref[W_IT][VEC];
#pragma unroll
for (int it = 0; it < W_IT; ++it) {
const int sl = it * NTHR * VEC + tid * VEC;
const int lane_ = sl & 31, rest = sl >> 5;
const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T;
const int r = ntl * 16 + (lane_ & 15);
const int gn = n0 + r;
const int gc = gn < N - VEC ? gn : N - VEC;
s_r[it] = r; s_kst[it] = kst; s_kloc[it] = kst * 16 + (lane_ >> 4) * 8;
s_gc[it] = gc; s_lanec[it] = (lane_ & 16) | (gc & 15);
#pragma unroll
for (int q = 0; q < VEC; ++q) {
s_ref[it][q] = (int)Wref[gc + q];
s_ksh[it][q] = r4d_m2xfp4_kshift(s_kloc[it]);
}
}
typedef unsigned wv_t __attribute__((ext_vector_type(VEC)));
wv_t rw[W_IT];
int rd[W_IT][VEC], rk[W_IT][VEC];
m2d_u4 ra[A_IT];
auto load = [&](int s) {
const int k0 = s * DBK;
#pragma unroll
for (int j = 0; j < A_IT; ++j) {
const int idx = j * NTHR * 16 + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
const int rc = r < M - 1 ? r : M - 1;
ra[j] = *(const m2d_u4*)(A + (size_t)rc * lda + k0 + c);
}
}
const int kstep0 = k0 / 16;
#pragma unroll
for (int it = 0; it < W_IT; ++it) {
const size_t slot =
((size_t)(s_gc[it] >> 4) * ksteps_g + kstep0 + s_kst[it]) * 32 + s_lanec[it];
rw[it] = m2d_ld<NT>((const wv_t*)&Wp[slot]);
const int blk = (k0 + s_kst[it] * 16) / R4D_MXFP4_GROUP;
#pragma unroll
for (int q = 0; q < VEC; ++q) {
rd[it][q] = (int)Ws[(size_t)blk * ldws + s_gc[it] + q];
rk[it][q] = (int)Wm[(size_t)blk * ldws + s_gc[it] + q];
}
}
};
auto store = [&]() {
#pragma unroll
for (int j = 0; j < A_IT; ++j) {
const int idx = j * NTHR * 16 + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
*(m2d_u4*)(&sA[r * STR + c]) = ra[j];
}
}
#pragma unroll
for (int it = 0; it < W_IT; ++it) {
#pragma unroll
for (int q = 0; q < VEC; ++q) {
unsigned int lo, hi;
r4d_m2xfp4_unpack8(rw[it][q], r4d_mxfp4_fold_d(s_ref[it][q], rd[it][q]),
(rk[it][q] >> s_ksh[it][q]) & 3, &lo, &hi);
*(m2d_u2*)(&sW[(s_r[it] + q) * STR + s_kloc[it]]) = m2d_u2{lo, hi};
}
}
};
if (s_lo < s_hi) load(s_lo);
for (int s = s_lo; s < s_hi; ++s) {
const int k0 = s * DBK;
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
if constexpr (ABLK) {
if (bnd && tid < ROWS) sR[tid] = m2d_ratio(ns, np, asrow, k0 >> 7);
}
store();
__syncthreads();
if (s + 1 < s_hi) load(s + 1); // the next slab's loads fly across this slab's WMMAs
if constexpr (ABLK) {
if (bnd) m2d_rescale(acc, sR, col);
if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) {
ns = asrow[(k0 >> 7) + 1];
np = asrow[k0 >> 7];
}
}
#pragma unroll
for (int step = 0; step < DBK / 16; ++step) {
const int kk = step * 16 + kb8;
m2d_v2i af[DTM], wf;
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const unsigned char* pa = &sA[(i * 16 + col) * STR + kk];
af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4);
}
const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk];
wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4);
#pragma unroll
for (int i = 0; i < DTM; ++i)
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]);
}
__syncthreads();
}
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
m2d_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, ldc, n0, wave, col, kb8, ks,
kb_end, &s_last, sR);
}
namespace {
// The arrival counters, one block per output buffer (see the header). They cannot live in the
// scratch, which other ops overwrite, because they must be zero at entry. One allocation per
// (device, output), kept zero by the reducer and never freed (a recorded pass replays the
// pointer), as gemm_mxfp4a8_decode's mxd_out_ctr.
unsigned* m2d_out_ctr(const void* out) {
static std::mutex mu;
static std::map<std::pair<int, const void*>, unsigned*> blocks;
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
const auto key = std::make_pair(dev, out);
{
// Not held while the block is made, as in split_ctr (r4d_gemm_fp8a8.hip): the zeroing waits
// for the card.
std::lock_guard<std::mutex> lk(mu);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
}
const size_t n = R4D_M2D_MAX_N / (R4D_M2D_DWN * 16);
unsigned* p = nullptr;
if (hipMalloc((void**)&p, n * sizeof(unsigned)) != hipSuccess) return nullptr;
// Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has finished
// when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it runs on the
// null stream, which a non-blocking stream does not wait for, so wait here.
if (hipMemset(p, 0, n * sizeof(unsigned)) != hipSuccess || hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return nullptr;
}
unsigned* kept = nullptr;
{
std::lock_guard<std::mutex> lk(mu);
const auto [it, fresh] = blocks.emplace(key, p);
if (fresh) return it->second;
kept = it->second;
}
(void)hipFree(p); // another thread made this key's block in the meantime
return kept;
}
// The split, slab and load hint for a launch, from M, the shape and the tunables (0 = the rule).
// The rule doubles the split while the grid has fewer than 48 blocks (M <= 16), 56 (M <= 96) or 40
// (above) and the doubled split keeps KS * M <= 512; at K >= 8192 it doubles on, under the same
// bound, while each split still waits on 24 or more 128-wide slabs. The slab is 64 wide at the
// cases below, and wherever a 128-wide one would run past K. Shared by the launch and the scratch
// hook so the sized partial is the one written.
struct M2dPlan { int ks, bk; bool nt; };
M2dPlan m2d_plan(int M, int K, int N, int KS, int BK, int NT) {
const int nblk = (N + R4D_M2D_DWN * 16 - 1) / (R4D_M2D_DWN * 16);
const int tm = (M + R4D_M2D_MTILE - 1) / R4D_M2D_MTILE;
M2dPlan p;
int ks = 1;
const int fill = M <= 16 ? 48 : (M <= 96 ? 56 : 40);
while (ks < R4D_M2D_MAX_KS && nblk * ks < fill && 2 * ks * M <= 512) ks <<= 1;
if (K >= 8192) // a deep K: a split of 24 or more slabs still waits on them
while (ks < R4D_M2D_MAX_KS && (K / 128) / ks >= 24 && 2 * ks * M <= 512) ks <<= 1;
p.ks = KS > 0 ? KS : ks;
// 64-wide slabs where LDS per block would cost resident blocks: DTM 4 unsplit on 110+ column
// blocks, and DTM 8 on those or at a split of 4 or more.
const bool slab64 = (tm == 4 && p.ks == 1 && nblk >= 110) || (tm == 8 && (nblk >= 110 || p.ks >= 4));
p.bk = BK > 0 ? BK : (slab64 ? 64 : 128);
p.nt = NT == 1 || (NT == 0 && (long)N * K / 2 >= (4l << 20));
if (K % p.bk) { // a slab may not run past K
p.bk = 64;
if (p.ks == 2) p.ks = 4;
}
return p;
}
long m2d_partial_bytes(int M, int N, int ks) {
return ks > 1 ? (long)ks * M * N * (long)sizeof(float) : 0;
}
void m2d_launch(long a, long ascale, long wq, long ws, long wm, long wref, long c, int M, int K,
int N, int KS, int BK, int NT, int as_group, int as_rs, long stream, long scratch,
long scratch_bytes, int lda, int ldws, int ldc) {
// A caller reading windows of larger planes passes their row pitches; 0 means the plane's own
// width, as r4d_gemm_mxfp4a8_nt_m64's launcher spells it.
if (!lda) lda = K;
if (!ldws) ldws = N;
if (!ldc) ldc = N;
if (M < 1 || M > R4D_M2D_MTILE * R4D_M2D_MAX_TM)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: M must be 1..128");
if (N < 16 || N % 16 || N > R4D_M2D_MAX_N)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: N must be a multiple of 16 up to 36864");
if (K < 64 || K % 64)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: K must be a multiple of 64");
if (as_group != 0 && as_group != 128)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: the activation scale is per row or per "
"128 of K");
const M2dPlan pl = m2d_plan(M, K, N, KS, BK, NT);
const int ks = pl.ks, bk = pl.bk;
if (ks != 1 && ks != 2 && ks != 4 && ks != 8 && ks != 16)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: KS must be 1, 2, 4, 8 or 16");
if (bk != 64 && bk != 128)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: BK must be 64 or 128");
if (scratch_bytes < m2d_partial_bytes(M, N, ks) || (ks > 1 && !scratch))
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: the op's scratch is shorter than the split "
"partial; the scratch hook sizes it");
float* P = (float*)scratch;
unsigned* cnt = m2d_out_ctr((const void*)c);
if (!cnt) throw std::runtime_error("r4d gemm_m2xfp4a8_decode: split counter alloc failed");
const bool ablk = as_group == 128, nt = pl.nt;
const int nblk = (N + R4D_M2D_DWN * 16 - 1) / (R4D_M2D_DWN * 16);
const int tm = (M + R4D_M2D_MTILE - 1) / R4D_M2D_MTILE;
hipStream_t st = (hipStream_t)stream;
dim3 grid(nblk, 1, ks), block(R4D_M2D_DWN * 32);
auto Ap = (const unsigned char*)a;
auto Sp = (const float*)ascale;
auto Wp = (const unsigned char*)wq;
auto Zp = (const unsigned char*)ws;
auto Mp = (const unsigned char*)wm;
auto Rp = (const unsigned char*)wref;
auto Cp = (uint16_t*)c;
#define M2D_L(BK_, KS_, TM_, NT_, AB_) \
hipLaunchKernelGGL((r4d_gemm_m2xfp4a8_decode_kernel<BK_, KS_, TM_, NT_, AB_>), grid, block, 0, \
st, Ap, Sp, Wp, Zp, Mp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc)
#define M2D_L1(BK_, KS_, NT_, AB_) \
hipLaunchKernelGGL((r4d_gemm_m2xfp4a8_decode1_kernel<BK_, KS_, NT_, AB_>), grid, block, 0, st, \
Ap, Sp, Wp, Zp, Mp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc)
#define M2D_AB(BK_, KS_, TM_, NT_) \
{ if (ablk) M2D_L(BK_, KS_, TM_, NT_, true); else M2D_L(BK_, KS_, TM_, NT_, false); }
#define M2D_NT(BK_, KS_, TM_) \
{ if (nt) M2D_AB(BK_, KS_, TM_, true) else M2D_AB(BK_, KS_, TM_, false) }
#define M2D_AB1(BK_, KS_, NT_) \
{ if (ablk) M2D_L1(BK_, KS_, NT_, true); else M2D_L1(BK_, KS_, NT_, false); }
#define M2D_NT1(BK_, KS_) { if (nt) M2D_AB1(BK_, KS_, true) else M2D_AB1(BK_, KS_, false) }
#define M2D_TM(BK_, KS_) \
{ switch (tm) { case 1: M2D_NT1(BK_, KS_) break; case 2: M2D_NT(BK_, KS_, 2) break; \
case 3: M2D_NT(BK_, KS_, 3) break; case 4: M2D_NT(BK_, KS_, 4) break; \
case 5: M2D_NT(BK_, KS_, 5) break; case 6: M2D_NT(BK_, KS_, 6) break; \
case 7: M2D_NT(BK_, KS_, 7) break; default: M2D_NT(BK_, KS_, 8) break; } }
#define M2D_KS(BK_) \
{ switch (ks) { case 1: M2D_TM(BK_, 1) break; case 2: M2D_TM(BK_, 2) break; \
case 4: M2D_TM(BK_, 4) break; case 8: M2D_TM(BK_, 8) break; \
default: M2D_TM(BK_, 16) break; } }
if (bk == 64) M2D_KS(64) else M2D_KS(128)
#undef M2D_KS
#undef M2D_TM
#undef M2D_NT1
#undef M2D_AB1
#undef M2D_NT
#undef M2D_AB
#undef M2D_L1
#undef M2D_L
}
} // namespace
extern "C" int r4d_gemm_m2xfp4a8_decode_max_m(void) { return R4D_M2D_MTILE * R4D_M2D_MAX_TM; }
// The raw entry, as r4d_gemm_fp8a8_nt_m16: plain C ABI for a caller that sizes the split itself.
// The scratch is the split partial, m2d_partial_bytes at m2d_plan's split (r4d_m2xfp4.h gives
// the sizes a caller can use); `scratch` null runs unsplit only when KS is 1.
extern "C" void r4d_gemm_m2xfp4a8_decode(long a, long ascale, long wq, long ws, long wm, long wref,
long c, int M, int K, int N, int KS, int BK, int NT,
int as_group, int as_rs, long scratch,
long scratch_bytes, long stream, int lda, int ldws,
int ldc) {
m2d_launch(a, ascale, wq, ws, wm, wref, c, M, K, N, KS, BK, NT, as_group, as_rs, stream, scratch,
scratch_bytes, lda, ldws, ldc);
}
// ============================================================== the plugin ABI entry point
extern "C" int r4d_rad_gemm_m2xfp4a8_decode(const RadArgs* a, RadStream s) {
GemmOps g;
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
if (rc != RAD_OK) return rc;
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL);
MxParts mp;
rc = mx_parts(a, &g, &mp);
if (rc != RAD_OK) return rc;
if (g.K % 64) return R4D_NO(RAD_E_SHAPE);
if (g.M > r4d_gemm_m2xfp4a8_decode_max_m() || g.N > R4D_M2D_MAX_N) return R4D_NO(RAD_E_SHAPE);
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
if (rc != RAD_OK) return rc;
R4dMxDecCfg t;
r4d_cfg_mxfp4_decode(a, &t);
const long long kb = (g.K + 127) / 128;
// The meta plane rides the weight blob's tail, in the scale plane's [K/32][N] order: a part of
// a partitioned weight (mx_parts) windows it at n0 as it does the exponent plane, and the codes
// at n0 * K / 2.
const long meta0 = (long)g.N * g.K / 2;
for (int p = 0; p < mp.n; ++p) {
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
R4D_TRY("gemm_m2xfp4a8_decode",
m2d_launch(r4d_addr(g.a) + p * g.K, r4d_addr(g.ascale) + (long)(p * kb * 4),
r4d_addr(g.b) + n0 * g.K / 2, r4d_addr(g.bscale) + n0,
r4d_addr(g.b) + meta0 + n0, r4d_addr(g.bref) + n0,
r4d_addr(g.y) + n0 * 2,
(int)g.M, (int)g.K, (int)np, t.ks, t.bk, t.nt, as_group, as_rs,
(long)(uintptr_t)s, (long)(uintptr_t)a->scratch, (long)a->scratch_bytes,
(int)(mp.lda ? mp.lda : g.K), (int)g.N, (int)g.N));
}
return RAD_OK;
}
/* The op's scratch size. A narrower M can split wider than the band's widest M, so the size is the
* widest split over the band times the widest M, an upper bound for every launch. Parts of a
* partitioned weight split at their own N and run in turn sharing the scratch, so the bound is the
* largest part's. */
extern "C" int64_t r4d_rad_gemm_m2xfp4a8_decode_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0);
const long long K = r4d_geti_or(a, "K", 0);
if (M < 1 || N < 16 || K < 64 || M > r4d_gemm_m2xfp4a8_decode_max_m()) return 0;
R4dMxDecCfg t;
r4d_cfg_mxfp4_decode(a, &t);
long long bound[4];
mx_part_bounds(N, r4d_geti_or(a, "pb1", 0), r4d_geti_or(a, "pb2", 0), bound);
int64_t worst = 0;
for (int i = 0; i < 3; ++i) {
const long long np = bound[i + 1] - bound[i];
if (np < 16) continue;
int ks = 1;
for (int m = 1; m <= (int)M; ++m) {
const int k = m2d_plan(m, (int)K, (int)np, t.ks, t.bk, t.nt).ks;
if (k > ks) ks = k;
}
const int64_t b = (int64_t)m2d_partial_bytes((int)M, (int)np, ks);
if (b > worst) worst = b;
}
return worst;
}
-374
View File
@@ -1,374 +0,0 @@
// r4d_gemm_m2xfp4a8_tiled.hip - r4d_gemm_m2xfp4a8_tiled: the M2XFP4 x fp8 GEMM for prefill row
// counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the operands, weight layout, fold and
// tile of r4d_gemm_mxfp4a8_tiled, plus the weight-side Sg-EM (arXiv 2601.19213 §4.4.2) the decode
// row decodes: per group of 32 K a meta byte of four two-bit subgroup multipliers, folded into the
// e4m3 staging bytes through r4d_m2xfp4.h's second table index, so the WMMA chain, the Wref
// epilogue and the activation scale grids are the mxfp4 kernel's unchanged.
//
// The meta byte is staged beside the exponent byte: one byte per (weight row, 32 of K), in the
// scale plane's [K/32][N] order and row pitch, in the tail of the same stored weight (the relayout
// appends it after the fragment-order codes, r4d_layout.cpp). A staged slot's eight elements sit at
// an offset that is a multiple of 8 inside their 32-column group, so one two-bit field per slot
// covers it whole; the shift is fixed per slot across slabs and read with the geometry the scale
// dword already uses.
//
// The fold's bound: Wref[n] is the row's largest exponent byte as for MXFP4, so d >= 0 holds for
// every block, and the largest element any table cell then holds is 6 * 1.75 * 2^-d = 10.5 * 2^-d
// -- an e4m3 normal at every d >= 0 (r4d_m2xfp4.h). The table is four times the mxfp4 one, 512
// bytes, still nothing against sW; the LDS copy widens with it.
#include "r4d.h"
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_m2xfp4.h"
// bf16 output as uint16 pairs (the emulator-compatible spelling, r4d_common.h): the OCP
// rows read __hip_bfloat16 from hip_bf16.h, whose bytes these are.
#include <cstdint>
#include <stdexcept>
#define R4D_M2T_TM 4 // 16-row fragments per wave
#define R4D_M2T_WM 4 // waves along M
#define R4D_M2T_WN 2 // waves along N
#define R4D_M2T_PAD 8 // LDS row pad: 16 lanes reading rows 64 B apart collide 8 ways
#define R4D_M2T_NTHR (R4D_M2T_WM * R4D_M2T_WN * 32)
#define R4D_M2T_BMF (R4D_M2T_WM * R4D_M2T_TM * 16)
#define R4D_M2T_KUNIT 64 // the narrowest K slab, so K must be a multiple of it
// tn=0's M crossover to TN=4 for this kernel, as its tn axis (tGemmMxfp4Tiled) states it.
#define R4D_M2T_TN4_MIN_M 2048
typedef int m2t_v2i __attribute__((ext_vector_type(2)));
typedef unsigned m2t_u2 __attribute__((ext_vector_type(2)));
typedef unsigned m2t_u4 __attribute__((ext_vector_type(4)));
// The re-tile: one thread per 8-byte slot of the fragment-ordered plane; writes are contiguous.
// (r4d_mxfp4a8_tile_a_kernel, shared work; this row runs its own copy so the two units stay
// independent.)
__global__ __launch_bounds__(256) void r4d_m2xfp4a8_tile_a_kernel(
const unsigned char* __restrict__ A, unsigned char* __restrict__ AT, int M, int K,
long long slots, int lda) {
const long long o = (long long)blockIdx.x * 256 + threadIdx.x;
if (o >= slots) return;
const int ks = K / 16;
const int lane = (int)(o & 31);
const long long f = o >> 5;
const int mt = (int)(f / ks), kst = (int)(f % ks);
const int r = mt * 16 + (lane & 15), k = kst * 16 + (lane >> 4) * 8;
m2t_u2 v = { 0u, 0u };
if (r < M) v = *(const m2t_u2*)(A + (size_t)r * lda + k);
*(m2t_u2*)(AT + o * 8) = v;
}
template <int TN, int LBK, bool ABLK>
__global__ __launch_bounds__(R4D_M2T_NTHR) void r4d_gemm_m2xfp4a8_tiled_kernel(
const unsigned char* __restrict__ AT, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wm, const unsigned char* __restrict__ Wref,
uint16_t* __restrict__ C, int M, int K, int N, int as_rs, int ldws, int ldc) {
constexpr int TM = R4D_M2T_TM, WN = R4D_M2T_WN, NTHR = R4D_M2T_NTHR, BMF = R4D_M2T_BMF;
constexpr int NS = LBK / 16, STR = LBK + R4D_M2T_PAD, BNF = WN * TN * 16;
constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32;
// 4 weight slots (one 16 B read) wherever the tile has enough of them, else 2 (8 B), else 1.
constexpr int WSLOTS = (TOT_SLOTS >= NTHR * 4) ? 4 : (TOT_SLOTS >= NTHR * 2 ? 2 : 1);
constexpr int NW = TOT_SLOTS / (NTHR * WSLOTS);
static_assert(NW * NTHR * WSLOTS == TOT_SLOTS, "the W tile must split evenly over the block");
__shared__ unsigned char sW[BNF * STR];
__shared__ unsigned int sMag[128]; // kM2xfp4Mag: [16][4][2] words
__shared__ float sR[ABLK ? BMF : 1]; // ABLK: a boundary's ratio a row, then each row's final scale
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int wm = wave / WN, wn = wave % WN;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int m0 = blockIdx.y * BMF, n0 = blockIdx.x * BNF;
const int ksteps = K / 16, Mt = (M + 15) >> 4;
if (tid < 128) sMag[tid] = (&kM2xfp4Mag[0][0][0])[tid];
// One A base per M fragment, wave-uniform: readfirstlane keeps it in an SGPR so loads take the
// SADDR form with a 32-bit lane offset. A tile past M reads the last real one.
const unsigned char* abase[TM];
#pragma unroll
for (int i = 0; i < TM; ++i) {
int mt = (m0 >> 4) + wm * TM + i;
mt = mt < Mt - 1 ? mt : Mt - 1;
abase[i] = AT + (size_t)__builtin_amdgcn_readfirstlane(mt * ksteps * 256);
}
const unsigned int aoff = (unsigned int)lane * 8;
// The W slots this thread stages, fixed across slabs: WSLOTS adjacent rows of one (n-tile,
// k-step), so the wave reads contiguous bytes; the clamp keeps the vector read aligned. The meta
// shift moves with the slot: its eight elements' offset inside their 32-column group is
// kst*16 + (lane>>4)*8, a multiple of 8 (r4d_m2xfp4.h).
int wrow[NW], wkloc[NW], wrc[NW], wkst[NW], wlanec[NW], wksh[NW];
unsigned int wref[NW];
#pragma unroll
for (int it = 0; it < NW; ++it) {
const int sl = it * NTHR * WSLOTS + tid * WSLOTS;
const int lane_ = sl & 31, rest = sl >> 5;
const int kst = rest % NS, ntl = rest / NS;
wrow[it] = ntl * 16 + (lane_ & 15);
wkloc[it] = kst * 16 + (lane_ >> 4) * 8;
wksh[it] = r4d_m2xfp4_kshift(wkloc[it]);
const int gn = n0 + wrow[it];
wrc[it] = gn < N - WSLOTS ? gn : N - WSLOTS;
wlanec[it] = (lane_ & 16) | (wrc[it] & 15);
wkst[it] = kst;
wref[it] = WSLOTS == 4 ? *(const unsigned int*)(Wref + wrc[it])
: WSLOTS == 2 ? *(const unsigned short*)(Wref + wrc[it])
: Wref[wrc[it]];
}
v8f acc[TM][TN];
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int j = 0; j < TN; ++j) acc[i][j] = (v8f)(0.f);
// ABLK: thread t owns row m0 + t (BMF == NTHR) and loads the next 128 boundary's two scales (the
// block starting there and the one before it) a boundary early.
const int trow = m0 + tid < M ? m0 + tid : M - 1;
const float* __restrict__ asrow = As + (size_t)trow * as_rs;
float ns = 0.f, np = 0.f;
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
lds_barrier(); // sMag
for (int k0 = 0; k0 < K; k0 += LBK) {
// ABLK: at a 128 boundary each row's ratio goes to LDS, published by the staging barrier below
// (sR's previous readers finished before the last slab's closing barrier). A zero block keeps
// the carried scale; after a zero block the carried scale is looked up from the grid.
const bool bnd = ABLK && k0 && (k0 & 127) == 0;
if constexpr (ABLK) {
if (bnd)
sR[tid] = ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(asrow, (k0 >> 7) - 2)) / ns : 1.f;
}
// A fragments for the whole slab, one clause, consumed only at the WMMAs.
m2t_v2i af[TM][NS];
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int st = 0; st < NS; ++st)
af[i][st] = *(const m2t_v2i*)(abase[i] +
(aoff + (unsigned int)(k0 * 16) + (unsigned int)(st * 256)));
// W slab -> LDS, folded to e4m3. The meta bytes ride the same dword reads as the exponents.
const int kstep0 = k0 / 16;
#pragma unroll
for (int it = 0; it < NW; ++it) {
const unsigned int* src =
&Wp[((size_t)(wrc[it] >> 4) * ksteps + kstep0 + wkst[it]) * 32 + wlanec[it]];
const int blk = (k0 + wkst[it] * 16) / R4D_MXFP4_GROUP;
unsigned int wq[WSLOTS], wsw, wmw;
if constexpr (WSLOTS == 4) {
const m2t_u4 v = *(const m2t_u4*)src;
wq[0] = v[0]; wq[1] = v[1]; wq[2] = v[2]; wq[3] = v[3];
wsw = *(const unsigned int*)(Ws + (size_t)blk * ldws + wrc[it]);
wmw = *(const unsigned int*)(Wm + (size_t)blk * ldws + wrc[it]);
} else if constexpr (WSLOTS == 2) {
const m2t_u2 v = *(const m2t_u2*)src;
wq[0] = v[0]; wq[1] = v[1];
wsw = *(const unsigned short*)(Ws + (size_t)blk * ldws + wrc[it]);
wmw = *(const unsigned short*)(Wm + (size_t)blk * ldws + wrc[it]);
} else {
wq[0] = *src;
wsw = Ws[(size_t)blk * ldws + wrc[it]];
wmw = Wm[(size_t)blk * ldws + wrc[it]];
}
#pragma unroll
for (int q = 0; q < WSLOTS; ++q) {
const int d = r4d_mxfp4_fold_d((int)((wref[it] >> (8 * q)) & 0xFF),
(int)((wsw >> (8 * q)) & 0xFF));
const int k = (int)((wmw >> (8 * q + wksh[it])) & 3);
const int ti = (d * 4 + k) * 2;
unsigned int lo, hi;
r4d_mxfp4_unpack8_t(wq[q], sMag[ti], sMag[ti + 1], &lo, &hi);
*(m2t_u2*)(&sW[(wrow[it] + q) * STR + wkloc[it]]) = m2t_u2{lo, hi};
}
}
lds_barrier();
if constexpr (ABLK) {
// Re-express each row's partial sum in the new block's scale: one ratio a lane a row.
if (bnd) {
#pragma unroll
for (int i = 0; i < TM; ++i) {
const float r = sR[wm * TM * 16 + i * 16 + col];
#pragma unroll
for (int j = 0; j < TN; ++j)
#pragma unroll
for (int e = 0; e < 8; ++e) acc[i][j][e] *= r;
}
}
// The next boundary's scales, issued behind this slab's loads and needed a boundary later.
if ((k0 & 127) == 0 && k0 + 128 < K) {
ns = asrow[(k0 >> 7) + 1];
np = asrow[k0 >> 7];
}
}
#pragma unroll
for (int step = 0; step < NS; ++step) {
const int kk = step * 16 + kb8;
m2t_v2i wf[TN];
#pragma unroll
for (int j = 0; j < TN; ++j) {
const unsigned char* p = &sW[(wn * TN * 16 + j * 16 + col) * STR + kk];
wf[j][0] = *(const int*)p; wf[j][1] = *(const int*)(p + 4);
}
// Keep one step's W fragments live at a time; otherwise the compiler hoists every step's
// loads above the first WMMA.
__builtin_amdgcn_sched_barrier(0);
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int j = 0; j < TN; ++j)
acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf[j], af[i][step],
acc[i][j]);
}
lds_barrier();
}
// Epilogue. A lane holds row m0 + 64*wm + 16i + col of M fragment i and eight consecutive columns
// of N fragment j, one 16-byte store per (i, j). 2^(Wref[n]-127) is the float whose exponent
// field is Wref[n]; N % 16 == 0 keeps a lane's eight columns all inside or all outside N.
float sc[TM];
if constexpr (ABLK) {
// the scale each row ends in, once a row; the K loop's closing barrier retired the ratio reads
sR[tid] = r4d_mxfp4_carried(asrow, (K - 1) >> 7);
lds_barrier();
#pragma unroll
for (int i = 0; i < TM; ++i) sc[i] = sR[wm * TM * 16 + i * 16 + col];
} else {
#pragma unroll
for (int i = 0; i < TM; ++i) {
const int m = m0 + wm * TM * 16 + i * 16 + col;
sc[i] = As[(size_t)(m < M ? m : M - 1) * as_rs];
}
}
#pragma unroll
for (int j = 0; j < TN; ++j) {
const int nb = n0 + wn * TN * 16 + j * 16 + kb8;
if (nb >= N) continue;
const m2t_u2 rb = *(const m2t_u2*)(Wref + nb);
#pragma unroll
for (int i = 0; i < TM; ++i) {
const int m = m0 + wm * TM * 16 + i * 16 + col;
if (m >= M) continue;
// rounded as the bf16 store rounds, packed in whole registers (see bf16x2_rne_nan)
float v[8];
#pragma unroll
for (int e = 0; e < 8; ++e) {
const float rf = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23);
v[e] = acc[i][j][e] * rf * sc[i];
}
m2t_u4 o;
o.x = bf16x2_rne_nan(v[0], v[1]);
o.y = bf16x2_rne_nan(v[2], v[3]);
o.z = bf16x2_rne_nan(v[4], v[5]);
o.w = bf16x2_rne_nan(v[6], v[7]);
*(m2t_u4*)(C + (size_t)m * ldc + nb) = o;
}
}
}
extern "C" int r4d_gemm_m2xfp4a8_tiled_group(void) { return R4D_MXFP4_GROUP; }
extern "C" long r4d_m2xfp4a8_tile_a_bytes(int M, int K) {
return M < 1 || K < 16 ? 0 : (long)((M + 15) / 16) * 16 * K;
}
extern "C" void r4d_m2xfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda) {
if (!lda) lda = K;
if (M < 1) throw std::runtime_error("r4d m2xfp4a8_tile_a: M must be >= 1");
if (K < 16 || K % 16) throw std::runtime_error("r4d m2xfp4a8_tile_a: K must be a multiple of 16");
const long long slots = (long long)((M + 15) / 16) * (K / 16) * 32;
hipLaunchKernelGGL(r4d_m2xfp4a8_tile_a_kernel, dim3((unsigned)((slots + 255) / 256)), dim3(256),
0, (hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K,
slots, lda);
}
extern "C" void r4d_gemm_m2xfp4a8_tiled(long at, long ascale, long wq, long ws, long wm, long wref,
long c, int M, int K, int N, int TN, int as_group,
int as_rs, long stream, int ldws, int ldc) {
if (!ldws) ldws = N;
if (!ldc) ldc = N;
if (M < 1) throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: M must be >= 1");
if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: N must be a multiple of 16");
if (K < R4D_M2T_KUNIT || K % R4D_M2T_KUNIT)
throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: K must be a multiple of 64");
// tn=0: TN=4 from the M crossover on, unless its 128-wide tile leaves fewer than 128 blocks
// (narrow N), where TN=2's extra blocks win.
if (TN == 0)
TN = M >= R4D_M2T_TN4_MIN_M && (long)((N + 127) / 128) * ((M + R4D_M2T_BMF - 1) / R4D_M2T_BMF) >= 128
? 4 : 2;
if (TN != 2 && TN != 4) throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: TN must be 2 or 4");
if (as_group != 0 && as_group != 128)
throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: the activation scale is per row or per 128 of K");
const bool ablk = as_group == 128;
if (ablk && as_rs < (K + 127) / 128)
throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: activation scale rows shorter than ceil(K/128)");
const bool wide_slab = TN == 2 && K % 128 == 0;
const int bnf = R4D_M2T_WN * TN * 16;
dim3 grid((N + bnf - 1) / bnf, (M + R4D_M2T_BMF - 1) / R4D_M2T_BMF), block(R4D_M2T_NTHR);
auto Ap = (const unsigned char*)at;
auto Sp = (const float*)ascale;
auto Wp = (const unsigned char*)wq;
auto Zp = (const unsigned char*)ws;
auto Mp = (const unsigned char*)wm;
auto Rp = (const unsigned char*)wref;
auto Cp = (uint16_t*)c;
hipStream_t st = (hipStream_t)stream;
#define M2T_LAUNCH(TNv, LBKv, ABv) \
hipLaunchKernelGGL((r4d_gemm_m2xfp4a8_tiled_kernel<TNv, LBKv, ABv>), grid, block, 0, st, Ap, Sp, \
Wp, Zp, Mp, Rp, Cp, M, K, N, as_rs, ldws, ldc)
if (TN == 4) { if (ablk) M2T_LAUNCH(4, 64, true); else M2T_LAUNCH(4, 64, false); }
else if (wide_slab) { if (ablk) M2T_LAUNCH(2, 128, true); else M2T_LAUNCH(2, 128, false); }
else { if (ablk) M2T_LAUNCH(2, 64, true); else M2T_LAUNCH(2, 64, false); }
#undef M2T_LAUNCH
}
// ============================================================== the plugin ABI entry point
// The row-major activation is re-tiled into the op's scratch and the GEMM reads it there. For a
// partitioned weight (mx_parts), each part's activation copy is re-tiled and multiplied in turn.
extern "C" int r4d_rad_gemm_m2xfp4a8_tiled(const RadArgs* a, RadStream s) {
GemmOps g;
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
if (rc != RAD_OK) return rc;
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
if (!g.ascale) return R4D_NO(RAD_E_INVAL);
/* The per-row reference exponent is required, as in r4d_rad_gemm_mxfp4a8_m64. */
if (!g.bref) return R4D_NO(RAD_E_INVAL);
MxParts mp;
rc = mx_parts(a, &g, &mp);
if (rc != RAD_OK) return rc;
if (g.K % R4D_M2T_KUNIT) return R4D_NO(RAD_E_SHAPE);
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
if (rc != RAD_OK) return rc;
const long long slab = r4d_m2xfp4a8_tile_a_bytes((int)g.M, (int)g.K);
if (!a->scratch || a->scratch_bytes < slab) return R4D_NO(RAD_E_INVAL);
R4dMxTileCfg t;
r4d_cfg_mxfp4_tiled(a, &t);
const long kb = (long)((g.K + 127) / 128);
const long at = (long)(uintptr_t)a->scratch;
// The meta plane rides the weight blob's tail, in the scale plane's [K/32][N] order; a part
// windows it at n0, as it does the exponent plane.
const long meta0 = (long)g.N * g.K / 2;
for (int p = 0; p < mp.n; ++p) {
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
R4D_TRY("gemm_m2xfp4a8_tiled",
r4d_m2xfp4a8_tile_a(r4d_addr(g.a) + p * g.K, at, (int)g.M, (int)g.K,
(long)(uintptr_t)s, (int)(mp.lda ? mp.lda : g.K));
r4d_gemm_m2xfp4a8_tiled(at, r4d_addr(g.ascale) + p * kb * 4,
r4d_addr(g.b) + n0 * g.K / 2, r4d_addr(g.bscale) + n0,
r4d_addr(g.b) + meta0 + n0, r4d_addr(g.bref) + n0,
r4d_addr(g.y) + n0 * 2, (int)g.M, (int)g.K, (int)np, t.tn,
as_group, as_rs, (long)(uintptr_t)s, (int)g.N, (int)g.N));
}
return RAD_OK;
}
/* The op's scratch, sized at the band's widest M: the fragment-tiled activation in whole 16-row
* fragments. One copy serves every part: parts run in order on the op's stream, so a re-tile
* cannot overtake the previous part's GEMM. */
extern "C" int64_t r4d_rad_gemm_m2xfp4a8_tiled_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), K = r4d_geti_or(a, "K", 0);
return (int64_t)r4d_m2xfp4a8_tile_a_bytes((int)M, (int)K);
}
+5 -32
View File
@@ -47,6 +47,7 @@
// boundary early). Each split's partial is converted to absolute units before it is written,
// since splits end in different blocks.
#include "r4d.h"
#include "r4d_keyed.h"
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_mxfp4.h"
@@ -488,39 +489,11 @@ void r4d_gemm_mxfp4a8_decode1_kernel(
namespace {
// The arrival counters, one block per output buffer (see the header). They cannot live in the
// scratch, which other ops overwrite, because they must be zero at entry. One allocation per
// (device, output), kept zero by the reducer and never freed (a recorded pass replays the
// pointer), as gemm_fp8a8_nt_m16's split_ctr.
// (device, output), kept zero by the reducer and freed only with the output's memory (a recorded
// pass replays the pointer; r4d_keyed.h), as gemm_fp8a8_nt_m16's split_ctr.
unsigned* mxd_out_ctr(const void* out) {
static std::mutex mu;
static std::map<std::pair<int, const void*>, unsigned*> blocks;
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
const auto key = std::make_pair(dev, out);
{
// Not held while the block is made, as in split_ctr (r4d_gemm_fp8a8.hip): the zeroing waits
// for the card.
std::lock_guard<std::mutex> lk(mu);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
}
const size_t n = R4D_MXD_MAX_N / (R4D_MXD_DWN * 16);
unsigned* p = nullptr;
if (hipMalloc((void**)&p, n * sizeof(unsigned)) != hipSuccess) return nullptr;
// Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has finished
// when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it runs on the
// null stream, which a non-blocking stream does not wait for, so wait here.
if (hipMemset(p, 0, n * sizeof(unsigned)) != hipSuccess || hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return nullptr;
}
unsigned* kept = nullptr;
{
std::lock_guard<std::mutex> lk(mu);
const auto [it, fresh] = blocks.emplace(key, p);
if (fresh) return it->second;
kept = it->second;
}
(void)hipFree(p); // another thread made this key's block in the meantime
return kept;
return r4d::keyed_block(r4d::Keyed::MxDecode, nullptr, out,
(size_t)(R4D_MXD_MAX_N / (R4D_MXD_DWN * 16)) * sizeof(unsigned));
}
// The split, slab and load hint for a launch, from M, the shape and the tunables (0 = the rule; see
+1 -175
View File
@@ -33,6 +33,7 @@
// counters: there is no split across blocks (the gated folds at the end of the file, at 1..8 rows and
// at 9..64, have both).
#include "r4d.h"
#include "r4d_keyed.h"
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_mxfp4.h"
@@ -670,89 +671,7 @@ void r4d_gemm_mxfp4a8_gatedw_kernel(
}
namespace {
// The arrival counters, one block per output buffer, as the decode row's (mxd_out_ctr): not in the
// scratch, which other ops overwrite, since they must be zero at entry. One allocation per (device,
// output), kept zero by the reducer and never freed (a recorded pass replays the pointer).
unsigned* mxgg_out_ctr(const void* out) {
static std::mutex mu;
static std::map<std::pair<int, const void*>, unsigned*> blocks;
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
const auto key = std::make_pair(dev, out);
{
// Not held while the block is made, as in split_ctr (r4d_gemm_fp8a8.hip): the zeroing waits
// for the card.
std::lock_guard<std::mutex> lk(mu);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
}
unsigned* p = nullptr;
if (hipMalloc((void**)&p, R4D_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess) return nullptr;
// Zero before any launch reads it: the memset is on the null stream, which the engine's streams
// need not wait for, so wait here (as mxd_out_ctr and r4d_moe.hip's router counters do).
if (hipMemset(p, 0, R4D_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess ||
hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return nullptr;
}
unsigned* kept = nullptr;
{
std::lock_guard<std::mutex> lk(mu);
const auto [it, fresh] = blocks.emplace(key, p);
if (fresh) return it->second;
kept = it->second;
}
(void)hipFree(p); // another thread made this key's block in the meantime
return kept;
}
// The scratch: the bf16 product [M, n], then each tile's per-row amax [n / 16][M] fp32.
long long mxgg_h_bytes(long long M, long long n) { return (M * n * 2 + 255) / 256 * 256; }
long long mxgg_scratch_bytes(long long M, long long n) {
return mxgg_h_bytes(M, n) + (n / 16) * M * (long long)sizeof(float);
}
void mxgg_launch(bool ablk, int act, const void* a, const void* as, const void* w, const void* ws,
const void* wr, void* q, void* s, void* y, void* scratch, unsigned* cnt, int M,
int K, int n, int as_rs, int lda, int ldws, int q_ld, int s_ld, int y_ld,
RadStream stream) {
const dim3 grid((uint32_t)(n / 16)), block(2 * R4D_MXG_KW * 32);
hipStream_t st = (hipStream_t)stream;
uint16_t* h = (uint16_t*)scratch;
float* x = (float*)((char*)scratch + mxgg_h_bytes(M, n));
#define MXGG_L(AB_, ACT_) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gated_kernel<AB_, ACT_>), grid, block, 0, st, \
(const unsigned char*)a, (const float*)as, (const unsigned char*)w, \
(const unsigned char*)ws, (const unsigned char*)wr, (uint8_t*)q, (float*)s, \
(uint16_t*)y, h, x, cnt, M, K, n, as_rs, lda, ldws, q_ld, s_ld, y_ld)
if (act == 0) { if (ablk) MXGG_L(true, 0); else MXGG_L(false, 0); }
else { if (ablk) MXGG_L(true, 1); else MXGG_L(false, 1); }
#undef MXGG_L
}
// The wide form: one block of eight K waves a 16-column tile of the gated output, ceil(M / 16) row
// tiles.
void mxggw_launch(bool ablk, int act, const void* a, const void* as, const void* w, const void* ws,
const void* wr, void* q, void* s, void* y, void* scratch, unsigned* cnt, int M,
int K, int n, int as_rs, int lda, int ldws, int q_ld, int s_ld, int y_ld,
RadStream stream) {
const dim3 grid((uint32_t)(n / 16)), block(R4D_MXG_KW * 32);
hipStream_t st = (hipStream_t)stream;
uint16_t* h = (uint16_t*)scratch;
float* x = (float*)((char*)scratch + mxgg_h_bytes(M, n));
const int rt = (M + 15) / 16;
#define MXGW_L(AB_, ACT_, RT_) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gatedw_kernel<AB_, ACT_, RT_>), grid, block, 0, st, \
(const unsigned char*)a, (const float*)as, (const unsigned char*)w, \
(const unsigned char*)ws, (const unsigned char*)wr, (uint8_t*)q, (float*)s, \
(uint16_t*)y, h, x, cnt, M, K, n, as_rs, lda, ldws, q_ld, s_ld, y_ld)
#define MXGW_RT(AB_, ACT_) \
{ if (rt <= 1) MXGW_L(AB_, ACT_, 1); else if (rt == 2) MXGW_L(AB_, ACT_, 2); \
else if (rt == 3) MXGW_L(AB_, ACT_, 3); else MXGW_L(AB_, ACT_, 4); }
if (act == 0) { if (ablk) MXGW_RT(true, 0) else MXGW_RT(false, 0) }
else { if (ablk) MXGW_RT(true, 1) else MXGW_RT(false, 1) }
#undef MXGW_RT
#undef MXGW_L
}
} // namespace
/* The gated GEMM's shim. Operand indices are `gemm_nt_q_gated_mx`'s (oGemmNtQGatedMx in
@@ -761,96 +680,3 @@ void mxggw_launch(bool ablk, int act, const void* a, const void* as, const void*
enum { MXGG_A = 0, MXGG_AS = 1, MXGG_B = 2, MXGG_BS = 3, MXGG_BR = 4, MXGG_Q = 5, MXGG_S = 6,
MXGG_Y = 7 };
/* Both rows' entry: the narrow form at 1..8 rows (gemm_mxfp4a8_gated_gemv), the wide one at 9..64
* (gemm_mxfp4a8_gated_gemv_wide), each refusing the other's band as its GEMM row does. */
static int mxgg_entry(const RadArgs* a, RadStream s, bool wide) {
const RadTensor* x = r4d_opt(a, MXGG_A);
const RadTensor* xs = r4d_opt(a, MXGG_AS);
const RadTensor* w = r4d_opt(a, MXGG_B);
const RadTensor* ws = r4d_opt(a, MXGG_BS);
const RadTensor* wr = r4d_opt(a, MXGG_BR);
const RadTensor* q = r4d_opt(a, MXGG_Q);
const RadTensor* sc = r4d_opt(a, MXGG_S);
const RadTensor* y = r4d_opt(a, MXGG_Y);
if (!x || !xs || !w || !ws || !wr || !q || !sc) return R4D_NO(RAD_E_INVAL);
if (x->dtype != RAD_F8E4M3 || xs->dtype != RAD_F32 || q->dtype != RAD_F8E4M3 ||
sc->dtype != RAD_F32 || (y && y->dtype != RAD_BF16))
return R4D_NO(RAD_E_DTYPE);
if (q->rank != 2 || sc->rank != 2 || x->rank != 2) return R4D_NO(RAD_E_SHAPE);
if (y && y->rank != 2) return R4D_NO(RAD_E_SHAPE);
if (r4d_geti_or(a, "group", 32) != 32) return R4D_NO(RAD_E_SHAPE);
/* silu (the SwiGLU MLP) or gelu_tanh (GeGLU, gelu_mul's). The GeGLU chain's bf16 plane is
* gelu_mul's output, which the fold's replaces-hook cannot hand to the optional `out_bf16`, so
* that form writes none. */
const char* act = r4d_gets(a, "act");
const int actm = !act ? -1 : !std::strcmp(act, "silu") ? 0 : !std::strcmp(act, "gelu_tanh") ? 1 : -1;
if (actm < 0) return R4D_NO(RAD_E_UNSUPPORTED);
if (actm == 1 && y) return R4D_NO(RAD_E_UNSUPPORTED);
/* The gated width from `q`, the buffer written; N and K from the op's parameters, since the
* weight operands are packed bytes. */
const long long M = q->shape[0], nout = q->shape[1];
const long long N = r4d_geti_or(a, "N", 0), K = r4d_geti_or(a, "K", 0);
const long long m_lo = wide ? R4D_MXG_MAX_M + 1 : 1, m_hi = wide ? R4D_MXG_WMMA_MAX_M : R4D_MXG_MAX_M;
if (M < m_lo || M > m_hi || nout < 128 || nout % 128 || nout / 128 > R4D_MXGG_MAX_GROUPS)
return R4D_NO(RAD_E_SHAPE);
if (N != 2 * nout || K < 128 || K % 128) return R4D_NO(RAD_E_SHAPE);
if (x->shape[0] != M || r4d_numel(x) != M * K) return R4D_NO(RAD_E_SHAPE);
if (sc->shape[0] != M || sc->shape[1] != nout / 128) return R4D_NO(RAD_E_SHAPE);
if (y && (y->shape[0] != M || y->shape[1] != nout)) return R4D_NO(RAD_E_SHAPE);
/* The activation scale grid as the gemm_nt_q rows read it (mx_ascale_grid), so the fold and the
* GEMM it replaces take every scale plane the same way. */
GemmOps go{};
go.ascale = xs; go.M = M; go.K = K;
int as_group = 0, as_rs_i = 1;
if (mx_ascale_grid(go, &as_group, &as_rs_i) != RAD_OK) return R4D_NO(RAD_E_SHAPE);
const bool ablk = as_group == 128;
const long long as_rs = as_rs_i;
/* Row pitches; r4d_row_pitch is -1 for a tensor not contiguous past its leading axis. A is read
* a dword at a time. */
const long long lda = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc);
const long long yp = y ? r4d_row_pitch(y) : 0;
if (lda < K || lda % 4 || qp < nout || sp < nout / 128 || (y && yp < nout))
return R4D_NO(RAD_E_STRIDE);
if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16) || !r4d_aligned(q->data, 4) ||
!r4d_aligned(ws->data, 4) || !r4d_aligned(wr->data, 4) || qp % 4)
return R4D_NO(RAD_E_ALIGN);
/* The cross-block product and amaxes are the op's scratch (sized by the hook below); a
* shorter one is refused. */
if (!a->scratch || a->scratch_bytes < mxgg_scratch_bytes(M, nout)) return R4D_NO(RAD_E_SCRATCH);
unsigned* cnt = mxgg_out_ctr(q->data);
if (!cnt) return R4D_NO(RAD_E_NOMEM);
if (wide)
R4D_TRY("gemm_mxfp4a8_gated_wide",
mxggw_launch(ablk, actm, x->data, xs->data, w->data, ws->data, wr->data, q->data, sc->data,
y ? y->data : nullptr, a->scratch, cnt, (int)M, (int)K, (int)nout, (int)as_rs,
(int)lda, (int)N, (int)qp, (int)sp, (int)yp, s));
else
R4D_TRY("gemm_mxfp4a8_gated",
mxgg_launch(ablk, actm, x->data, xs->data, w->data, ws->data, wr->data, q->data, sc->data,
y ? y->data : nullptr, a->scratch, cnt, (int)M, (int)K, (int)nout, (int)as_rs,
(int)lda, (int)N, (int)qp, (int)sp, (int)yp, s));
return RAD_OK;
}
extern "C" int r4d_rad_gemm_mxfp4a8_gated(const RadArgs* a, RadStream s) {
return mxgg_entry(a, s, false);
}
extern "C" int r4d_rad_gemm_mxfp4a8_gated_wide(const RadArgs* a, RadStream s) {
return mxgg_entry(a, s, true);
}
/* The op's scratch: the product and amaxes at the band's widest M, from N (twice the gated
* width). */
static int64_t mxgg_scratch(const RadArgs* a, long long m_hi) {
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0);
if (M < 1 || M > m_hi || N < 256 || N % 256) return 0;
return (int64_t)mxgg_scratch_bytes(M, N / 2);
}
extern "C" int64_t r4d_rad_gemm_mxfp4a8_gated_scratch(const RadArgs* a) {
return mxgg_scratch(a, R4D_MXG_MAX_M);
}
extern "C" int64_t r4d_rad_gemm_mxfp4a8_gated_wide_scratch(const RadArgs* a) {
return mxgg_scratch(a, R4D_MXG_WMMA_MAX_M);
}
+36 -13
View File
@@ -28,6 +28,7 @@
// r4d_gemm_w4a8_asym_nt_m64.
#include "r4d.h"
#include "r4d_gemm_args.h"
#include "r4d_chain.h"
#include "r4d_common.h"
#include "r4d_gdn_wmma.h"
#include <hip/hip_bf16.h>
@@ -77,12 +78,13 @@ __device__ __forceinline__ v8i w2_mmai(v2i a, v2i b, v8i c) {
#define R4D_W2A8_BOUNDS(MT, NPW) \
((MT) >= 4 ? 256 : (((MT) >= 2 || (NPW) >= 4) ? 512 : 1024))
#define R4D_GEMM_W2A8_NT_PARAMS \
const signed char* __restrict__ A, const float* __restrict__ Ascale, \
const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws, \
const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C, int M, int K, int N, \
int WV, int SK
template <int MT, int NPW, bool NT>
__global__ __launch_bounds__(R4D_W2A8_BOUNDS(MT, NPW)) void r4d_gemm_w2a8_nt_kernel(
const signed char* __restrict__ A, const float* __restrict__ Ascale,
const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws,
const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C,
int M, int K, int N, int WV, int SK) {
__device__ __forceinline__ void r4d_gemm_w2a8_nt_body(R4D_GEMM_W2A8_NT_PARAMS) {
extern __shared__ float redw2[];
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
const int col_local = wave / SK, ksplit = wave % SK;
@@ -223,8 +225,20 @@ __global__ __launch_bounds__(R4D_W2A8_BOUNDS(MT, NPW)) void r4d_gemm_w2a8_nt_ker
}
}
void r4d_gemm_w2a8_nt(long a, long ascale, long wq, long ws, long asum, long c,
int M, int K, int N, int WV, int SK, int MB, int NPW, int NT, long stream) {
// The kernel around the body: CH `r4dchain` is the chained form (r4d_chain.h), taken at decode
// heights.
template <int MT, int NPW, bool NT, class CH>
__global__ __launch_bounds__(R4D_W2A8_BOUNDS(MT, NPW))
void r4d_gemm_w2a8_nt_kernel(R4D_GEMM_W2A8_NT_PARAMS) {
if (CH::on) r4d_chain_wait();
r4d_gemm_w2a8_nt_body<MT, NPW, NT>(A, Ascale, Wq, Ws, Asum, C, M, K, N, WV, SK);
if (CH::on) r4d_chain_done();
}
#undef R4D_GEMM_W2A8_NT_PARAMS
static void gemm_w2a8_nt_emit(long a, long ascale, long wq, long ws, long asum, long c,
int M, int K, int N, int WV, int SK, int MB, int NPW, int NT,
long stream, bool chain) {
if (M < 1) throw std::runtime_error("r4d gemm_w2a8_nt: M must be >= 1");
if (N % 16) throw std::runtime_error("r4d gemm_w2a8_nt: N must be a multiple of 16");
if (K % (SK * R4D_GEMM_W2A8_GROUP))
@@ -249,8 +263,11 @@ void r4d_gemm_w2a8_nt(long a, long ascale, long wq, long ws, long asum, long c,
auto Sump = (const float*)asum;
auto Cp = (__hip_bfloat16*)c;
hipStream_t st = (hipStream_t)stream;
#define LW2(MT, NP, TT) hipLaunchKernelGGL((r4d_gemm_w2a8_nt_kernel<MT, NP, TT>), grid, block, \
smem, st, Ap, Asp, Wp, Sp, Sump, Cp, M, K, N, WV, SK)
#define LW2C(MT, NP, TT, CH_) \
hipLaunchKernelGGL((r4d_gemm_w2a8_nt_kernel<MT, NP, TT, CH_>), grid, block, smem, st, Ap, Asp, \
Wp, Sp, Sump, Cp, M, K, N, WV, SK)
#define LW2(MT, NP, TT) \
do { if (chain) LW2C(MT, NP, TT, r4dchain); else LW2C(MT, NP, TT, R4dUnchained); } while (0)
#define LW2_MB(NP, TT) switch (MB) { \
case 1: LW2(1, NP, TT); break; \
case 2: LW2(2, NP, TT); break; \
@@ -266,6 +283,12 @@ void r4d_gemm_w2a8_nt(long a, long ascale, long wq, long ws, long asum, long c,
}
#undef LW2_MB
#undef LW2
#undef LW2C
}
void r4d_gemm_w2a8_nt(long a, long ascale, long wq, long ws, long asum, long c,
int M, int K, int N, int WV, int SK, int MB, int NPW, int NT, long stream) {
gemm_w2a8_nt_emit(a, ascale, wq, ws, asum, c, M, K, N, WV, SK, MB, NPW, NT, stream, false);
}
int r4d_gemm_w2a8_nt_group(void) { return R4D_GEMM_W2A8_GROUP; }
@@ -288,10 +311,10 @@ extern "C" int r4d_rad_gemm_w2a8(const RadArgs* a, RadStream s) {
if (c.mb < 1 || c.mb > 4) return R4D_NO(RAD_E_SHAPE);
if (c.npw != 1 && c.npw != 2 && c.npw != 4) return R4D_NO(RAD_E_SHAPE);
R4D_TRY("gemm_w2a8_nt",
r4d_gemm_w2a8_nt(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale),
r4d_addr(g.asum), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt,
(long)(uintptr_t)s));
gemm_w2a8_nt_emit(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale),
r4d_addr(g.asum), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt,
(long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0 && g.M <= 64));
return RAD_OK;
}
+55 -13
View File
@@ -13,6 +13,7 @@
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_fwht.h"
#include "r4d_gdn_wmma.h"
#include "r4d_q8.h"
#include "rad_philox.h"
@@ -184,9 +185,16 @@ __global__ __launch_bounds__(kT) void chan_stats_kernel(
// ln_mod_kernel's order through the same block_sum, the norm output is rounded to bf16 before
// quantising, and the codes are r4d_q8.h's. A 128-column group is sixteen consecutive lanes, so its
// amax is a half-wave reduction.
//
// HI8 is ln_mod_had_quant_i8g: had_quant_act_i8g's quantiser in place of quant_act_fp8's. The
// bf16-rounded norm output is rotated by the 128-wide Hadamard where it lies, eight columns a lane
// and sixteen lanes a block (strides 1, 2, 4 in the lane, then 8 to 64 across lanes, the order
// r4d_fwht_wave takes them in, so the sums are the standalone kernel's), then int8 codes under
// one scale per (row, 128 * SUB): SUB 2 is IQ8R's 256-wide group, a whole wave. `z` receives the
// unrotated norm output. Byte-identical to gate_add, ln_mod and had_quant_act_i8g.
constexpr int kLnqChunks = 4; // 8-wide chunks a thread keeps: n <= kT * 8 * 4 = 8192
template <bool GATED>
template <bool GATED, bool HI8 = false, int SUB = 1>
__global__ __launch_bounds__(kT) void ln_mod_quant_kernel(
const uint16_t* __restrict__ yd, const uint16_t* __restrict__ g, const uint16_t* __restrict__ s,
const int* __restrict__ cu, uint16_t* __restrict__ x, uint8_t* __restrict__ q,
@@ -237,6 +245,23 @@ __global__ __launch_bounds__(kT) void ln_mod_quant_kernel(
#pragma unroll
for (int j = 0; j < 8; ++j) o[j] = bfr(bfr((v[k][j] - mean) * rs) * bfr(1.0f + gs[j]));
if (z) st8(z + (size_t)r * z_ld + i, o);
if constexpr (HI8) {
#pragma unroll
for (int h = 1; h < 8; h <<= 1) {
#pragma unroll
for (int j = 0; j < 8; ++j)
if ((j & h) == 0) {
const float a = o[j], b = o[j + h];
o[j] = a + b;
o[j + h] = a - b;
}
}
const int lane = (int)threadIdx.x & 31;
r4d_fwht_xstage<8, 1>(o, lane);
r4d_fwht_xstage<8, 2>(o, lane);
r4d_fwht_xstage<8, 4>(o, lane);
r4d_fwht_xstage<8, 8>(o, lane);
}
float m = 0.0f;
#pragma unroll
for (int j = 0; j < 8; ++j) m = fmaxf(m, fabsf(o[j]));
@@ -244,12 +269,13 @@ __global__ __launch_bounds__(kT) void ln_mod_quant_kernel(
m = fmaxf(m, r4d_xor_lane<4>(m));
m = fmaxf(m, r4d_xor_lane<2>(m));
m = fmaxf(m, r4d_xor_lane<1>(m));
const float sc = m > 0.0f ? m * (1.0f / q8_top<false>()) : 1.0f;
if constexpr (SUB == 2) m = fmaxf(m, r4d_xor_lane<16>(m));
const float sc = m > 0.0f ? m * (1.0f / q8_top<HI8>()) : 1.0f;
const float inv = 1.0f / sc;
if ((threadIdx.x & 15) == 0) qs[(size_t)r * qs_ld + i / 128] = sc;
if ((threadIdx.x & (16 * SUB - 1)) == 0) qs[(size_t)r * qs_ld + i / (128 * SUB)] = sc;
*(uint2*)(q + (size_t)r * q_ld + i) =
make_uint2(q8_pack4<false>(o[0], o[1], o[2], o[3], inv),
q8_pack4<false>(o[4], o[5], o[6], o[7], inv));
make_uint2(q8_pack4<HI8>(o[0], o[1], o[2], o[3], inv),
q8_pack4<HI8>(o[4], o[5], o[6], o[7], inv));
}
}
@@ -999,7 +1025,9 @@ extern "C" int r4d_rad_ln_mod(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_ln_mod_quant_fp8(const RadArgs* a, RadStream s) {
/* ln_mod_quant_fp8 (E4M3 codes, group 128) and with `hi8` ln_mod_had_quant_i8g (rotated int8
* codes, group 128 or 256). */
static int ln_mod_quant_launch(const RadArgs* a, RadStream s, bool hi8) {
const RadTensor *y = r4d_opt(a, 0), *g = r4d_opt(a, 1), *sc = r4d_opt(a, 2);
const RadTensor *cu = r4d_opt(a, 3), *x = r4d_opt(a, 4), *q = r4d_opt(a, 5);
const RadTensor *qs = r4d_opt(a, 6), *z = r4d_opt(a, 7);
@@ -1007,10 +1035,11 @@ extern "C" int r4d_rad_ln_mod_quant_fp8(const RadArgs* a, RadStream s) {
const bool gated = r4d_geti_or(a, "gated", 0) != 0;
if (gated && (!y || !g)) return R4D_NO(RAD_E_INVAL);
if (!is_bf16(x) || !is_bf16(sc) || (gated && (!is_bf16(y) || !is_bf16(g))) ||
(z && !is_bf16(z)) || q->dtype != RAD_F8E4M3 || qs->dtype != RAD_F32)
(z && !is_bf16(z)) || q->dtype != (hi8 ? RAD_I8 : RAD_F8E4M3) || qs->dtype != RAD_F32)
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0);
if (n <= 0 || n % 128 || r4d_geti_or(a, "group", 0) != 128 ||
const long long grp = r4d_geti_or(a, "group", 0);
if (n <= 0 || (grp != 128 && !(hi8 && grp == 256)) || n % grp ||
n > (long long)kT * 8 * kLnqChunks)
return R4D_NO(RAD_E_SHAPE);
long long rx = 0, xl = 0, ry = 0, yl = 0, rg = 0, gl = 0, rs = 0, sl = 0, rz = 0, zl = 0;
@@ -1019,26 +1048,39 @@ extern "C" int r4d_rad_ln_mod_quant_fp8(const RadArgs* a, RadStream s) {
(gated && (!rows8(y, n, &ry, &yl) || !rows8(g, n, &rg, &gl))) ||
(z && !rows8(z, n, &rz, &zl)))
return R4D_NO(RAD_E_STRIDE);
const long long ql = r4d_rows_pitch(q, n, &rq), qsl = r4d_rows_pitch(qs, n / 128, &rqs);
const long long ql = r4d_rows_pitch(q, n, &rq), qsl = r4d_rows_pitch(qs, n / grp, &rqs);
if (ql < 0 || (ql & 7) || ((uintptr_t)q->data & 7) || qsl < 0) return R4D_NO(RAD_E_STRIDE);
const long long n_seq = r4d_numel(cu) - 1, rows = rq;
if (rows <= 0 || n_seq <= 0 || rx < rows || rqs < rows || rs < n_seq ||
(gated && (ry < rows || rg < n_seq)) || (z && rz < rows))
return R4D_NO(RAD_E_SHAPE);
const float eps = (float)r4d_getf(a, "eps", 1e-6);
#define R4D_LNQ(G) \
hipLaunchKernelGGL(ln_mod_quant_kernel<G>, dim3((unsigned)rows), dim3(kT), 0, (hipStream_t)s, \
#define R4D_LNQ(G, ...) \
hipLaunchKernelGGL((ln_mod_quant_kernel<G, ##__VA_ARGS__>), dim3((unsigned)rows), dim3(kT), 0, \
(hipStream_t)s, \
G ? (const uint16_t*)y->data : nullptr, \
G ? (const uint16_t*)g->data : nullptr, (const uint16_t*)sc->data, \
(const int*)cu->data, (uint16_t*)x->data, (uint8_t*)q->data, \
(float*)qs->data, z ? (uint16_t*)z->data : nullptr, (int)n, (int)n_seq, \
eps, (int)yl, (int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl)
if (gated) R4D_LNQ(true);
else R4D_LNQ(false);
if (!hi8) {
if (gated) R4D_LNQ(true);
else R4D_LNQ(false);
} else if (grp == 256) {
if (gated) R4D_LNQ(true, true, 2);
else R4D_LNQ(false, true, 2);
} else {
if (gated) R4D_LNQ(true, true, 1);
else R4D_LNQ(false, true, 1);
}
#undef R4D_LNQ
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_ln_mod_had_quant_i8g(const RadArgs* a, RadStream s) {
return ln_mod_quant_launch(a, s, true);
}
extern "C" int r4d_rad_gate_add(const RadArgs* a, RadStream s) {
const RadTensor *y = r4d_opt(a, 0), *g = r4d_opt(a, 1), *cu = r4d_opt(a, 2), *x = r4d_opt(a, 3);
if (!y || !g || !cu || !x) return R4D_NO(RAD_E_INVAL);
-167
View File
@@ -1,167 +0,0 @@
// r4d_givens_dense.hip -- ParoQuant's rotation as a dense per-group matrix on the matrix cores.
//
// The Givens stages of a 128-column group compose to one orthogonal 128 x 128 matrix T, so
// y = T (x / D) is a small GEMM: out[m][j] = sum_i T[j][i] * (x[m][i] / D[i]). The sequential
// kernel (r4d_givens_rotate.hip) runs `stages` dependent LDS rounds per group and is latency bound
// (~100-130 GB/s of ~640); this one spends ~8x the multiply-adds on f16 WMMA (5 us of math for
// 2048 rows) and quantises in the epilogue: int8 (scale amax / 127, for the int8 prefill GEMMs) or
// E4M3 (amax / 448, for the mxfp4a8 GEMMs), the sequential producer's scale grid. About 3x faster
// at prefill sizes and no slower at decode.
//
// The matrices are the weight: rad-convert composes them from the Givens stages into the
// encoding's `t.dense` table, [parts * K / 128][128 (j)][128 (i)] f16, which the layout
// (r4d_layout.cpp, r4d.givens.dense) takes as is. The channel scale stays a separate table
// (`rscale`), divided on the way in: folding 1/D into T would mix very different magnitudes in one
// f16 matrix.
//
// One block per (part, group) x row chunk. The group's T (32 KiB of f16) is staged in LDS once and
// each of the four waves takes 16-row tiles: per k step one B fragment (the activation row's eight
// k, divided by D, as f16) meets the eight j tiles of T. The accumulators are C[j][m]: lane l holds
// column m = l & 15 and rows j = 8 * (l >> 4) + e, so a row's 128 outputs are split over lanes m
// and m + 16 and its amax is a max over 64 registers and one xor-16 shuffle.
//
// A tile's eight activation loads are issued together and the issue order is pinned per k step
// (sched_barrier), so the A fragments are not hoisted whole into registers: 137 VGPRs, no spills.
#include "r4d.h"
#include "r4d_emit.h"
#include "r4d_fp8_args.h"
#include "r4d_common.h"
#include "r4d_q8.h"
#include <hip/hip_fp16.h>
#include <algorithm>
#include <cstdint>
#include <cstring>
namespace {
constexpr uint32_t kGroup = 128;
constexpr uint32_t kThreads = 128;
constexpr uint32_t kWaves = kThreads / 32;
constexpr uint32_t kTStride = kGroup + 8; // T row pitch in f16: 16 B pad for conflict-free b128
static_assert(kThreads == kGroup, "a thread stages one channel scale of the group (invd[tid])");
typedef _Float16 v8h_t __attribute__((ext_vector_type(8)));
template <bool I8>
__global__ __launch_bounds__(kThreads) void givens_dense_kernel(
const uint16_t* __restrict__ x, const uint16_t* __restrict__ tdense, const float* __restrict__ rscale,
uint8_t* __restrict__ q, float* __restrict__ s, uint32_t M, uint32_t K, uint32_t nkb, uint32_t x_ld,
uint32_t q_ld, uint32_t s_ld) {
__shared__ uint16_t Tl[kGroup * kTStride];
__shared__ float invd[kGroup];
const uint32_t gp = blockIdx.x, part = gp / nkb, g = gp % nkb;
const uint32_t tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
// all sixteen loads in flight before the first LDS store: the staging is latency, not bandwidth
const uint4* tg = (const uint4*)(tdense + (size_t)gp * kGroup * kGroup);
constexpr uint32_t kStage = kGroup * kGroup / 8 / kThreads;
uint4 tv[kStage];
#pragma unroll
for (uint32_t k = 0; k < kStage; ++k) tv[k] = tg[tid + k * kThreads];
#pragma unroll
for (uint32_t k = 0; k < kStage; ++k) {
const uint32_t i = tid + k * kThreads, j = i / (kGroup / 8), c = i % (kGroup / 8);
*(uint4*)&Tl[j * kTStride + c * 8] = tv[k];
}
invd[tid] = 1.0f / rscale[(size_t)part * K + g * kGroup + tid];
__syncthreads();
const uint32_t h = lane >> 4, col = lane & 15;
const uint32_t Mt = (M + 15) >> 4;
const uint32_t step = gridDim.y * kWaves;
for (uint32_t tile = blockIdx.y * kWaves + wave; tile < Mt; tile += step) {
// Lane (col, h) reads columns 8h .. 8h+7 of every 16-wide k step of row tile * 16 + col.
// All eight k steps are loaded at once: one load latency per tile.
uint32_t m = tile * 16 + col;
const bool live = m < M;
if (!live) m = M - 1;
const uint16_t* xr = x + (size_t)m * x_ld + g * kGroup + 8 * h;
uint4 raw[8];
#pragma unroll
for (uint32_t ks = 0; ks < 8; ++ks) raw[ks] = *(const uint4*)(xr + ks * 16);
v8f acc[8];
#pragma unroll
for (int jt = 0; jt < 8; ++jt) acc[jt] = (v8f)(0.f);
#pragma unroll
for (uint32_t ks = 0; ks < 8; ++ks) {
const uint32_t c0 = ks * 16 + 8 * h;
const uint32_t w[4] = { raw[ks].x, raw[ks].y, raw[ks].z, raw[ks].w };
v8h_t bf;
#pragma unroll
for (int e = 0; e < 8; ++e) {
const uint32_t b = (w[e >> 1] >> (16 * (e & 1))) & 0xFFFFu;
const float v = __uint_as_float(b << 16) * invd[c0 + e];
bf[e] = (_Float16)fminf(fmaxf(v, -65504.0f), 65504.0f);
}
#pragma unroll
for (int jt = 0; jt < 8; ++jt) {
const v8h_t af = *(const v8h_t*)&Tl[(jt * 16 + col) * kTStride + c0];
acc[jt] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(af, bf, acc[jt]);
}
__builtin_amdgcn_sched_barrier(0); // keep a k step's A fragments from being hoisted over the last
}
float amax = 0.0f;
#pragma unroll
for (int jt = 0; jt < 8; ++jt)
#pragma unroll
for (int e = 0; e < 8; ++e) amax = fmaxf(amax, fabsf(acc[jt][e]));
amax = fmaxf(amax, __shfl_xor(amax, 16));
const float sc = amax > 0.0f ? amax * (1.0f / q8_top<I8>()) : 1.0f;
const float inv = 1.0f / sc;
if (!live) continue;
if (h == 0) s[(size_t)m * s_ld + (size_t)part * nkb + g] = sc;
uint8_t* qr = q + (size_t)m * q_ld + (size_t)part * K + g * kGroup + 8 * h;
#pragma unroll
for (int jt = 0; jt < 8; ++jt) {
const uint32_t lo = q8_pack4<I8>(acc[jt][0], acc[jt][1], acc[jt][2], acc[jt][3], inv);
const uint32_t hi = q8_pack4<I8>(acc[jt][4], acc[jt][5], acc[jt][6], acc[jt][7], inv);
*(uint2*)(qr + jt * 16) = make_uint2(lo, hi);
}
}
}
} // namespace
// x [M][K] bf16, `x_ld` elements a row (0 = K)
// tdense [parts * K/128][128][128] f16, T[j][i] of each (part, group), laid out by r4d_layout.cpp
// rscale [parts][K] f32, the factor the stored row was multiplied by
// q [M][parts * K] int8 or E4M3, `q_ld` elements a row (0 = parts * K)
// s [M][parts * K/128] f32, `s_ld` elements a row (0 = parts * K/128)
enum { GD_X = 0, GD_T = 1, GD_RSCALE = 2, GD_Q = 3, GD_S = 4 };
extern "C" int r4d_rad_givens_dense_quant(const RadArgs* a, RadStream stream) {
const RadTensor* x = r4d_opt(a, GD_X);
const RadTensor* t = r4d_opt(a, GD_T);
const RadTensor* rs = r4d_opt(a, GD_RSCALE);
const RadTensor* q = r4d_opt(a, GD_Q);
const RadTensor* sc = r4d_opt(a, GD_S);
if (!x || !t || !rs || !q || !sc) return R4D_NO(RAD_E_INVAL);
if (x->rank < 2 || q->rank != 2 || sc->rank != 2 || t->rank != 2 || rs->rank != 2)
return R4D_NO(RAD_E_SHAPE);
if (t->dtype != RAD_F16 || rs->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
// `out` names the quantiser and q's dtype must be it: a mismatch is refused, not read from q
const char* out = r4d_gets(a, "out");
const bool i8 = q->dtype == RAD_I8;
if (!i8 && q->dtype != RAD_F8E4M3) return R4D_NO(RAD_E_DTYPE);
if (!out || std::strcmp(out, i8 ? "i8" : "fp8") != 0) return R4D_NO(RAD_E_DTYPE);
const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1);
const long long parts = r4d_geti_or(a, "parts", 1), nkb = K / kGroup;
if (r4d_geti_or(a, "group", kGroup) != kGroup || K % kGroup || parts < 1) return R4D_NO(RAD_E_SHAPE);
if (q->shape[0] != M || q->shape[1] != parts * K) return R4D_NO(RAD_E_SHAPE);
if (sc->shape[0] != M || sc->shape[1] != parts * nkb) return R4D_NO(RAD_E_SHAPE);
// tdense is a packed blob: its byte count is the layout hook's ([parts * K, 128] f16), not a shape to check
if (rs->shape[0] != parts || rs->shape[1] != K) return R4D_NO(RAD_E_SHAPE);
if (!r4d_aligned(t->data, 16) || !r4d_aligned(x->data, 16) || !r4d_aligned(q->data, 8))
return R4D_NO(RAD_E_ALIGN);
const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc);
if (xp < 0 || qp < 0 || sp < 0 || (xp * 2) % 16) return R4D_NO(RAD_E_STRIDE);
const long long mt = (M + 15) / 16;
const uint32_t gy = (uint32_t)std::max<long long>(1, (mt + 4 * kWaves - 1) / (4 * kWaves));
const dim3 grid((uint32_t)(parts * nkb), gy);
#define GD_EMIT(I8_) R4D_EMIT(stream, (givens_dense_kernel<I8_>), grid, dim3(kThreads), 0, \
(const uint16_t*)x->data, (const uint16_t*)t->data, (const float*)rs->data, (uint8_t*)q->data, \
(float*)sc->data, (uint32_t)M, (uint32_t)K, (uint32_t)nkb, (uint32_t)xp, (uint32_t)qp, (uint32_t)sp)
const int rc = i8 ? GD_EMIT(true) : GD_EMIT(false);
#undef GD_EMIT
return rc;
}
-170
View File
@@ -1,170 +0,0 @@
// ParoQuant's rotation to f16: the channel scale and Givens stages applied to a bf16 activation,
// for the 16-bit-activation GEMMs (w5a16 / w4a16_asym, rows up to 64, i.e. decode). The weight is
// stored as v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens"), so with
// x' = x . D^-1 . G_1 ... G_S, <v, x'> = <w, x>: the activation is rotated once a token and the
// GEMM reads the weight unchanged. The quantising form, for prefill-sized rows and MXFP4, is
// r4d_givens_dense.hip.
//
// A group at a time: ParoQuant's pairs never leave a group of 128 columns (the checkpoint is
// trained that way, and the converter and loader, r4d_rad_relayout_givens_pairs, refuse one that
// does), so a group's 128 values are rotated by S stages of 64 disjoint pairs. A wave owns a group,
// held in LDS (128 floats a wave). No block barrier is needed: a wave's LDS accesses are in order
// and a stage's pairs are disjoint, so no two lanes touch one address. Each lane takes two pairs
// per stage.
//
// Parts: a fused projection (gate|up, q|k|v) is rotated per piece, so a row yields `parts` rotated
// copies side by side: y is [M, parts * K]. A (part, group) is one wave's work (a row spans several
// blocks, grid.y). The tables stack the parts as the "givens" encoding does: `stages` rows each of
// pairs and angle, one row of channel scales.
//
// The channel scale is a true IEEE divide: t.scale is the factor D the stored row was multiplied
// by, and libref also divides in f32, so the two agree exactly on this step. Cos and sin are
// computed here in f32 from the stored angle (sincosf, an ulp or two, as libref's libm).
//
// Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip.
#include "r4d.h"
#include "r4d_emit.h"
#include "r4d_fp8_args.h"
#include <hip/hip_fp16.h>
namespace {
constexpr uint32_t kWave = 32;
constexpr uint32_t kThreads = 256;
constexpr uint32_t kWaves = kThreads / kWave;
constexpr uint32_t kGroup = 128;
constexpr uint32_t kPairsPerLane = kGroup / 2 / kWave; // 2
// kPre stages' tables are loaded and their sines and cosines taken before the first is applied, so
// each stage's dependent chain (table load, LDS read, rotate, LDS write) overlaps its neighbours'
// loads. At decode it is latency bound: a row is 40 groups of 128, each eight serial stages.
constexpr uint32_t kPre = 8;
__device__ __forceinline__ void wave_sync() {
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront");
__builtin_amdgcn_wave_barrier();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront");
}
// One wave rotates one (part, group) of one row: grid.x is the row and grid.y spreads the row's
// `parts * nkb` groups over blocks of kWaves waves, so a decode step of a few rows still fills the
// part. A wave with no group returns at once; there is no block barrier. The rotated row is
// written as f16 into `y`, y_ld elements a row.
__global__ __launch_bounds__(kThreads) void givens_rotate_kernel(
const uint16_t* __restrict__ x, const int32_t* __restrict__ pairs,
const float* __restrict__ angle, const float* __restrict__ rscale, uint16_t* __restrict__ y,
uint32_t K, uint32_t nkb, uint32_t parts, uint32_t stages, uint32_t x_ld, uint32_t y_ld) {
__shared__ float sbuf[kWaves][kGroup];
const uint32_t row = blockIdx.x;
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
const uint32_t item = blockIdx.y * kWaves + wave;
if (item >= parts * nkb) return;
const uint32_t part = item / nkb, g = item % nkb;
const uint32_t c0 = g * kGroup;
const size_t xrow = (size_t)row * x_ld;
float* buf = sbuf[wave];
// channel scale: v = x / D, four consecutive columns a lane
{
const float4 d = *(const float4*)(rscale + (size_t)part * K + c0 + lane * 4u);
const uint32_t xc = c0 + lane * 4u;
const float v0 = __uint_as_float((uint32_t)x[xrow + xc + 0] << 16) / d.x;
const float v1 = __uint_as_float((uint32_t)x[xrow + xc + 1] << 16) / d.y;
const float v2 = __uint_as_float((uint32_t)x[xrow + xc + 2] << 16) / d.z;
const float v3 = __uint_as_float((uint32_t)x[xrow + xc + 3] << 16) / d.w;
*(float4*)(buf + lane * 4u) = make_float4(v0, v1, v2, v3);
}
for (uint32_t st0 = 0; st0 < stages; st0 += kPre) {
const uint32_t nst = (stages - st0) < kPre ? (stages - st0) : kPre;
int2 ab[kPre][kPairsPerLane];
float th[kPre][kPairsPerLane], cs[kPre][kPairsPerLane], sn[kPre][kPairsPerLane];
#pragma unroll
for (uint32_t k = 0; k < kPre; ++k)
if (k < nst) {
const size_t trow = (size_t)part * stages + st0 + k;
const int32_t* pr = pairs + trow * K + c0;
const float* an = angle + trow * (K / 2u) + g * (kGroup / 2u);
#pragma unroll
for (uint32_t u = 0; u < kPairsPerLane; ++u) {
const uint32_t j = lane + u * kWave;
ab[k][u] = *(const int2*)(pr + 2u * j);
th[k][u] = an[j];
}
}
#pragma unroll
for (uint32_t k = 0; k < kPre; ++k)
if (k < nst)
#pragma unroll
for (uint32_t u = 0; u < kPairsPerLane; ++u) sincosf(th[k][u], &sn[k][u], &cs[k][u]);
wave_sync(); // the scaled row (or the previous chunk's last stage) is in LDS
#pragma unroll
for (uint32_t k = 0; k < kPre; ++k)
if (k < nst) {
#pragma unroll
for (uint32_t u = 0; u < kPairsPerLane; ++u) {
const int ia = ab[k][u].x - (int)c0, ib = ab[k][u].y - (int)c0;
const float va = buf[ia], vb = buf[ib];
buf[ia] = fmaf(cs[k][u], va, sn[k][u] * vb);
buf[ib] = fmaf(cs[k][u], vb, -sn[k][u] * va);
}
wave_sync();
}
}
const float4 r = *(const float4*)(buf + lane * 4u);
const float v[4] = { r.x, r.y, r.z, r.w };
// f16 holds +-65504; a rotated post-norm row is far below that, and the clamp keeps an outlier
// finite.
union { __half h[4]; uint2 u; } o;
#pragma unroll
for (int j = 0; j < 4; ++j) o.h[j] = __float2half(fminf(fmaxf(v[j], -65504.0f), 65504.0f));
*(uint2*)(y + (size_t)row * y_ld + (size_t)part * K + c0 + lane * 4u) = o.u;
}
} // namespace
// x [M][K] bf16, `x_ld` elements a row (0 = K)
// pairs [parts*stages][K] int32 column indices; (pairs[2j], pairs[2j+1]) is pair j
// angle [parts*stages][K/2] f32
// rscale [parts][K] f32, the factor the stored row was multiplied by
// y [M][parts*K] f16
enum { GV_X = 0, GV_PAIRS = 1, GV_ANGLE = 2, GV_RSCALE = 3, GV_Y = 4 };
extern "C" int r4d_rad_givens_rotate(const RadArgs* a, RadStream stream) {
const RadTensor* x = r4d_opt(a, GV_X);
const RadTensor* pr = r4d_opt(a, GV_PAIRS);
const RadTensor* an = r4d_opt(a, GV_ANGLE);
const RadTensor* rs = r4d_opt(a, GV_RSCALE);
const RadTensor* y = r4d_opt(a, GV_Y);
if (!x || !pr || !an || !rs || !y) return R4D_NO(RAD_E_INVAL);
if (x->rank < 2 || y->rank != 2 || pr->rank != 2 || an->rank != 2 || rs->rank != 2)
return R4D_NO(RAD_E_SHAPE);
if (y->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE);
if (pr->dtype != RAD_I32 || an->dtype != RAD_F32 || rs->dtype != RAD_F32)
return R4D_NO(RAD_E_DTYPE);
// rows are dim 0 and everything after it is the row
const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1);
const long long grp = (long long)kGroup, nkb = K / grp;
const long long parts = r4d_geti_or(a, "parts", 1), stages = r4d_geti_or(a, "stages", 0);
if (M <= 0 || r4d_geti_or(a, "group", grp) != grp || K % grp || parts < 1 || stages < 1)
return R4D_NO(RAD_E_SHAPE);
if (y->shape[0] != M || y->shape[1] != parts * K) return R4D_NO(RAD_E_SHAPE);
// the tables are the weight's, contiguous: parts * stages rows of K pairs and K/2 angles
if (pr->shape[0] != parts * stages || pr->shape[1] != K) return R4D_NO(RAD_E_SHAPE);
if (an->shape[0] != parts * stages || an->shape[1] != K / 2) return R4D_NO(RAD_E_SHAPE);
if (rs->shape[0] != parts || rs->shape[1] != K) return R4D_NO(RAD_E_SHAPE);
// A lane stores four f16 (8 bytes) at a time, so y's base and row pitch keep 8-byte alignment.
if (!r4d_aligned(rs->data, 16) || !r4d_aligned(pr->data, 8) || !r4d_aligned(y->data, 8))
return R4D_NO(RAD_E_ALIGN);
const long long xp = r4d_row_pitch(x), yp = r4d_row_pitch(y);
if (xp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE);
if (yp % 4) return R4D_NO(RAD_E_ALIGN);
const uint32_t gy = ((uint32_t)(parts * nkb) + kWaves - 1) / kWaves;
return R4D_EMIT(stream, givens_rotate_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0,
(const uint16_t*)x->data, (const int32_t*)pr->data, (const float*)an->data,
(const float*)rs->data, (uint16_t*)y->data, (uint32_t)K, (uint32_t)nkb,
(uint32_t)parts, (uint32_t)stages, (uint32_t)(xp ? xp : K),
(uint32_t)(yp ? yp : parts * K));
}
-3
View File
@@ -542,9 +542,6 @@ extern "C" int r4d_rad_swiglu_step(const RadArgs* a, RadStream stream) {
extern "C" int r4d_rad_router_sigmoid_group_topk(const RadArgs* a, RadStream stream) {
return router_group_body(a, stream);
}
extern "C" int r4d_rad_swiglu_clamped_quant_fp8(const RadArgs* a, RadStream stream) {
return clamped_quant_body(a, stream);
}
extern "C" int r4d_rad_gemm_nt_f32(const RadArgs* a, RadStream stream) {
return gemm_f32_body(a, stream);
}
+529 -1114
View File
File diff suppressed because it is too large. Load diff
+143
View File
@@ -0,0 +1,143 @@
/* r4d_hsimd.cpp -- CPU detection and dispatch for r4d_hsimd.h.
*
* Baseline-compiled (no -m flags): it decides which levels may run, so it must not itself contain
* an instruction above the baseline. The tables are the per-level objects of r4d_hsimd_kernels.cpp;
* off x86-64 only the scalar one exists. Detection as the core's util/simd.cpp.
*/
#include "r4d_hsimd.h"
#include <atomic>
#if defined(__x86_64__)
#define R4D_HSIMD_X86 1
#endif
extern "C" {
#define R4D_HSIMD_DECLS(sfx) \
void r4d_hsimd_moew4_permute##sfx(const uint8_t*, uint8_t*, int64_t, bool); \
void r4d_hsimd_iqr_trellis_tile##sfx(const uint8_t*, int64_t, int, int64_t, uint8_t*); \
void r4d_hsimd_w2a8_tile##sfx(const uint8_t*, int64_t, int64_t, uint8_t*); \
void r4d_hsimd_dword_transpose16##sfx(const uint32_t*, int64_t, int64_t, uint32_t*); \
void r4d_hsimd_byte_transpose##sfx(const uint8_t*, int64_t, int64_t, uint8_t*); \
void r4d_hsimd_fp8_frag_tile##sfx(const uint8_t*, int64_t, int64_t, uint8_t*)
R4D_HSIMD_DECLS(_sc);
#ifdef R4D_HSIMD_X86
R4D_HSIMD_DECLS(_s4);
R4D_HSIMD_DECLS(_v1);
R4D_HSIMD_DECLS(_v2);
R4D_HSIMD_DECLS(_v3);
#endif
#undef R4D_HSIMD_DECLS
}
namespace r4d_hsimd {
namespace {
struct Table {
void (*moew4_permute)(const uint8_t*, uint8_t*, int64_t, bool);
void (*iqr_trellis_tile)(const uint8_t*, int64_t, int, int64_t, uint8_t*);
void (*w2a8_tile)(const uint8_t*, int64_t, int64_t, uint8_t*);
void (*dword_transpose16)(const uint32_t*, int64_t, int64_t, uint32_t*);
void (*byte_transpose)(const uint8_t*, int64_t, int64_t, uint8_t*);
void (*fp8_frag_tile)(const uint8_t*, int64_t, int64_t, uint8_t*);
};
#define R4D_HSIMD_TABLE(sfx) \
{ r4d_hsimd_moew4_permute##sfx, r4d_hsimd_iqr_trellis_tile##sfx, r4d_hsimd_w2a8_tile##sfx, \
r4d_hsimd_dword_transpose16##sfx, r4d_hsimd_byte_transpose##sfx, r4d_hsimd_fp8_frag_tile##sfx }
const Table kTables[kLevels] = {
R4D_HSIMD_TABLE(_sc),
#ifdef R4D_HSIMD_X86
R4D_HSIMD_TABLE(_s4), R4D_HSIMD_TABLE(_v1), R4D_HSIMD_TABLE(_v2), R4D_HSIMD_TABLE(_v3),
#else
R4D_HSIMD_TABLE(_sc), R4D_HSIMD_TABLE(_sc), R4D_HSIMD_TABLE(_sc), R4D_HSIMD_TABLE(_sc),
#endif
};
#undef R4D_HSIMD_TABLE
/* The live level, read on every call (a relaxed load) so force_level takes effect between calls. */
std::atomic<int> g_level{ -1 };
const Table& live() {
int l = g_level.load(std::memory_order_relaxed);
if (l < 0) {
l = detect_level();
g_level.store(l, std::memory_order_relaxed);
}
return kTables[l];
}
} // namespace
int detect_level() {
static const int lvl = [] {
#ifdef R4D_HSIMD_X86
__builtin_cpu_init();
/* AVX-512 as the conjunction F && BW && DQ && VL: Knights Landing has F without the
* others. */
if (__builtin_cpu_supports("avx512f") && __builtin_cpu_supports("avx512bw") &&
__builtin_cpu_supports("avx512dq") && __builtin_cpu_supports("avx512vl") &&
__builtin_cpu_supports("avx2"))
return (int)kAvx512;
if (__builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") &&
__builtin_cpu_supports("f16c"))
return (int)kAvx2;
if (__builtin_cpu_supports("avx")) return (int)kAvx;
if (__builtin_cpu_supports("sse4.2") && __builtin_cpu_supports("sse4.1") &&
__builtin_cpu_supports("popcnt"))
return (int)kSse4;
#endif
return (int)kScalar;
}();
return lvl;
}
int level() {
const int l = g_level.load(std::memory_order_relaxed);
return l < 0 ? detect_level() : l;
}
const char* level_name(int lvl) {
switch (lvl) {
case kScalar: return "scalar";
case kSse4: return "sse4";
case kAvx: return "avx";
case kAvx2: return "avx2";
case kAvx512: return "avx512";
default: return "?";
}
}
int force_level(int lvl) {
const int top = detect_level();
if (lvl > top) lvl = top;
if (lvl < 0) lvl = 0;
g_level.store(lvl, std::memory_order_relaxed);
return lvl;
}
void moew4_permute(const uint8_t* s, uint8_t* d, int64_t bytes, bool forward) {
live().moew4_permute(s, d, bytes, forward);
}
void iqr_trellis_tile(const uint8_t* rows, int64_t rb, int B, int64_t nkb, uint8_t* out) {
live().iqr_trellis_tile(rows, rb, B, nkb, out);
}
void w2a8_tile(const uint8_t* rows, int64_t rb, int64_t kpb, uint8_t* out) {
live().w2a8_tile(rows, rb, kpb, out);
}
void dword_transpose16(const uint32_t* in, int64_t stride, int64_t cols, uint32_t* out) {
live().dword_transpose16(in, stride, cols, out);
}
void byte_transpose(const uint8_t* in, int64_t rows, int64_t cols, uint8_t* out) {
live().byte_transpose(in, rows, cols, out);
}
void fp8_frag_tile(const uint8_t* rows, int64_t K, int64_t ksuper, uint8_t* out) {
live().fp8_frag_tile(rows, K, ksuper, out);
}
} // namespace r4d_hsimd
+66
View File
@@ -0,0 +1,66 @@
/* r4d_hsimd.h -- libr4d's host-side hot loops (the load-time relayouts), dispatched by CPU feature
* as the core's util/simd.h is: the plugin runs on machines it was not built on, so no
* -march=native. r4d_hsimd_kernels.cpp is compiled once per level into separate objects with their
* own -m flags (cmake/RadSimdLevels.cmake); r4d_hsimd.cpp (baseline, no -m flags) picks one at
* first use through __builtin_cpu_supports, which also checks the OS has enabled the register
* state.
*
* Every function here moves bits and has one exact result: all levels agree bit for bit on every
* input, which tests/relayout_iqr_test.cpp and tests/relayout_parity_test.cpp check by forcing
* each level (force_level) against the scalar level and a reference written in the test.
*
* Levels, as util/simd.h: 0 scalar, 1 SSE4.1/4.2, 2 AVX (integer work in 128-bit halves), 3 AVX2,
* 4 AVX-512 F/BW/DQ/VL. On a non-x86 build only the scalar level exists.
*/
#pragma once
#include <cstdint>
namespace r4d_hsimd {
enum Level { kScalar = 0, kSse4 = 1, kAvx = 2, kAvx2 = 3, kAvx512 = 4, kLevels = 5 };
/* The highest level this CPU and OS can execute, computed once. */
int detect_level();
/* The level in use (detect_level() unless forced). */
int level();
const char* level_name(int lvl);
/* Forces a level, clamped to detect_level(); for tests only. Returns the level now in use. */
int force_level(int lvl);
/* MoE w4 codes between canonical and kernel nibble order, `bytes` (a multiple of four) from `s` to
* `d`: in every dword, canonical nibble i (element i, two a byte, the first low) goes to nibble
* 2i (i < 4) or 2(i - 4) + 1, a perfect shuffle of the dword's halves (r4d_layout.cpp); `forward`
* false undoes it. */
void moew4_permute(const uint8_t* s, uint8_t* d, int64_t bytes, bool forward);
/* One 16-row tile of an IQR trellis weight into its `nkb` stored units (r4d_iqr.h, "the codes:
* lane segments"): `rows` is the tile's first row of B-bit codes (2 <= B <= 7, LSB first), rows
* `rb` bytes apart; unit kb, at `out` + kb * 256 * B, holds for each lane l and column
* e = 0..3 the 16 codes of column 128 kb + 4 l + e bottom-up (row 15 first). Reads only the
* tile's own bytes. */
void iqr_trellis_tile(const uint8_t* rows, int64_t rb, int B, int64_t nkb, uint8_t* out);
/* One 16-row tile of a w2a8 weight's u2 codes into its `kpb` stored units (r4d_layout.cpp,
* w2_slot): `rows` is the tile's first row of codes (four a byte, the first in the low bits), rows
* `rb` bytes apart; unit kb, at `out` + 512 kb, holds for half lh and row r, at
* 16 (16 lh + r), four dwords d, whose field 4j + b + 2h is the code of column
* 128 kb + 16 (2d + h) + 8b + 4 lh + j. Reads only the tile's own bytes. */
void w2a8_tile(const uint8_t* rows, int64_t rb, int64_t kpb, uint8_t* out);
/* A 16-row tile of dwords transposed: out[16 c + r] = in[r * stride + c] for r < 16, c < cols
* (dword units; `in` rows `stride` dwords apart). MXFP4's stored codes are this (r4d_layout.cpp,
* mx_slot): each 16-code group's two 4-byte halves go to the n-tile's slots whole. */
void dword_transpose16(const uint32_t* in, int64_t stride, int64_t cols, uint32_t* out);
/* A rows x cols byte matrix transposed: out[c * rows + r] = in[r * cols + c]. MXFP4's exponents go
* from canonical [N][K/32] to the stored [K/32][N] so. */
void byte_transpose(const uint8_t* in, int64_t rows, int64_t cols, uint8_t* out);
/* One 16-row tile of a block-FP8 or int8 weight into fragment order (r4d_fp8_frag.h): `rows` is
* the tile's first row of byte codes, rows K bytes apart; the `ksuper` 1024-byte units at `out`
* hold, for each 64-byte K step, lane l's 32 bytes at 32 l: row l % 16's qwords 2t + l / 16 for
* t = 0..3. Reads only the tile's own bytes. */
void fp8_frag_tile(const uint8_t* rows, int64_t K, int64_t ksuper, uint8_t* out);
} // namespace r4d_hsimd
+770
View File
@@ -0,0 +1,770 @@
/* r4d_hsimd_kernels.cpp -- the per-level bodies behind r4d_hsimd.h. Compiled once per level with
* R4D_HSIMD_LEVEL=0..4 and matching -m flags (cmake/RadSimdLevels.cmake); names carry the level's
* suffix and r4d_hsimd.cpp holds the table. Every body moves bits and is exact: each level gives
* the scalar level's bytes on every input.
*
* The trellis tile is three passes over a 16-row x 128-K unit, all in L1: each row's 128 B-bit
* codes are unpacked to bytes, the 16 x 128 byte matrix is transposed with its rows reversed (the
* stored order is column-major, row 15 first), and the 2048 bytes are packed back to B bits, which
* is the unit: lane l's segment is columns 4l .. 4l + 3, 16 codes each, so the transposed matrix's
* rows in order are the segments in order.
*
* The w2a8 tile moves 2-bit codes within a row: each stored dword is four bytes of the row's unit
* gathered and transposed as a 4 x 4 matrix of 2-bit fields, a shuffle and two delta swaps.
*/
#include "r4d_hsimd.h"
#include <cstring>
#if R4D_HSIMD_LEVEL >= 1
#include <immintrin.h>
#endif
#if R4D_HSIMD_LEVEL == 0
#define R4D_HSIMD_SUFFIX _sc
#elif R4D_HSIMD_LEVEL == 1
#define R4D_HSIMD_SUFFIX _s4
#elif R4D_HSIMD_LEVEL == 2
#define R4D_HSIMD_SUFFIX _v1
#elif R4D_HSIMD_LEVEL == 3
#define R4D_HSIMD_SUFFIX _v2
#elif R4D_HSIMD_LEVEL == 4
#define R4D_HSIMD_SUFFIX _v3
#else
#error "R4D_HSIMD_LEVEL out of range"
#endif
#define R4D_HSIMD_CAT2(a, b) a##b
#define R4D_HSIMD_CAT(a, b) R4D_HSIMD_CAT2(a, b)
#define R4D_HSIMD_FN(name) R4D_HSIMD_CAT(r4d_hsimd_##name, R4D_HSIMD_SUFFIX)
namespace {
/* `n` bytes from L1 scratch to a destination the host never reads back (a pinned staging ring or a
* pool slot the card reads), with streaming stores where both are aligned: an ordinary store first
* reads each destination line in, which during a restore is DRAM traffic beside the drive's DMA.
* The caller fences once (stream_fence) before the bytes are handed on. */
inline bool stream_copy(uint8_t* d, const uint8_t* s, int64_t n) {
#if R4D_HSIMD_LEVEL == 4
if ((((uintptr_t)d | (uintptr_t)s | (uintptr_t)n) & 63) == 0) {
for (int64_t i = 0; i < n; i += 64)
_mm512_stream_si512((__m512i*)(d + i), _mm512_load_si512((const __m512i*)(s + i)));
return true;
}
#elif R4D_HSIMD_LEVEL == 3
if ((((uintptr_t)d | (uintptr_t)s | (uintptr_t)n) & 31) == 0) {
for (int64_t i = 0; i < n; i += 32)
_mm256_stream_si256((__m256i*)(d + i), _mm256_load_si256((const __m256i*)(s + i)));
return true;
}
#elif R4D_HSIMD_LEVEL >= 1
if ((((uintptr_t)d | (uintptr_t)s | (uintptr_t)n) & 15) == 0) {
for (int64_t i = 0; i < n; i += 16)
_mm_stream_si128((__m128i*)(d + i), _mm_load_si128((const __m128i*)(s + i)));
return true;
}
#endif
std::memcpy(d, s, (size_t)n);
return false;
}
/* Orders the streaming stores before whatever publishes the bytes. */
inline void stream_fence(bool streamed) {
#if R4D_HSIMD_LEVEL >= 1
if (streamed) _mm_sfence();
#else
(void)streamed;
#endif
}
/* ---- the MoE w4 nibble shuffle ------------------------------------------------------------- */
/* Scalar, two dwords at a time: forward swaps each dword's middle bytes, then each half's middle
* nibbles; back does the steps in reverse. */
inline uint64_t mw_bytes(uint64_t x) {
return (x & 0xFF0000FFFF0000FFull) | ((x & 0x0000FF000000FF00ull) << 8) |
((x >> 8) & 0x0000FF000000FF00ull);
}
inline uint64_t mw_nibbles(uint64_t x) {
return (x & 0xF00FF00FF00FF00Full) | ((x & 0x00F000F000F000F0ull) << 4) |
((x >> 4) & 0x00F000F000F000F0ull);
}
void mw_scalar(const uint8_t* s, uint8_t* d, int64_t bytes, bool fwd) {
int64_t i = 0;
for (; i + 8 <= bytes; i += 8) {
uint64_t x;
std::memcpy(&x, s + i, 8);
x = fwd ? mw_nibbles(mw_bytes(x)) : mw_bytes(mw_nibbles(x));
std::memcpy(d + i, &x, 8);
}
if (i < bytes) { /* one dword left; no step crosses dwords */
uint32_t w;
std::memcpy(&w, s + i, 4);
uint64_t x = w;
x = fwd ? mw_nibbles(mw_bytes(x)) : mw_bytes(mw_nibbles(x));
w = (uint32_t)x;
std::memcpy(d + i, &w, 4);
}
}
/* Vector form: output byte b of a dword is a low nibble of input byte A[b] and a high nibble of
* input byte B[b], each from the input byte's low or high half. Forward, byte b takes element b
* low and b + 4 high: A = (0, 0, 1, 1), B = (2, 2, 3, 3), odd bytes from the high halves. Back,
* A = (0, 2, 0, 2), B = (1, 3, 1, 3), bytes 2 and 3 from the high halves. */
#if R4D_HSIMD_LEVEL >= 1
inline int8_t mw_idx(int k, bool fwd) { /* A's byte for output byte k of a 16-byte lane */
const int dw = k & ~3, b = k & 3;
return (int8_t)(dw + (fwd ? (b >> 1) : (b & 1) * 2));
}
/* Whether a permute streams its output (stream_copy says why): a whole weight into its pinned or
* pool destination does, aligned to the vector. A row into scratch the caller reads straight back
* (moew4_frag_permute, moew5_row: a few KiB) keeps ordinary stores, which leave it in cache. */
inline bool mw_stream(const uint8_t* d, int64_t bytes, int vec) {
return bytes >= ((int64_t)64 << 10) && ((uintptr_t)d & (uintptr_t)(vec - 1)) == 0;
}
#endif
#if R4D_HSIMD_LEVEL == 1 || R4D_HSIMD_LEVEL == 2
void mw_vec(const uint8_t* s, uint8_t* d, int64_t bytes, bool fwd) {
alignas(16) int8_t t[16];
for (int k = 0; k < 16; ++k) t[k] = mw_idx(k, fwd);
const __m128i ia = _mm_load_si128((const __m128i*)t);
const __m128i ib = _mm_add_epi8(ia, _mm_set1_epi8(fwd ? 2 : 1));
const __m128i m = fwd ? _mm_set1_epi16((short)0xFF00) : _mm_set1_epi32((int)0xFFFF0000);
const __m128i lo = _mm_set1_epi8(0x0F), hi = _mm_set1_epi8((char)0xF0);
const bool nt = mw_stream(d, bytes, 16);
int64_t i = 0;
for (; i + 16 <= bytes; i += 16) {
const __m128i x = _mm_loadu_si128((const __m128i*)(s + i));
const __m128i a = _mm_shuffle_epi8(x, ia), b = _mm_shuffle_epi8(x, ib);
const __m128i a2 = _mm_blendv_epi8(a, _mm_srli_epi16(a, 4), m);
const __m128i b2 = _mm_blendv_epi8(_mm_slli_epi16(b, 4), b, m);
const __m128i v = _mm_or_si128(_mm_and_si128(a2, lo), _mm_and_si128(b2, hi));
if (nt) _mm_stream_si128((__m128i*)(d + i), v);
else _mm_storeu_si128((__m128i*)(d + i), v);
}
stream_fence(nt);
mw_scalar(s + i, d + i, bytes - i, fwd);
}
#elif R4D_HSIMD_LEVEL == 3
void mw_vec(const uint8_t* s, uint8_t* d, int64_t bytes, bool fwd) {
alignas(32) int8_t t[32];
for (int k = 0; k < 32; ++k) t[k] = mw_idx(k & 15, fwd);
const __m256i ia = _mm256_load_si256((const __m256i*)t);
const __m256i ib = _mm256_add_epi8(ia, _mm256_set1_epi8(fwd ? 2 : 1));
const __m256i m = fwd ? _mm256_set1_epi16((short)0xFF00) : _mm256_set1_epi32((int)0xFFFF0000);
const __m256i lo = _mm256_set1_epi8(0x0F), hi = _mm256_set1_epi8((char)0xF0);
const bool nt = mw_stream(d, bytes, 32);
int64_t i = 0;
for (; i + 32 <= bytes; i += 32) {
const __m256i x = _mm256_loadu_si256((const __m256i*)(s + i));
const __m256i a = _mm256_shuffle_epi8(x, ia), b = _mm256_shuffle_epi8(x, ib);
const __m256i a2 = _mm256_blendv_epi8(a, _mm256_srli_epi16(a, 4), m);
const __m256i b2 = _mm256_blendv_epi8(_mm256_slli_epi16(b, 4), b, m);
const __m256i v = _mm256_or_si256(_mm256_and_si256(a2, lo), _mm256_and_si256(b2, hi));
if (nt) _mm256_stream_si256((__m256i*)(d + i), v);
else _mm256_storeu_si256((__m256i*)(d + i), v);
}
stream_fence(nt);
mw_scalar(s + i, d + i, bytes - i, fwd);
}
#elif R4D_HSIMD_LEVEL == 4
void mw_vec(const uint8_t* s, uint8_t* d, int64_t bytes, bool fwd) {
alignas(64) int8_t t[64];
for (int k = 0; k < 64; ++k) t[k] = mw_idx(k & 15, fwd);
const __m512i ia = _mm512_load_si512(t);
const __m512i ib = _mm512_add_epi8(ia, _mm512_set1_epi8(fwd ? 2 : 1));
const __mmask64 m = fwd ? 0xAAAAAAAAAAAAAAAAull : 0xCCCCCCCCCCCCCCCCull;
const __m512i lo = _mm512_set1_epi8(0x0F);
const bool nt = mw_stream(d, bytes, 64);
int64_t i = 0;
for (; i + 64 <= bytes; i += 64) {
const __m512i x = _mm512_loadu_si512(s + i);
const __m512i a = _mm512_shuffle_epi8(x, ia), b = _mm512_shuffle_epi8(x, ib);
const __m512i a2 = _mm512_mask_mov_epi8(a, m, _mm512_srli_epi16(a, 4));
const __m512i b2 = _mm512_mask_mov_epi8(_mm512_slli_epi16(b, 4), m, b);
/* lo ? a2 : b2, bit by bit */
const __m512i v = _mm512_ternarylogic_epi64(lo, a2, b2, 0xCA);
if (nt) _mm512_stream_si512((__m512i*)(d + i), v);
else _mm512_storeu_si512(d + i, v);
}
stream_fence(nt);
mw_scalar(s + i, d + i, bytes - i, fwd);
}
#endif
/* ---- the trellis tile ------------------------------------------------------------------------ */
/* A row's codes for one unit: 128 codes, 16 B bytes. */
constexpr int kCodes = 128;
#if R4D_HSIMD_LEVEL == 0
/* 128 codes of B bits from `s` to one byte each. */
void unpack_row(const uint8_t* s, int B, uint8_t* u) {
const uint64_t m = (1u << B) - 1u;
for (int g = 0; g < kCodes / 8; ++g) {
uint64_t x = 0;
std::memcpy(&x, s + g * B, (size_t)B);
for (int i = 0; i < 8; ++i) u[g * 8 + i] = (uint8_t)((x >> (i * B)) & m);
}
}
/* T[k][q] = U[15 - q][k]. */
void transpose_rev(const uint8_t (*U)[kCodes], uint8_t* T) {
for (int k = 0; k < kCodes; ++k)
for (int q = 0; q < 16; ++q) T[k * 16 + q] = U[15 - q][k];
}
/* `n` bytes of B-bit values to the stream, eight values (B bytes) at a time. */
void pack(const uint8_t* t, int n, int B, uint8_t* out) {
for (int g = 0; g < n / 8; ++g) {
uint64_t x = 0;
for (int i = 0; i < 8; ++i) x |= (uint64_t)t[g * 8 + i] << (i * B);
std::memcpy(out + g * B, &x, (size_t)B);
}
}
#else
/* 128-bit lanes, shared by every vector level: one lane unpacks 16 codes (2B bytes) or packs 16
* bytes. Unpacking spreads the lane's two B-byte halves to its 64-bit halves, then halves each
* width in turn (64 -> 32 -> 16 -> 8 bits a field); packing runs the same steps backwards. The
* shift counts follow B, so they go in a register. */
struct Lanes {
__m128i up_idx, pk_idx, c4, c2, c1, c32, c16, c8;
__m128i m4, m2, m1, k32, k16, k8;
explicit Lanes(int B) {
alignas(16) int8_t u[16], p[16];
for (int i = 0; i < 16; ++i) {
u[i] = (int8_t)(i < 8 ? (i < B ? i : -128) : (i - 8 < B ? B + (i - 8) : -128));
p[i] = (int8_t)(i < B ? i : i < 2 * B ? 8 + (i - B) : -128);
}
up_idx = _mm_load_si128((const __m128i*)u);
pk_idx = _mm_load_si128((const __m128i*)p);
c4 = _mm_cvtsi32_si128(4 * B);
c2 = _mm_cvtsi32_si128(2 * B);
c1 = _mm_cvtsi32_si128(B);
c32 = _mm_cvtsi32_si128(32);
c16 = _mm_cvtsi32_si128(16);
c8 = _mm_cvtsi32_si128(8);
m4 = _mm_set1_epi64x((long long)((1ull << (4 * B)) - 1ull));
m2 = _mm_set1_epi32((int)((1u << (2 * B)) - 1u));
m1 = _mm_set1_epi16((short)((1u << B) - 1u));
k32 = _mm_set1_epi64x(0xFFFFFFFFll);
k16 = _mm_set1_epi32(0xFFFF);
k8 = _mm_set1_epi16(0xFF);
}
};
#endif
#if R4D_HSIMD_LEVEL == 1 || R4D_HSIMD_LEVEL == 2
inline __m128i unpack16(const Lanes& L, __m128i x) {
x = _mm_shuffle_epi8(x, L.up_idx);
x = _mm_or_si128(_mm_and_si128(x, L.m4), _mm_sll_epi64(_mm_srl_epi64(x, L.c4), L.c32));
x = _mm_or_si128(_mm_and_si128(x, L.m2), _mm_sll_epi32(_mm_srl_epi32(x, L.c2), L.c16));
return _mm_or_si128(_mm_and_si128(x, L.m1), _mm_sll_epi16(_mm_srl_epi16(x, L.c1), L.c8));
}
inline __m128i pack16(const Lanes& L, __m128i x) {
x = _mm_or_si128(_mm_and_si128(x, L.k8), _mm_sll_epi16(_mm_srl_epi16(x, L.c8), L.c1));
x = _mm_or_si128(_mm_and_si128(x, L.k16), _mm_sll_epi32(_mm_srl_epi32(x, L.c16), L.c2));
x = _mm_or_si128(_mm_and_si128(x, L.k32), _mm_sll_epi64(_mm_srl_epi64(x, L.c32), L.c4));
return _mm_shuffle_epi8(x, L.pk_idx);
}
/* `s` may be read 16 bytes past each group: the caller pads where the plane ends. */
void unpack_row(const Lanes& L, const uint8_t* s, int B, uint8_t* u) {
for (int g = 0; g < kCodes / 16; ++g)
_mm_storeu_si128((__m128i*)(u + g * 16),
unpack16(L, _mm_loadu_si128((const __m128i*)(s + g * 2 * B))));
}
/* Four rounds of interleaving rows i and i + 8 transpose a 16 x 16 byte block: each round rotates
* an element's 8-bit (row, column) address left by one bit. */
void transpose_rev(const uint8_t (*U)[kCodes], uint8_t* T) {
for (int c = 0; c < kCodes / 16; ++c) {
__m128i x[16], y[16];
for (int q = 0; q < 16; ++q) x[q] = _mm_loadu_si128((const __m128i*)(U[15 - q] + 16 * c));
for (int round = 0; round < 4; ++round) {
for (int i = 0; i < 8; ++i) {
y[2 * i] = _mm_unpacklo_epi8(x[i], x[i + 8]);
y[2 * i + 1] = _mm_unpackhi_epi8(x[i], x[i + 8]);
}
for (int i = 0; i < 16; ++i) x[i] = y[i];
}
for (int j = 0; j < 16; ++j) _mm_storeu_si128((__m128i*)(T + (16 * c + j) * 16), x[j]);
}
}
/* Writes up to 16 bytes past the 2B n / 16 the stream holds: `out` has room. */
void pack(const Lanes& L, const uint8_t* t, int n, int B, uint8_t* out) {
for (int g = 0; g < n / 16; ++g)
_mm_storeu_si128((__m128i*)(out + g * 2 * B), pack16(L, _mm_loadu_si128((const __m128i*)(t + g * 16))));
}
#elif R4D_HSIMD_LEVEL == 3
inline __m256i bc(__m128i x) { return _mm256_broadcastsi128_si256(x); }
inline __m256i unpack32(const Lanes& L, __m256i x) {
x = _mm256_shuffle_epi8(x, bc(L.up_idx));
x = _mm256_or_si256(_mm256_and_si256(x, bc(L.m4)), _mm256_sll_epi64(_mm256_srl_epi64(x, L.c4), L.c32));
x = _mm256_or_si256(_mm256_and_si256(x, bc(L.m2)), _mm256_sll_epi32(_mm256_srl_epi32(x, L.c2), L.c16));
return _mm256_or_si256(_mm256_and_si256(x, bc(L.m1)), _mm256_sll_epi16(_mm256_srl_epi16(x, L.c1), L.c8));
}
inline __m256i pack32(const Lanes& L, __m256i x) {
x = _mm256_or_si256(_mm256_and_si256(x, bc(L.k8)), _mm256_sll_epi16(_mm256_srl_epi16(x, L.c8), L.c1));
x = _mm256_or_si256(_mm256_and_si256(x, bc(L.k16)), _mm256_sll_epi32(_mm256_srl_epi32(x, L.c16), L.c2));
x = _mm256_or_si256(_mm256_and_si256(x, bc(L.k32)), _mm256_sll_epi64(_mm256_srl_epi64(x, L.c32), L.c4));
return _mm256_shuffle_epi8(x, bc(L.pk_idx));
}
void unpack_row(const Lanes& L, const uint8_t* s, int B, uint8_t* u) {
for (int g = 0; g < kCodes / 16; g += 2) {
const __m256i x = _mm256_inserti128_si256(
_mm256_castsi128_si256(_mm_loadu_si128((const __m128i*)(s + g * 2 * B))),
_mm_loadu_si128((const __m128i*)(s + (g + 1) * 2 * B)), 1);
_mm256_storeu_si256((__m256i*)(u + g * 16), unpack32(L, x));
}
}
/* Two 16 x 16 blocks at once, one a 128-bit lane. */
void transpose_rev(const uint8_t (*U)[kCodes], uint8_t* T) {
for (int c = 0; c < kCodes / 16; c += 2) {
__m256i x[16], y[16];
for (int q = 0; q < 16; ++q) x[q] = _mm256_loadu_si256((const __m256i*)(U[15 - q] + 16 * c));
for (int round = 0; round < 4; ++round) {
for (int i = 0; i < 8; ++i) {
y[2 * i] = _mm256_unpacklo_epi8(x[i], x[i + 8]);
y[2 * i + 1] = _mm256_unpackhi_epi8(x[i], x[i + 8]);
}
for (int i = 0; i < 16; ++i) x[i] = y[i];
}
for (int j = 0; j < 16; ++j) {
_mm_storeu_si128((__m128i*)(T + (16 * c + j) * 16), _mm256_castsi256_si128(x[j]));
_mm_storeu_si128((__m128i*)(T + (16 * (c + 1) + j) * 16), _mm256_extracti128_si256(x[j], 1));
}
}
}
void pack(const Lanes& L, const uint8_t* t, int n, int B, uint8_t* out) {
for (int g = 0; g < n / 16; g += 2) {
const __m256i x = pack32(L, _mm256_loadu_si256((const __m256i*)(t + g * 16)));
_mm_storeu_si128((__m128i*)(out + g * 2 * B), _mm256_castsi256_si128(x));
_mm_storeu_si128((__m128i*)(out + (g + 1) * 2 * B), _mm256_extracti128_si256(x, 1));
}
}
#elif R4D_HSIMD_LEVEL == 4
inline __m512i bc(__m128i x) { return _mm512_broadcast_i32x4(x); }
inline __m512i unpack64(const Lanes& L, __m512i x) {
x = _mm512_shuffle_epi8(x, bc(L.up_idx));
x = _mm512_or_si512(_mm512_and_si512(x, bc(L.m4)), _mm512_sll_epi64(_mm512_srl_epi64(x, L.c4), L.c32));
x = _mm512_or_si512(_mm512_and_si512(x, bc(L.m2)), _mm512_sll_epi32(_mm512_srl_epi32(x, L.c2), L.c16));
return _mm512_or_si512(_mm512_and_si512(x, bc(L.m1)), _mm512_sll_epi16(_mm512_srl_epi16(x, L.c1), L.c8));
}
inline __m512i pack64(const Lanes& L, __m512i x) {
x = _mm512_or_si512(_mm512_and_si512(x, bc(L.k8)), _mm512_sll_epi16(_mm512_srl_epi16(x, L.c8), L.c1));
x = _mm512_or_si512(_mm512_and_si512(x, bc(L.k16)), _mm512_sll_epi32(_mm512_srl_epi32(x, L.c16), L.c2));
x = _mm512_or_si512(_mm512_and_si512(x, bc(L.k32)), _mm512_sll_epi64(_mm512_srl_epi64(x, L.c32), L.c4));
return _mm512_shuffle_epi8(x, bc(L.pk_idx));
}
void unpack_row(const Lanes& L, const uint8_t* s, int B, uint8_t* u) {
for (int g = 0; g < kCodes / 16; g += 4) {
__m512i x = _mm512_castsi128_si512(_mm_loadu_si128((const __m128i*)(s + g * 2 * B)));
x = _mm512_inserti32x4(x, _mm_loadu_si128((const __m128i*)(s + (g + 1) * 2 * B)), 1);
x = _mm512_inserti32x4(x, _mm_loadu_si128((const __m128i*)(s + (g + 2) * 2 * B)), 2);
x = _mm512_inserti32x4(x, _mm_loadu_si128((const __m128i*)(s + (g + 3) * 2 * B)), 3);
_mm512_storeu_si512(u + g * 16, unpack64(L, x));
}
}
/* Four 16 x 16 blocks at once, one a 128-bit lane. */
void transpose_rev(const uint8_t (*U)[kCodes], uint8_t* T) {
for (int c = 0; c < kCodes / 16; c += 4) {
__m512i x[16], y[16];
for (int q = 0; q < 16; ++q) x[q] = _mm512_loadu_si512(U[15 - q] + 16 * c);
for (int round = 0; round < 4; ++round) {
for (int i = 0; i < 8; ++i) {
y[2 * i] = _mm512_unpacklo_epi8(x[i], x[i + 8]);
y[2 * i + 1] = _mm512_unpackhi_epi8(x[i], x[i + 8]);
}
for (int i = 0; i < 16; ++i) x[i] = y[i];
}
for (int j = 0; j < 16; ++j) {
_mm_storeu_si128((__m128i*)(T + (16 * c + j) * 16), _mm512_extracti32x4_epi32(x[j], 0));
_mm_storeu_si128((__m128i*)(T + (16 * (c + 1) + j) * 16), _mm512_extracti32x4_epi32(x[j], 1));
_mm_storeu_si128((__m128i*)(T + (16 * (c + 2) + j) * 16), _mm512_extracti32x4_epi32(x[j], 2));
_mm_storeu_si128((__m128i*)(T + (16 * (c + 3) + j) * 16), _mm512_extracti32x4_epi32(x[j], 3));
}
}
}
void pack(const Lanes& L, const uint8_t* t, int n, int B, uint8_t* out) {
for (int g = 0; g < n / 16; g += 4) {
const __m512i x = pack64(L, _mm512_loadu_si512(t + g * 16));
_mm_storeu_si128((__m128i*)(out + g * 2 * B), _mm512_extracti32x4_epi32(x, 0));
_mm_storeu_si128((__m128i*)(out + (g + 1) * 2 * B), _mm512_extracti32x4_epi32(x, 1));
_mm_storeu_si128((__m128i*)(out + (g + 2) * 2 * B), _mm512_extracti32x4_epi32(x, 2));
_mm_storeu_si128((__m128i*)(out + (g + 3) * 2 * B), _mm512_extracti32x4_epi32(x, 3));
}
}
#endif
/* ---- the w2a8 tile --------------------------------------------------------------------------- */
/* Dword d of half lh gathers four bytes of the unit's 32: bytes 8d + lh + {0, 2, 4, 6}, which
* are codes 4 lh .. 4 lh + 3 of columns 16 (2d + h) + 8b for (b, h) = (0, 0), (1, 0), (0, 1),
* (1, 1), a 4 x 4 matrix of 2-bit fields with group s = b + 2h in byte s. The stored dword has
* code j of group s in field 4j + s, its transpose: two delta swaps, the 2 x 2 blocks' corners
* then the blocks. */
inline uint32_t w2_transpose(uint32_t x) {
uint32_t t = (x ^ (x >> 6)) & 0x00CC00CCu;
x ^= t ^ (t << 6);
t = (x ^ (x >> 12)) & 0x0000F0F0u;
return x ^ t ^ (t << 12);
}
#if R4D_HSIMD_LEVEL == 0
void w2_row(const uint8_t* s, int64_t kpb, uint8_t* o) {
for (int64_t kb = 0; kb < kpb; ++kb, s += 32, o += 512)
for (int lh = 0; lh < 2; ++lh)
for (int d = 0; d < 4; ++d) {
const uint8_t* b = s + 8 * d + lh;
const uint32_t x = (uint32_t)b[0] | (uint32_t)b[2] << 8 | (uint32_t)b[4] << 16 |
(uint32_t)b[6] << 24;
const uint32_t w = w2_transpose(x);
std::memcpy(o + 256 * lh + 4 * d, &w, 4);
}
}
#else
/* A 16-byte lane of a unit holds the bytes of dwords d = 2m, 2m + 1: the shuffle gathers half 0's
* two dwords, then half 1's, and the transpose runs on all four. */
inline __m128i w2_idx() { return _mm_setr_epi8(0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15); }
#endif
#if R4D_HSIMD_LEVEL == 1 || R4D_HSIMD_LEVEL == 2
inline __m128i w2_lane(__m128i x, __m128i idx) {
x = _mm_shuffle_epi8(x, idx);
__m128i t = _mm_and_si128(_mm_xor_si128(x, _mm_srli_epi32(x, 6)), _mm_set1_epi32(0x00CC00CC));
x = _mm_xor_si128(x, _mm_xor_si128(t, _mm_slli_epi32(t, 6)));
t = _mm_and_si128(_mm_xor_si128(x, _mm_srli_epi32(x, 12)), _mm_set1_epi32(0x0000F0F0));
return _mm_xor_si128(x, _mm_xor_si128(t, _mm_slli_epi32(t, 12)));
}
void w2_row(const uint8_t* s, int64_t kpb, uint8_t* o) {
const __m128i idx = w2_idx();
for (int64_t kb = 0; kb < kpb; ++kb, s += 32, o += 512) {
const __m128i a = w2_lane(_mm_loadu_si128((const __m128i*)s), idx);
const __m128i b = w2_lane(_mm_loadu_si128((const __m128i*)(s + 16)), idx);
_mm_storeu_si128((__m128i*)o, _mm_unpacklo_epi64(a, b));
_mm_storeu_si128((__m128i*)(o + 256), _mm_unpackhi_epi64(a, b));
}
}
#elif R4D_HSIMD_LEVEL == 3
void w2_row(const uint8_t* s, int64_t kpb, uint8_t* o) {
const __m256i idx = _mm256_broadcastsi128_si256(w2_idx());
const __m256i k6 = _mm256_set1_epi32(0x00CC00CC), k12 = _mm256_set1_epi32(0x0000F0F0);
for (int64_t kb = 0; kb < kpb; ++kb, s += 32, o += 512) {
__m256i x = _mm256_shuffle_epi8(_mm256_loadu_si256((const __m256i*)s), idx);
__m256i t = _mm256_and_si256(_mm256_xor_si256(x, _mm256_srli_epi32(x, 6)), k6);
x = _mm256_xor_si256(x, _mm256_xor_si256(t, _mm256_slli_epi32(t, 6)));
t = _mm256_and_si256(_mm256_xor_si256(x, _mm256_srli_epi32(x, 12)), k12);
x = _mm256_xor_si256(x, _mm256_xor_si256(t, _mm256_slli_epi32(t, 12)));
/* Quadwords (a0, a1, b0, b1) to (a0, b0, a1, b1): half 0, then half 1. */
x = _mm256_permute4x64_epi64(x, 0xD8);
_mm_storeu_si128((__m128i*)o, _mm256_castsi256_si128(x));
_mm_storeu_si128((__m128i*)(o + 256), _mm256_extracti128_si256(x, 1));
}
}
#elif R4D_HSIMD_LEVEL == 4
void w2_row(const uint8_t* s, int64_t kpb, uint8_t* o) {
const __m512i idx = _mm512_broadcast_i32x4(w2_idx());
const __m512i k6 = _mm512_set1_epi32(0x00CC00CC), k12 = _mm512_set1_epi32(0x0000F0F0);
const __m512i perm = _mm512_setr_epi64(0, 2, 1, 3, 4, 6, 5, 7);
int64_t kb = 0;
/* Two units a step; xor-and-xor is one ternary op. */
for (; kb + 2 <= kpb; kb += 2, s += 64, o += 1024) {
__m512i x = _mm512_shuffle_epi8(_mm512_loadu_si512(s), idx);
__m512i t = _mm512_and_si512(_mm512_xor_si512(x, _mm512_srli_epi32(x, 6)), k6);
x = _mm512_ternarylogic_epi32(x, t, _mm512_slli_epi32(t, 6), 0x96);
t = _mm512_and_si512(_mm512_xor_si512(x, _mm512_srli_epi32(x, 12)), k12);
x = _mm512_ternarylogic_epi32(x, t, _mm512_slli_epi32(t, 12), 0x96);
x = _mm512_permutexvar_epi64(perm, x);
_mm_storeu_si128((__m128i*)o, _mm512_extracti32x4_epi32(x, 0));
_mm_storeu_si128((__m128i*)(o + 256), _mm512_extracti32x4_epi32(x, 1));
_mm_storeu_si128((__m128i*)(o + 512), _mm512_extracti32x4_epi32(x, 2));
_mm_storeu_si128((__m128i*)(o + 768), _mm512_extracti32x4_epi32(x, 3));
}
if (kb < kpb) {
const __m256i idx2 = _mm512_castsi512_si256(idx);
__m256i x = _mm256_shuffle_epi8(_mm256_loadu_si256((const __m256i*)s), idx2);
__m256i t = _mm256_and_si256(_mm256_xor_si256(x, _mm256_srli_epi32(x, 6)), _mm512_castsi512_si256(k6));
x = _mm256_ternarylogic_epi32(x, t, _mm256_slli_epi32(t, 6), 0x96);
t = _mm256_and_si256(_mm256_xor_si256(x, _mm256_srli_epi32(x, 12)), _mm512_castsi512_si256(k12));
x = _mm256_ternarylogic_epi32(x, t, _mm256_slli_epi32(t, 12), 0x96);
x = _mm256_permute4x64_epi64(x, 0xD8);
_mm_storeu_si128((__m128i*)o, _mm256_castsi256_si128(x));
_mm_storeu_si128((__m128i*)(o + 256), _mm256_extracti128_si256(x, 1));
}
}
#endif
/* ---- the 16-row dword transpose ---------------------------------------------------------------- */
void dt_scalar(const uint32_t* in, int64_t stride, int64_t c0, int64_t cols, uint32_t* out) {
for (int64_t c = c0; c < cols; ++c)
for (int r = 0; r < 16; ++r) out[16 * c + r] = in[r * stride + c];
}
#if R4D_HSIMD_LEVEL >= 1
/* Rows 4g .. 4g + 3 of columns c .. c + 3: v[i] becomes column c + i of those rows. */
inline void dt_4x4(const uint32_t* in, int64_t stride, int64_t c, int g, __m128i v[4]) {
const uint32_t* p = in + 4 * g * stride + c;
const __m128i a = _mm_loadu_si128((const __m128i*)p);
const __m128i b = _mm_loadu_si128((const __m128i*)(p + stride));
const __m128i e = _mm_loadu_si128((const __m128i*)(p + 2 * stride));
const __m128i f = _mm_loadu_si128((const __m128i*)(p + 3 * stride));
const __m128i ab0 = _mm_unpacklo_epi32(a, b), ab1 = _mm_unpackhi_epi32(a, b);
const __m128i ef0 = _mm_unpacklo_epi32(e, f), ef1 = _mm_unpackhi_epi32(e, f);
v[0] = _mm_unpacklo_epi64(ab0, ef0);
v[1] = _mm_unpackhi_epi64(ab0, ef0);
v[2] = _mm_unpacklo_epi64(ab1, ef1);
v[3] = _mm_unpackhi_epi64(ab1, ef1);
}
#endif
#if R4D_HSIMD_LEVEL == 1 || R4D_HSIMD_LEVEL == 2
void dt_vec(const uint32_t* in, int64_t stride, int64_t cols, uint32_t* out) {
int64_t c = 0;
for (; c + 4 <= cols; c += 4)
for (int g = 0; g < 4; ++g) {
__m128i v[4];
dt_4x4(in, stride, c, g, v);
for (int i = 0; i < 4; ++i) _mm_storeu_si128((__m128i*)(out + 16 * (c + i) + 4 * g), v[i]);
}
dt_scalar(in, stride, c, cols, out);
}
#elif R4D_HSIMD_LEVEL == 3
/* Eight columns a step: the 4 x 4 transpose in each 128-bit lane, the high lane columns c + 4 ..
* c + 7. */
void dt_vec(const uint32_t* in, int64_t stride, int64_t cols, uint32_t* out) {
int64_t c = 0;
for (; c + 8 <= cols; c += 8)
for (int g = 0; g < 4; ++g) {
const uint32_t* p = in + 4 * g * stride + c;
const __m256i a = _mm256_loadu_si256((const __m256i*)p);
const __m256i b = _mm256_loadu_si256((const __m256i*)(p + stride));
const __m256i e = _mm256_loadu_si256((const __m256i*)(p + 2 * stride));
const __m256i f = _mm256_loadu_si256((const __m256i*)(p + 3 * stride));
const __m256i ab0 = _mm256_unpacklo_epi32(a, b), ab1 = _mm256_unpackhi_epi32(a, b);
const __m256i ef0 = _mm256_unpacklo_epi32(e, f), ef1 = _mm256_unpackhi_epi32(e, f);
const __m256i v[4] = { _mm256_unpacklo_epi64(ab0, ef0), _mm256_unpackhi_epi64(ab0, ef0),
_mm256_unpacklo_epi64(ab1, ef1), _mm256_unpackhi_epi64(ab1, ef1) };
for (int i = 0; i < 4; ++i) {
_mm_storeu_si128((__m128i*)(out + 16 * (c + i) + 4 * g), _mm256_castsi256_si128(v[i]));
_mm_storeu_si128((__m128i*)(out + 16 * (c + 4 + i) + 4 * g), _mm256_extracti128_si256(v[i], 1));
}
}
for (; c + 4 <= cols; c += 4)
for (int g = 0; g < 4; ++g) {
__m128i v[4];
dt_4x4(in, stride, c, g, v);
for (int i = 0; i < 4; ++i) _mm_storeu_si128((__m128i*)(out + 16 * (c + i) + 4 * g), v[i]);
}
dt_scalar(in, stride, c, cols, out);
}
#elif R4D_HSIMD_LEVEL == 4
/* Four columns a step, each one whole 64-byte column of the tile: four 4 x 4 transposes, one per
* group of rows, joined lane by lane. */
void dt_vec(const uint32_t* in, int64_t stride, int64_t cols, uint32_t* out) {
int64_t c = 0;
for (; c + 4 <= cols; c += 4) {
__m128i v[4][4];
for (int g = 0; g < 4; ++g) dt_4x4(in, stride, c, g, v[g]);
for (int i = 0; i < 4; ++i) {
__m512i z = _mm512_castsi128_si512(v[0][i]);
z = _mm512_inserti32x4(z, v[1][i], 1);
z = _mm512_inserti32x4(z, v[2][i], 2);
z = _mm512_inserti32x4(z, v[3][i], 3);
_mm512_storeu_si512(out + 16 * (c + i), z);
}
}
dt_scalar(in, stride, c, cols, out);
}
#endif
/* ---- the byte transpose ----------------------------------------------------------------------- */
void bt_scalar(const uint8_t* in, int64_t rows, int64_t cols, int64_t r0, int64_t r1, int64_t c0,
int64_t c1, uint8_t* out) {
for (int64_t r = r0; r < r1; ++r)
for (int64_t c = c0; c < c1; ++c) out[c * rows + r] = in[r * cols + c];
}
#if R4D_HSIMD_LEVEL >= 1
/* A 16 x 16 block at (r, c): four rounds of interleaving rows i and i + 8, as the trellis tile's
* transpose (without its row reversal). */
void bt_block(const uint8_t* in, int64_t rows, int64_t cols, int64_t r, int64_t c, uint8_t* out) {
__m128i x[16], y[16];
for (int q = 0; q < 16; ++q) x[q] = _mm_loadu_si128((const __m128i*)(in + (r + q) * cols + c));
for (int round = 0; round < 4; ++round) {
for (int i = 0; i < 8; ++i) {
y[2 * i] = _mm_unpacklo_epi8(x[i], x[i + 8]);
y[2 * i + 1] = _mm_unpackhi_epi8(x[i], x[i + 8]);
}
for (int i = 0; i < 16; ++i) x[i] = y[i];
}
for (int j = 0; j < 16; ++j) _mm_storeu_si128((__m128i*)(out + (c + j) * rows + r), x[j]);
}
#endif
#if R4D_HSIMD_LEVEL == 3 || R4D_HSIMD_LEVEL == 4
/* Two 16 x 16 blocks side by side, one a 128-bit lane: rows r .. r + 15, columns c .. c + 31. */
void bt_block2(const uint8_t* in, int64_t rows, int64_t cols, int64_t r, int64_t c, uint8_t* out) {
__m256i x[16], y[16];
for (int q = 0; q < 16; ++q) x[q] = _mm256_loadu_si256((const __m256i*)(in + (r + q) * cols + c));
for (int round = 0; round < 4; ++round) {
for (int i = 0; i < 8; ++i) {
y[2 * i] = _mm256_unpacklo_epi8(x[i], x[i + 8]);
y[2 * i + 1] = _mm256_unpackhi_epi8(x[i], x[i + 8]);
}
for (int i = 0; i < 16; ++i) x[i] = y[i];
}
for (int j = 0; j < 16; ++j) {
_mm_storeu_si128((__m128i*)(out + (c + j) * rows + r), _mm256_castsi256_si128(x[j]));
_mm_storeu_si128((__m128i*)(out + (c + 16 + j) * rows + r), _mm256_extracti128_si256(x[j], 1));
}
}
#endif
void bt_run(const uint8_t* in, int64_t rows, int64_t cols, uint8_t* out) {
#if R4D_HSIMD_LEVEL == 0
bt_scalar(in, rows, cols, 0, rows, 0, cols, out);
#else
const int64_t R = rows / 16 * 16, C = cols / 16 * 16;
for (int64_t r = 0; r < R; r += 16) {
int64_t c = 0;
#if R4D_HSIMD_LEVEL >= 3
for (; c + 32 <= C; c += 32) bt_block2(in, rows, cols, r, c, out);
#endif
for (; c < C; c += 16) bt_block(in, rows, cols, r, c, out);
}
bt_scalar(in, rows, cols, 0, R, C, cols, out);
bt_scalar(in, rows, cols, R, rows, 0, cols, out);
#endif
}
} // namespace
extern "C" void R4D_HSIMD_FN(byte_transpose)(const uint8_t* in, int64_t rows, int64_t cols, uint8_t* out) {
bt_run(in, rows, cols, out);
}
extern "C" void R4D_HSIMD_FN(dword_transpose16)(const uint32_t* in, int64_t stride, int64_t cols,
uint32_t* out) {
#if R4D_HSIMD_LEVEL == 0
dt_scalar(in, stride, 0, cols, out);
#else
dt_vec(in, stride, cols, out);
#endif
}
extern "C" void R4D_HSIMD_FN(w2a8_tile)(const uint8_t* rows, int64_t rb, int64_t kpb, uint8_t* out) {
for (int r = 0; r < 16; ++r) w2_row(rows + r * rb, kpb, out + 16 * r);
}
extern "C" void R4D_HSIMD_FN(moew4_permute)(const uint8_t* s, uint8_t* d, int64_t bytes, bool fwd) {
#if R4D_HSIMD_LEVEL == 0
mw_scalar(s, d, bytes, fwd);
#else
mw_vec(s, d, bytes, fwd);
#endif
}
extern "C" void R4D_HSIMD_FN(iqr_trellis_tile)(const uint8_t* rows, int64_t rb, int B, int64_t nkb,
uint8_t* out) {
alignas(64) uint8_t U[16][kCodes];
alignas(64) uint8_t T[kCodes * 16];
const int64_t per = 16 * B, ub = 256 * B;
#if R4D_HSIMD_LEVEL >= 1
alignas(64) uint8_t pad[16 * 8 + 64]; /* a row's 16 B bytes with room to read past */
alignas(64) uint8_t pk[256 * 8 + 64]; /* a unit with room to write past */
const Lanes L(B);
bool streamed = false;
#endif
for (int64_t kb = 0; kb < nkb; ++kb) {
for (int r = 0; r < 16; ++r) {
const uint8_t* s = rows + r * rb + kb * per;
#if R4D_HSIMD_LEVEL == 0
unpack_row(s, B, U[r]);
#else
/* The vector unpack reads up to 16 bytes past a group; only the tile's last row of
* its last unit may end where the plane does. */
if (r == 15 && kb == nkb - 1) {
std::memcpy(pad, s, (size_t)per);
s = pad;
}
unpack_row(L, s, B, U[r]);
#endif
}
transpose_rev(U, T);
#if R4D_HSIMD_LEVEL == 0
pack(T, kCodes * 16, B, out + kb * ub);
#else
pack(L, T, kCodes * 16, B, pk);
streamed |= stream_copy(out + kb * ub, pk, ub);
#endif
}
#if R4D_HSIMD_LEVEL >= 1
stream_fence(streamed);
#endif
}
/* A row's eight qwords of one 64-byte K step: the even ones to lane r, the odd ones to lane
* 16 + r, 32 bytes each (r4d_fp8_frag.h, frag_src). */
/* With `out` aligned the 32-byte pieces go out as streaming stores (stream_copy says why); the two
* of a destination line are written by consecutive rows, so the line leaves whole. */
template <bool kStream>
inline void fp8_frag_body(const uint8_t* rows, int64_t K, int64_t ksuper, uint8_t* out) {
#if R4D_HSIMD_LEVEL == 4
const __m512i idx = _mm512_setr_epi64(0, 2, 4, 6, 1, 3, 5, 7);
#endif
#if R4D_HSIMD_LEVEL >= 3
auto put = [](uint8_t* d, __m256i v) {
if (kStream) _mm256_stream_si256((__m256i*)d, v);
else _mm256_storeu_si256((__m256i*)d, v);
};
#elif R4D_HSIMD_LEVEL >= 1
auto put = [](uint8_t* d, __m128i v) {
if (kStream) _mm_stream_si128((__m128i*)d, v);
else _mm_storeu_si128((__m128i*)d, v);
};
#endif
for (int64_t ks = 0; ks < ksuper; ++ks) {
uint8_t* t = out + ks * 1024;
for (int r = 0; r < 16; ++r) {
const uint8_t* s = rows + r * K + ks * 64;
uint8_t* lo = t + 32 * r;
uint8_t* hi = t + 32 * (16 + r);
#if R4D_HSIMD_LEVEL == 4
const __m512i x = _mm512_permutexvar_epi64(idx, _mm512_loadu_si512(s));
put(lo, _mm512_castsi512_si256(x));
put(hi, _mm512_extracti64x4_epi64(x, 1));
#elif R4D_HSIMD_LEVEL == 3
const __m256i a = _mm256_permute4x64_epi64(_mm256_loadu_si256((const __m256i*)s), 0xD8);
const __m256i b = _mm256_permute4x64_epi64(_mm256_loadu_si256((const __m256i*)(s + 32)), 0xD8);
put(lo, _mm256_permute2x128_si256(a, b, 0x20));
put(hi, _mm256_permute2x128_si256(a, b, 0x31));
#elif R4D_HSIMD_LEVEL >= 1
const __m128i a = _mm_loadu_si128((const __m128i*)s);
const __m128i b = _mm_loadu_si128((const __m128i*)(s + 16));
const __m128i c = _mm_loadu_si128((const __m128i*)(s + 32));
const __m128i d = _mm_loadu_si128((const __m128i*)(s + 48));
put(lo, _mm_unpacklo_epi64(a, b));
put(lo + 16, _mm_unpacklo_epi64(c, d));
put(hi, _mm_unpackhi_epi64(a, b));
put(hi + 16, _mm_unpackhi_epi64(c, d));
#else
for (int q = 0; q < 4; ++q) {
std::memcpy(lo + 8 * q, s + 16 * q, 8);
std::memcpy(hi + 8 * q, s + 16 * q + 8, 8);
}
#endif
}
}
}
extern "C" void R4D_HSIMD_FN(fp8_frag_tile)(const uint8_t* rows, int64_t K, int64_t ksuper,
uint8_t* out) {
#if R4D_HSIMD_LEVEL >= 1
if (((uintptr_t)out & 63) == 0) {
fp8_frag_body<true>(rows, K, ksuper, out);
stream_fence(true);
return;
}
#endif
fp8_frag_body<false>(rows, K, ksuper, out);
}
+4 -3
View File
@@ -47,8 +47,9 @@
* ---- the rest ------------------------------------------------------------------------------------
*
* After the codes, at aux_off(), the form's table (Table: 256 int8, zero-padded; Grid: 2^B * V;
* Trellis: 2^L; TrellisMad: its 2^L values, kept for the unrelayout, then A and B as two u32) or,
* for Zero, its zero plane as u8 in the scale order below. The scale buffer is
* Trellis: 2^L; TrellisMad: A and B alone as two u32, the values being computed from them where
* they are read and the stored table regenerated on the way back) or, for Zero, its zero plane as
* u8 in the scale order below. The scale buffer is
* tile-major, [N/16][K/128][16]: the 16 rows of a tile side by side for one 128-K block, as the
* int8 GEMMs' (r4d_fp8_layout.cpp): bf16, or E4M3 bytes followed at s2_off() by the second level as
* f32 (one, or one a row) and, with rb > 1, at blk_off() the bf16 block scale B per [N/rb][K/128].
@@ -124,7 +125,7 @@ R4D_IQR_HD constexpr int64_t aux_bytes(const Form& f, int64_t N, int64_t K) {
return f.kind == kTable ? 256
: f.kind == kGrid ? ((int64_t)1 << f.bits) << f.lv
: f.kind == kTrellis ? (int64_t)1 << f.L
: f.kind == kTrellisMad ? ((int64_t)1 << f.L) + 8
: f.kind == kTrellisMad ? 8
: f.kind == kZero ? N * (K / 128)
: 0;
}
+23 -10
View File
@@ -211,12 +211,25 @@ struct Dec {
#pragma unroll
for (uint32_t i = 0; i < NW; ++i) cw[e][i] = colw(r, e, i);
}
/* Bits 16 .. 47 of words i and i + 1 of each column's stream. A state that crosses that
* bound starts past bit 16 of word i (L is at most 16), so it is a field of this word: one
* extract a state, where a funnel shift and a mask each would be two. */
__device__ static void mids(const uint32_t (&cw)[4][NW], uint32_t (&mw)[4][NW]) {
#pragma unroll
for (uint32_t e = 0; e < 4; ++e)
#pragma unroll
for (uint32_t i = 0; i < NW; ++i)
mw[e][i] = i + 1u < NW ? __builtin_amdgcn_alignbit(cw[e][i + 1u], cw[e][i], 16u) : 0u;
}
/* Row q's state of column e: L bits from bit q B of the column's stream. */
__device__ static uint32_t state(const uint32_t (&cw)[4][NW], uint32_t q, uint32_t e) {
__device__ static uint32_t state(const uint32_t (&cw)[4][NW], const uint32_t (&mw)[4][NW],
uint32_t q, uint32_t e) {
constexpr uint32_t L = F::L;
static_assert(L <= 16u, "a crossing state within bits 16 .. 47");
const uint32_t o = q * B, i = o >> 5, s = o & 31u;
if (s + L <= 32u) return (cw[e][i] >> s) & ((1u << L) - 1u);
return window(cw[e][i], cw[e][i + 1u], s, L);
if (s % 8u == 0u && L % 8u == 0u) return window(cw[e][i], cw[e][i + 1u], s, L);
return (mw[e][i] >> (s - 16u)) & ((1u << L) - 1u);
}
static constexpr bool HALF = H16 && TR && !MAD && F::LRB != 0;
static constexpr uint32_t kTab = F::KIND == kTable ? 256u
@@ -280,20 +293,20 @@ struct Dec {
if constexpr (TR) {
/* All 64 states, then all 64 lookups, then the values: the LDS reads go out together
* instead of each waiting on the last's use. */
uint32_t st[64], cw[4][NW];
uint32_t st[64], cw[4][NW], mw[4][NW];
columns(r, cw);
mids(cw, mw);
#pragma unroll
for (uint32_t q = 0; q < 16; ++q)
#pragma unroll
for (uint32_t e = 0; e < 4; ++e) st[q * 4 + e] = state(cw, q, e);
for (uint32_t e = 0; e < 4; ++e) st[q * 4 + e] = state(cw, mw, q, e);
[[maybe_unused]] int32_t t[HALF ? 1 : 64];
[[maybe_unused]] _Float16 th[HALF ? 64 : 1];
if constexpr (MAD) {
/* bytesum((st * A + B) & 0x3F3F3F3F) - 126: st < 2^16 and A < 2^24, so the
* 24-bit multiply is the full product mod 2^32 */
constexpr Form f{ F::KIND, F::B, F::LV, F::L, F::LRB, F::SC, 0 };
const uint32_t* ab = (const uint32_t*)(c.W + aux_off(f, c.N, (int64_t)c.nkb * 128) +
((int64_t)1 << F::L));
const uint32_t* ab = (const uint32_t*)(c.W + aux_off(f, c.N, (int64_t)c.nkb * 128));
const uint32_t A = ab[0], Bc = ab[1];
#pragma unroll
for (uint32_t i = 0; i < 64; ++i) {
@@ -370,15 +383,15 @@ struct Dec {
__device__ static void hashes(const Raw& r, const Ctx& c, uint32_t (&h)[16][4]) {
static_assert(MAD, "hashes: a computed trellis");
constexpr Form f{ F::KIND, F::B, F::LV, F::L, F::LRB, F::SC, 0 };
const uint32_t* ab = (const uint32_t*)(c.W + aux_off(f, c.N, (int64_t)c.nkb * 128) +
((int64_t)1 << F::L));
const uint32_t* ab = (const uint32_t*)(c.W + aux_off(f, c.N, (int64_t)c.nkb * 128));
const uint32_t A = ab[0], Bc = ab[1];
uint32_t cw[4][NW];
uint32_t cw[4][NW], mw[4][NW];
columns(r, cw);
mids(cw, mw);
#pragma unroll
for (uint32_t q = 0; q < 16; ++q)
#pragma unroll
for (uint32_t e = 0; e < 4; ++e) h[15u - q][e] = (__umul24(state(cw, q, e), A) + Bc) & 0x3F3F3F3Fu;
for (uint32_t e = 0; e < 4; ++e) h[15u - q][e] = (__umul24(state(cw, mw, q, e), A) + Bc) & 0x3F3F3F3Fu;
}
/* Zero: the zero of row (rt*16 + q) for block kb is subtracted bytewise after `rows`. */
+203 -34
View File
@@ -12,6 +12,8 @@
#include "r4d_iqr.h"
#include "r4d_fp8_frag.h"
#include "r4d_enc.h"
#include "r4d_hsimd.h"
#include "r4d_par.h"
#include <algorithm>
#include <atomic>
@@ -159,6 +161,13 @@ bool classify(const RadEncoding* enc, const char* tr, Form* f, int64_t* entries)
struct Geom { long long N, K, nkb; };
/* tcq_code=mad's value of state `st`: bytesum((st * A + B) mod 2^32 & 0x3F3F3F3F) - 126, the
* product from the low 24 bits of each factor (libquant's grid_tcq_mad_values). */
inline int mad_value(uint32_t st, uint32_t a, uint32_t b) {
const uint32_t h = ((st & 0xFFFFFFu) * (a & 0xFFFFFFu) + b) & 0x3F3F3F3Fu;
return (int)((h & 0xFFu) + ((h >> 8) & 0xFFu) + ((h >> 16) & 0xFFu) + (h >> 24)) - 126;
}
int geom(const RadParam* p, int n_p, Geom* g) {
g->N = r4d_pgeti_or(p, n_p, "N", 0);
g->K = r4d_pgeti_or(p, n_p, "K", 0);
@@ -242,17 +251,46 @@ inline void put_bits(uint8_t* dst, long long o, uint64_t v, int n) {
for (int i = 0; i < bytes; ++i) b[i] |= (uint8_t)(v >> (8 * i));
}
/* Runs f(lo, hi) over [0, n) in parallel chunks. A model's weights relayout at load, gigabytes of
* them, so the walk is split over the host's cores. */
template <typename F>
void par_for(long long n, F f) {
const unsigned hc = std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
const long long per = std::max(1ll, (n + hc - 1) / hc);
std::vector<std::thread> th;
for (long long lo = 0; lo < n; lo += per) th.emplace_back(f, lo, std::min(n, lo + per));
for (std::thread& t : th) t.join();
using r4d_par::par_for;
/* 16-row tiles a relayout thread takes: about 16 MiB of codes. */
long long tiles_a_thread(const Form& f, long long K) {
return std::max(1ll, ((long long)16 << 20) / std::max(1ll, (long long)(K / 128) * unit_bytes(f)));
}
/* Bits [o, o + n) of a plane row, n <= 32, read with one unaligned 8-byte load (fewer bytes where
* the plane ends within 8 bytes, at `end`). */
inline uint32_t peek_bits(const uint8_t* row, long long o, int n, const uint8_t* end) {
const uint8_t* b = row + (o >> 3);
uint64_t w = 0;
if (end - b >= 8) std::memcpy(&w, b, 8);
else std::memcpy(&w, b, (size_t)(end - b));
return (uint32_t)((w >> (o & 7)) & ((1ull << n) - 1ull));
}
/* Appends fields of up to 32 bits to a byte-aligned stream, a dword at a time. */
struct BitOut {
uint8_t* p;
uint64_t acc = 0;
int n = 0; /* bits held, below 32 between puts */
explicit BitOut(uint8_t* at) : p(at) {}
void put(uint64_t v, int w) {
acc |= v << n;
n += w;
if (n >= 32) {
const uint32_t x = (uint32_t)acc;
std::memcpy(p, &x, 4);
p += 4;
acc >>= 32;
n -= 32;
}
}
/* The held bits, a whole number of bytes at a segment's end. */
void done() {
for (; n > 0; n -= 8, acc >>= 8) *p++ = (uint8_t)acc;
}
};
/* Visits each code of the weight with its row-major position (row r, code column c in the codes
* plane) and its bit in the stored codes plane: the one definition of r4d_iqr.h's order, walked
* forwards by the relayout and backwards by the unrelayout. `per_tile(rt, visit)` gives a worker a
@@ -294,24 +332,77 @@ int scalar_value(const Form& f, const Planes& v, int64_t entries, long long r, l
return 0;
}
/* The codes in r4d_iqr.h's lane segments. A trellis tile goes to r4d_hsimd::iqr_trellis_tile;
* for the other forms, a segment at a time, each of the tile's 16 rows gives a lane its codes
* 4l .. 4l + 3 (4/V for a grid) as one field read with a single load, and the segment is written
* as a stream of dwords. walk_tile's order, which the unrelayout walks, element
* for element: relayout_iqr_test holds the two to each other on every form. A code the form cannot
* read (no entry answers it, or its value is outside -127..127) refuses the weight. */
int weight_relayout(const Form& f, const Geom& g, int64_t entries, const Planes& v, uint8_t* d,
int64_t bytes) {
if (bytes != weight_bytes(f, g.N, g.K) || !v.codes->data) return RAD_E_SHAPE;
std::memset(d, 0, (size_t)bytes);
/* The segments cover the codes area whole; only what follows it is cleared. */
const int64_t cb = codes_bytes(f, g.N, g.K);
std::memset(d + cb, 0, (size_t)(bytes - cb));
std::atomic<int> bad{ RAD_OK };
const int B = (int)f.bits;
par_for(g.N / 16, [&](long long lo, long long hi) {
for (long long rt = lo; rt < hi; ++rt)
walk_tile(f, g.K, rt, [&](long long r, long long c, long long bit) {
const uint32_t code = (uint32_t)get_bits(r4d_enc::row(*v.codes, r), c * B, B);
if (f.kind == kSigned || f.kind == kTable || f.kind == kZero) {
const int val = scalar_value(f, v, entries, r, c, code);
if (val < -127 || val > 127) bad = RAD_E_FORMAT;
} else if (f.kind == kGrid && (int64_t)code >= entries) {
bad = RAD_E_FORMAT;
const bool tr = is_trellis(f.kind);
const int per = f.kind == kGrid ? 4 >> f.lv : 4; /* codes a row gives a lane */
const int w = per * B;
const uint32_t m = (1u << B) - 1u;
const long long rb = rad_dtype_bytes(v.codes->dtype, v.codes->shape[1]);
const uint8_t* c0p = (const uint8_t*)v.codes->data;
const uint8_t* end = c0p + rb * g.N;
const long long ub = unit_bytes(f), lb = lane_bits(f) / 8;
/* Which codes refuse, for the forms whose check is the code alone. */
std::vector<uint8_t> refuse;
if (f.kind == kSigned || f.kind == kTable || f.kind == kGrid) {
refuse.assign((size_t)1 << B, 0);
for (uint32_t c = 0; c <= m; ++c) {
const int val = f.kind == kGrid ? 0 : scalar_value(f, v, entries, 0, 0, c);
refuse[c] = f.kind == kGrid ? (int64_t)c >= entries : (val < -127 || val > 127);
}
}
const int zb = f.kind == kZero ? unsigned_bits(v.aux->dtype) : 0;
par_for(g.N / 16, tiles_a_thread(f, g.K), [&](long long lo, long long hi) {
uint32_t ch[16];
int zero[16];
for (long long rt = lo; rt < hi; ++rt) {
const uint8_t* rows = c0p + rt * 16 * rb;
/* A trellis tile is a transpose of its codes, done a unit at a time in vector
* registers (r4d_hsimd.h). */
if (tr) {
r4d_hsimd::iqr_trellis_tile(rows, rb, B, g.nkb, d + rt * g.nkb * ub);
continue;
}
for (long long kb = 0; kb < g.nkb; ++kb) {
uint8_t* u = d + (rt * g.nkb + kb) * ub;
if (f.kind == kZero)
for (int r = 0; r < 16; ++r)
zero[r] = (int)rad_load_bits(r4d_enc::row(*v.aux, rt * 16 + r), zb, kb);
for (int lane = 0; lane < 32; ++lane) {
const long long c = f.kind == kGrid ? (kb * 128 + 4 * lane) >> f.lv : kb * 128 + 4 * lane;
for (int r = 0; r < 16; ++r) ch[r] = peek_bits(rows + r * rb, c * B, w, end);
BitOut o(u + lane * lb);
{
if (!refuse.empty()) {
uint32_t any = 0;
for (int r = 0; r < 16; ++r)
for (int e = 0; e < per; ++e) any |= refuse[(ch[r] >> (e * B)) & m];
if (any) bad = RAD_E_FORMAT;
} else if (f.kind == kZero) {
for (int r = 0; r < 16; ++r)
for (int e = 0; e < per; ++e) {
const int val = (int)((ch[r] >> (e * B)) & m) - zero[r];
if (val < -127 || val > 127) bad = RAD_E_FORMAT;
}
}
for (int r = 0; r < 16; ++r) o.put(ch[r], w);
}
o.done();
}
put_bits(d, bit, code, B);
});
}
}
});
if (bad != RAD_OK) return bad;
uint8_t* aux = d + aux_off(f, g.N, g.K);
@@ -321,17 +412,16 @@ int weight_relayout(const Form& f, const Geom& g, int64_t entries, const Planes&
const int8_t* t = (const int8_t*)v.aux->data;
for (long long i = 0; i < n; ++i)
if (t[i] < -127 && f.kind != kTable) return RAD_E_FORMAT;
std::memcpy(aux, t, (size_t)n);
if (f.kind == kTrellisMad) {
/* The kernels compute the values from A and B: the stored table must be that code. */
/* The kernels compute the values from A and B, which is all the layout keeps: the
* stored table must be that code. */
if (!v.mad || !v.mad->data) return RAD_E_SHAPE;
const uint32_t a = ((const uint32_t*)v.mad->data)[0], b = ((const uint32_t*)v.mad->data)[1];
for (long long st = 0; st < n; ++st) {
const uint32_t h = (((uint32_t)st & 0xFFFFFFu) * (a & 0xFFFFFFu) + b) & 0x3F3F3F3Fu;
const int q = (int)((h & 0xFFu) + ((h >> 8) & 0xFFu) + ((h >> 16) & 0xFFu) + (h >> 24)) - 126;
if (q != t[st]) return RAD_E_FORMAT;
}
std::memcpy(aux + n, v.mad->data, 8);
for (long long st = 0; st < n; ++st)
if (mad_value((uint32_t)st, a, b) != t[st]) return RAD_E_FORMAT;
std::memcpy(aux, v.mad->data, 8);
} else {
std::memcpy(aux, t, (size_t)n);
}
} else if (f.kind == kZero) {
const int zb = unsigned_bits(v.aux->dtype);
@@ -348,7 +438,7 @@ int weight_unrelayout(const Form& f, const Geom& g, int64_t entries, const Plane
const int B = (int)f.bits;
const long long rb = rad_dtype_bytes(v.codes->dtype, v.codes->shape[1]);
std::memset(v.codes->data, 0, (size_t)(rb * g.N));
par_for(g.N / 16, [&](long long lo, long long hi) {
par_for(g.N / 16, tiles_a_thread(f, g.K), [&](long long lo, long long hi) {
for (long long rt = lo; rt < hi; ++rt)
walk_tile(f, g.K, rt, [&](long long r, long long c, long long bit) {
put_bits((uint8_t*)v.codes->data + r * rb, c * B, get_bits(s, bit, B), B);
@@ -357,8 +447,16 @@ int weight_unrelayout(const Form& f, const Geom& g, int64_t entries, const Plane
const uint8_t* aux = s + aux_off(f, g.N, g.K);
if (f.kind == kTable || f.kind == kGrid || is_trellis(f.kind)) {
const long long n = f.kind == kGrid ? entries << f.lv : entries;
std::memcpy(v.aux->data, aux, (size_t)n);
if (f.kind == kTrellisMad && v.mad && v.mad->data) std::memcpy(v.mad->data, aux + n, 8);
if (f.kind == kTrellisMad) {
/* The table back from the constants the layout kept. */
uint32_t ab[2];
std::memcpy(ab, aux, 8);
for (long long st = 0; st < n; ++st)
((int8_t*)v.aux->data)[st] = (int8_t)mad_value((uint32_t)st, ab[0], ab[1]);
if (v.mad && v.mad->data) std::memcpy(v.mad->data, aux, 8);
} else {
std::memcpy(v.aux->data, aux, (size_t)n);
}
} else if (f.kind == kZero) {
const int zb = unsigned_bits(v.aux->dtype);
const long long zr = rad_dtype_bytes(v.aux->dtype, v.aux->shape[1]);
@@ -612,10 +710,11 @@ extern "C" int r4d_rad_relayout_iqr_embed(const RadParam* p, int n_p, int operan
(v.scale2 && !v.scale2->data))
return RAD_E_SHAPE;
uint8_t* d = (uint8_t*)dst;
std::memset(d, 0, (size_t)dst_bytes);
const long long nkb = dim / 128, crow = rad_dtype_bytes(v.codes->dtype, v.codes->shape[1]);
if (crow != o.codes_row) return RAD_E_SHAPE;
/* The codes are copied whole; only what follows them is cleared first. */
std::memcpy(d, v.codes->data, (size_t)(rows * crow));
if (dst_bytes > rows * crow) std::memset(d + rows * crow, 0, (size_t)(dst_bytes - rows * crow));
uint8_t* aux = d + o.aux;
if (f.kind == kTable || f.kind == kGrid || f.kind == kTrellis) {
const long long na = f.kind == kGrid ? entries << f.lv : entries;
@@ -699,13 +798,17 @@ extern "C" int r4d_rad_relayout_iqr_logits(const RadParam* p, int n_p, int opera
if (dst_bytes != lm_bytes(f, rows, dim) || !v.codes->data || !v.scale->data || !v.aux->data)
return RAD_E_SHAPE;
uint8_t* d = (uint8_t*)dst;
std::memset(d, 0, (size_t)dst_bytes);
const long long stride = lm_row(f, dim), cb = dim / 8 * f.bits, nkb = dim / 128;
/* Each row written once: its codes, its scales, then the padding cleared; then everything
* past the rows, the table's area included. */
const long long used = cb + 2 * nkb;
for (long long r = 0; r < rows; ++r) {
uint8_t* row = d + r * stride;
std::memcpy(row, r4d_enc::row(*v.codes, r), (size_t)cb);
std::memcpy(row + cb, r4d_enc::row(*v.scale, r), (size_t)(2 * nkb));
if (stride > used) std::memset(row + used, 0, (size_t)(stride - used));
}
if (dst_bytes > rows * stride) std::memset(d + rows * stride, 0, (size_t)(dst_bytes - rows * stride));
const int8_t* t = (const int8_t*)v.aux->data;
for (int64_t i = 0; i < entries; ++i)
if (t[i] < -127) return RAD_E_FORMAT;
@@ -800,3 +903,69 @@ extern "C" int r4d_rad_unrelayout_iqr_vocab(const RadParam* p, int n_p, int oper
if (rc != RAD_OK) return rc;
return r4d_rad_unrelayout_iqr(q, 4, il, enc, sel, src, src_bytes, pl, n);
}
/* ==================================================================== the routed experts
*
* moe_gemm_iqr's tables: every entry is one expert's IQR weight, relayouted by the dense hooks at
* its class's geometry. The op's class operands (r4d_layout.cpp's moe_view: `w` / `w_scale` at
* 2 / 3, the odd class at 6 / 7 with N_odd and K_odd; under four classes 6 .. 11 with N_q and K_q)
* are answered as the dense GEMM's weight and scale operands with N and K set to the class's. */
namespace {
struct MoeParams {
RadParam p[32];
int n = 0;
int operand = 0;
};
int moe_params(const RadParam* p, int n_p, int operand, bool mod4, MoeParams* v) {
if (n_p < 0 || n_p > 32 || (n_p > 0 && !p)) return RAD_E_INVAL;
v->n = n_p;
v->operand = operand;
for (int i = 0; i < n_p; ++i) v->p[i] = p[i];
if (operand < 6 || operand > (mod4 ? 11 : 7)) return RAD_OK;
static const char* const kN[4] = { "N", "N_1", "N_2", "N_3" };
static const char* const kK[4] = { "K", "K_1", "K_2", "K_3" };
const int q = (operand - 4) / 2; /* 6/7 -> 1, 8/9 -> 2, 10/11 -> 3 */
v->operand = 2 + (operand & 1);
const long long nq = r4d_pgeti_or(p, n_p, mod4 ? kN[q] : "N_odd", -1);
const long long kq = r4d_pgeti_or(p, n_p, mod4 ? kK[q] : "K_odd", -1);
for (int i = 0; i < n_p; ++i) {
if (!v->p[i].key) continue;
if (nq > 0 && std::strcmp(v->p[i].key, "N") == 0) v->p[i].ival = nq;
if (kq > 0 && std::strcmp(v->p[i].key, "K") == 0) v->p[i].ival = kq;
}
return RAD_OK;
}
} /* namespace */
#define R4D_MOE_IQR_HOOKS(name, mod4) \
extern "C" int r4d_rad_layout_##name(const RadParam* p, int n_p, int operand, \
const RadEncoding* enc, const int* sel, \
const RadTensor* pl, int n, RadLayout* out) { \
MoeParams v; \
const int rc = moe_params(p, n_p, operand, mod4, &v); \
return rc != RAD_OK ? rc : r4d_rad_layout_iqr(v.p, v.n, v.operand, enc, sel, pl, n, out); \
} \
extern "C" int r4d_rad_relayout_##name(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) { \
MoeParams v; \
const int rc = moe_params(p, n_p, operand, mod4, &v); \
return rc != RAD_OK ? rc : r4d_rad_relayout_iqr(v.p, v.n, v.operand, enc, sel, pl, n, \
dst, dst_bytes); \
} \
extern "C" int r4d_rad_unrelayout_##name(const RadParam* p, int n_p, int operand, \
const RadEncoding* enc, const int* sel, \
const void* src, int64_t src_bytes, \
const RadTensor* pl, int n) { \
MoeParams v; \
const int rc = moe_params(p, n_p, operand, mod4, &v); \
return rc != RAD_OK ? rc : r4d_rad_unrelayout_iqr(v.p, v.n, v.operand, enc, sel, src, \
src_bytes, pl, n); \
}
R4D_MOE_IQR_HOOKS(moe_iqr, false)
R4D_MOE_IQR_HOOKS(moe_iqr_mod4, true)
#undef R4D_MOE_IQR_HOOKS
+33
View File
@@ -0,0 +1,33 @@
/* r4d_keyed.h -- device blocks a kernel keeps between launches, keyed by the buffer they serve.
*
* Several rows keep arrival counters that must be zero when a launch starts and that the launch
* leaves zero: one block per (stream or device, output buffer), made at the first launch and
* replayed by recorded passes. They cannot live in the scratch, which other ops overwrite. The
* blocks are keyed by the output's address, so when the core frees the memory an output lived in
* (an engine of a process that loads and unloads models goes away), the blocks for it are freed
* too (rad_plugin_freed, abi/rad_abi.h); otherwise every load would leave its blocks behind.
*/
#pragma once
#include <cstddef>
namespace r4d {
/* Which row's blocks: rows keep blocks of different sizes and protocols for the same output, so
* each has its own. */
enum class Keyed : int { SplitFp8 = 1, GdnConv, MxDecode, M2xDecode, MxGemv };
/* The zeroed block of `bytes` for (row, owner, out), made on first use. `owner` is the stream for
* a row whose launches overlap across streams, or null for one block per device. Null when it
* cannot be made; the caller then runs its unfused path.
*
* The lock is not held while a block is made. Zeroing it waits for the card, and under tensor
* parallelism the card can be inside an all-reduce whose other half the peer rank has yet to issue;
* if the peer's first launch then waited on this lock, neither rank would advance. */
unsigned* keyed_block(Keyed row, const void* owner, const void* out, size_t bytes);
/* State a row keeps under keys of its own, released when the memory [lo, hi) is freed. */
using FreedFn = void (*)(const char* lo, const char* hi);
/* Registers `f`; returns 0, so a file can register from a static initialiser. */
int on_freed(FreedFn f);
} // namespace r4d
+91
View File
@@ -0,0 +1,91 @@
/* r4d_keyed.hip -- device blocks keyed by the buffer they serve (r4d_keyed.h), and the release
* the core calls when it frees memory (rad_plugin_freed). */
#include "r4d_keyed.h"
#include <hip/hip_runtime.h>
#include <cstdint>
#include <map>
#include <mutex>
#include <tuple>
#include <vector>
namespace r4d {
namespace {
struct Block { unsigned* p; int dev; };
using Key = std::tuple<int, int, const void*, const char*>; /* row, device, owner, out */
std::mutex& mu() { static std::mutex m; return m; }
std::map<Key, Block>& blocks() { static std::map<Key, Block> b; return b; }
std::vector<FreedFn>& freed_fns() { static std::vector<FreedFn> v; return v; }
} // namespace
unsigned* keyed_block(Keyed row, const void* owner, const void* out, size_t bytes) {
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
const Key key{ (int)row, dev, owner, static_cast<const char*>(out) };
{
std::lock_guard<std::mutex> lk(mu());
if (auto it = blocks().find(key); it != blocks().end()) return it->second.p;
}
void* p = nullptr;
if (hipMalloc(&p, bytes) != hipSuccess) return nullptr;
/* Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has
* finished when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it
* runs on the null stream, which a non-blocking stream does not wait for, so wait here. */
if (hipMemset(p, 0, bytes) != hipSuccess || hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return nullptr;
}
unsigned* kept = nullptr;
{
std::lock_guard<std::mutex> lk(mu());
const auto [it, fresh] = blocks().emplace(key, Block{ (unsigned*)p, dev });
if (fresh) return it->second.p;
kept = it->second.p;
}
(void)hipFree(p); /* another thread made this key's block in the meantime */
return kept;
}
int on_freed(FreedFn f) {
std::lock_guard<std::mutex> lk(mu());
freed_fns().push_back(f);
return 0;
}
} // namespace r4d
/* The memory [base, base + bytes) is free and nothing launched against it runs any more: every
* block kept for an output inside it goes. */
extern "C" void rad_plugin_freed(const void* base, int64_t bytes) {
using namespace r4d;
const char* lo = static_cast<const char*>(base);
const char* hi = lo + bytes;
std::vector<Block> gone;
std::vector<FreedFn> fns;
{
std::lock_guard<std::mutex> lk(mu());
for (auto it = blocks().begin(); it != blocks().end();) {
const char* out = std::get<3>(it->first);
if (out >= lo && out < hi) {
gone.push_back(it->second);
it = blocks().erase(it);
} else {
++it;
}
}
fns = freed_fns();
}
int was = 0;
(void)hipGetDevice(&was);
for (const Block& b : gone) {
(void)hipSetDevice(b.dev);
(void)hipFree(b.p);
}
(void)hipSetDevice(was);
for (FreedFn f : fns) f(lo, hi);
}
+85 -286
View File
@@ -20,6 +20,8 @@
*/
#include "r4d_plugin.h"
#include "r4d_hsimd.h"
#include "r4d_par.h"
#include "r4d_enc.h"
#include <cstdint>
@@ -177,8 +179,12 @@ static bool w4_asym(const RadParam* p, int n_p) {
static int moe_w4_nl(const RadParam* p, int n_p) {
const char* d = r4d_pgets(p, n_p, "dtype");
return d && (std::strcmp(d, "w4nla8h") == 0 || std::strcmp(d, "w4nl64a8h") == 0 ||
std::strcmp(d, "w4nl32a8h") == 0 || std::strcmp(d, "w5nl64a8h") == 0);
std::strcmp(d, "w4nl32a8h") == 0 || std::strcmp(d, "w5nl64a8h") == 0 ||
std::strcmp(d, "w4nl64a8i8h") == 0 || std::strcmp(d, "w4nl32a8i8h") == 0);
}
/* The `a8i8` names are the same stored planes met by an int8 activation (moe_gemm_w4a8i8):
* `w4a8i8` and `w4a8i8h` are w4a8's and w4a8h's, `w4nl64a8i8h` and `w4nl32a8i8h` the subgroup-scaled
* codebook's. The hooks answer for them as for the names they stand beside. */
/* `w5nl64a8h` is w4nl64a8h at five bits: `u5*fp8_e4m3[1x64]*f32[*x*]/fwht128`, codes indexing
* libquant's 32-entry `table=w5nl`. Its codes view relays each row into R4D_DT_MOEW5 (the low four
* bits of every code as w4nla8h's nibble plane, then each code's high bit, the sign, one dword per
@@ -198,12 +204,14 @@ static bool moe_w5(const RadParam* p, int n_p) {
static int moe_w4_g64(const RadParam* p, int n_p) {
const char* d = r4d_pgets(p, n_p, "dtype");
if (!d) return 0;
return (std::strcmp(d, "w4nl64a8h") == 0 || std::strcmp(d, "w5nl64a8h") == 0) ? 2
: std::strcmp(d, "w4nl32a8h") == 0 ? 4 : 0;
return (std::strcmp(d, "w4nl64a8h") == 0 || std::strcmp(d, "w5nl64a8h") == 0 ||
std::strcmp(d, "w4nl64a8i8h") == 0) ? 2
: (std::strcmp(d, "w4nl32a8h") == 0 || std::strcmp(d, "w4nl32a8i8h") == 0) ? 4 : 0;
}
static int moe_w4_rot(const RadParam* p, int n_p) {
const char* d = r4d_pgets(p, n_p, "dtype");
return d && (std::strcmp(d, "w4a8h") == 0 || moe_w4_nl(p, n_p));
return d && (std::strcmp(d, "w4a8h") == 0 || std::strcmp(d, "w4a8i8h") == 0 ||
moe_w4_nl(p, n_p));
}
/* ================================================================== moe_gemm_q's two classes
@@ -568,63 +576,8 @@ namespace {
constexpr int GV_PAIRS_OPERAND = 1;
constexpr long long GV_GROUP = 128;
int gv_pairs_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
if (!out || !pl) return RAD_E_INVAL;
if (operand != GV_PAIRS_OPERAND) return RAD_E_UNSUPPORTED;
const long long K = r4d_pgeti_or(p, n_p, "n", 0);
if (K <= 0 || K % GV_GROUP || !selects(enc, sel, n, "t.pairs") || pl[0].rank != 2 ||
pl[0].dtype != RAD_I32 || pl[0].shape[1] != K) return RAD_E_SHAPE;
fill(out, "r4d.givens.pairs", RAD_I32, pl[0].shape[0], K, pl[0].shape[0] * K * 4);
return RAD_OK;
}
/* Every row (a stage of a part) is, group by group, a perfect matching of the group's columns. */
bool gv_pairs_ok(const int32_t* pairs, long long rows, long long K) {
for (long long r = 0; r < rows; ++r)
for (long long g = 0; g < K; g += GV_GROUP) {
bool seen[GV_GROUP] = {};
for (long long i = 0; i < GV_GROUP; ++i) {
const long long c = (long long)pairs[r * K + g + i] - g;
if (c < 0 || c >= GV_GROUP || seen[c]) return false;
seen[c] = true;
}
}
return true;
}
} /* namespace */
extern "C" int r4d_rad_layout_givens_pairs(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
return gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, out);
}
extern "C" int r4d_rad_relayout_givens_pairs(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) {
RadLayout L;
const int rc = gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, &L);
if (rc != RAD_OK) return rc;
if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
if (!gv_pairs_ok((const int32_t*)pl[0].data, L.shape[0], L.shape[1])) return RAD_E_FORMAT;
std::memcpy(dst, pl[0].data, (size_t)L.bytes);
return RAD_OK;
}
extern "C" int r4d_rad_unrelayout_givens_pairs(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const void* src, int64_t src_bytes,
const RadTensor* pl, int n) {
RadLayout L;
const int rc = gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, &L);
if (rc != RAD_OK) return rc;
if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
std::memcpy(pl[0].data, src, (size_t)L.bytes);
return RAD_OK;
}
/* ---- givens_dense: ParoQuant's rotation as one dense matrix per (part, group).
*
* The dense kernel (r4d_givens_dense.hip) applies a part's Givens stages over each group of 128
@@ -803,21 +756,21 @@ extern "C" int r4d_rad_relayout_w2a8(const RadParam* p, int n_p, int operand,
const int rc = w2_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g);
if (rc != RAD_OK) return rc;
if (dst_bytes != L.bytes) return RAD_E_SHAPE;
std::memset(dst, 0, (size_t)dst_bytes);
if (operand == Q_BSCALE) {
std::memset(dst, 0, (size_t)dst_bytes);
sz_write(g, pl, -1, (uint32_t*)dst);
return RAD_OK;
}
uint32_t* wq = (uint32_t*)dst;
for (long long nn = 0; nn < g.N; ++nn) {
const uint8_t* row = pdata(pl[0]) + nn * (g.K / 4);
for (long long k = 0; k < g.K; ++k) {
long long w;
int f;
w2_slot(g, nn, k, &w, &f);
wq[w] |= (uint32_t)((row[k >> 2] >> (2 * (k & 3))) & 3) << (2 * f);
}
}
/* A tile at a time (w2_slot's order, r4d_hsimd::w2a8_tile), every stored byte written: a
* draft head of 2-bit codes is a 300 MiB weight that a code at a time took 2.7 s, the last
* piece of a load or restore to finish. */
const long long kpb = g.K / 128, rb = g.K / 4, tile = R4D_NTILE * rb;
const uint8_t* codes = pdata(pl[0]);
uint8_t* out = (uint8_t*)dst;
r4d_par::par_for(g.N / R4D_NTILE, std::max(1ll, (16ll << 20) / tile), [&](long long lo, long long hi) {
for (long long t = lo; t < hi; ++t)
r4d_hsimd::w2a8_tile(codes + t * tile, rb, kpb, out + t * tile);
});
return RAD_OK;
}
@@ -894,13 +847,6 @@ int mx_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
return RAD_OK;
}
long long mx_slot(const WGeom& g, long long n, long long k) {
const long long ks = g.K / 16;
const long long t = n / R4D_NTILE, r = n % R4D_NTILE;
const long long ksi = k / 16, kin = k % 16;
const long long lh = kin / 8, bin = (kin % 8) / 2;
return ((t * ks + ksi) * R4D_WAVE + lh * 16 + r) * 4 + bin;
}
} /* namespace */
extern "C" int r4d_rad_layout_mxfp4(const RadParam* p, int n_p, int operand,
@@ -917,57 +863,34 @@ extern "C" int r4d_rad_relayout_mxfp4(const RadParam* p, int n_p, int operand,
const int rc = mx_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g);
if (rc != RAD_OK) return rc;
if (dst_bytes != L.bytes) return RAD_E_SHAPE;
std::memset(dst, 0, (size_t)dst_bytes);
const long long nblk = g.K / R4D_MXFP4_GROUP;
uint8_t* d = (uint8_t*)dst;
if (operand == Q_BSCALE || operand == Q_BREF) {
const uint8_t* e = pdata(pl[0]);
if (operand == Q_BSCALE) {
r4d_hsimd::byte_transpose(e, g.N, nblk, d);
return RAD_OK;
}
for (long long nn = 0; nn < g.N; ++nn) {
uint8_t mx = 0;
for (long long b = 0; b < nblk; ++b) {
const uint8_t v = e[nn * nblk + b];
if (operand == Q_BSCALE) d[b * g.N + nn] = v;
if (v > mx) mx = v;
}
if (operand == Q_BREF) d[nn] = mx;
for (long long b = 0; b < nblk; ++b) mx = std::max(mx, e[nn * nblk + b]);
d[nn] = mx;
}
return RAD_OK;
}
for (long long nn = 0; nn < g.N; ++nn) {
const uint8_t* row = pdata(pl[0]) + nn * (g.K / 2);
for (long long k = 0; k < g.K; ++k) {
const uint8_t code = (uint8_t)((row[k >> 1] >> (4 * (k & 1))) & 0xF);
const long long idx = mx_slot(g, nn, k);
if (k & 1) d[idx] = (uint8_t)((d[idx] & 0x0Fu) | (uint32_t)(code << 4));
else d[idx] = (uint8_t)((d[idx] & 0xF0u) | code);
}
}
/* mx_slot moves each 16-code group's halves, four bytes each, whole: half lh of group ksi of
* row r is dword 2 ksi + lh of the row, and goes to dword (2 ksi + lh) * 16 + r of the n-tile.
* So a tile is a transpose of its 16 rows of K / 8 dwords, every stored byte written. */
const long long words = g.K / 8, tile = R4D_NTILE * words;
const uint32_t* codes = (const uint32_t*)pdata(pl[0]);
uint32_t* out = (uint32_t*)dst;
r4d_par::par_for(g.N / R4D_NTILE, std::max(1ll, (4ll << 20) / tile), [&](long long lo, long long hi) {
for (long long t = lo; t < hi; ++t)
r4d_hsimd::dword_transpose16(codes + t * tile, words, words, out + t * tile);
});
return RAD_OK;
}
/* gemm_nt_q_gated_mx's weights are gemm_nt_q's mxfp4a8 planes in the same stored forms, but its
* `b_ref` is operand 4, where gemm_nt_q has `y`: mapped to gemm_nt_q's index, so both ops ask for
* the reference plane in one form and the loader stores it once. */
static int mx_gated_operand(int operand) {
return operand == Q_B || operand == Q_BSCALE ? operand : operand == 4 ? Q_BREF : -1;
}
extern "C" int r4d_rad_layout_mxfp4_gated(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
const int o = mx_gated_operand(operand);
return o < 0 ? RAD_E_UNSUPPORTED : r4d_rad_layout_mxfp4(p, n_p, o, enc, sel, pl, n, out);
}
extern "C" int r4d_rad_relayout_mxfp4_gated(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) {
const int o = mx_gated_operand(operand);
return o < 0 ? RAD_E_UNSUPPORTED
: r4d_rad_relayout_mxfp4(p, n_p, o, enc, sel, pl, n, dst, dst_bytes);
}
/* ---- M2XFP4: the M2 analogue of MXFP4 above, the paper's weight-side Sg-EM (arXiv 2601.19213
* §4.4.2). The quantiser's own scheme "m2xfp4", three TILED planes over the same 32-column groups:
*
@@ -991,117 +914,9 @@ extern "C" int r4d_rad_relayout_mxfp4_gated(const RadParam* p, int n_p, int oper
* the meta plane. The GEMM reads the planes as for an unrotated weight; the rotation is applied to
* the activation (givens_dense_quant), whose tables are separate weight operands. */
namespace {
/* The scheme's three planes, whichever kind of weight carries them. */
bool m2_planes(const RadEncoding* enc) {
if (!enc || !rad_enc_is(enc, "m2xfp4")) return false;
if (enc->plane[0].dtype != RAD_FP4E2M1 || enc->plane[0].block[0] != 1 ||
enc->plane[0].block[1] != 1)
return false;
const int s = rad_enc_find(enc, "scale"), m = rad_enc_find(enc, "meta");
if (s < 0 || m < 0) return false;
if (enc->plane[s].dtype != RAD_E8M0 || enc->plane[s].kind != RAD_PLANE_TILED ||
enc->plane[s].block[0] != 1 || enc->plane[s].block[1] != R4D_MXFP4_GROUP)
return false;
if (enc->plane[m].dtype != RAD_U8 || enc->plane[m].kind != RAD_PLANE_TILED ||
enc->plane[m].block[0] != 1 || enc->plane[m].block[1] != R4D_MXFP4_GROUP)
return false;
return true;
}
/* A rotated one: the three planes in the basis of a "givens" transform, whose tables are views of
* the weight's planes. Only the presence and the dtype of the tables is checked here (the arch
* declares them as operands the rotation op reads); any other transform would decode to other
* numbers, so it is refused. */
bool m2_paro_enc(const RadEncoding* enc, long long K) {
if (!enc || std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) return false;
if (enc->n_planes < 6 || !rad_enc_valid(enc) || !m2_planes(enc)) return false;
const int p = rad_enc_find(enc, "t.pairs"), an = rad_enc_find(enc, "t.angle"),
sc = rad_enc_find(enc, "t.scale");
if (p < 0 || an < 0 || sc < 0) return false;
if (enc->plane[p].dtype != RAD_I32 || enc->plane[an].dtype != RAD_F32 ||
enc->plane[sc].dtype != RAD_F32)
return false;
/* The quantiser rotates whole groups of 128 columns, one scale per group. */
return K % 128 == 0 && enc->plane[p].extent[1] == K;
}
int m2_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out, WGeom* gout) {
if (!out || !pl) return RAD_E_INVAL;
WGeom g;
int rc = wgeom(p, n_p, R4D_MXFP4_GROUP, &g);
if (rc != RAD_OK) return rc;
if (g.group != R4D_MXFP4_GROUP || g.K % 16) return RAD_E_SHAPE;
if (!m2_planes(enc)) return RAD_E_DTYPE;
const bool plain = !enc->transform[0] && enc->n_planes == 3;
if (!plain && !m2_paro_enc(enc, g.K)) return RAD_E_DTYPE;
if (gout) *gout = g;
const long long nblk = g.K / R4D_MXFP4_GROUP;
if (operand == Q_BSCALE || operand == Q_BREF) {
if (!selects(enc, sel, n, "scale") || !dims(pl[0], g.N, nblk)) return RAD_E_SHAPE;
if (operand == Q_BSCALE) fill(out, "r4d.mxfp4.e8m0", R4D_DT_E8M0, nblk, g.N, nblk * g.N);
else fill(out, "r4d.mxfp4.wref", R4D_DT_E8M0, g.N, 1, g.N);
return RAD_OK;
}
if (operand != Q_B) return RAD_E_UNSUPPORTED;
/* The weight operand takes codes and meta: the codes go to fragment order, the meta to the
* stored blob's tail. */
if (!selects(enc, sel, n, "codes", "meta") || !dims(pl[0], g.N, g.K) ||
!dims(pl[1], g.N, nblk))
return RAD_E_SHAPE;
fill(out, "r4d.m2xfp4.frag.g32.meta", R4D_DT_M2XFP4_FRAG, g.N, g.K,
g.N * g.K / 2 + nblk * g.N);
return RAD_OK;
}
} /* namespace */
extern "C" int r4d_rad_layout_m2xfp4(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
return m2_enc_layout(p, n_p, operand, enc, sel, pl, n, out, nullptr);
}
extern "C" int r4d_rad_relayout_m2xfp4(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) {
RadLayout L;
WGeom g;
const int rc = m2_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g);
if (rc != RAD_OK) return rc;
if (dst_bytes != L.bytes) return RAD_E_SHAPE;
std::memset(dst, 0, (size_t)dst_bytes);
const long long nblk = g.K / R4D_MXFP4_GROUP;
uint8_t* d = (uint8_t*)dst;
if (operand == Q_BSCALE || operand == Q_BREF) {
const uint8_t* e = pdata(pl[0]);
for (long long nn = 0; nn < g.N; ++nn) {
uint8_t mx = 0;
for (long long b = 0; b < nblk; ++b) {
const uint8_t v = e[nn * nblk + b];
if (operand == Q_BSCALE) d[b * g.N + nn] = v;
if (v > mx) mx = v;
}
if (operand == Q_BREF) d[nn] = mx;
}
return RAD_OK;
}
/* Codes to fragment order (mx_slot, as r4d_rad_relayout_mxfp4), then the meta plane appended:
* canonical [N][K/32] read into stored [K/32][N]. */
const uint8_t* meta = pdata(pl[1]);
uint8_t* md = d + g.N * g.K / 2;
for (long long nn = 0; nn < g.N; ++nn) {
const uint8_t* row = pdata(pl[0]) + nn * (g.K / 2);
for (long long k = 0; k < g.K; ++k) {
const uint8_t code = (uint8_t)((row[k >> 1] >> (4 * (k & 1))) & 0xF);
const long long idx = mx_slot(g, nn, k);
if (k & 1) d[idx] = (uint8_t)((d[idx] & 0x0Fu) | (uint32_t)(code << 4));
else d[idx] = (uint8_t)((d[idx] & 0xF0u) | code);
}
for (long long b = 0; b < nblk; ++b) md[b * g.N + nn] = meta[nn * nblk + b];
}
return RAD_OK;
}
/* ---- the MoE experts. I4 at BF16 scales per 128 K uses 16-column/64-K fragment tiles,
* coalescing a wave's register loads without another copy of the weight. The staged prefill
* kernels read the same tiles back in row segments. Subgroup-scaled codebooks keep their
@@ -1176,8 +991,8 @@ bool moew5_table_is_kernels(const RadTensor& t) {
* nibble i of dword g; stored, byte b holds element b low and b+4 high (nibbles n0 n4 n1 n5 n2 n6
* n3 n7, a perfect shuffle of the dword's halves). Swapping the middle bytes, then each half's
* middle nibbles, produces it; each step swaps two fields, so the steps in reverse order undo it.
* Every routed expert passes through here at load, so a nibble-at-a-time loop would dominate the
* load's CPU time. */
* The load's forward pass is r4d_hsimd's vector form of the same steps; this one serves the
* inverse of the fragment tiles. */
inline uint64_t moew4_bytes(uint64_t x) {
return (x & 0xFF0000FFFF0000FFull) | ((x & 0x0000FF000000FF00ull) << 8) |
((x >> 8) & 0x0000FF000000FF00ull);
@@ -1187,49 +1002,45 @@ inline uint64_t moew4_nibbles(uint64_t x) {
((x >> 4) & 0x00F000F000F000F0ull);
}
/* Permutes `bytes` of codes (a multiple of four) from `s` to `d`, forward or back. */
void moew4_permute(const uint8_t* s, uint8_t* d, int64_t bytes, bool forward) {
int64_t i = 0;
for (; i + 8 <= bytes; i += 8) {
uint64_t x;
std::memcpy(&x, s + i, 8);
x = forward ? moew4_nibbles(moew4_bytes(x)) : moew4_bytes(moew4_nibbles(x));
std::memcpy(d + i, &x, 8);
}
if (i < bytes) { /* one dword left; no step crosses dwords */
uint32_t w;
std::memcpy(&w, s + i, 4);
uint64_t x = w;
x = forward ? moew4_nibbles(moew4_bytes(x)) : moew4_bytes(moew4_nibbles(x));
w = (uint32_t)x;
std::memcpy(d + i, &w, 4);
}
/* Permutes `bytes` of codes (a multiple of four) from `s` to `d`, forward or back: vectorised
* by CPU level (r4d_hsimd.h), since every routed expert passes through here at load. */
inline void moew4_permute(const uint8_t* s, uint8_t* d, int64_t bytes, bool forward) {
r4d_hsimd::moew4_permute(s, d, bytes, forward);
}
/* Signed-I4 fragment tiles: [N/16][K/64][lane=32][step=4] dwords. A lane owns column
* lane%16 and K bytes step*16 + (lane/16)*8 .. +7, in the nibble order above. Two adjacent
* canonical dwords supply the low/high lane halves; the inverse restores the exact source codes.
* No precision or byte-count change, and no second resident weight plane. */
void moew4_frag_permute(const uint8_t* src, uint8_t* dst, int64_t N, int64_t K, bool forward) {
if (forward) {
/* A row at a time: its codes permuted in one vector pass, then its dwords dealt to the
* lanes, low halves at `packed` and high ones 256 bytes on. */
std::vector<uint8_t> row((size_t)(K / 2));
for (int64_t r = 0; r < N; ++r) {
moew4_permute(src + (size_t)(r * (K / 2)), row.data(), K / 2, true);
const int64_t nt = r / 16, n = r % 16;
for (int64_t kb = 0; kb < K / 64; ++kb)
for (int64_t s = 0; s < 4; ++s) {
const size_t packed = (size_t)(((nt * (K / 64) + kb) * 32 + n) * 16 + s * 4);
const uint8_t* x = row.data() + kb * 32 + s * 8;
std::memcpy(dst + packed, x, 4);
std::memcpy(dst + packed + 256, x + 4, 4);
}
}
return;
}
/* Back (the oracle's inverse): a dword pair at a time. */
for (int64_t nt = 0; nt < N / 16; ++nt)
for (int64_t kb = 0; kb < K / 64; ++kb)
for (int64_t n = 0; n < 16; ++n)
for (int64_t s = 0; s < 4; ++s) {
const size_t canonical = (size_t)((nt * 16 + n) * (K / 2) + kb * 32 + s * 8);
const size_t packed = (size_t)(((nt * (K / 64) + kb) * 32 + n) * 16 + s * 4);
uint64_t x;
if (forward) {
std::memcpy(&x, src + canonical, sizeof x);
x = moew4_nibbles(moew4_bytes(x));
const uint32_t lo = (uint32_t)x, hi = (uint32_t)(x >> 32);
std::memcpy(dst + packed, &lo, sizeof lo);
std::memcpy(dst + packed + 256, &hi, sizeof hi);
} else {
uint32_t lo, hi;
std::memcpy(&lo, src + packed, sizeof lo);
std::memcpy(&hi, src + packed + 256, sizeof hi);
x = moew4_bytes(moew4_nibbles((uint64_t)lo | ((uint64_t)hi << 32)));
std::memcpy(dst + canonical, &x, sizeof x);
}
uint32_t lo, hi;
std::memcpy(&lo, src + packed, sizeof lo);
std::memcpy(&hi, src + packed + 256, sizeof hi);
const uint64_t x = moew4_bytes(moew4_nibbles((uint64_t)lo | ((uint64_t)hi << 32)));
std::memcpy(dst + canonical, &x, sizeof x);
}
}
@@ -1395,38 +1206,22 @@ extern "C" int r4d_rad_unrelayout_moe_w4_mod4(const RadParam* p, int n_p, int op
return moew4_unrelayout_by(moe_view_mod4, p, n_p, operand, enc, sel, src, src_bytes, pl, n);
}
extern "C" int r4d_rad_layout_moe_mxfp4(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout*) {
if (operand != 2 && operand != 3 && operand != 6 && operand != 7) return RAD_E_UNSUPPORTED;
if (!r4d_enc::affine(enc, RAD_FP4E2M1, RAD_E8M0, 1, 32)) return RAD_E_DTYPE;
/* moe_gemm_i8a8's experts: each class's int8 codes and row scales as stored. */
extern "C" int r4d_rad_layout_moe_i8(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
MoeView v;
const int rc = moe_view(p, n_p, operand, &v);
if (rc != RAD_OK) return rc;
const long long N = r4d_pgeti_or(v.p, v.n, "N", 0), K = r4d_pgeti_or(v.p, v.n, "K", 0);
const bool scale = operand == 3 || operand == 7;
if (n != 1 || !pl || !sel || !selects(enc, sel, n, scale ? "scale" : "codes") ||
!dims(pl[0], N, scale ? K / 32 : K) || K % 128) return RAD_E_SHAPE;
/* The exact selected canonical plane, not a relayout: it remains readable in place
* from the container or a mapped host pool. Unsupported is the ABI spelling for that. */
return RAD_E_UNSUPPORTED;
return rc != RAD_OK ? rc : r4d_rad_layout_i8_rowmajor(v.p, v.n, v.operand, enc, sel, pl, n,
out);
}
extern "C" int r4d_rad_layout_moe_fp8(const RadParam* p, int n_p, int operand,
extern "C" int r4d_rad_layout_moe_i8_mod4(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
MoeView v;
const int rc = moe_view(p, n_p, operand, &v);
return rc != RAD_OK ? rc : r4d_rad_layout_fp8_rowmajor(v.p, v.n, v.operand, enc, sel, pl,
n, out);
}
extern "C" int r4d_rad_layout_moe_fp8_mod4(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
MoeView v;
const int rc = moe_view_mod4(p, n_p, operand, &v);
return rc != RAD_OK ? rc : r4d_rad_layout_fp8_rowmajor(v.p, v.n, v.operand, enc, sel, pl,
n, out);
return rc != RAD_OK ? rc : r4d_rad_layout_i8_rowmajor(v.p, v.n, v.operand, enc, sel, pl, n,
out);
}
/* ---- conv2d_nhwc: PyTorch's [cout][cin][k][k] stored tap-major, [cout][k][k][cin].
@@ -1478,10 +1273,14 @@ extern "C" int r4d_rad_relayout_conv_tap(const RadParam* p, int n_p, int operand
const uint16_t* s = (const uint16_t*)pl[0].data;
uint16_t* d = (uint16_t*)dst;
const long long kk = k * k;
for (long long o = 0; o < co; ++o)
for (long long c = 0; c < ci; ++c)
for (long long t = 0; t < kk; ++t)
d[(o * kk + t) * ci + c] = s[(o * ci + c) * kk + t];
/* Written in order, a tap's channels at a time: an output channel's [cin][k * k] block is a
* few KiB the reads stay inside, where storing a channel's taps cin apart missed every time. */
for (long long o = 0; o < co; ++o) {
const uint16_t* so = s + o * ci * kk;
uint16_t* dt = d + o * kk * ci;
for (long long t = 0; t < kk; ++t, dt += ci)
for (long long c = 0; c < ci; ++c) dt[c] = so[c * kk + t];
}
return RAD_OK;
}
+1 -1
View File
@@ -246,7 +246,7 @@ __device__ __forceinline__ void vocab_tile(const Head& h, const Cls& cl, uint32_
for (uint32_t p = 0; p < kU; ++p) pf[p] = D::fetch(c.W, c.nkb, arow, p, lane, alive);
/* the computed code's A and B, after its 2^16 values (kept for the unrelayout) */
constexpr Form fm{ F::KIND, F::B, F::LV, F::L, F::LRB, F::SC, 0 };
const uint32_t* const ab = (const uint32_t*)(c.W + aux_off(fm, c.N, (int64_t)K) + (1 << 16));
const uint32_t* const ab = (const uint32_t*)(c.W + aux_off(fm, c.N, (int64_t)K));
const uint32_t mA = ab[0], mB = ab[1];
for (uint32_t k0 = 0; k0 < K; k0 += FK) {
+37 -8
View File
@@ -53,7 +53,9 @@
#include <map>
#include <mutex>
#include <utility>
#include <vector>
#include "r4d_keyed.h"
#include "r4d_plugin.h"
#include "r4d_launch.h"
#include "rad_plugin.h"
@@ -962,23 +964,50 @@ static int z_fan(int64_t base, int64_t S, int64_t M, int64_t tile) {
* that could overlap never share a block; the reducer leaves every counter zero. A block too small
* for a launch is replaced by a larger one and the old one is kept, since a recorded pass may
* still name it. */
/* Every block made for a (device, t), the current one last; all of them go when the memory `t`
* lives in is freed (r4d_keyed.h). */
struct ShrinkBlocks { std::vector<unsigned*> all; int64_t cap = 0; };
static std::mutex g_shrink_mu;
static std::map<std::pair<int, const char*>, ShrinkBlocks> g_shrink;
static void shrink_freed(const char* lo, const char* hi) {
std::vector<std::pair<int, unsigned*>> gone;
{
std::lock_guard<std::mutex> lk(g_shrink_mu);
for (auto it = g_shrink.begin(); it != g_shrink.end();) {
if (it->first.second >= lo && it->first.second < hi) {
for (unsigned* p : it->second.all) gone.push_back({ it->first.first, p });
it = g_shrink.erase(it);
} else {
++it;
}
}
}
int was = 0;
(void)hipGetDevice(&was);
for (auto& [dev, p] : gone) {
(void)hipSetDevice(dev);
(void)hipFree(p);
}
(void)hipSetDevice(was);
}
[[maybe_unused]] static const int g_shrink_reg = r4d::on_freed(shrink_freed);
static unsigned* shrink_ctr(const void* t, int64_t n, RadStream stream) {
static std::mutex mu;
static std::map<std::pair<int, const void*>, std::pair<unsigned*, int64_t>> blocks;
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
std::lock_guard<std::mutex> lk(mu);
const auto key = std::make_pair(dev, t);
auto it = blocks.find(key);
if (it != blocks.end() && it->second.second >= n) return it->second.first;
int64_t cap = it != blocks.end() ? 2 * it->second.second : 4096;
std::lock_guard<std::mutex> lk(g_shrink_mu);
ShrinkBlocks& b = g_shrink[std::make_pair(dev, static_cast<const char*>(t))];
if (!b.all.empty() && b.cap >= n) return b.all.back();
int64_t cap = !b.all.empty() ? 2 * b.cap : 4096;
while (cap < n) cap *= 2;
void* p = nullptr;
if (hipMalloc(&p, (size_t)cap * sizeof(unsigned)) != hipSuccess) return nullptr;
/* On the launch's own stream, so the zeros land before the kernel that counts on them. */
if (hipMemsetAsync(p, 0, (size_t)cap * sizeof(unsigned), (hipStream_t)stream) != hipSuccess)
return nullptr;
blocks[key] = std::make_pair((unsigned*)p, cap);
b.all.push_back((unsigned*)p);
b.cap = cap;
return (unsigned*)p;
}
-129
View File
@@ -1,129 +0,0 @@
// Shared device code for the M2XFP4 GEMMs (r4d_gemm_m2xfp4a8_decode, r4d_gemm_m2xfp4a8_tiled):
// the folded-magnitude table and the eight-element unpack that reads it. The M2 analogue of
// r4d_mxfp4.h: the same e2m1 codes and E8M0 exponents, plus one more per-group byte of weight-side
// Sg-EM metadata (arXiv 2601.19213 §4.4.2), which folds the same way -- through a table, with a
// v_perm_b32 per half-word.
//
// The container ("m2xfp4", the quantiser's scheme) stores, per group of 32 K, an E8M0 exponent byte
// whose adaptive bias b in {-1,0,1} is already folded in, and a meta byte holding one two-bit
// subgroup multiplier k_s per eight columns, s = columns [8s, 8s+8) of the group: the stored byte's
// bits [2s, 2s+2). The exact weight is
//
// w = e2m1mag[c & 7] * sign(c) * 2^(scale - 127) * (1 + k_s / 4)
//
// with e2m1mag = {0, .5, 1, 1.5, 2, 3, 4, 6} and k -> {1.0, 1.25, 1.5, 1.75}. The fold of
// r4d_gemm_mxfp4a8_nt_m64.hip applies to it unchanged: d = Wref[n] - E8M0[n][blk] goes through the
// table, 2^(Wref[n]-127) once in the epilogue. Wref[n] is still the row's largest exponent byte,
// so d >= 0 holds for every block; what the meta adds is bounded the same way -- the largest
// element a table cell holds is 6 * 1.75 * 2^-d = 10.5 * 2^-d, an E4M3 normal for every d >= 0, so
// no cell saturates and the fold is exact in its exponent at every block.
#pragma once
#include "r4d_mxfp4.h" // the fold clamp r4d_mxfp4_fold_d, the carried-scale reader, GROUP
// kM2xfp4Mag[d][k] is the eight e2m1 magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} scaled by
// (1 + k/4) * 2^-d, as packed e4m3 bytes (low word, high word), indexed by the 3-bit magnitude
// through v_perm_b32 -- kMxfp4Mag's table with a second index. Entries are the round-to-nearest-even
// e4m3 of the product, matching the hardware conversion.
//
// Exactness, per magnitude and k, in the normal range of e4m3 (every entry here down to its
// subnormal floor behaves exactly like r4d_mxfp4.h's table one binade earlier, where the 2^-9 step
// is coarse; the entries flush the same way and the sums they miss are invisible next to the
// accumulator):
// - k = 0 is r4d_mxfp4.h's kMxfp4Mag row, byte for byte.
// - k = 1, 2: exact. The products' mantissas (1.25, 1.5 and 1.75 times a magnitude whose own
// mantissa is 1.0 or 1.1) take at most the three e4m3 mantissa bits, at every d while the
// value is normal.
// - k = 3 (x1.75): the even-mantissa magnitudes {0, .5, 1, 2, 4} stay exact (1.11 x 1.0); the odd
// ones {1.5, 3, 6} land on 1.0101, four mantissa bits, and round to the tie's even side -- 2.5,
// 5 and 10 scaled by 2^-d. That is 2^-4.4 relative error on those elements and nothing on the
// rest, accepted here: the CPU decode (and the reference) stay exact, and 6 * 1.75 = 10.5 at
// d = 0 is what the row-maximum bound above has to fit, which it does.
//
// Static: each kernel's code object carries its own copy.
static __device__ __constant__ unsigned int kM2xfp4Mag[16][4][2] = {
{{0x3c383000u, 0x4c484440u}, {0x3f3a3200u, 0x4f4a4742u}, {0x413c3400u, 0x514c4944u},
{0x423e3600u, 0x524e4a46u}},
{{0x34302800u, 0x44403c38u}, {0x37322a00u, 0x47423f3au}, {0x39342c00u, 0x4944413cu},
{0x3a362e00u, 0x4a46423eu}},
{{0x2c282000u, 0x3c383430u}, {0x2f2a2200u, 0x3f3a3732u}, {0x312c2400u, 0x413c3934u},
{0x322e2600u, 0x423e3a36u}},
{{0x24201800u, 0x34302c28u}, {0x27221a00u, 0x37322f2au}, {0x29241c00u, 0x3934312cu},
{0x2a261e00u, 0x3a36322eu}},
{{0x1c181000u, 0x2c282420u}, {0x1f1a1200u, 0x2f2a2722u}, {0x211c1400u, 0x312c2924u},
{0x221e1600u, 0x322e2a26u}},
{{0x14100800u, 0x24201c18u}, {0x17120a00u, 0x27221f1au}, {0x19140c00u, 0x2924211cu},
{0x1a160e00u, 0x2a26221eu}},
{{0x0c080400u, 0x1c181410u}, {0x0f0a0500u, 0x1f1a1712u}, {0x110c0600u, 0x211c1914u},
{0x120e0700u, 0x221e1a16u}},
{{0x06040200u, 0x14100c08u}, {0x08050200u, 0x17120f0au}, {0x09060300u, 0x1914110cu},
{0x0a070400u, 0x1a16120eu}},
{{0x03020100u, 0x0c080604u}, {0x04020100u, 0x0f0a0805u}, {0x04030200u, 0x110c0906u},
{0x05040200u, 0x120e0a07u}},
{{0x02010000u, 0x06040302u}, {0x02010100u, 0x08050402u}, {0x02020100u, 0x09060403u},
{0x03020100u, 0x0a070504u}},
{{0x01000000u, 0x03020201u}, {0x01010000u, 0x04020201u}, {0x01010000u, 0x04030202u},
{0x01010000u, 0x05040302u}},
{{0x00000000u, 0x02010100u}, {0x00000000u, 0x02010101u}, {0x01000000u, 0x02020101u},
{0x01000000u, 0x03020101u}},
{{0x00000000u, 0x01000000u}, {0x00000000u, 0x01010000u}, {0x00000000u, 0x01010100u},
{0x00000000u, 0x01010100u}},
{{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x01000000u},
{0x00000000u, 0x01000000u}},
{{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
{0x00000000u, 0x00000000u}},
{{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
{0x00000000u, 0x00000000u}},
};
// The two-bit field of a meta byte that covers `koff`, an element offset inside a 32-column group
// that is a multiple of 8 (which the kernels' staging offsets all are): the subgroup s = koff / 8,
// bits [2s, 2s+2). A thread whose eight elements start at koff takes this shift once and one meta
// byte per (row, block) alongside the exponent byte.
static __device__ __forceinline__ int r4d_m2xfp4_kshift(int koff) {
return 2 * ((koff >> 3) & 3);
}
// Eight e2m1 codes (four packed 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), with the exponent difference `d` and the
// subgroup multiplier `k` folded in. r4d_mxfp4_unpack8_t with the [d][k] table row; see there. A
// caller that already holds the row, e.g. in an LDS copy (the tiled kernel's sMag, which keeps the
// lookup off the global load counter the weight and activation loads wait on), calls
// r4d_mxfp4_unpack8_t with it directly.
static __device__ __forceinline__ void r4d_m2xfp4_unpack8(unsigned int wv, int d, int k,
unsigned int* lo, unsigned int* hi) {
r4d_mxfp4_unpack8_t(wv, kM2xfp4Mag[d][k][0], kM2xfp4Mag[d][k][1], lo, hi);
}
// ---- The raw entry points, kept beside the table rather than in r4d.h so the M2XFP4 kernels'
// whole surface is in their own files (the plugin ABI's entries are r4d_plugin.h's).
extern "C" {
// M2XFP4 weight, fp8 activation: the MXFP4 rows at the paper's weight-side Sg-EM (arXiv 2601.19213
// §4.4.2). Beside each E8M0 exponent per 32 K (whose adaptive bias the quantiser already folded
// in) the weight carries one meta byte per (row, 32 of K): four two-bit subgroup multipliers, the
// subgroup s covering columns [8s, 8s+8) of the group, value k_s in 0..3. The exact weight is
// e2m1mag[c&7] * sign(c) * 2^(scale-127) * (1 + k_s/4); r4d_m2xfp4.h folds it into the same e4m3
// staging bytes through a second table index, so the fold, the Wref epilogue and the activation
// scale grids are the MXFP4 kernels'. `wm` is the [K/32][N] meta plane, `ldws` its row pitch (0 =
// N); the k=3 multipliers on odd-mantissa codes round as r4d_m2xfp4.h documents, up to 2^-4.4
// relative.
void r4d_gemm_m2xfp4a8_tiled(long at, long ascale, long wq, long ws, long wm, long wref, long c,
int M, int K, int N, int TN, int as_group, int as_rs, long stream,
int ldws = 0, int ldc = 0);
void r4d_m2xfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda = 0);
long r4d_m2xfp4a8_tile_a_bytes(int M, int K);
int r4d_gemm_m2xfp4a8_tiled_group(void);
// The decode band (M <= 128). The plugin ABI's r4d_rad_gemm_m2xfp4a8_decode serves it in the
// engine, the split partial in the op's scratch as for mxfp4a8; this raw entry takes that scratch
// from the caller: KS * M * N * 4 bytes when KS > 1 (a KS of 2 runs as 4 where a 128-wide slab
// would run past K), 16 * M * N * 4 when KS is 0 (the widest split the rule picks), null only at
// KS 1. The arrival counters are the unit's own, one block per output buffer.
void r4d_gemm_m2xfp4a8_decode(long a, long ascale, long wq, long ws, long wm, long wref, long c,
int M, int K, int N, int KS, int BK, int NT, int as_group,
int as_rs, long scratch, long scratch_bytes, long stream,
int lda = 0, int ldws = 0, int ldc = 0);
int r4d_gemm_m2xfp4a8_decode_max_m(void);
} // extern "C"
+344 -169
View File
@@ -351,10 +351,12 @@ __global__ __launch_bounds__(kThreads) void rmsnorm_p_kernel(
// `b_step` 0 reads one element per row; with b_ld 0 too, a scalar for the whole op. `div` (add
// only) divides the sum after its rounding and rounds again, the last step of a mean summed
// pairwise; 1 is the plain sum.
__global__ __launch_bounds__(kThreads) void binary_kernel(
const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, uint16_t* __restrict__ y,
uint32_t n, uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, int mul, uint32_t b_step,
float div) {
//
// r4dchain_binary is the chained form (r4d_chain.h), taken at decode heights.
#define R4D_BIN_PARAMS \
const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, uint16_t* __restrict__ y, \
uint32_t n, uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, int mul, uint32_t b_step, float div
__device__ __forceinline__ void binary_body(R4D_BIN_PARAMS) {
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ ar = a + (size_t)m * a_ld;
const uint16_t* __restrict__ br = b + (size_t)m * b_ld;
@@ -366,6 +368,15 @@ __global__ __launch_bounds__(kThreads) void binary_kernel(
yr[i] = f32_to_bf16(r);
}
}
__global__ __launch_bounds__(kThreads) void binary_kernel(R4D_BIN_PARAMS) {
binary_body(a, b, y, n, a_ld, b_ld, y_ld, mul, b_step, div);
}
__global__ __launch_bounds__(kThreads) void r4dchain_binary(R4D_BIN_PARAMS) {
r4d_chain_wait();
binary_body(a, b, y, n, a_ld, b_ld, y_ld, mul, b_step, div);
r4d_chain_done();
}
#undef R4D_BIN_PARAMS
// The f32 form (a video decoder's residual stream, a vocoder's branch mean), with the same
// broadcast rule and `div`. Flat over the M x n extent: a vocoder's last stages are a few channels
@@ -417,15 +428,27 @@ __global__ __launch_bounds__(kThreads) void mul_weight_f32_kernel(
//
// Row-wise with a pitch because the operand is a column slice: the gate is the second half of each
// head of an interleaved [tokens, heads, 2*head_dim] projection, `n` wide inside a stride of 2n.
__global__ __launch_bounds__(kThreads) void sigmoid_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
uint32_t n, uint32_t x_ld, uint32_t y_ld) {
//
// r4dchain_sigmoid is the chained form (r4d_chain.h), taken at decode heights.
#define R4D_SIG_PARAMS \
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld, \
uint32_t y_ld
__device__ __forceinline__ void sigmoid_body(R4D_SIG_PARAMS) {
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
yr[i] = f32_to_bf16(1.0f / (1.0f + expf(-bf16_to_f32(xr[i]))));
}
__global__ __launch_bounds__(kThreads) void sigmoid_kernel(R4D_SIG_PARAMS) {
sigmoid_body(x, y, n, x_ld, y_ld);
}
__global__ __launch_bounds__(kThreads) void r4dchain_sigmoid(R4D_SIG_PARAMS) {
r4d_chain_wait();
sigmoid_body(x, y, n, x_ld, y_ld);
r4d_chain_done();
}
#undef R4D_SIG_PARAMS
// ---------------------------------------------------------------------------- logit_softcap
// ref_logit_softcap: y = cap * tanh(x / cap), the final-logit softcap. Row-wise with a pitch like
@@ -507,10 +530,13 @@ __global__ __launch_bounds__(kThreads) void scale_kernel(
// A row is split over grid.y, kSiluPer elements per thread, so decode's few rows use more than a
// few workgroups. A thread's loads are unconditional (a column past the row reads the last element
// and its store is dropped), so all are in flight at once.
//
// r4dchain_silu_mul is the chained form (r4d_chain.h), taken up to a decode step's routed slots.
constexpr uint32_t kSiluPer = 4;
__global__ __launch_bounds__(kThreads) void silu_mul_kernel(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y,
uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
#define R4D_SM_PARAMS \
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint32_t n, uint32_t gu_ld, \
uint32_t y_ld
__device__ __forceinline__ void silu_mul_body(R4D_SM_PARAMS) {
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ gr = gu + (size_t)m * gu_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
@@ -529,14 +555,25 @@ __global__ __launch_bounds__(kThreads) void silu_mul_kernel(
if (i < n) yr[i] = f32_to_bf16((g / (1.0f + expf(-g))) * bf16_to_f32(uv[u]));
}
}
__global__ __launch_bounds__(kThreads) void silu_mul_kernel(R4D_SM_PARAMS) {
silu_mul_body(gu, y, n, gu_ld, y_ld);
}
__global__ __launch_bounds__(kThreads) void r4dchain_silu_mul(R4D_SM_PARAMS) {
r4d_chain_wait();
silu_mul_body(gu, y, n, gu_ld, y_ld);
r4d_chain_done();
}
#undef R4D_SM_PARAMS
// ---------------------------------------------------------------------------- gelu_mul
// ref_gelu_mul: y[.., i] = gelu_tanh(gu[.., i]) * gu[.., n + i], gate first as in silu_mul. The tanh
// GELU (gemma's gelu_pytorch_tanh), not erf, with the same constants as the gemm_nt_bias
// "gelu_tanh" epilogue so the two agree bit for bit.
__global__ __launch_bounds__(kThreads) void gelu_mul_kernel(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y,
uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
// r4dchain_gelu_mul is the chained form (r4d_chain.h), taken at decode heights.
#define R4D_GM_PARAMS \
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint32_t n, uint32_t gu_ld, \
uint32_t y_ld
__device__ __forceinline__ void gelu_mul_body(R4D_GM_PARAMS) {
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ gr = gu + (size_t)m * gu_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
@@ -547,6 +584,15 @@ __global__ __launch_bounds__(kThreads) void gelu_mul_kernel(
yr[i] = f32_to_bf16(gelu * bf16_to_f32(gr[n + i]));
}
}
__global__ __launch_bounds__(kThreads) void gelu_mul_kernel(R4D_GM_PARAMS) {
gelu_mul_body(gu, y, n, gu_ld, y_ld);
}
__global__ __launch_bounds__(kThreads) void r4dchain_gelu_mul(R4D_GM_PARAMS) {
r4d_chain_wait();
gelu_mul_body(gu, y, n, gu_ld, y_ld);
r4d_chain_done();
}
#undef R4D_GM_PARAMS
// ---------------------------------------------------------------------------- rope
// ref_rope, in place over a fused [n_head + 2*n_head_kv] head row; the trailing V heads are left
@@ -579,11 +625,16 @@ __device__ __forceinline__ int rope_comp(int mode, uint32_t i, const int* sec, i
return c;
}
__global__ __launch_bounds__(kThreads) void rope_kernel(
uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos,
uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, uint32_t nfreq, int den, int gptj,
float theta, float rscale, uint32_t row_pitch,
int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn, RadLlama3 l3) {
// r4dchain_rope is the chained form (r4d_chain.h), taken at decode heights.
#define R4D_ROPE_PARAMS \
uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos, uint32_t head_dim, \
uint32_t n_rope_heads, uint32_t rot, uint32_t nfreq, int den, int gptj, float theta, \
float rscale, uint32_t row_pitch, int mode, int s0, int s1, int s2, int n_sec, \
uint32_t plane, RadYarn yarn, RadLlama3 l3
#define R4D_ROPE_ARGS \
qkv, pos, head_dim, n_rope_heads, rot, nfreq, den, gptj, theta, rscale, row_pitch, mode, s0, \
s1, s2, n_sec, plane, yarn, l3
__device__ __forceinline__ void rope_body(R4D_ROPE_PARAMS) {
const uint32_t m = blockIdx.x;
const uint32_t half = rot / 2;
const float div = rscale != 0.0f ? rscale : 1.0f;
@@ -620,6 +671,16 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
hd[i1] = f32_to_bf16(x0 * s + x1 * c);
}
}
__global__ __launch_bounds__(kThreads) void rope_kernel(R4D_ROPE_PARAMS) {
rope_body(R4D_ROPE_ARGS);
}
__global__ __launch_bounds__(kThreads) void r4dchain_rope(R4D_ROPE_PARAMS) {
r4d_chain_wait();
rope_body(R4D_ROPE_ARGS);
r4d_chain_done();
}
#undef R4D_ROPE_ARGS
#undef R4D_ROPE_PARAMS
// The same rotary at prefill row counts with each (token, pair) angle computed once. rope_kernel
// gives every (head, pair) its own thread, which recomputes powf and the accurate sincosf for every
@@ -675,11 +736,13 @@ __global__ __launch_bounds__(kThreads) void rope_rows_kernel(
// K then V inside a slot: key element d at [..., d], value element d at [..., head_dim + d]. A flat
// slot index (`slot_mapping`) splits into block = slot / block_size, offset = slot % block_size. A
// negative slot is padding and stores nothing.
__global__ __launch_bounds__(kThreads) void kv_store_kernel(
const uint16_t* __restrict__ k, const uint16_t* __restrict__ v,
const int32_t* __restrict__ slot, uint16_t* __restrict__ kv,
uint32_t head_dim, uint32_t kv_heads, uint32_t block_size, uint32_t n_blocks,
uint32_t k_ld, uint32_t v_ld) {
// The body: a padding row's block returns early, so the chained form (r4dchain_kv_store,
// r4d_chain.h; taken at decode heights) wraps it.
#define R4D_KVS_PARAMS \
const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, \
const int32_t* __restrict__ slot, uint16_t* __restrict__ kv, uint32_t head_dim, \
uint32_t kv_heads, uint32_t block_size, uint32_t n_blocks, uint32_t k_ld, uint32_t v_ld
__device__ __forceinline__ void kv_store_body(R4D_KVS_PARAMS) {
const uint32_t t = blockIdx.x;
const int32_t s = slot[t];
if (s < 0 || (uint32_t)s / block_size >= n_blocks) return;
@@ -694,6 +757,15 @@ __global__ __launch_bounds__(kThreads) void kv_store_kernel(
c[head_dim + d] = v[(size_t)t * v_ld + j];
}
}
__global__ __launch_bounds__(kThreads) void kv_store_kernel(R4D_KVS_PARAMS) {
kv_store_body(k, v, slot, kv, head_dim, kv_heads, block_size, n_blocks, k_ld, v_ld);
}
__global__ __launch_bounds__(kThreads) void r4dchain_kv_store(R4D_KVS_PARAMS) {
r4d_chain_wait();
kv_store_body(k, v, slot, kv, head_dim, kv_heads, block_size, n_blocks, k_ld, v_ld);
r4d_chain_done();
}
#undef R4D_KVS_PARAMS
// The same scatter into an E4M3 cache: the write side of the fp8kv attention family and its
// `k_descale` / `v_descale` operands.
@@ -814,84 +886,106 @@ __global__ __launch_bounds__(kThreads) void kv_store_streamed_kernel(
}
}
// The fp8_v4 store: K as kv_store_fp8 writes it, V as int4 in groups of 32 with an f16 scale
// (absmax / 7). Four columns a thread as above, so a group of 32 is 8 lanes; head_dim is a multiple
// of 32, so a group never straddles two heads. A token's row is `row` bytes. K6 is the k6_v4 store:
// K as int6 in groups of 32 (absmax / 31) in the row layout of abi/rad_builder.h's RAD_KVQ_K6V4, V
// as above after it.
template <int K6>
__global__ __launch_bounds__(kThreads) void kv_store_fp8v4_kernel(
// The int8 store (abi/rad_builder.h): a head's K and its V each as int8 codes against one f16
// scale, the head's absmax / 127, written after the codes. One workgroup a (token, head) and one
// dim a lane, so the absmax is a block reduction through LDS. The scale is rounded to f16 first
// and the codes are taken against the rounded value, which is what a reader multiplies by; it is
// clamped so 127 times it stays an f16. An all-zero head stores scale 0 and codes 0.
//
// kv_i8_quant is a lane's part of that: its K and V codes and the head's two scales. It holds the
// block's barrier, so every lane of the block calls it, a padding row's included.
struct KvI8 { uint8_t k, v; uint16_t ks, vs; };
__device__ __forceinline__ KvI8 kv_i8_quant(const uint16_t* __restrict__ k,
const uint16_t* __restrict__ v, uint32_t head_dim,
uint32_t k_ld, uint32_t v_ld, float (*s_m)[32]) {
const uint32_t t = blockIdx.x, h = blockIdx.y, d = threadIdx.x;
const bool in = d < head_dim;
const float kf = in ? bf16_to_f32(k[(size_t)t * k_ld + (size_t)h * head_dim + d]) : 0.0f;
const float vf = in ? bf16_to_f32(v[(size_t)t * v_ld + (size_t)h * head_dim + d]) : 0.0f;
float km = r4d_wave_max(fabsf(kf)), vm = r4d_wave_max(fabsf(vf));
if ((d & 31u) == 0u) { s_m[0][d >> 5] = km; s_m[1][d >> 5] = vm; }
__syncthreads();
km = 0.0f; vm = 0.0f;
for (uint32_t w = 0; w < blockDim.x / 32u; ++w) {
km = fmaxf(km, s_m[0][w]);
vm = fmaxf(vm, s_m[1][w]);
}
const __fp16 k16 = (__fp16)fminf(km / 127.0f, 515.0f);
const __fp16 v16 = (__fp16)fminf(vm / 127.0f, 515.0f);
const float ksc = (float)k16, vsc = (float)v16;
const float kr = ksc > 0.0f ? rintf(kf / ksc) : 0.0f;
const float vr = vsc > 0.0f ? rintf(vf / vsc) : 0.0f;
KvI8 q;
q.k = (uint8_t)(int8_t)(int)fminf(fmaxf(kr, -127.0f), 127.0f);
q.v = (uint8_t)(int8_t)(int)fminf(fmaxf(vr, -127.0f), 127.0f);
q.ks = __builtin_bit_cast(uint16_t, k16);
q.vs = __builtin_bit_cast(uint16_t, v16);
return q;
}
// A lane's bytes into a token's row of a head.
__device__ __forceinline__ void kv_i8_put(uint8_t* __restrict__ c, uint32_t head_dim, KvI8 q) {
const uint32_t d = threadIdx.x;
c[d] = q.k;
c[head_dim + d] = q.v;
if (d == 0u) {
*(uint16_t*)(c + 2 * head_dim) = q.ks;
*(uint16_t*)(c + 2 * head_dim + 2) = q.vs;
}
}
// The body takes the block's reduction table from the kernel that calls it; it is a function
// because a padding row's block returns early and the chained form (r4dchain_kv_store_i8,
// r4d_chain.h, taken at decode heights) must still add to its queue's counter.
#define R4D_KVI_PARAMS \
const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, \
const int32_t* __restrict__ slot, uint8_t* __restrict__ kv, uint32_t head_dim, \
uint32_t kv_heads, uint32_t block_size, uint32_t n_blocks, uint32_t k_ld, uint32_t v_ld
#define R4D_KVI_ARGS k, v, slot, kv, head_dim, kv_heads, block_size, n_blocks, k_ld, v_ld
__device__ __forceinline__ void kv_store_i8_body(R4D_KVI_PARAMS, float (*s_m)[32]) {
const uint32_t t = blockIdx.x, h = blockIdx.y, d = threadIdx.x;
const KvI8 q = kv_i8_quant(k, v, head_dim, k_ld, v_ld, s_m);
const int32_t s = slot[t];
if (d >= head_dim || s < 0 || (uint32_t)s / block_size >= n_blocks) return;
const uint32_t blk = (uint32_t)s / block_size, off = (uint32_t)s % block_size;
const size_t row = 2 * (size_t)head_dim + 4;
kv_i8_put(kv + (((size_t)blk * kv_heads + h) * block_size + off) * row, head_dim, q);
}
__global__ __launch_bounds__(1024) void kv_store_i8_kernel(R4D_KVI_PARAMS) {
__shared__ float s_m[2][32];
kv_store_i8_body(R4D_KVI_ARGS, s_m);
}
__global__ __launch_bounds__(1024) void r4dchain_kv_store_i8(R4D_KVI_PARAMS) {
__shared__ float s_m[2][32];
r4d_chain_wait();
kv_store_i8_body(R4D_KVI_ARGS, s_m);
r4d_chain_done();
}
#undef R4D_KVI_ARGS
#undef R4D_KVI_PARAMS
// The int8 store of a streamed group: kv_store_i8's bytes to the token's row of its block in the
// host mirror always, and to the ring at `res[block]` when that block is resident. A slot past the
// id space stores nothing and a map entry outside [-1, slots) reads as absent, as in
// kv_store_streamed_kernel.
__global__ __launch_bounds__(1024) void kv_store_streamed_i8_kernel(
const uint16_t* __restrict__ k, const uint16_t* __restrict__ v,
const int32_t* __restrict__ slot, uint8_t* __restrict__ kv,
uint32_t head_dim, uint32_t kv_heads, uint32_t block_size, uint32_t n_blocks,
uint32_t k_ld, uint32_t v_ld, float k_inv, float v_inv, uint32_t row) {
const uint32_t t = blockIdx.x;
const int32_t* __restrict__ res, uint8_t* __restrict__ host,
uint32_t head_dim, uint32_t kv_heads, uint32_t block_size, uint32_t blocks, uint32_t slots,
uint32_t k_ld, uint32_t v_ld) {
__shared__ float s_m[2][32];
const uint32_t t = blockIdx.x, h = blockIdx.y, d = threadIdx.x;
const KvI8 q = kv_i8_quant(k, v, head_dim, k_ld, v_ld, s_m);
const int32_t s = slot[t];
if (s < 0 || (uint32_t)s / block_size >= n_blocks) return;
if (d >= head_dim || s < 0) return;
const uint32_t blk = (uint32_t)s / block_size, off = (uint32_t)s % block_size;
const size_t slot_base = ((size_t)blk * kv_heads * block_size + (size_t)off) * row;
const size_t head_step = (size_t)block_size * row;
for (uint32_t j = threadIdx.x * 4u; j < kv_heads * head_dim; j += kThreads * 4u) {
const uint32_t h = j / head_dim, d = j % head_dim;
uint8_t* __restrict__ c = kv + slot_base + (size_t)h * head_step;
float kf[4], vf[4];
#pragma unroll
for (int e = 0; e < 4; ++e) {
kf[e] = bf16_to_f32(k[(size_t)t * k_ld + j + (uint32_t)e]) * k_inv;
vf[e] = bf16_to_f32(v[(size_t)t * v_ld + j + (uint32_t)e]) * v_inv;
}
const uint32_t voff = K6 ? head_dim * 3 / 4 : head_dim;
const uint32_t vsoff = K6 ? head_dim * 21 / 16 : head_dim * 3 / 2;
if constexpr (K6) {
// A group of 32 is 8 lanes; its scale absmax / 31 in f16, codes 6-bit two's complement.
float kmax = fmaxf(fmaxf(fabsf(kf[0]), fabsf(kf[1])), fmaxf(fabsf(kf[2]), fabsf(kf[3])));
for (int m = 4; m >= 1; m >>= 1) kmax = fmaxf(kmax, __shfl_xor(kmax, m, 32));
// Clamped so 31 times it stays an f16 (65504): a group gone inf
// or NaN decodes finite, as the E4M3 form's clamp to 448 does.
const __fp16 k16 = (__fp16)fminf(kmax / 31.0f, 2112.0f);
const float ksc = (float)k16;
uint32_t q[4];
#pragma unroll
for (int e = 0; e < 4; ++e) {
const float r = ksc > 0.0f ? rintf(kf[e] / ksc) : 0.0f;
q[e] = (uint32_t)((int)fminf(fmaxf(r, -31.0f), 31.0f)) & 0x3Fu;
}
*(uint16_t*)(c + d / 2) = (uint16_t)((q[0] & 15u) | ((q[1] & 15u) << 4) |
((q[2] & 15u) << 8) | ((q[3] & 15u) << 12));
// The high bits of dims x..x+3 of a 16-dim chunk (x = d % 16 in 0, 4, 8, 12): bits
// 0-3 of bytes x/2 and x/2+1 for x < 8, bits 4-7 of bytes (x-8)/2 and (x-8)/2+1 for
// x >= 8. The lane two over holds the dims eight on, so the lower lane writes both.
const uint32_t hb = ((q[0] >> 4) | ((q[1] >> 4) << 2)) | ((((q[2] >> 4) | ((q[3] >> 4) << 2))) << 8);
const uint32_t up = (uint32_t)__shfl_xor((int)hb, 2, 32);
if ((d & 15u) < 8u)
*(uint16_t*)(c + head_dim / 2 + (d / 16) * 4 + (d & 7u) / 2) = (uint16_t)(hb | (up << 4));
if ((d & 31u) == 0)
*(uint16_t*)(c + head_dim * 5 / 4 + (d / 32) * 2) = __builtin_bit_cast(uint16_t, k16);
} else {
int pk = 0;
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf[0], -448.0f), 448.0f),
fminf(fmaxf(kf[1], -448.0f), 448.0f), pk, false);
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf[2], -448.0f), 448.0f),
fminf(fmaxf(kf[3], -448.0f), 448.0f), pk, true);
*(uint32_t*)(c + d) = (uint32_t)pk;
}
float amax = fmaxf(fmaxf(fabsf(vf[0]), fabsf(vf[1])), fmaxf(fabsf(vf[2]), fabsf(vf[3])));
for (int m = 4; m >= 1; m >>= 1) amax = fmaxf(amax, __shfl_xor(amax, m, 32));
// Clamped so 7 times it stays an f16: see the K scale above.
const __fp16 s16 = (__fp16)fminf(amax / 7.0f, 8188.0f);
const float sc = (float)s16;
uint32_t q[4];
#pragma unroll
for (int e = 0; e < 4; ++e) {
const float r = sc > 0.0f ? rintf(vf[e] / sc) : 0.0f;
q[e] = (uint32_t)((int)fminf(fmaxf(r, -7.0f), 7.0f)) & 0xFu;
}
*(uint16_t*)(c + voff + d / 2) = (uint16_t)(q[0] | (q[1] << 4) | (q[2] << 8) | (q[3] << 12));
if ((d & 31u) == 0)
*(uint16_t*)(c + vsoff + (d / 32) * 2) = __builtin_bit_cast(uint16_t, s16);
}
if (blk >= blocks) return;
const size_t row = 2 * (size_t)head_dim + 4;
const size_t brow = (size_t)kv_heads * block_size * row; // one block of every head
const size_t o = ((size_t)h * block_size + off) * row;
kv_i8_put(host + (size_t)blk * brow + o, head_dim, q);
const int32_t sl = res[blk];
if (sl >= 0 && (uint32_t)sl < slots) kv_i8_put(kv + (size_t)sl * brow + o, head_dim, q);
}
} // namespace
@@ -1132,31 +1226,48 @@ extern "C" int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps,
// `op` is 0 for a sum, 1 for a product. `b_ld` 0 broadcasts one row of n down the rows; -1 is a
// one-element b, broadcast as a scalar.
extern "C" int r4d_binary_bf16(long a, long b, long y, int M, int n, int op,
int a_ld, int b_ld, int y_ld, long stream) {
static int binary_bf16_emit(long a, long b, long y, int M, int n, int op, int a_ld, int b_ld,
int y_ld, long stream, bool chain) {
if (!a || !b || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!a_ld) a_ld = n;
if (!y_ld) y_ld = n;
const uint32_t b_step = b_ld < 0 ? 0u : 1u;
if (b_ld < 0) b_ld = 0;
hipLaunchKernelGGL(binary_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(const uint16_t*)a, (const uint16_t*)b, (uint16_t*)y, (uint32_t)n,
(uint32_t)a_ld, (uint32_t)b_ld, (uint32_t)y_ld, op, b_step, 1.0f);
#define R4D_BIN(K_) \
hipLaunchKernelGGL(K_, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, \
(const uint16_t*)a, (const uint16_t*)b, (uint16_t*)y, (uint32_t)n, \
(uint32_t)a_ld, (uint32_t)b_ld, (uint32_t)y_ld, op, b_step, 1.0f)
if (chain) R4D_BIN(r4dchain_binary);
else R4D_BIN(binary_kernel);
#undef R4D_BIN
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream) {
extern "C" int r4d_binary_bf16(long a, long b, long y, int M, int n, int op,
int a_ld, int b_ld, int y_ld, long stream) {
return binary_bf16_emit(a, b, y, M, n, op, a_ld, b_ld, y_ld, stream, false);
}
static int sigmoid_emit(long x, long y, int M, int n, int x_ld, int y_ld, long stream, bool chain) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(sigmoid_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(const uint16_t*)x, (uint16_t*)y, (uint32_t)n,
(uint32_t)x_ld, (uint32_t)y_ld);
#define R4D_SIG(K_) \
hipLaunchKernelGGL(K_, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, \
(const uint16_t*)x, (uint16_t*)y, (uint32_t)n, (uint32_t)x_ld, \
(uint32_t)y_ld)
if (chain) R4D_SIG(r4dchain_sigmoid);
else R4D_SIG(sigmoid_kernel);
#undef R4D_SIG
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream) {
return sigmoid_emit(x, y, M, n, x_ld, y_ld, stream, false);
}
// ---------------------------------------------------------------------------- fill
// y[m, i] = v over an [M, n] extent with a row pitch, for a rank with nothing to compute whose
// downstream reader (an all-reduce, a residual) still needs a defined buffer. A memset cannot
@@ -1254,31 +1365,49 @@ extern "C" int r4d_scale_bf16(long x, long s, uint32_t s_dt, long y, int M, int
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream) {
static int silu_mul_emit(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream,
bool chain) {
if (!gu || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!gu_ld) gu_ld = 2 * n;
if (!y_ld) y_ld = n;
const uint32_t chunks = ((uint32_t)n + kSiluPer * kThreads - 1u) / (kSiluPer * kThreads);
hipLaunchKernelGGL(silu_mul_kernel, dim3((uint32_t)M, chunks), dim3(kThreads), 0,
(hipStream_t)stream, (const uint16_t*)gu, (uint16_t*)y, (uint32_t)n,
(uint32_t)gu_ld, (uint32_t)y_ld);
#define R4D_SM(K_) \
hipLaunchKernelGGL(K_, dim3((uint32_t)M, chunks), dim3(kThreads), 0, (hipStream_t)stream, \
(const uint16_t*)gu, (uint16_t*)y, (uint32_t)n, (uint32_t)gu_ld, \
(uint32_t)y_ld)
if (chain) R4D_SM(r4dchain_silu_mul);
else R4D_SM(silu_mul_kernel);
#undef R4D_SM
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream) {
return silu_mul_emit(gu, y, M, n, gu_ld, y_ld, stream, false);
}
// GELU-gated product, the gemma FFN activation. Same shape and gate order as silu_mul; tanh GELU to
// match ref_gelu_mul's act_gelu_tanh.
extern "C" int r4d_gelu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream) {
static int gelu_mul_emit(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream,
bool chain) {
if (!gu || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!gu_ld) gu_ld = 2 * n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(gelu_mul_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(const uint16_t*)gu, (uint16_t*)y, (uint32_t)n,
(uint32_t)gu_ld, (uint32_t)y_ld);
#define R4D_GM(K_) \
hipLaunchKernelGGL(K_, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, \
(const uint16_t*)gu, (uint16_t*)y, (uint32_t)n, (uint32_t)gu_ld, \
(uint32_t)y_ld)
if (chain) R4D_GM(r4dchain_gelu_mul);
else R4D_GM(gelu_mul_kernel);
#undef R4D_GM
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_gelu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream) {
return gelu_mul_emit(gu, y, M, n, gu_ld, y_ld, stream, false);
}
// `n_rope_heads` is n_head + n_head_kv: the Q heads and the K heads of a fused projection, or just
// the one buffer's heads when q and k are separate tensors (which is what the gated block does).
extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
@@ -1295,7 +1424,8 @@ extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope
static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den,
int gptj, float theta, float rscale, int row_pitch, int mode,
const int* sec, int n_sec, int plane, RadYarn yarn, long stream,
int nfreq = -1, RadLlama3 l3 = RadLlama3{}, bool rows_form = false) {
int nfreq = -1, RadLlama3 l3 = RadLlama3{}, bool rows_form = false,
bool chain = false) {
if (!qkv || !pos) return -1;
if (M <= 0 || head_dim <= 0 || n_rope_heads <= 0) return -2;
if (rot <= 0 || rot > head_dim || (rot & 1)) return -3;
@@ -1318,11 +1448,15 @@ static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads
s0, s1, s2, n_sec, (uint32_t)plane, yarn, l3);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
hipLaunchKernelGGL(rope_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, (hipStream_t)stream,
(uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim,
(uint32_t)n_rope_heads, (uint32_t)rot, (uint32_t)nfreq, (int)den, gptj, theta,
rscale,
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, yarn, l3);
#define R4D_ROPE(K_) \
hipLaunchKernelGGL(K_, dim3((uint32_t)M, gy), dim3(kThreads), 0, (hipStream_t)stream, \
(uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim, \
(uint32_t)n_rope_heads, (uint32_t)rot, (uint32_t)nfreq, (int)den, gptj, \
theta, rscale, (uint32_t)row_pitch, mode, s0, s1, s2, n_sec, \
(uint32_t)plane, yarn, l3)
if (chain) R4D_ROPE(r4dchain_rope);
else R4D_ROPE(rope_kernel);
#undef R4D_ROPE
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -1336,22 +1470,32 @@ extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_r
row_pitch, mode, sec, n_sec, plane, RadYarn{}, stream);
}
extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim,
int kv_heads, int block_size, int n_blocks,
int k_ld, int v_ld, long stream) {
static int kv_store_emit(long k, long v, long slot, long kv, int M, int head_dim, int kv_heads,
int block_size, int n_blocks, int k_ld, int v_ld, long stream,
bool chain) {
if (!k || !v || !slot || !kv) return -1;
if (M <= 0 || head_dim <= 0 || kv_heads <= 0 || block_size <= 0 || n_blocks <= 0) return -2;
if (!k_ld) k_ld = kv_heads * head_dim;
if (!v_ld) v_ld = kv_heads * head_dim;
/* The fp8 cache is a separate entry point (r4d_kv_store_fp8), selected by --kv-cache-dtype. */
hipLaunchKernelGGL(kv_store_kernel, dim3((uint32_t)M), dim3(kThreads), 0,
(hipStream_t)stream,
(const uint16_t*)k, (const uint16_t*)v, (const int32_t*)slot,
(uint16_t*)kv, (uint32_t)head_dim, (uint32_t)kv_heads,
(uint32_t)block_size, (uint32_t)n_blocks, (uint32_t)k_ld, (uint32_t)v_ld);
#define R4D_KVS(K_) \
hipLaunchKernelGGL(K_, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, \
(const uint16_t*)k, (const uint16_t*)v, (const int32_t*)slot, \
(uint16_t*)kv, (uint32_t)head_dim, (uint32_t)kv_heads, \
(uint32_t)block_size, (uint32_t)n_blocks, (uint32_t)k_ld, (uint32_t)v_ld)
if (chain) R4D_KVS(r4dchain_kv_store);
else R4D_KVS(kv_store_kernel);
#undef R4D_KVS
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim,
int kv_heads, int block_size, int n_blocks,
int k_ld, int v_ld, long stream) {
return kv_store_emit(k, v, slot, kv, M, head_dim, kv_heads, block_size, n_blocks, k_ld, v_ld,
stream, false);
}
// bf16 k and v in, E4M3 cache out. `k_scale` and `v_scale` are the reader's descales, so this
// divides by them; 1.0 is the vLLM default and what the attention kernels assume when their
// descale pointers are null.
@@ -2023,9 +2167,10 @@ static int binary(const RadArgs* a, int mul, RadStream s) {
(float)div);
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
return r4d_binary_bf16(r4d_addr(A), r4d_addr(B), r4d_addr(Y), (int)M, (int)n, mul,
(int)a_ld, (int)b_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
return binary_bf16_emit(r4d_addr(A), r4d_addr(B), r4d_addr(Y), (int)M, (int)n, mul,
(int)a_ld, (int)b_ld, (int)y_ld, (long)(uintptr_t)s,
r4d_geti_or(a, "chain", 0) != 0 && M <= 64) == 0 ? RAD_OK
: RAD_E_DEVICE;
}
extern "C" int r4d_rad_add(const RadArgs* a, RadStream s) { return binary(a, 0, s); }
@@ -2103,8 +2248,10 @@ extern "C" int r4d_rad_sigmoid(const RadArgs* a, RadStream s) {
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
return r4d_sigmoid_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
return sigmoid_emit(r4d_addr(x), r4d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld,
(long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0 && M <= 64) == 0
? RAD_OK
: RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ fill */
@@ -2206,8 +2353,10 @@ extern "C" int r4d_rad_silu_mul(const RadArgs* a, RadStream s) {
if (y_ld < 0 || gu_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || Mg < M) return R4D_NO(RAD_E_SHAPE);
return r4d_silu_mul_bf16(r4d_addr(gu), r4d_addr(y), (int)M, (int)n, (int)gu_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
return silu_mul_emit(r4d_addr(gu), r4d_addr(y), (int)M, (int)n, (int)gu_ld, (int)y_ld,
(long)(uintptr_t)s,
r4d_geti_or(a, "chain", 0) != 0 && M <= 1024) == 0 ? RAD_OK
: RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ gelu_mul */
@@ -2227,8 +2376,8 @@ extern "C" int r4d_rad_gelu_mul(const RadArgs* a, RadStream s) {
if (y_ld < 0 || gu_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || Mg < M) return R4D_NO(RAD_E_SHAPE);
const int rc = r4d_gelu_mul_bf16(r4d_addr(gu), r4d_addr(y), (int)M, (int)n, (int)gu_ld, (int)y_ld,
(long)(uintptr_t)s);
const int rc = gelu_mul_emit(r4d_addr(gu), r4d_addr(y), (int)M, (int)n, (int)gu_ld, (int)y_ld,
(long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0 && M <= 64);
return rc == 0 ? RAD_OK : RAD_E_DEVICE;
}
@@ -2324,7 +2473,7 @@ static int rope_emit(const RadArgs* a, RadStream s, bool rows_form) {
return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
(int)(n_head + n_head_kv), (int)rot_l, (int)den, gptj, theta, rscale,
(int)pitch, mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s,
(int)nfreq, l3, rows_form) == 0
(int)nfreq, l3, rows_form, r4d_geti_or(a, "chain", 0) != 0 && Mp <= 64) == 0
? RAD_OK
: RAD_E_DEVICE;
}
@@ -2350,7 +2499,9 @@ struct KvStoreGeom {
long long head_dim, block_size, kv_heads, n_blocks, k_ld, v_ld, T;
};
static int kv_store_geom(const RadArgs* a, KvStoreGeom* g, long long row_per_hd16 = 32) {
/* A token's row in a (block, head) page is head_dim * row_per_hd16 / 16 + row_extra elements. */
static int kv_store_geom(const RadArgs* a, KvStoreGeom* g, long long row_per_hd16 = 32,
long long row_extra = 0) {
g->k = r4d_opt(a, KS_K);
g->v = r4d_opt(a, KS_V);
g->sm = r4d_opt(a, KS_SLOT);
@@ -2369,7 +2520,7 @@ static int kv_store_geom(const RadArgs* a, KvStoreGeom* g, long long row_per_hd1
* disagrees. */
if (g->kv->rank != 4) return R4D_NO(RAD_E_SHAPE);
if (g->kv->shape[1] != g->kv_heads || g->kv->shape[2] != g->block_size ||
g->kv->shape[3] != g->head_dim * row_per_hd16 / 16) return R4D_NO(RAD_E_SHAPE);
g->kv->shape[3] != g->head_dim * row_per_hd16 / 16 + row_extra) return R4D_NO(RAD_E_SHAPE);
g->n_blocks = g->kv->shape[0];
const long long lane = g->kv_heads * g->head_dim;
@@ -2388,10 +2539,11 @@ extern "C" int r4d_rad_kv_store(const RadArgs* a, RadStream s) {
if (rc != RAD_OK) return rc;
R4D_NEED(dt_bf16(g.kv));
return r4d_kv_store_bf16(r4d_addr(g.k), r4d_addr(g.v), r4d_addr(g.sm), r4d_addr(g.kv),
(int)g.T, (int)g.head_dim, (int)g.kv_heads, (int)g.block_size,
(int)g.n_blocks, (int)g.k_ld, (int)g.v_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
return kv_store_emit(r4d_addr(g.k), r4d_addr(g.v), r4d_addr(g.sm), r4d_addr(g.kv),
(int)g.T, (int)g.head_dim, (int)g.kv_heads, (int)g.block_size,
(int)g.n_blocks, (int)g.k_ld, (int)g.v_ld, (long)(uintptr_t)s,
r4d_geti_or(a, "chain", 0) != 0 && g.T <= 64) == 0 ? RAD_OK
: RAD_E_DEVICE;
}
/* The E4M3 store. `k_scale` and `v_scale` are the attention side's descales (one per sequence and
@@ -2415,42 +2567,35 @@ extern "C" int r4d_rad_kv_store_fp8(const RadArgs* a, RadStream stream) {
(float)ks, (float)vs, stream) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* The fp8_v4 and k6_v4 stores: the cache's last extent is a token's row, 25 or 22 * head_dim / 16
* bytes. */
static int kv_store_q4(const RadArgs* a, RadStream stream, int k6) {
const long long r16 = k6 ? 22 : 25;
/* The int8 store: the cache's last extent is a token's row, 2 * head_dim + 4 bytes. A workgroup is
* a head's dims rounded up to whole waves. */
extern "C" int r4d_rad_kv_store_i8(const RadArgs* a, RadStream stream) {
KvStoreGeom g{};
const int rc = kv_store_geom(a, &g, r16);
const int rc = kv_store_geom(a, &g, 32, 4);
if (rc != RAD_OK) return rc;
if (g.kv->dtype != RAD_F8E4M3) return R4D_NO(RAD_E_DTYPE);
if (g.head_dim % 32) return R4D_NO(RAD_E_SHAPE);
const double ks = r4d_getf(a, "k_scale", 1.0);
const double vs = r4d_getf(a, "v_scale", 1.0);
if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL);
long long k_ld = g.k_ld ? g.k_ld : g.kv_heads * g.head_dim;
long long v_ld = g.v_ld ? g.v_ld : g.kv_heads * g.head_dim;
if (k6)
return R4D_EMIT(stream, kv_store_fp8v4_kernel<1>, dim3((uint32_t)g.T), dim3(kThreads), 0,
(const uint16_t*)r4d_addr(g.k), (const uint16_t*)r4d_addr(g.v),
(const int32_t*)r4d_addr(g.sm), (uint8_t*)r4d_addr(g.kv),
(uint32_t)g.head_dim, (uint32_t)g.kv_heads, (uint32_t)g.block_size,
(uint32_t)g.n_blocks, (uint32_t)k_ld, (uint32_t)v_ld, (float)(1.0 / ks),
(float)(1.0 / vs), (uint32_t)(g.head_dim * r16 / 16)) == RAD_OK ? RAD_OK : RAD_E_DEVICE;
return R4D_EMIT(stream, kv_store_fp8v4_kernel<0>, dim3((uint32_t)g.T), dim3(kThreads), 0,
(const uint16_t*)r4d_addr(g.k), (const uint16_t*)r4d_addr(g.v),
if (g.kv->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE);
if (g.head_dim % 4 || g.head_dim > 1024) return R4D_NO(RAD_E_SHAPE);
const long long k_ld = g.k_ld ? g.k_ld : g.kv_heads * g.head_dim;
const long long v_ld = g.v_ld ? g.v_ld : g.kv_heads * g.head_dim;
const uint32_t thr = (uint32_t)((g.head_dim + 31) / 32 * 32);
const bool chain = r4d_geti_or(a, "chain", 0) != 0 && g.T <= 64;
return R4D_EMIT(stream, (chain ? r4dchain_kv_store_i8 : kv_store_i8_kernel),
dim3((uint32_t)g.T, (uint32_t)g.kv_heads), dim3(thr),
0, (const uint16_t*)r4d_addr(g.k), (const uint16_t*)r4d_addr(g.v),
(const int32_t*)r4d_addr(g.sm), (uint8_t*)r4d_addr(g.kv),
(uint32_t)g.head_dim, (uint32_t)g.kv_heads, (uint32_t)g.block_size,
(uint32_t)g.n_blocks, (uint32_t)k_ld, (uint32_t)v_ld, (float)(1.0 / ks),
(float)(1.0 / vs), (uint32_t)(g.head_dim * r16 / 16)) == RAD_OK ? RAD_OK : RAD_E_DEVICE;
(uint32_t)g.n_blocks, (uint32_t)k_ld, (uint32_t)v_ld) == RAD_OK ? RAD_OK
: RAD_E_DEVICE;
}
extern "C" int r4d_rad_kv_store_fp8v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 0); }
extern "C" int r4d_rad_kv_store_k6v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 1); }
/* The store of a streamed group: kv_store's geometry and conversion (E4M3, or bf16 with no
* descales), plus the residency map `res` (read, never written: residency is the resolve's) and the
* host mirror `host`. Both are one block a row of the same byte pitch. State faults are guarded,
* not refused (see kv_store_streamed_kernel). */
static int kv_store_streamed_i8(const RadArgs* a, RadStream stream);
extern "C" int r4d_rad_kv_store_streamed(const RadArgs* a, RadStream stream) {
const RadTensor* kvt = r4d_opt(a, 3);
if (kvt && kvt->dtype == RAD_I8) return kv_store_streamed_i8(a, stream);
KvStoreGeom g{};
const int rc = kv_store_geom(a, &g);
if (rc != RAD_OK) return rc;
@@ -2501,6 +2646,36 @@ extern "C" int r4d_rad_kv_store_streamed(const RadArgs* a, RadStream stream) {
k_inv, v_inv) == RAD_OK ? RAD_OK : RAD_E_DEVICE;
}
/* The same into the int8 cache: kv_store_i8's workgroup, a head's dims one a lane, and a row of
* 2 * head_dim + 4 bytes in both planes. */
static int kv_store_streamed_i8(const RadArgs* a, RadStream stream) {
KvStoreGeom g{};
const int rc = kv_store_geom(a, &g, 32, 4);
if (rc != RAD_OK) return rc;
if (g.head_dim % 4 || g.head_dim > 1024) return R4D_NO(RAD_E_SHAPE);
const RadTensor* res = r4d_opt(a, 4);
const RadTensor* host = r4d_opt(a, 5);
if (!res || !host) return R4D_NO(RAD_E_INVAL);
if (res->dtype != RAD_I32 || !r4d_contig(res)) return R4D_NO(RAD_E_STRIDE);
if (host->dtype != RAD_U8 || !r4d_contig(host) || host->rank != 2)
return R4D_NO(RAD_E_STRIDE);
const long long row = g.kv_heads * g.block_size * (2 * g.head_dim + 4);
const long long blocks = host->shape[0], slots = g.kv->shape[0];
if (blocks <= 0 || slots <= 0 || row <= 0) return R4D_NO(RAD_E_SHAPE);
if (host->shape[1] != row || host->stride[0] != row) return R4D_NO(RAD_E_STRIDE);
if (r4d_numel(res) < blocks) return R4D_NO(RAD_E_SHAPE);
const long long k_ld = g.k_ld ? g.k_ld : g.kv_heads * g.head_dim;
const long long v_ld = g.v_ld ? g.v_ld : g.kv_heads * g.head_dim;
return R4D_EMIT(stream, kv_store_streamed_i8_kernel, dim3((uint32_t)g.T, (uint32_t)g.kv_heads),
dim3((uint32_t)((g.head_dim + 31) / 32 * 32)), 0,
(const uint16_t*)r4d_addr(g.k), (const uint16_t*)r4d_addr(g.v),
(const int32_t*)r4d_addr(g.sm), (uint8_t*)r4d_addr(g.kv),
(const int32_t*)r4d_addr(res), (uint8_t*)r4d_addr(host),
(uint32_t)g.head_dim, (uint32_t)g.kv_heads, (uint32_t)g.block_size,
(uint32_t)blocks, (uint32_t)slots, (uint32_t)k_ld,
(uint32_t)v_ld) == RAD_OK ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ logits_gemm
*
* gemm_nt's arithmetic with `n_vocab`/`n_embd` for N/K, but writing f32 (see the kernel above).
+294 -214
View File
@@ -39,10 +39,10 @@
// breaking the byte-level reproducibility of spec §17.
#include "r4d.h"
#include "r4d_common.h"
#include "r4d_chain.h"
#include "r4d_fp8_wmma.h"
#include "r4d_plugin.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_gemm_args.h"
#include "r4d_moe_sort.h"
#include "r4d_moe_gather.h"
@@ -74,6 +74,7 @@ using r4d_moesort::scatter_small_kernel;
using r4d_moegather::kGatherSlots;
using r4d_moegather::kGatherSelfT;
using r4d_moegather::gather_kernel;
using r4d_moegather::r4dchain_moe_gather;
constexpr uint32_t kBlock = 128; // the fp8 scale block, along K and along N
/* Run-map entry that owns no expert: rows above `off[n_expert]` are dropped slots whose output must
* be zeroed. Declared here because the GEMM reads it; the map is built further down. */
@@ -84,6 +85,8 @@ using r4d_fp8::i2v;
using r4d_fp8::f8v;
using r4d_fp8::mma;
using r4d_fp8::acc_zero;
using r4d_fp8::acc_val;
using r4d_fp8::mma8;
using r4d_fp8::acc_row;
using r4d_fp8::frag_c;
using r4d_fp8::frag;
@@ -488,6 +491,26 @@ __device__ __forceinline__ Stage8 w5_expand(uint4 p, uint32_t sg, const uint32_t
return r;
}
/* ---- the codebook levels against an int8 activation ---------------------------------------------
*
* The iu8 WMMA wants the levels as int8. The two's-complement nibble is its own value
* (kW4IntPermI8). w4nl's magnitudes are 1.125, 3.25, 5.5, 8, 11, 14, 18 and 22: the unit that makes
* all of them integers is 1/8, at which 22 is 176 and past int8, and a second WMMA over the other
* half of each level costs a third of the kernel's time. So the levels are read as the int8 set
* nearest them at one unit, r4d_args.h's kW4nlI8 times kW4nlI8Unit (folded into the scale): each
* within 1.2% of its level. */
static constexpr uint32_t kW4IntPermI8[4] = { 0x03020100u, 0x07060504u, 0xFBFAF9F8u, 0xFFFEFDFCu };
static constexpr uint32_t kW4nlPermI8[4] = {
w4nl_i8_dword(0), w4nl_i8_dword(1), w4nl_i8_dword(2), w4nl_i8_dword(3) };
/* The staged bytes of a four-bit row segment: E4M3 from `tab`, or at I8 the int8 levels, `tab`'s
* for the integer grid and w4nl's at the subgroup-scaled forms (W4 2 and 3). */
template <int W4, bool I8>
__device__ __forceinline__ Stage8 moe_w4_bytes(uint4 p, const uint32_t (&tab)[4]) {
if constexpr (I8 && (W4 == 2 || W4 == 3)) return w4_expand(p, kW4nlPermI8);
else return w4_expand(p, tab);
}
/* The packed half of a Stage8's worth of K, or zeros for a row this block does not own. Zeros
* expand to entry 0 (E4M3 zero under -8..7, 1.125 under w4nl); either way the column contributes
* nothing, since staging gives an unowned column a weight scale of zero. */
@@ -675,29 +698,41 @@ constexpr uint32_t moe_waves(uint32_t ntl, int w4, bool es, bool al, uint32_t fk
: (w4 <= 1 ? 9u : 8u);
}
#define R4D_MOEGQ_PARAMS \
const uint8_t* __restrict__ Aq, const float* __restrict__ As, const MoeCls c_even, \
const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3, \
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, \
uint16_t* __restrict__ Y, const uint32_t* __restrict__ map, uint32_t T, uint32_t N, \
uint32_t n_expert, uint32_t top_k, uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, \
uint32_t mode, const MoeTab tab
template <uint32_t MT, uint32_t NTL, uint32_t WGM, uint32_t WGN, int W4 = 0,
bool ES = false, bool AL = false, bool SK = false, uint32_t FK = kFK, bool UW = false,
bool RS = false>
__device__ __forceinline__ void moe_gemm_q_kernel_body(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off,
uint16_t* __restrict__ Y, const uint32_t* __restrict__ map,
uint32_t T, uint32_t N, uint32_t n_expert, uint32_t top_k,
uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) {
/* `mode`: bit 0 `a_sorted`, bits 1-2 the class shift (1 for two classes, 2 for four), bits 8+
* `parts`. */
bool RS = false, bool I8 = false>
__device__ __forceinline__ void moe_gemm_q_body(R4D_MOEGQ_PARAMS) {
/* `mode`: bit 0 `a_sorted`, bits 1-2 the class shift (1 for two classes, 2 for four), bit 3
* the activation's scale per 256 of K instead of per 128 (`a_group`: block b reads scale
* b >> 1), bits 8+ `parts`. */
const uint32_t a_sorted = mode & 1u, cshift = (mode >> 1) & 3u, parts = mode >> 8;
const uint32_t ash = (mode >> 3) & 1u;
constexpr uint32_t FM = MT * 16, FN = NTL * 16;
constexpr uint32_t NTHR = WGM * WGN * kWave;
constexpr uint32_t WM = MT / WGM, WN = NTL / WGN;
static_assert(MT % WGM == 0 && NTL % WGN == 0, "the wave grid must divide the tile");
/* The block-fp8 weight has one scale per 128x128 tile; a w4 weight one per row, so its block
* may span two fp8 scale rows (the aligned form's 256-column down tile). */
static_assert(W4 != 0 || kBlock % FN == 0,
/* I8: the activation is int8 and the WMMA the iu8 one, its int32 sums read as numbers at the
* fold (r4d_fp8_wmma.h, mma8). The weight is then int8 too: at W4 0 the codes themselves with
* one bf16 scale per (row, 128 of K), the four-bit forms' scale grid, and at W4 1 to 3 the
* levels as int8 (moe_w4_bytes). kRowS: the weight's scale varies per row. */
constexpr bool kRowS = W4 != 0 || I8;
static_assert(!I8 || W4 <= 3, "the five-bit levels have no int8 form");
static_assert(kRowS || kBlock % FN == 0,
"a block's N rows must sit in one 128-row weight scale row");
/* Scale groups per 128-wide block: one, or the 64- or 32-column groups at W4 2-4. */
constexpr uint32_t kSub = W4 == 3 ? 4u : (W4 == 2 || W4 == 4) ? 2u : 1u;
/* What multiplies a subgroup's E4M3 scale: the format's fixed second level, and at I8 the
* levels' unit. */
constexpr float kSubScale = I8 ? kW4G64Scale * kW4nlI8Unit : kW4G64Scale;
/* 128-wide blocks per staged pass (one, or two at FK 256), and scale groups per pass. */
constexpr uint32_t kBpS = FK / kBlock;
constexpr uint32_t kSubT = kSub * kBpS;
@@ -1029,7 +1064,7 @@ __device__ __forceinline__ void moe_gemm_q_kernel_body(
const uint32_t wn0 = part * fc + j0; /* the weight row of the block's column 0 */
const uint32_t K = C.k, w_ld = C.w_ld, ws_ld = C.s_ld;
const uint32_t kb_n = wn0 / kBlock; /* the weight scale's N row for this block */
if constexpr (W4) (void)kb_n; /* w4 scales vary per ROW, not per N block */
if constexpr (kRowS) (void)kb_n; /* these scales vary per ROW, not per N block */
/* Both table entries load before either is made uniform, so the two readfirstlanes wait on
* one round trip. */
@@ -1113,9 +1148,9 @@ __device__ __forceinline__ void moe_gemm_q_kernel_body(
if (tid < FM) {
const int32_t tok = s_tok[tid];
pok = tok >= 0 && (r0 + tid) >= rs && (r0 + tid) < re;
const size_t ar = (size_t)(pok ? tok : 0) * as_ld + kbk;
const size_t ar = (size_t)(pok ? tok : 0) * as_ld;
#pragma unroll
for (uint32_t h = 0; h < kBpS; ++h) pau[h] = As[ar + h];
for (uint32_t h = 0; h < kBpS; ++h) pau[h] = As[ar + ((kbk + h) >> ash)];
} else if (tid < FM + FN) {
const uint32_t nn = tid - FM;
pok = j0 + nn < fc;
@@ -1124,7 +1159,7 @@ __device__ __forceinline__ void moe_gemm_q_kernel_body(
for (uint32_t h = 0; h < kBpS; ++h) {
if constexpr (W4 == 3)
pwu[h] = u32_load_w<UW>((const uint32_t*)Wsp + wr + h);
else if constexpr (W4)
else if constexpr (kRowS)
pwu[h] = u16_load_w<UW>(Wsp + wr + h);
else
pwu[h] = u16_load_w<UW>(Wsp + (size_t)kb_n * ws_ld + kbk + h);
@@ -1135,7 +1170,7 @@ __device__ __forceinline__ void moe_gemm_q_kernel_body(
const bool ok = tok >= 0 && (r0 + tid) >= rs && (r0 + tid) < re;
#pragma unroll
for (uint32_t h = 0; h < kBpS; ++h)
pas[h] = ok ? As[(size_t)tok * as_ld + kbk + h] : 0.0f;
pas[h] = ok ? As[(size_t)tok * as_ld + ((kbk + h) >> ash)] : 0.0f;
} else if (tid < FM + FN) {
const uint32_t nn = tid - FM;
#pragma unroll
@@ -1145,7 +1180,7 @@ __device__ __forceinline__ void moe_gemm_q_kernel_body(
? u32_load_w<UW>((const uint32_t*)Wsp +
(size_t)(wn0 + nn) * ws_ld + kbk + h)
: 0u;
else if constexpr (W4)
else if constexpr (kRowS)
pws[h] = j0 + nn < fc
? u16_load_w<UW>(Wsp + (size_t)(wn0 + nn) * ws_ld + kbk + h)
: 0u;
@@ -1254,7 +1289,7 @@ __device__ __forceinline__ void moe_gemm_q_kernel_body(
if constexpr (W4 == 4)
stage8_store<FK>(s_b, r, sk, w5_expand(b4, live ? spre[p] : 0u, tab.v));
else if constexpr (W4)
stage8_store<FK>(s_b, r, sk, w4_expand(b4, tab.v));
stage8_store<FK>(s_b, r, sk, moe_w4_bytes<W4, I8>(b4, tab.v));
else
stage8_store<FK>(s_b, r, sk, kUL ? stage8_keep(bpre8[p], live) : bpre8[p]);
}
@@ -1280,9 +1315,9 @@ __device__ __forceinline__ void moe_gemm_q_kernel_body(
for (uint32_t q = 0; q < kSub; ++q)
s_ws[(h * kSub + q) * FN + tid - FM] =
r4d_fp8::e4m3((uint32_t)((pws_v(h) >> (8 * q)) & 0xFFu)) *
kW4G64Scale;
kSubScale;
} else {
s_ws[tid - FM] = (W4 || tid == FM) ? bscale(pws_v(0)) : 0.0f;
s_ws[tid - FM] = (kRowS || tid == FM) ? bscale(pws_v(0)) : 0.0f;
}
}
if (c0 + FK < K) issue(c0 + FK, std::false_type{});
@@ -1306,7 +1341,7 @@ __device__ __forceinline__ void moe_gemm_q_kernel_body(
if (SK && r0 + (wgm * WM + i) * 16 >= re) continue;
#pragma unroll
for (uint32_t j = 0; j < WN; ++j)
acc[i][j] = mma(af[i], bf[j], fresh ? acc_zero() : acc[i][j]);
acc[i][j] = mma8<I8>(af[i], bf[j], fresh ? acc_zero() : acc[i][j]);
}
};
/* At W4 2-4 each scale group of the tile has its own accumulator, so no group's WMMA
@@ -1359,22 +1394,23 @@ __device__ __forceinline__ void moe_gemm_q_kernel_body(
for (uint32_t j = 0; j < WN; ++j)
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
float v = raw[i][j][t] * wq[0][j];
float v = acc_val<I8>(raw[i][j][t]) * wq[0][j];
#pragma unroll
for (uint32_t q = 1; q < kSub; ++q) v += rx[q - 1][i][j][t] * wq[q][j];
for (uint32_t q = 1; q < kSub; ++q)
v += acc_val<I8>(rx[q - 1][i][j][t]) * wq[q][j];
out[i][j][t] += v * as[0][i][t];
if constexpr (kBpS > 1) {
/* FK 256: the second 128-wide block, folded after the first
* with the expression a separate 128 pass would use, so `out`
* sees the same updates. */
float v1 = rx[kSub - 1][i][j][t] * wq[kSub][j];
float v1 = acc_val<I8>(rx[kSub - 1][i][j][t]) * wq[kSub][j];
#pragma unroll
for (uint32_t q = 1; q < kSub; ++q)
v1 += rx[kSub + q - 1][i][j][t] * wq[kSub + q][j];
v1 += acc_val<I8>(rx[kSub + q - 1][i][j][t]) * wq[kSub + q][j];
out[i][j][t] += v1 * as[1][i][t];
}
}
} else if constexpr (W4) {
} else if constexpr (kRowS) {
float wsj[WN];
#pragma unroll
for (uint32_t j = 0; j < WN; ++j)
@@ -1385,7 +1421,7 @@ __device__ __forceinline__ void moe_gemm_q_kernel_body(
for (uint32_t j = 0; j < WN; ++j)
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
out[i][j][t] += raw[i][j][t] * as[0][i][t] * wsj[j];
out[i][j][t] += acc_val<I8>(raw[i][j][t]) * as[0][i][t] * wsj[j];
raw[i][j][t] = 0.0f;
}
} else {
@@ -1431,35 +1467,20 @@ __device__ __forceinline__ void moe_gemm_q_kernel_body(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <uint32_t MT, uint32_t NTL, uint32_t WGM, uint32_t WGN, int W4 = 0,
bool ES = false, bool AL = false, bool SK = false, uint32_t FK = kFK, bool UW = false,
bool RS = false>
/* The kernel around the body, whose blocks return where their work ends: CH `r4dchain` is the
* chained form (r4d_chain.h), every block waiting before its first read and adding once after
* its last write. */
template <uint32_t MT, uint32_t NTL, uint32_t WGM, uint32_t WGN, int W4, bool ES, bool AL, bool SK,
uint32_t FK, bool UW, bool RS, bool I8, class CH>
__global__ __launch_bounds__(WGM * WGN * kWave) R4D_WAVES(moe_waves(NTL, W4, ES, AL, FK, RS))
void moe_gemm_q_kernel(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off,
uint16_t* __restrict__ Y, const uint32_t* __restrict__ map,
uint32_t T, uint32_t N, uint32_t n_expert, uint32_t top_k,
uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) {
moe_gemm_q_kernel_body<MT, NTL, WGM, WGN, W4, ES, AL, SK, FK, UW, RS>(Aq, As, c_even, c_odd, c_2, c_3, sorted, off, Y, map, T, N, n_expert, top_k, a_ld, as_ld, y_ld, mode, tab);
}
template <uint32_t MT, uint32_t NTL, uint32_t WGM, uint32_t WGN, int W4 = 0,
bool ES = false, bool AL = false, bool SK = false, uint32_t FK = kFK, bool UW = false,
bool RS = false>
__global__ __launch_bounds__(WGM * WGN * kWave) R4D_WAVES(moe_waves(NTL, W4, ES, AL, FK, RS))
void r4dchain_moe_gemm_q(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off,
uint16_t* __restrict__ Y, const uint32_t* __restrict__ map,
uint32_t T, uint32_t N, uint32_t n_expert, uint32_t top_k,
uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) {
r4d_chain_wait();
moe_gemm_q_kernel_body<MT, NTL, WGM, WGN, W4, ES, AL, SK, FK, UW, RS>(Aq, As, c_even, c_odd, c_2, c_3, sorted, off, Y, map, T, N, n_expert, top_k, a_ld, as_ld, y_ld, mode, tab);
r4d_chain_done();
void moe_gemm_q_kernel(R4D_MOEGQ_PARAMS) {
if (CH::on) r4d_chain_wait();
moe_gemm_q_body<MT, NTL, WGM, WGN, W4, ES, AL, SK, FK, UW, RS, I8>(
Aq, As, c_even, c_odd, c_2, c_3, sorted, off, Y, map, T, N, n_expert, top_k, a_ld, as_ld,
y_ld, mode, tab);
if (CH::on) r4d_chain_done();
}
#undef R4D_MOEGQ_PARAMS
/* ================================================================== moe_gemm_q, the down decode form
*
@@ -1492,21 +1513,25 @@ void r4dchain_moe_gemm_q(
*
* Sorted operand only: a run's activation rows are [rs, re) of `Aq` with no gather. Every row in a
* run is a placed slot (the scatter fills exactly [0, off[n_expert])), so `sorted` is not read. */
template <int W4>
__device__ __forceinline__ void moe_down_dec_kernel_body(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
const int32_t* __restrict__ off, uint16_t* __restrict__ Y,
uint32_t T, uint32_t N, uint32_t n_expert, uint32_t G,
uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) {
#define R4D_MOEDD_PARAMS \
const uint8_t* __restrict__ Aq, const float* __restrict__ As, const MoeCls c_even, \
const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3, const int32_t* __restrict__ off, \
uint16_t* __restrict__ Y, uint32_t T, uint32_t N, uint32_t n_expert, uint32_t G, \
uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab
template <int W4, bool I8 = false>
__device__ __forceinline__ void moe_down_dec_body(R4D_MOEDD_PARAMS) {
constexpr bool UW = true;
constexpr uint32_t FM = 16, FN = 64, FK = kFK, NTHR = 4 * kWave;
constexpr uint32_t kSub = W4 == 3 ? 4u : (W4 == 2 || W4 == 4) ? 2u : 1u;
/* moe_gemm_q_kernel's I8, with its per-row scale and its subgroup unit. */
constexpr bool kRowS = W4 != 0 || I8;
constexpr float kSubScale = I8 ? kW4G64Scale * kW4nlI8Unit : kW4G64Scale;
static_assert(!I8 || W4 <= 3, "the five-bit levels have no int8 form");
constexpr uint32_t NPT = kMaxExpert / NTHR;
static_assert(kMaxExpert % NTHR == 0, "the offsets divide over the block's threads");
static_assert(FK % (kSub * r4d_fp8::kK) == 0, "a scale group is whole WMMA K steps");
static_assert(FM + FN <= NTHR, "a thread stages each row's and each column's scale");
const uint32_t cshift = (mode >> 1) & 3u, parts = mode >> 8;
const uint32_t cshift = (mode >> 1) & 3u, parts = mode >> 8, ash = (mode >> 3) & 1u;
__shared__ uint8_t s_a[FM * lds_pitch<FK>()];
__shared__ uint8_t s_b[FN * lds_pitch<FK>()];
@@ -1645,18 +1670,18 @@ __device__ __forceinline__ void moe_down_dec_kernel_body(
const uint32_t n0 = cg0 + s.g * FN, part = n0 / fy, j0 = n0 - part * fy;
const uint32_t wn0 = part * fc + j0; /* the weight row of the tile's column 0 */
const uint32_t kb_n = wn0 / kBlock;
if constexpr (W4) (void)kb_n;
if constexpr (kRowS) (void)kb_n;
if (tid < FM) {
const uint32_t row = rs + tid;
pok = row < re;
pau[0] = As[(size_t)(pok ? row : 0u) * as_ld + kbk];
pau[0] = As[(size_t)(pok ? row : 0u) * as_ld + (kbk >> ash)];
} else if (tid < FM + FN) {
const uint32_t nn = tid - FM;
pok = j0 + nn < fc;
const size_t wr = (size_t)(pok ? wn0 + nn : wn0) * ws_ld + kbk;
if constexpr (W4 == 3)
pwu[0] = u32_load_w<UW>((const uint32_t*)Wsp + wr);
else if constexpr (W4)
else if constexpr (kRowS)
pwu[0] = u16_load_w<UW>(Wsp + wr);
else
pwu[0] = u16_load_w<UW>(Wsp + (size_t)kb_n * ws_ld + kbk);
@@ -1709,7 +1734,7 @@ __device__ __forceinline__ void moe_down_dec_kernel_body(
if constexpr (W4 == 4)
stage8_store<FK>(s_b, r, sk, w5_expand(bpre4[q], spre[q], tab.v));
else if constexpr (W4)
stage8_store<FK>(s_b, r, sk, w4_expand(bpre4[q], tab.v));
stage8_store<FK>(s_b, r, sk, moe_w4_bytes<W4, I8>(bpre4[q], tab.v));
else
stage8_store<FK>(s_b, r, sk, bpre8[q]);
}
@@ -1721,9 +1746,9 @@ __device__ __forceinline__ void moe_down_dec_kernel_body(
#pragma unroll
for (uint32_t q = 0; q < kSub; ++q)
s_ws[q * FN + tid - FM] =
r4d_fp8::e4m3((uint32_t)((pws >> (8 * q)) & 0xFFu)) * kW4G64Scale;
r4d_fp8::e4m3((uint32_t)((pws >> (8 * q)) & 0xFFu)) * kSubScale;
} else {
s_ws[tid - FM] = (W4 || tid == FM) ? bscale(pws) : 0.0f;
s_ws[tid - FM] = (kRowS || tid == FM) ? bscale(pws) : 0.0f;
}
}
const Pass nxt = advance(cur);
@@ -1734,7 +1759,7 @@ __device__ __forceinline__ void moe_down_dec_kernel_body(
auto kstep = [&](uint32_t ks, f8v& acc, bool fresh = false) {
const i2v af = frag<FK>(s_a, 0, ks, lane);
const i2v bf = frag<FK>(s_b, wave * 16, ks, lane);
acc = mma(af, bf, fresh ? acc_zero() : acc);
acc = mma8<I8>(af, bf, fresh ? acc_zero() : acc);
};
if constexpr (kSub > 1) {
constexpr uint32_t kG = FK / kSub;
@@ -1759,16 +1784,16 @@ __device__ __forceinline__ void moe_down_dec_kernel_body(
for (uint32_t q = 0; q < kSub; ++q) wq[q] = s_ws[q * FN + wave * 16 + frag_c(lane)];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
float v = raw[t] * wq[0];
float v = acc_val<I8>(raw[t]) * wq[0];
#pragma unroll
for (uint32_t q = 1; q < kSub; ++q) v += rx[q - 1][t] * wq[q];
for (uint32_t q = 1; q < kSub; ++q) v += acc_val<I8>(rx[q - 1][t]) * wq[q];
out[t] += v * as[t];
}
} else if constexpr (W4) {
} else if constexpr (kRowS) {
const float wsj = s_ws[wave * 16 + frag_c(lane)];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
out[t] += raw[t] * as[t] * wsj;
out[t] += acc_val<I8>(raw[t]) * as[t] * wsj;
raw[t] = 0.0f;
}
} else {
@@ -1799,27 +1824,17 @@ __device__ __forceinline__ void moe_down_dec_kernel_body(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <int W4>
__global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
const int32_t* __restrict__ off, uint16_t* __restrict__ Y,
uint32_t T, uint32_t N, uint32_t n_expert, uint32_t G,
uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) {
moe_down_dec_kernel_body<W4>(Aq, As, c_even, c_odd, c_2, c_3, off, Y, T, N, n_expert, G, a_ld, as_ld, y_ld, mode, tab);
}
template <int W4>
__global__ __launch_bounds__(4 * kWave) void r4dchain_moe_down_dec(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
const int32_t* __restrict__ off, uint16_t* __restrict__ Y,
uint32_t T, uint32_t N, uint32_t n_expert, uint32_t G,
uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) {
r4d_chain_wait();
moe_down_dec_kernel_body<W4>(Aq, As, c_even, c_odd, c_2, c_3, off, Y, T, N, n_expert, G, a_ld, as_ld, y_ld, mode, tab);
r4d_chain_done();
/* The kernel around the body, as moe_gemm_q_kernel around its own: CH `r4dchain` is the chained
* form. */
template <int W4, bool I8, class CH>
__global__ __launch_bounds__(4 * kWave)
void moe_down_dec_kernel(R4D_MOEDD_PARAMS) {
if (CH::on) r4d_chain_wait();
moe_down_dec_body<W4, I8>(Aq, As, c_even, c_odd, c_2, c_3, off, Y, T, N, n_expert, G, a_ld,
as_ld, y_ld, mode, tab);
if (CH::on) r4d_chain_done();
}
#undef R4D_MOEDD_PARAMS
/* One or a few routed rows at I4 with BF16 scales per 128 K (signed or a 16-entry codebook).
* A block owns one sorted row and 64 columns;
@@ -1831,6 +1846,7 @@ __global__ __launch_bounds__(4 * kWave) void r4dchain_moe_down_dec(
*
* Sorted rows are resolved independently, so singleton, repeated and empty expert runs, both
* activation orders, parity/mod4 classes and dropped slots all retain their ordinary meaning. */
template <bool I8 = false>
__global__ __launch_bounds__(4 * kWave) void moe_w4_rows_kernel(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
@@ -1851,7 +1867,7 @@ __global__ __launch_bounds__(4 * kWave) void moe_w4_rows_kernel(
else hi = mid;
}
const uint32_t e = (uint32_t)__builtin_amdgcn_readfirstlane((int)lo);
const uint32_t cshift = (mode >> 1) & 3u, parts = mode >> 8;
const uint32_t cshift = (mode >> 1) & 3u, parts = mode >> 8, ash = (mode >> 3) & 1u;
const uint32_t cls = e & ((1u << cshift) - 1u);
const MoeCls& C = cls == 0 ? c_even : cls == 1 ? c_odd : cls == 2 ? c_2 : c_3;
const uint32_t fy = N / parts, fc = C.n / parts;
@@ -1867,7 +1883,7 @@ __global__ __launch_bounds__(4 * kWave) void moe_w4_rows_kernel(
const uint16_t* Ws = uw_ptr<true>((const uint16_t*)wtab_at(C.s, C.s_s0, e >> cshift));
float out = 0.f;
for (uint32_t g = 0; g < C.k / kBlock; ++g) {
const float as = As[(size_t)arow * as_ld + g];
const float as = As[(size_t)arow * as_ld + (g >> ash)];
const float ws = bscale(u16_load_w<true>(Ws + (size_t)(wn0 + col) * C.s_ld + g));
f8v raw = acc_zero();
#pragma unroll
@@ -1882,10 +1898,10 @@ __global__ __launch_bounds__(4 * kWave) void moe_w4_rows_kernel(
const i2v af = { (int)a.x, (int)a.y };
const i2v bf = { (int)w4_e4m3(w & 0x0f0f0f0fu, tab.v),
(int)w4_e4m3((w >> 4) & 0x0f0f0f0fu, tab.v) };
raw = mma(af, bf, raw);
raw = mma8<I8>(af, bf, raw);
}
}
out += raw[0] * as * ws;
out += acc_val<I8>(raw[0]) * as * ws;
}
if (lane < 16 && n0 + col < N) Y[(size_t)row * y_ld + n0 + col] = f32_to_bf16(out);
}
@@ -1928,15 +1944,15 @@ __device__ __forceinline__ mb_v8bf mb_frag(const uint16_t* __restrict__ tile, ui
return u.f;
}
#define R4D_MOE16_PARAMS \
const uint16_t* __restrict__ A, const void* const* __restrict__ Wt, size_t w_s0, \
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, \
uint16_t* __restrict__ Y, uint32_t T, uint32_t N, uint32_t K, uint32_t n_expert, \
uint32_t top_k, uint32_t a_sorted, uint32_t a_ld, uint32_t w_ld, uint32_t y_ld, \
const uint32_t* __restrict__ map
template <uint32_t MT, uint32_t NTL, uint32_t WGM, uint32_t WGN, bool ES = false, bool AL = false,
bool SK = false>
__global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_bf16_kernel(
const uint16_t* __restrict__ A, const void* const* __restrict__ Wt, size_t w_s0,
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off,
uint16_t* __restrict__ Y,
uint32_t T, uint32_t N, uint32_t K, uint32_t n_expert, uint32_t top_k, uint32_t a_sorted,
uint32_t a_ld, uint32_t w_ld, uint32_t y_ld,
const uint32_t* __restrict__ map) {
__device__ __forceinline__ void moe_gemm_bf16_body(R4D_MOE16_PARAMS) {
constexpr uint32_t FM = MT * 16, FN = NTL * 16;
constexpr uint32_t NTHR = WGM * WGN * kWave;
constexpr uint32_t WM = MT / WGM, WN = NTL / WGN;
@@ -2152,6 +2168,17 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_bf16_kernel(
}
}
/* The kernel around the body, as moe_gemm_q_kernel around its own: CH `r4dchain` is the chained
* form, which the launcher takes at decode heights. */
template <uint32_t MT, uint32_t NTL, uint32_t WGM, uint32_t WGN, bool ES, bool AL, bool SK, class CH>
__global__ __launch_bounds__(WGM * WGN * kWave)
void moe_gemm_bf16_kernel(R4D_MOE16_PARAMS) {
if (CH::on) r4d_chain_wait();
moe_gemm_bf16_body<MT, NTL, WGM, WGN, ES, AL, SK>(A, Wt, w_s0, sorted, off, Y, T, N, K, n_expert, top_k, a_sorted, a_ld, w_ld, y_ld, map);
if (CH::on) r4d_chain_done();
}
#undef R4D_MOE16_PARAMS
/* ================================================================== moe_gather
*
* y[t, :] = sum over a token's slots of expert_w[t, j] * y_expert[position of (t, j)], summed in
@@ -2651,10 +2678,12 @@ static inline long long r4d_blockmap_bytes(long long cap) {
* The prefix is parallel (a DPP scan per wave and one exchange of wave totals, 256 counts per tile;
* three tiles at 512 experts), not 513 dependent LDS round trips on one thread ahead of a GEMM that
* waits for the map. Integer sums are order-independent. */
template <class CH>
__global__ __launch_bounds__(256) void moe_blockmap_kernel(
const int32_t* __restrict__ off, uint32_t n_expert, uint32_t T, uint32_t FM, uint32_t cap,
uint32_t* __restrict__ map) {
constexpr uint32_t NT = 256, NW = NT / kWave, kTiles = (kMaxExpert + NT) / NT;
if (CH::on) r4d_chain_wait();
__shared__ uint32_t s_cnt[kMaxExpert + 1];
__shared__ int32_t s_wt[kTiles][NW];
const uint32_t tid = threadIdx.x, lane = tid % kWave, wave = tid / kWave;
@@ -2722,6 +2751,7 @@ __global__ __launch_bounds__(256) void moe_blockmap_kernel(
map[1 + 2 * o + 1] = r;
}
}
if (CH::on) r4d_chain_done();
}
/* Launch form: 0 the rule; for tests, 1 pins the run-aligned prefill form, 2 the (tile, run)
@@ -2738,7 +2768,9 @@ static int g_moe_down_tile_pin = 0;
*
* `ncls` is the class count: 2 for `moe_gemm_q` (odd class = operands 6 and 7 at N_odd/K_odd), 4
* for `moe_gemm_q_mod4` (classes 1..3 = operands 6/7, 8/9, 10/11 at N_1/K_1 .. N_3/K_3, `y` at 12). */
template <int W4>
/* I8: the int8 activation's rows (dtypes i8a8 and i8a8h at W4 0, the four-bit forms' `a8i8`
* names), the kernels' I8. */
template <int W4, bool I8 = false>
static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
int emit_rc = RAD_OK;
if (ncls != 2 && ncls != 4) return R4D_NO(RAD_E_INVAL);
@@ -2776,15 +2808,21 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
const long long group = r4d_geti_or(a, "group", kBlock);
if (parts <= 0 || n_expert <= 0 || top_k <= 0) return R4D_NO(RAD_E_SHAPE);
if (group != (long long)kBlock) return R4D_NO(RAD_E_SHAPE);
/* `a_group`: the K one activation scale covers, 128 or, for an int8 activation quantised as
* IQ8R's are, 256 (two of the kernel's K blocks under one scale). */
const long long a_group = r4d_geti_or(a, "a_group", kBlock);
if (a_group != (long long)kBlock && !(I8 && a_group == 2 * (long long)kBlock))
return R4D_NO(RAD_E_UNSUPPORTED);
long long N = 0, K = 0;
for (int q = 0; q < ncls; ++q) {
if (Nc[q] <= 0 || Kc[q] <= 0) return R4D_NO(RAD_E_SHAPE);
/* A part of every class is whole 64-column tiles, so a tile is all weight or all padding. */
if (Kc[q] % kBlock || Nc[q] % (64 * parts)) return R4D_NO(RAD_E_SHAPE);
if (Kc[q] % a_group || Nc[q] % (64 * parts)) return R4D_NO(RAD_E_SHAPE);
if (Nc[q] > N) N = Nc[q];
if (Kc[q] > K) K = Kc[q];
}
if (Aq->dtype != RAD_F8E4M3 || As->dtype != RAD_F32 || Y->dtype != RAD_BF16)
if (Aq->dtype != (I8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3) || As->dtype != RAD_F32 ||
Y->dtype != RAD_BF16)
return R4D_NO(RAD_E_DTYPE);
if (sorted->dtype != RAD_I32 || off->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE);
@@ -2795,7 +2833,7 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
const long long a_ld = r4d_rows_pitch(Aq, K, &M);
if (a_ld < 0 || M <= 0) return R4D_NO(RAD_E_STRIDE);
long long Ms = 0;
const long long as_ld = r4d_rows_pitch(As, K / kBlock, &Ms);
const long long as_ld = r4d_rows_pitch(As, K / a_group, &Ms);
if (as_ld < 0 || Ms < M) return R4D_NO(RAD_E_STRIDE);
if (r4d_numel(sorted) < T || r4d_numel(off) < n_expert + 1) return R4D_NO(RAD_E_SHAPE);
@@ -2809,7 +2847,8 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
/* The code table, from the dtype the layout hook accepted: w4nla8h's levels, w5nl64a8h's
* magnitudes, or two's complement for w4a8 and w4a8h. */
const char* wdt = r4d_gets(a, "dtype");
const uint32_t* tab = W4 == 4 ? kW5nlMagPerm
const uint32_t* tab = I8 ? kW4IntPermI8
: W4 == 4 ? kW5nlMagPerm
: (W4 && wdt && (!std::strcmp(wdt, "w4nla8h") ||
!std::strcmp(wdt, "w4nl64a8h") ||
!std::strcmp(wdt, "w4nl32a8h"))) ? kW4nlPerm : kW4IntPerm;
@@ -2822,7 +2861,8 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
long long w_ld = 0, ws_ld = 0;
size_t w_s0 = 0, s_s0 = 0;
int rc = wtab_of(w, W4 == 4 ? (uint32_t)R4D_DT_MOEW5
: W4 ? (uint32_t)R4D_DT_MOEW4 : (uint32_t)RAD_F8E4M3,
: W4 ? (uint32_t)R4D_DT_MOEW4
: I8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3,
W4 == 4 ? 5 : W4 ? 4 : 8, cnt, n, k, &c->w, &w_s0, &w_ld);
if (rc != RAD_OK) return rc;
if constexpr (W4 >= 2) {
@@ -2844,6 +2884,10 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
if (rc != RAD_OK) return rc;
if (w_ld < k || w_ld % 64) return R4D_NO(RAD_E_STRIDE); // whole 64-K fragment tiles
w_ld /= 2;
} else if constexpr (I8) {
/* Int8 codes row-major, one bf16 scale per (row, 128 of K). */
rc = wtab_of(ws, RAD_BF16, 16, cnt, n, k / kBlock, &c->s, &s_s0, &ws_ld);
if (rc != RAD_OK) return rc;
} else {
rc = wtab_of(ws, RAD_BF16, 16, cnt, (n + kBlock - 1) / kBlock, k / kBlock, &c->s,
&s_s0, &ws_ld);
@@ -2873,7 +2917,8 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
const MoeCls& c3 = cl[3];
const uint32_t cshift = ncls == 4 ? 2u : 1u;
if (parts > 0xFFFFFF) return R4D_NO(RAD_E_SHAPE);
const uint32_t mode = (a_sorted ? 1u : 0u) | (cshift << 1) | ((uint32_t)parts << 8);
const uint32_t mode = (a_sorted ? 1u : 0u) | (cshift << 1) |
(a_group != (long long)kBlock ? 8u : 0u) | ((uint32_t)parts << 8);
MoeTab tabv{};
for (int i = 0; i < 4; ++i) tabv.v[i] = tab[i];
@@ -2883,7 +2928,7 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
if constexpr (W4 == 1) {
if (T <= top_k && T <= 32 && g_moe_prefill_form == 0 &&
g_moe_down_dec_pin == 0 && g_moe_fk_pin == 0) {
emit_rc = R4D_EMIT(stream, (moe_w4_rows_kernel),
emit_rc = R4D_EMIT(stream, (moe_w4_rows_kernel<I8>),
dim3((unsigned)T, (unsigned)(N / 64)), dim3(4 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
(const int32_t*)sorted->data, (const int32_t*)off->data,
@@ -2900,9 +2945,8 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
* rows take the aligned 32-row form; r4d_moe_decode_band has the crossover. */
const uint32_t ny = (uint32_t)(N / 64);
const int form = g_moe_prefill_form;
/* The chained forms (r4d_chain.h) where the row resolved with `chain`, at decode heights. */
const bool ch = r4d_geti_or(a, "chain", 0) != 0 &&
r4d_chain_rows_ok(a_sorted ? (T + top_k - 1) / top_k : M);
/* The decode band's launch has a chained form (r4d_chain.h); the prefill forms have none. */
const bool chain = r4d_geti_or(a, "chain", 0) != 0;
if ((form == 0 && r4d_moe_decode_band(T, n_expert)) || form == 2) {
/* The decode grid is (tile, run) wide (the kernel's ES note); decode has one tile of rows,
* which alone would give only N/64 workgroups. */
@@ -2916,12 +2960,15 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
if (dn_dec && g2 > 0) {
const unsigned slots = (unsigned)(std::min(T, n_expert) + (T + 15) / 16);
const unsigned groups = (unsigned)((N + 64 * g2 - 1) / (64 * g2));
emit_rc = R4D_EMIT(stream, (ch ? &r4dchain_moe_down_dec<W4> : &moe_down_dec_kernel<W4>),
dim3(slots + 1u, groups), dim3(4 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
(const int32_t*)off->data, (uint16_t*)Y->data,
(uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)g2,
(uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv);
#define R4D_MOE_DD(CH_) \
emit_rc = R4D_EMIT(stream, (moe_down_dec_kernel<W4, I8, CH_>), \
dim3(slots + 1u, groups), dim3(4 * kWave), 0, \
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, \
(const int32_t*)off->data, (uint16_t*)Y->data, \
(uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)g2, \
(uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv)
if (chain) R4D_MOE_DD(r4dchain); else R4D_MOE_DD(R4dUnchained);
#undef R4D_MOE_DD
if (emit_rc != RAD_OK) return emit_rc;
R4D_MOE_CHK();
return RAD_OK;
@@ -2933,11 +2980,15 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
const bool rs = n_expert <= (long long)kMaxExpert;
auto pick = [&](auto fk) {
constexpr uint32_t F = decltype(fk)::value;
if (ch)
return rs ? &r4dchain_moe_gemm_q<1, 4, 1, 4, W4, true, false, false, F, true, true>
: &r4dchain_moe_gemm_q<1, 4, 1, 4, W4, true, false, false, F, true, false>;
return rs ? &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true, true>
: &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true, false>;
if (chain)
return rs ? &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true, true, I8,
r4dchain>
: &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true, false, I8,
r4dchain>;
return rs ? &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true, true, I8,
R4dUnchained>
: &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true, false, I8,
R4dUnchained>;
};
auto kern = pick(std::integral_constant<uint32_t, kFK>{});
if constexpr (W4 >= 2) {
@@ -2970,24 +3021,25 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
* instead of 128 over eight. Each wave's share is unchanged, so every element is the same
* sum; the wider block stages the activation and run prologue once for twice the columns.
* Other shapes keep the 128- or 64-column tile. */
bool dn_wide = W4 != 0 && a_sorted && parts == 1 && N % (2 * kPrefillCols) == 0;
bool dn_wide = (W4 != 0 || I8) && a_sorted && parts == 1 &&
N % (2 * kPrefillCols) == 0;
for (int q = 0; q < ncls; ++q) dn_wide = dn_wide && Nc[q] % (2 * kPrefillCols) == 0;
const int tpin = g_moe_down_tile_pin;
if (tpin < 0 || tpin > 2) return R4D_NO(RAD_E_INVAL);
if (tpin == 2 && (!map || !dn_wide)) return R4D_NO(RAD_E_UNSUPPORTED);
if (tpin == 1) dn_wide = false;
if (map) {
emit_rc = R4D_EMIT(stream, moe_blockmap_kernel, dim3(1), dim3(256), 0,
emit_rc = R4D_EMIT(stream, moe_blockmap_kernel<R4dUnchained>, dim3(1), dim3(256), 0,
(const int32_t*)off->data, (uint32_t)n_expert, (uint32_t)T,
(uint32_t)kPrefillRows, (uint32_t)cap, map);
if (emit_rc != RAD_OK) return emit_rc;
/* Every aligned instantiation uses UW and issues its first pass at the map read (see
* the early-weight note at the kernel). */
if (dn_wide) {
/* Only a w4 weight takes it (dn_wide is false otherwise); the block-fp8
* instantiation would not compile, its scale being per 128x128 tile. */
if constexpr (W4 != 0)
emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel<kPrefillRows / 16, 2 * kPrefillCols / 16, 2, 8, W4, false, true, true, kFK, true>),
/* Only a weight with a scale per row takes it (dn_wide is false otherwise); the
* block-fp8 instantiation would not compile, its scale being per 128x128 tile. */
if constexpr (W4 != 0 || I8)
emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel<kPrefillRows / 16, 2 * kPrefillCols / 16, 2, 8, W4, false, true, true, kFK, true, false, I8, R4dUnchained>),
dim3((unsigned)cap, (unsigned)(N / (2 * kPrefillCols))),
dim3(16 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
@@ -2996,7 +3048,7 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
(uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k,
(uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv);
} else if (wide_n) {
emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel<kPrefillRows / 16, kPrefillCols / 16, 2, 4, W4, false, true, true, kFK, true>),
emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel<kPrefillRows / 16, kPrefillCols / 16, 2, 4, W4, false, true, true, kFK, true, false, I8, R4dUnchained>),
dim3((unsigned)cap, nyw), dim3(8 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
(const int32_t*)sorted->data, (const int32_t*)off->data,
@@ -3004,7 +3056,7 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
(uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k,
(uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv);
} else {
emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel<kPrefillRows / 16, 4, 2, 2, W4, false, true, true, kFK, true>),
emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel<kPrefillRows / 16, 4, 2, 2, W4, false, true, true, kFK, true, false, I8, R4dUnchained>),
dim3((unsigned)cap, ny), dim3(4 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
(const int32_t*)sorted->data, (const int32_t*)off->data,
@@ -3013,7 +3065,7 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
(uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv);
}
} else if (wide_n) {
emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel<kPrefillRows / 16, kPrefillCols / 16, 2, 4, W4, false, false, true>),
emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel<kPrefillRows / 16, kPrefillCols / 16, 2, 4, W4, false, false, true, kFK, false, false, I8, R4dUnchained>),
dim3((unsigned)((T + kPrefillRows - 1) / kPrefillRows), nyw),
dim3(8 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
@@ -3022,7 +3074,7 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
(uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k,
(uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv);
} else {
emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel<kPrefillRows / 16, 4, 2, 2, W4, false, false, true>),
emit_rc = R4D_EMIT(stream, (moe_gemm_q_kernel<kPrefillRows / 16, 4, 2, 2, W4, false, false, true, kFK, false, false, I8, R4dUnchained>),
dim3((unsigned)((T + kPrefillRows - 1) / kPrefillRows), ny),
dim3(4 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
@@ -3054,6 +3106,21 @@ static int64_t moe_gemm_map_scratch(const RadArgs* a) {
return r4d_blockmap_bytes(r4d_blockmap_cap(T, n_expert, kPrefillRows));
}
/* The run map and the decode band for another unit's grouped GEMM over the same sort
* (r4d_moe_iqr.hip): the map's entry bound and bytes at `fm` rows a block, and its one launch. */
long long r4d_moe_blockmap_cap(long long T, long long n_expert, long long fm) {
return r4d_blockmap_cap(T, n_expert, fm);
}
long long r4d_moe_blockmap_bytes(long long cap) { return r4d_blockmap_bytes(cap); }
int r4d_moe_blockmap_emit(RadStream s, const int32_t* off, uint32_t n_expert, uint32_t T,
uint32_t fm, uint32_t cap, uint32_t* map) {
return R4D_EMIT(s, moe_blockmap_kernel<R4dUnchained>, dim3(1), dim3(256), 0, off, n_expert, T, fm,
cap, map);
}
bool r4d_moe_in_decode_band(long long T, long long n_expert) {
return r4d_moe_decode_band(T, n_expert);
}
extern "C" int64_t r4d_rad_moe_gemm_q_scratch(const RadArgs* a) { return moe_gemm_map_scratch(a); }
extern "C" int64_t r4d_rad_moe_gemm_w4a8_scratch(const RadArgs* a) { return moe_gemm_map_scratch(a); }
@@ -3064,10 +3131,6 @@ extern "C" void r4d_moe_gemm_pin_down_dec(int pin) {
g_moe_down_dec_pin = pin < (int)kMoeDownDecMaxG ? pin : (int)kMoeDownDecMaxG;
}
extern "C" int r4d_rad_moe_gemm_q(const RadArgs* a, RadStream s) {
return moe_gemm_launch<0>(a, s);
}
/* The four-bit forms (an E4M3 scale per 64 or 32 of K for w4nl64a8h / w4nl32a8h, else a bf16
* scale per 128) and the five-bit w5nl64a8h. */
extern "C" int r4d_rad_moe_gemm_w4a8(const RadArgs* a, RadStream stream) {
@@ -3078,10 +3141,27 @@ extern "C" int r4d_rad_moe_gemm_w4a8(const RadArgs* a, RadStream stream) {
return moe_gemm_launch<1>(a, stream);
}
/* `moe_gemm_q_mod4`: the same launches over four classes, by expert number mod 4. The run map and
* its scratch are the two-class op's, since they depend only on the offsets. */
extern "C" int r4d_rad_moe_gemm_q_mod4(const RadArgs* a, RadStream s) {
return moe_gemm_launch<0>(a, s, 4);
/* The int8 activation's rows. `i8a8` and `i8a8h`: int8 experts, row-major codes with a bf16 scale
* per (row, 128 of K). The four-bit experts keep their stored planes: `w4a8i8` and `w4a8i8h` the
* integer grid with a bf16 scale per (row, 128), `w4nl64a8i8h` and `w4nl32a8i8h` the w4nl codebook
* with an E4M3 scale per (row, 64 or 32 of K). */
static int moe_gemm_w4a8i8(const RadArgs* a, RadStream stream, int ncls) {
const char* wdt = r4d_gets(a, "dtype");
if (wdt && !std::strcmp(wdt, "w4nl64a8i8h")) return moe_gemm_launch<2, true>(a, stream, ncls);
if (wdt && !std::strcmp(wdt, "w4nl32a8i8h")) return moe_gemm_launch<3, true>(a, stream, ncls);
return moe_gemm_launch<1, true>(a, stream, ncls);
}
extern "C" int r4d_rad_moe_gemm_i8a8(const RadArgs* a, RadStream s) {
return moe_gemm_launch<0, true>(a, s);
}
extern "C" int r4d_rad_moe_gemm_i8a8_mod4(const RadArgs* a, RadStream s) {
return moe_gemm_launch<0, true>(a, s, 4);
}
extern "C" int r4d_rad_moe_gemm_w4a8i8(const RadArgs* a, RadStream s) {
return moe_gemm_w4a8i8(a, s, 2);
}
extern "C" int r4d_rad_moe_gemm_w4a8i8_mod4(const RadArgs* a, RadStream s) {
return moe_gemm_w4a8i8(a, s, 4);
}
extern "C" int r4d_rad_moe_gemm_w4a8_mod4(const RadArgs* a, RadStream stream) {
const char* wdt = r4d_gets(a, "dtype");
@@ -3142,15 +3222,23 @@ extern "C" int r4d_rad_moe_gemm_bf16(const RadArgs* a, RadStream stream) {
const uint32_t ny = (uint32_t)(N / 64);
const int form = g_moe_prefill_form;
/* Chained forms (r4d_chain.h) up to a decode step's routed slots, in either band: a layer's
* few plain experts beside a quantised table are a table of at most eight, which a verify
* step's forty slots put in the prefill form, run map included. */
const bool chain = r4d_geti_or(a, "chain", 0) != 0 && T <= 1024;
if ((form == 0 && r4d_moe_decode_band(T, n_expert)) || form == 2) {
const unsigned tiles = (unsigned)((T + 15) / 16);
emit_rc = R4D_EMIT(stream, (moe_gemm_bf16_kernel<1, 4, 1, 4, true>),
dim3(tiles * 16u, ny), dim3(4 * kWave), 0,
(const uint16_t*)A->data, tab, w_s0,
(const int32_t*)sorted->data, (const int32_t*)off->data,
(uint16_t*)Y->data, (uint32_t)T, (uint32_t)N, (uint32_t)K,
(uint32_t)n_expert, (uint32_t)top_k, (uint32_t)(a_sorted ? 1 : 0),
(uint32_t)a_ld, (uint32_t)w_ld, (uint32_t)y_ld, nullptr);
#define R4D_MOE16D(CH_) \
R4D_EMIT(stream, (moe_gemm_bf16_kernel<1, 4, 1, 4, true, false, false, CH_>), \
dim3(tiles * 16u, ny), dim3(4 * kWave), 0, \
(const uint16_t*)A->data, tab, w_s0, \
(const int32_t*)sorted->data, (const int32_t*)off->data, \
(uint16_t*)Y->data, (uint32_t)T, (uint32_t)N, (uint32_t)K, \
(uint32_t)n_expert, (uint32_t)top_k, (uint32_t)(a_sorted ? 1 : 0), \
(uint32_t)a_ld, (uint32_t)w_ld, (uint32_t)y_ld, nullptr)
if (chain) emit_rc = R4D_MOE16D(r4dchain);
else emit_rc = R4D_MOE16D(R4dUnchained);
#undef R4D_MOE16D
} else {
const long long cap = r4d_blockmap_cap(T, n_expert, kPrefillRows);
uint32_t* map = (form != 3 && n_expert <= (long long)kMaxExpert && a->scratch &&
@@ -3161,25 +3249,34 @@ extern "C" int r4d_rad_moe_gemm_bf16(const RadArgs* a, RadStream stream) {
const unsigned nyw = (unsigned)(N / kPrefillCols);
const unsigned gx = map ? (unsigned)cap : (unsigned)((T + kPrefillRows - 1) / kPrefillRows);
if (map) {
emit_rc = R4D_EMIT(stream, moe_blockmap_kernel, dim3(1), dim3(256), 0,
(const int32_t*)off->data, (uint32_t)n_expert, (uint32_t)T,
(uint32_t)kPrefillRows, (uint32_t)cap, map);
#define R4D_MOEBM(CH_) \
R4D_EMIT(stream, moe_blockmap_kernel<CH_>, dim3(1), dim3(256), 0, \
(const int32_t*)off->data, (uint32_t)n_expert, (uint32_t)T, \
(uint32_t)kPrefillRows, (uint32_t)cap, map)
if (chain) emit_rc = R4D_MOEBM(r4dchain);
else emit_rc = R4D_MOEBM(R4dUnchained);
#undef R4D_MOEBM
if (emit_rc != RAD_OK) return emit_rc;
}
#define R4D_MOE16(AL_, NTL_, WGN_, NYG_) \
#define R4D_MOE16C(AL_, NTL_, WGN_, NYG_, CH_) \
R4D_EMIT(stream, \
(moe_gemm_bf16_kernel<kPrefillRows / 16, NTL_, 2, WGN_, false, AL_, true>), \
(moe_gemm_bf16_kernel<kPrefillRows / 16, NTL_, 2, WGN_, false, AL_, true, \
CH_>), \
dim3(gx, NYG_), dim3(2 * WGN_ * kWave), 0, \
(const uint16_t*)A->data, tab, w_s0, \
(const int32_t*)sorted->data, (const int32_t*)off->data, \
(uint16_t*)Y->data, (uint32_t)T, (uint32_t)N, (uint32_t)K, \
(uint32_t)n_expert, (uint32_t)top_k, (uint32_t)(a_sorted ? 1 : 0), \
(uint32_t)a_ld, (uint32_t)w_ld, (uint32_t)y_ld, (const uint32_t*)map)
#define R4D_MOE16(AL_, NTL_, WGN_, NYG_) \
(chain ? R4D_MOE16C(AL_, NTL_, WGN_, NYG_, r4dchain) \
: R4D_MOE16C(AL_, NTL_, WGN_, NYG_, R4dUnchained))
if (map) emit_rc = wide_n ? R4D_MOE16(true, kPrefillCols / 16, 4, nyw)
: R4D_MOE16(true, 4, 2, ny);
else emit_rc = wide_n ? R4D_MOE16(false, kPrefillCols / 16, 4, nyw)
: R4D_MOE16(false, 4, 2, ny);
#undef R4D_MOE16
#undef R4D_MOE16C
}
if (emit_rc != RAD_OK) return emit_rc;
R4D_MOE_CHK();
@@ -3291,25 +3388,26 @@ static int moe_gather_body(const RadArgs* a, RadStream s, bool given) {
}
const unsigned gy = (unsigned)((n + 255) / 256);
/* The chained form where the row resolved with `chain` and this launch is the op's only one
* (no prepass before it: a decode step). */
const bool chain = r4d_geti_or(a, "chain", 0) != 0 && (self || given) && M <= 64;
#define R4D_MG(...) \
hipLaunchKernelGGL((__VA_ARGS__), dim3((unsigned)M, gy), dim3(256), 0, (hipStream_t)s, \
(const uint16_t*)ye->data, (const void*)ew->data, inv, \
(uint16_t*)Y->data, (uint32_t)M, (uint32_t)n, (uint32_t)top_k, \
(uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld, \
self ? (const int32_t*)sorted->data : nullptr, (uint32_t)T, \
sh ? (const uint16_t*)sh->data : nullptr, \
sh ? (const uint16_t*)sg->data : nullptr, \
(uint32_t)sh_ld, (uint32_t)sg_ld, sig)
if (ew->dtype == RAD_F32) {
hipLaunchKernelGGL(
(gather_kernel<256, true>), dim3((unsigned)M, gy), dim3(256), 0, (hipStream_t)s,
(const uint16_t*)ye->data, ew->data, inv, (uint16_t*)Y->data, (uint32_t)M, (uint32_t)n,
(uint32_t)top_k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld,
self ? (const int32_t*)sorted->data : nullptr, (uint32_t)T,
sh ? (const uint16_t*)sh->data : nullptr, sh ? (const uint16_t*)sg->data : nullptr,
(uint32_t)sh_ld, (uint32_t)sg_ld, sig);
R4D_MOE_CHK();
return RAD_OK;
if (chain) R4D_MG(r4dchain_moe_gather<256, true>);
else R4D_MG(gather_kernel<256, true>);
} else {
if (chain) R4D_MG(r4dchain_moe_gather<256>);
else R4D_MG(gather_kernel<256>);
}
hipLaunchKernelGGL((gather_kernel<256>), dim3((unsigned)M, gy), dim3(256), 0, (hipStream_t)s,
(const uint16_t*)ye->data, (const uint16_t*)ew->data, inv,
(uint16_t*)Y->data, (uint32_t)M, (uint32_t)n, (uint32_t)top_k,
(uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld,
self ? (const int32_t*)sorted->data : nullptr, (uint32_t)T,
sh ? (const uint16_t*)sh->data : nullptr,
sh ? (const uint16_t*)sg->data : nullptr,
(uint32_t)sh_ld, (uint32_t)sg_ld, sig);
#undef R4D_MG
R4D_MOE_CHK();
return RAD_OK;
}
@@ -3461,8 +3559,8 @@ struct RgGeom {
};
/* `lg` is neither const nor __restrict__: every block writes it and the last one reads it back. */
template <uint32_t MAXOWN, uint32_t NW>
__device__ __forceinline__ void router_gemm_topk_scatter_kernel_body(
template <uint32_t MAXOWN, uint32_t NW, class CH>
__global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel(
const uint16_t* __restrict__ A, const uint16_t* __restrict__ W,
const uint16_t* __restrict__ Wg, uint16_t* lg, uint16_t* __restrict__ gate,
int32_t* __restrict__ ids, uint16_t* __restrict__ w, int32_t* __restrict__ sorted,
@@ -3470,6 +3568,7 @@ __device__ __forceinline__ void router_gemm_topk_scatter_kernel_body(
RgGeom g, Protect prot) {
/* The GEMM's partial tiles, then (last block only, after two barriers) the sort's LDS; the
* shim sizes it for the larger. */
if (CH::on) r4d_chain_wait();
extern __shared__ __align__(16) unsigned char rg_smem[];
float* const red = (float*)rg_smem;
const uint32_t tid = threadIdx.x, wave = tid / kWave, lane = tid % kWave;
@@ -3516,40 +3615,20 @@ __device__ __forceinline__ void router_gemm_topk_scatter_kernel_body(
if (tid == 0)
s_arrived = __hip_atomic_fetch_add(ctr, 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT);
__syncthreads();
if (s_arrived + 1u != gridDim.x * gridDim.y) return;
if (tid == 0) __hip_atomic_store(ctr, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
__threadfence();
if (s_arrived + 1u == gridDim.x * gridDim.y) {
if (tid == 0) __hip_atomic_store(ctr, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
__threadfence();
/* router_topk_scatter_kernel, from here to the end. */
ScatterLds<NW>& sl = *reinterpret_cast<ScatterLds<NW>*>(rg_smem);
for (uint32_t e = tid; e < g.n_local; e += blockDim.x) sl.cnt[e] = 0;
const SlotSink snk{sl.e, g.base, g.n_local, prot};
for (uint32_t m = wave; m < g.M; m += NW)
router_topk_row<MAXOWN>(lg, ids, w, m, g.n_expert, g.top_k, g.lg_ld, g.norm, lane, snk);
lds_barrier();
scatter_small_place(sorted, off, cnt, g.M * g.top_k, g.n_local, sl);
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <uint32_t MAXOWN, uint32_t NW>
__global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel(
const uint16_t* __restrict__ A, const uint16_t* __restrict__ W,
const uint16_t* __restrict__ Wg, uint16_t* lg, uint16_t* __restrict__ gate,
int32_t* __restrict__ ids, uint16_t* __restrict__ w, int32_t* __restrict__ sorted,
int32_t* __restrict__ off, int32_t* __restrict__ cnt, unsigned int* __restrict__ ctr,
RgGeom g, Protect prot) {
router_gemm_topk_scatter_kernel_body<MAXOWN, NW>(A, W, Wg, lg, gate, ids, w, sorted, off, cnt, ctr, g, prot);
}
template <uint32_t MAXOWN, uint32_t NW>
__global__ __launch_bounds__(NW * kWave) void r4dchain_router_gemm_topk_scatter(
const uint16_t* __restrict__ A, const uint16_t* __restrict__ W,
const uint16_t* __restrict__ Wg, uint16_t* lg, uint16_t* __restrict__ gate,
int32_t* __restrict__ ids, uint16_t* __restrict__ w, int32_t* __restrict__ sorted,
int32_t* __restrict__ off, int32_t* __restrict__ cnt, unsigned int* __restrict__ ctr,
RgGeom g, Protect prot) {
r4d_chain_wait();
router_gemm_topk_scatter_kernel_body<MAXOWN, NW>(A, W, Wg, lg, gate, ids, w, sorted, off, cnt, ctr, g, prot);
r4d_chain_done();
/* router_topk_scatter_kernel, from here to the end. */
ScatterLds<NW>& sl = *reinterpret_cast<ScatterLds<NW>*>(rg_smem);
for (uint32_t e = tid; e < g.n_local; e += blockDim.x) sl.cnt[e] = 0;
const SlotSink snk{sl.e, g.base, g.n_local, prot};
for (uint32_t m = wave; m < g.M; m += NW)
router_topk_row<MAXOWN>(lg, ids, w, m, g.n_expert, g.top_k, g.lg_ld, g.norm, lane, snk);
lds_barrier();
scatter_small_place(sorted, off, cnt, g.M * g.top_k, g.n_local, sl);
}
if (CH::on) r4d_chain_done();
}
/* The arrival counter belongs to the op instance and is taken at init, not on the launch path.
@@ -3725,18 +3804,18 @@ extern "C" int r4d_rad_router_gemm_topk_scatter(const RadArgs* a, RadStream stre
g.sk = (uint32_t)cr.sk; g.tpb = (uint32_t)tpb;
g.nrb = (uint32_t)nrb; g.skg = wg ? (uint32_t)cg.sk : 0u;
const dim3 grid((unsigned)(nrb + (wg ? 1 : 0)), (unsigned)((M + 15) / 16));
/* The chained form (r4d_chain.h) where the row resolved with `chain`. */
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && r4d_chain_rows_ok(M);
#define R4D_RG_L(OWN, NWV) \
emit_rc = R4D_EMIT(stream, (ch ? &r4dchain_router_gemm_topk_scatter<OWN, NWV> \
: &router_gemm_topk_scatter_kernel<OWN, NWV>), grid, \
#define R4D_RG_E(OWN, NWV, CH_) \
emit_rc = R4D_EMIT(stream, (router_gemm_topk_scatter_kernel<OWN, NWV, CH_>), grid, \
dim3((NWV) * kWave), lds, \
(const uint16_t*)x->data, (const uint16_t*)wr->data, \
wg ? (const uint16_t*)wg->data : (const uint16_t*)nullptr, \
(uint16_t*)lg->data, gate ? (uint16_t*)gate->data : (uint16_t*)nullptr, \
(int32_t*)ids->data, (uint16_t*)w->data, (int32_t*)sorted->data, \
(int32_t*)off->data, (int32_t*)cnt->data, ctr, g, prot)
#define R4D_RG_L(OWN, NWV) \
do { if (chain) R4D_RG_E(OWN, NWV, r4dchain); else R4D_RG_E(OWN, NWV, R4dUnchained); } while (0)
const bool chain = r4d_geti_or(a, "chain", 0) != 0;
if (n_expert <= (long long)(8 * kWave)) {
if (nw == 8) R4D_RG_L(8, 8);
else if (nw == 16) R4D_RG_L(8, 16);
@@ -3747,6 +3826,7 @@ extern "C" int r4d_rad_router_gemm_topk_scatter(const RadArgs* a, RadStream stre
else R4D_RG_L(16, 32);
}
#undef R4D_RG_L
#undef R4D_RG_E
if (emit_rc != RAD_OK) return emit_rc;
R4D_MOE_CHK();
return RAD_OK;
+32 -10
View File
@@ -7,6 +7,8 @@
#include "r4d_common.h"
// Internal linkage, as the unit's own definition had.
#include "r4d_chain.h"
namespace r4d_moegather {
namespace {
@@ -31,16 +33,19 @@ __device__ float gather_weight(const void* ew, size_t i) {
if constexpr (F32) return ((const float*)ew)[i];
else return bf16_to_f32(((const uint16_t*)ew)[i]);
}
template <uint32_t NTHR, bool F32 = false>
__global__ __launch_bounds__(NTHR) 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) {
__shared__ int32_t s_i[kGatherSlots];
__shared__ float s_w[kGatherSlots];
/* The body, over the block's two shared tables, which the kernel that calls it owns: a function
* because a block past the last token returns at once, and a chained block must still add to its
* queue's counter (r4d_chain.h). */
#define R4D_MG_PARAMS \
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
#define R4D_MG_ARGS \
ye, ew, inv, y, M, n, top_k, ye_ld, ew_ld, y_ld, sorted, T, sh, sg, sh_ld, sg_ld, sig
template <uint32_t NTHR, bool F32>
__device__ __forceinline__ void gather_body(R4D_MG_PARAMS, int32_t* s_i, float* s_w) {
const uint32_t t = blockIdx.x;
if (t >= M) return;
const bool cached = top_k <= kGatherSlots;
@@ -87,6 +92,23 @@ __global__ __launch_bounds__(NTHR) void gather_kernel(
y[(size_t)t * y_ld + c] = f32_to_bf16(bf16_to_f32(p) + bf16_to_f32(g));
}
}
template <uint32_t NTHR, bool F32 = false>
__global__ __launch_bounds__(NTHR) void gather_kernel(R4D_MG_PARAMS) {
__shared__ int32_t s_i[kGatherSlots];
__shared__ float s_w[kGatherSlots];
gather_body<NTHR, F32>(R4D_MG_ARGS, s_i, s_w);
}
/* The chained form, taken where the gather is the op's one launch (a decode step). */
template <uint32_t NTHR, bool F32 = false>
__global__ __launch_bounds__(NTHR) void r4dchain_moe_gather(R4D_MG_PARAMS) {
__shared__ int32_t s_i[kGatherSlots];
__shared__ float s_w[kGatherSlots];
r4d_chain_wait();
gather_body<NTHR, F32>(R4D_MG_ARGS, s_i, s_w);
r4d_chain_done();
}
#undef R4D_MG_ARGS
#undef R4D_MG_PARAMS
} // namespace
} // namespace r4d_moegather
+746
View File
@@ -0,0 +1,746 @@
// moe_gemm_q over routed experts stored as IQR weights (r4d_iqr.h): every expert's codes in VRAM at
// their own width, decoded where they are read.
//
// One kernel, the dense 16-token narrow tile (r4d_gemm_iqr.hip, iqr_m16_kernel) made run-aware. A
// block serves one run of sorted rows of one expert against a group of 16-row tiles of that
// expert's weight, and a wave decodes each 128-K unit of its tile where it reads it. Decode is the
// cost (about 300 vector instructions a unit and lane, whatever the code width), so the kernel is
// shaped to decode each unit once and to spend as little as it can beside that:
//
// a run of one or two rows takes no tile at all (dot_run): each decoded value's masked hash is
// dotted with its column's activation byte, which sums the hash's bytes and
// multiplies in one instruction. Nothing is packed, transposed or multiplied for
// token columns no row owns. A decode step's runs are almost all of this kind.
// a longer run transposes the unit into fragment order through the wave's LDS tile and runs its
// eight WMMA steps against each 16-row token tile the run reaches, the activation's
// fragments read from global memory where it sits in L2.
//
// There is no shared staging and no block barrier in the K loop; where a tile's K is shared between
// waves their partials are summed through LDS in ascending wave order. The output is the product
// within f32 rounding.
//
// Two grids over x, and the weight's tile groups over y:
// decode inside r4d_moe.hip's decode band. x is (16-row tile of the sorted rows, run within
// it), T slots in all since a tile of r rows holds at most r runs. The block's first
// wave finds the run from the expert offsets in one round of loads and the others take
// it from LDS, so a decode step issues no map. A wave takes a tile and a block four
// tiles; under twenty routed rows four waves share a wide-K tile (gate_up), and through
// the middle of the band a narrow-K wave (down) takes two tiles in turn.
// map above it (a prefill chunk). x is an entry of the run map moe_blockmap_kernel builds in
// the op's scratch, (expert, first row) at 64 rows an entry: a block decodes its
// expert's tiles once for up to four token tiles, a wave a weight tile down all of K.
//
// The forms built are the computed trellis under one f32 scale a row (TrellisMad, kRowF32), IQR-V4's
// form for a feed-forward weight: the fold is the block's factor times the activation's scale, one
// fma a slot, and a row's scale meets its sum once at the store.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_chain.h"
#include "r4d_emit.h"
#include "r4d_fp8_wmma.h"
#include "r4d_iqr.h"
#include "r4d_iqr_dec.h"
#include "r4d_moe_sort.h"
#include <algorithm>
#include <cstdio>
#include <cstring>
/* r4d_moe.hip: the run map of a grouped GEMM at `fm` rows a block, built in `scratch` by one
* launch; its entry count bound, and the bytes it takes. */
long long r4d_moe_blockmap_cap(long long T, long long n_expert, long long fm);
long long r4d_moe_blockmap_bytes(long long cap);
int r4d_moe_blockmap_emit(RadStream s, const int32_t* off, uint32_t n_expert, uint32_t T,
uint32_t fm, uint32_t cap, uint32_t* map);
/* Whether T sorted rows over n_expert experts are served by the decode grid. */
bool r4d_moe_in_decode_band(long long T, long long n_expert);
namespace {
using namespace r4d_fp8;
using namespace r4d_iqr;
using namespace r4d_iqr_dev;
using r4d_moesort::kMaxExpert;
using r4d_moesort::wave_incl_scan_i32;
constexpr uint32_t kWave = 32, kBlock = 128;
/* Sorted rows a block serves: one WMMA tile of tokens. */
constexpr uint32_t kRows = 16;
/* A run-map entry that owns no expert (r4d_moe.hip's kMapTail): dropped slots, zeroed. */
constexpr uint32_t kTail = 0xffffffffu;
/* The biased fold of the int8 tiles under one scale a block (r4d_gemm_8a8_prefill.h): a unit's
* int32 sums start at 0x4B400000, so a slot read as an f32 is 12582912 plus its sum and one fma
* folds it; 12582912 times the folded factors leaves every kRbFlush units and at the store. */
constexpr int kRbBias = 0x4B400000;
constexpr float kRbBiasF = 12582912.0f;
constexpr uint32_t kRbFlush = 8;
#define R4D_MOEIQR_CHK() do { hipError_t e_ = hipGetLastError(); \
if (e_ != hipSuccess) return -100 - (int)e_; } while (0)
/* One class of experts (r4d_moe.hip's MoeCls): expert e is entry e >> cshift of class
* e & (2^cshift - 1), each entry the expert's weight buffer and scale buffer in r4d_iqr.h's
* layout; `n` its rows and `k` its K on this rank. */
struct IqrCls {
const void* const* w;
const void* const* s;
uint32_t n, k;
uint32_t fc, pad_; /* its rows a part: n / parts */
};
/* Routed slot f's token, f / top_k, by the launch's reciprocal `inv_k` (0: top_k is 1): the high
* half of f * (2^32 / top_k + 1) is the quotient for every f below 2^32 / top_k, and a slot index
* is far below that. One multiply where a division is thirty instructions a lane. */
__device__ __forceinline__ uint32_t slot_token(uint32_t f, uint32_t inv_k) {
return inv_k ? __umulhi(f, inv_k) : f;
}
/* A wave-uniform pointer held in scalar registers: its loads take their base from there and a
* lane's offset beside it, with no 64-bit address arithmetic in the lanes. */
template <class T>
__device__ __forceinline__ T* uniform(T* p) {
const uint64_t u = (uint64_t)p;
/* the builtin returns an int: through uint32_t, or the low half sign-extends over the high */
const uint64_t lo = (uint32_t)__builtin_amdgcn_readfirstlane((uint32_t)u);
const uint64_t hi = (uint32_t)__builtin_amdgcn_readfirstlane((uint32_t)(u >> 32));
return (T*)(hi << 32 | lo);
}
/* A run of NR rows, NR at most kDotRows, without the WMMA tile: lane l holds columns 4l .. 4l + 3
* of each unit, and a value's masked hash dotted with its column's activation byte, repeated in
* each byte, sums the hash's bytes and multiplies in one instruction (the GEMV of
* r4d_gemm_iqr.hip). Nothing is packed, transposed through LDS or multiplied for token columns no
* row owns: a unit costs its decode and one dot a value and row. A row's dot starts at 0x4B400000
* less 126 times the lane's activation sum, so read as an f32 it is 12582912 plus the lane's sum
* and one fma folds it; 12582912 times the factors leaves at the end. Returns lane l's share: row
* m's sum over the wave of tile row red16_row(l), in v[m]. */
constexpr uint32_t kDotRows = 2;
template <class F, uint32_t KW, uint32_t NR>
__device__ __forceinline__ void dot_run(const Ctx& c, uint32_t rt, uint32_t kph, uint32_t lane,
const int8_t* const (&xrow)[kDotRows],
const float* const (&xsr)[kDotRows], uint32_t ash,
float (&v)[kDotRows]) {
using D = Dec<F>;
constexpr Form ff{ F::KIND, F::B, F::LV, F::L, F::LRB, F::SC, 0 };
const uint32_t* ab = (const uint32_t*)(c.W + aux_off(ff, c.N, (int64_t)c.nkb * 128));
const float* cf = (const float*)(c.S + cf_off(ff, c.N, (int64_t)c.nkb * 128));
const uint32_t A = ab[0], Bc = ab[1];
float acc[NR][16], fsum[NR];
#pragma unroll
for (uint32_t m = 0; m < NR; ++m) {
fsum[m] = 0.0f;
#pragma unroll
for (uint32_t q = 0; q < 16; ++q) acc[m][q] = 0.0f;
}
uint32_t nflush = 0;
typename D::Raw cur = D::fetch(c, rt, kph, lane, kph < c.nkb), nxt;
uint32_t xc[NR], xn[NR];
#pragma unroll
for (uint32_t m = 0; m < NR; ++m)
xc[m] = kph < c.nkb ? *(const uint32_t*)(xrow[m] + kph * kBlock + 4u * lane) : 0u;
for (uint32_t kb = kph; kb < c.nkb; kb += KW) {
if (kb + KW < c.nkb) {
nxt = D::fetch(c, rt, kb + KW, lane, true);
#pragma unroll
for (uint32_t m = 0; m < NR; ++m)
xn[m] = *(const uint32_t*)(xrow[m] + (kb + KW) * kBlock + 4u * lane);
}
uint32_t xs[NR][4];
float s[NR];
int b0[NR];
const float fb = cf[kb];
#pragma unroll
for (uint32_t m = 0; m < NR; ++m) {
#pragma unroll
for (uint32_t e = 0; e < 4; ++e)
xs[m][e] = __builtin_amdgcn_perm(0u, xc[m], e * 0x01010101u);
s[m] = fb * xsr[m][kb >> ash];
fsum[m] += s[m];
b0[m] = kRbBias -
__builtin_amdgcn_sudot4(true, (int)xc[m], false, 0x7E7E7E7E, 0, false);
}
uint32_t cw[4][D::NW], mw[4][D::NW];
D::columns(cur, cw);
D::mids(cw, mw);
#pragma unroll
for (uint32_t q = 0; q < 16; ++q) {
int d[NR];
#pragma unroll
for (uint32_t m = 0; m < NR; ++m) d[m] = b0[m];
#pragma unroll
for (uint32_t e = 0; e < 4; ++e) {
const uint32_t h = (__umul24(D::state(cw, mw, q, e), A) + Bc) & 0x3F3F3F3Fu;
#pragma unroll
for (uint32_t m = 0; m < NR; ++m)
d[m] = __builtin_amdgcn_sudot4(false, (int)h, true, (int)xs[m][e], d[m], false);
}
/* the stream's position q is tile row 15 - q */
#pragma unroll
for (uint32_t m = 0; m < NR; ++m)
acc[m][15u - q] = __builtin_fmaf(__int_as_float(d[m]), s[m], acc[m][15u - q]);
}
if (++nflush == kRbFlush) {
#pragma unroll
for (uint32_t m = 0; m < NR; ++m) {
#pragma unroll
for (uint32_t q = 0; q < 16; ++q)
acc[m][q] = __builtin_fmaf(-kRbBiasF, fsum[m], acc[m][q]);
fsum[m] = 0.0f;
}
nflush = 0;
}
cur = nxt;
#pragma unroll
for (uint32_t m = 0; m < NR; ++m) xc[m] = xn[m];
}
#pragma unroll
for (uint32_t m = 0; m < NR; ++m) {
#pragma unroll
for (uint32_t q = 0; q < 16; ++q) acc[m][q] = __builtin_fmaf(-kRbBiasF, fsum[m], acc[m][q]);
v[m] = red16(acc[m], lane);
}
#pragma unroll
for (uint32_t m = NR; m < kDotRows; ++m) v[m] = 0.0f;
}
/* KW waves across a tile's K, RTB tiles a block: a wide-K projection (gate_up) takes four waves a
* tile, a narrow one (down, two or three 128-K blocks a rank) one wave a tile and four tiles a
* block. MAP: the run-map grid, whose block serves NT token tiles of its run. */
#define R4D_MOEIQR_PARAMS \
const int8_t* __restrict__ X, const float* __restrict__ XS, const IqrCls c_0, \
const IqrCls c_1, const IqrCls c_2, const IqrCls c_3, const int32_t* __restrict__ sorted, \
const int32_t* __restrict__ off, uint16_t* __restrict__ Y, const uint32_t* __restrict__ map, \
uint32_t T, uint32_t fy, uint32_t n_expert, uint32_t inv_k, uint32_t x_ld, uint32_t xs_ld, \
uint32_t y_ld, uint32_t mode, uint32_t run_tiles, uint32_t inv_ft
template <class F, uint32_t KW, uint32_t RTB, bool MAP, uint32_t NT, uint32_t TPW>
__device__ __forceinline__ void moe_iqr_body(R4D_MOEIQR_PARAMS) {
using D = Dec<F>;
static_assert(D::MAD && F::SC == kRowF32 && F::LRB == 0,
"the routed kernel reads a computed trellis under one f32 scale a row");
static_assert(NT == 1u || (MAP && KW == 1u),
"several token tiles a block: the run map's grid, a wave a weight tile");
static_assert(TPW == 1u || KW == 1u, "several weight tiles a wave: a wave a tile's whole K");
constexpr uint32_t NW = KW * RTB, NTHR = NW * kWave, kCols = RTB * TPW * 16u;
/* `mode`: bit 0 `a_sorted`, bits 1-2 the class shift, bit 3 the activation's scale per 256 of
* K, bits 8+ `parts` (r4d_moe.hip's). */
const uint32_t a_sorted = mode & 1u, cshift = (mode >> 1) & 3u, ash = (mode >> 3) & 1u;
const uint32_t parts = mode >> 8;
/* the waves' transpose tiles, then their partials (8 x 32 floats a wave, in its own tile) */
__shared__ __attribute__((aligned(16))) uint8_t s_tr[NW * kTrBytes];
static_assert(8u * kWave * 4u <= kTrBytes, "a wave's partials in its transpose tile");
__shared__ uint32_t s_sel[4];
auto red = [&](uint32_t w) { return (float*)(s_tr + w * kTrBytes); };
const uint32_t tid = threadIdx.x, lane = tid & (kWave - 1);
const uint32_t wave = __builtin_amdgcn_readfirstlane(tid / kWave);
const uint32_t ycol0 = blockIdx.y * kCols;
/* Rows [ra, rb) of the block's columns, zeroed: dropped slots, which no run owns. */
auto zero_rows = [&](uint32_t ra, uint32_t rb) {
for (uint32_t x = tid; x < (rb - ra) * kCols; x += NTHR)
Y[(size_t)(ra + x / kCols) * y_ld + ycol0 + x % kCols] = 0;
};
/* ---- the block's run: expert e, sorted rows [rs, re). */
uint32_t e, rs, re;
if constexpr (MAP) {
if (blockIdx.x >= map[0]) return;
e = map[1 + 2 * blockIdx.x];
rs = map[2 + 2 * blockIdx.x];
if (e == kTail) {
zero_rows(rs, rs + kRows * NT < T ? rs + kRows * NT : T);
return;
}
const uint32_t oe = (uint32_t)off[e + 1];
re = oe < T ? oe : T;
if (re > rs + kRows * NT) re = rs + kRows * NT;
} else {
/* The (tile, run) grid. The block's first wave finds the run and the others take it from
* LDS after one barrier: each of its lanes holds kMaxExpert / 32 consecutive experts'
* offsets clamped to the tile's rows, so an expert's run meets the tile where its clamped
* bounds differ and those bounds are the run's rows there. The runs are numbered in expert
* order (a lane's own, then a running count over the lanes before it), and the lane holding
* run `jrun` hands over its expert and bounds. Offsets past the last expert read the last
* one's end: an empty run. */
constexpr uint32_t NPT = kMaxExpert / kWave;
static_assert(kMaxExpert % kWave == 0 && NPT <= 16, "a lane's experts in one mask");
const uint32_t r0 = (blockIdx.x / kRows) * kRows, jrun = blockIdx.x % kRows;
if (r0 >= T) return;
const uint32_t rN = r0 + kRows < T ? r0 + kRows : T;
if (wave == 0u) {
uint32_t cv[NPT + 1];
#pragma unroll
for (uint32_t k = 0; k <= NPT; ++k) {
const uint32_t x = lane * NPT + k;
const uint32_t o = (uint32_t)off[x < n_expert ? x : n_expert];
cv[k] = o < r0 ? r0 : o > rN ? rN : o;
}
uint32_t pm = 0;
#pragma unroll
for (uint32_t k = 0; k < NPT; ++k) pm |= (cv[k] < cv[k + 1] ? 1u : 0u) << k;
const uint32_t cnt = (uint32_t)__builtin_popcount(pm);
const uint32_t inc = (uint32_t)wave_incl_scan_i32((int32_t)cnt, lane);
if (lane == kWave - 1) s_sel[3] = inc;
const uint32_t before = inc - cnt;
if (jrun >= before && jrun < before + cnt) {
/* the lane's (jrun - before)-th run: a search of its mask by halves */
uint32_t rem = jrun - before, pos = 0, bits = pm;
#pragma unroll
for (uint32_t h = NPT / 2u; h; h >>= 1) {
const uint32_t c = (uint32_t)__builtin_popcount(bits & ((1u << h) - 1u));
const bool up = rem >= c;
rem -= up ? c : 0u;
pos += up ? h : 0u;
bits = up ? bits >> h : bits;
}
const uint32_t ex = lane * NPT + pos;
const uint32_t oa = (uint32_t)off[ex], ob = (uint32_t)off[ex + 1];
s_sel[0] = ex;
s_sel[1] = oa > r0 ? oa : r0;
s_sel[2] = ob < rN ? ob : rN;
}
}
lds_barrier();
/* The tile's dropped slots, by one of its blocks. */
const uint32_t live = (uint32_t)off[n_expert];
if (jrun == 0 && live < rN) zero_rows(r0 > live ? r0 : live, rN);
if (jrun >= s_sel[3]) return;
e = s_sel[0];
rs = s_sel[1];
re = s_sel[2];
}
/* The run is the block's: in scalar registers, and with it the expert's buffers. */
e = __builtin_amdgcn_readfirstlane(e);
rs = __builtin_amdgcn_readfirstlane(rs);
re = __builtin_amdgcn_readfirstlane(re);
const uint32_t nrows = re - rs;
/* ---- the expert's class and buffers, and this wave's tile of it. */
const uint32_t cls = e & ((1u << cshift) - 1u);
const IqrCls& C = cls == 0u ? c_0 : cls == 1u ? c_1 : cls == 2u ? c_2 : c_3;
Ctx c{};
c.W = uniform((const uint8_t*)C.w[e >> cshift]);
c.S = uniform((const uint8_t*)C.s[e >> cshift]);
c.tab = nullptr;
c.N = C.n;
c.nkb = C.k / kBlock;
c.run_tiles = run_tiles;
/* A part of the output is as wide as the widest class's; a narrower class fills each part's
* leading columns and the rest are zero (r4d_moe.hip's `parts`). */
const uint32_t rtb = wave / KW, kph = wave % KW;
/* `fy` is a part's rows at the widest class and `inv_ft` the reciprocal of its tiles (0: one
* part), the launch's, so the wave's part and tile cost a multiply, not two divisions. */
const uint32_t fc = C.fc, ft = fy / 16u;
/* ---- the run's activation rows, the same for every weight tile of the wave. A run of one or
* two rows takes the dot path, whose rows are the wave's (drow); a longer one the tile path:
* token tile j is the run's rows 16 j .. 16 j + 15, and a lane's token in it is its fragment
* column's sorted row, the run's last row past the run (those columns are not stored).
* gate_up gathers the token's row, down reads the sorted row. */
const bool dot = nrows <= kDotRows;
const uint32_t col = frag_c(lane);
const int8_t* drow[kDotRows];
const float* dsr[kDotRows];
bool dok[kDotRows];
const int8_t* xrow[NT];
const float* xsr[NT];
bool okr[NT];
if (dot) {
#pragma unroll
for (uint32_t m = 0; m < kDotRows; ++m) {
const uint32_t sr = rs + (m < nrows ? m : nrows - 1u);
const int32_t fr = (int32_t)__builtin_amdgcn_readfirstlane((uint32_t)sorted[sr]);
const uint32_t tk = a_sorted ? sr : (fr < 0 ? 0u : slot_token((uint32_t)fr, inv_k));
dok[m] = a_sorted || fr >= 0;
drow[m] = X + (size_t)tk * x_ld;
dsr[m] = XS + (size_t)tk * xs_ld;
}
} else {
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
const uint32_t rj = j * kRows + col;
const uint32_t srow = rs + (rj < nrows ? rj : nrows - 1u);
const int32_t f = sorted[srow];
const uint32_t tok = a_sorted ? srow : (f < 0 ? 0u : slot_token((uint32_t)f, inv_k));
xrow[j] = X + (size_t)tok * x_ld + frag_k0(lane);
xsr[j] = XS + (size_t)tok * xs_ld;
okr[j] = a_sorted || f >= 0;
}
}
/* ---- one weight tile of the wave: `ty` among the block's column tiles. */
auto tile = [&](const uint32_t ty) {
const uint32_t part = inv_ft ? __umulhi(ty, inv_ft) : 0u, tin = ty - part * ft;
const bool pad = tin * 16u >= fc;
const uint32_t rt = part * (fc / 16u) + tin, row0 = rt * 16u;
/* ---- a run of one or two rows: the dot path, no tile. */
if (dot) {
float v[kDotRows];
#pragma unroll
for (uint32_t m = 0; m < kDotRows; ++m) v[m] = 0.0f;
if (!pad) {
if (nrows == 1u) dot_run<F, KW, 1u>(c, rt, kph, lane, drow, dsr, ash, v);
else dot_run<F, KW, 2u>(c, rt, kph, lane, drow, dsr, ash, v);
}
/* Lanes 0-15 hold row 0's sums and 16-31 the same; the upper half takes row 1's. */
float o = r4d_pick(lane < 16u, v[0], v[1]);
if constexpr (KW > 1u) {
red(wave)[lane] = o;
__syncthreads();
if (kph != 0u) return;
o = 0.0f;
#pragma unroll
for (uint32_t w = 0; w < KW; ++w) o += red(rtb * KW + w)[lane];
}
const uint32_t m = lane >> 4, q = red16_row(lane);
if (m < nrows)
Y[(size_t)(rs + m) * y_ld + part * fy + tin * 16u + q] =
f32_to_bf16(!pad && dok[m] ? o * row_scale<F>(c, row0 + q) : 0.0f);
return;
}
/* ---- the tile path. A unit is decoded and transposed once and then multiplied against each
* token tile the run reaches, so a long run pays its decode once for NT * 16 rows. */
f8v out[NT];
float corr[NT]; /* the units' fold factors since the last flush */
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
out[j] = acc_zero();
corr[j] = 0.0f;
}
if (!pad) {
uint32_t nflush = 0;
auto bload = [&](uint32_t j, uint32_t kb, i2v (&b)[8]) {
#pragma unroll
for (uint32_t ks = 0; ks < 8; ++ks) {
const uint2 v = *(const uint2*)(xrow[j] + kb * kBlock + ks * kK);
b[ks][0] = (int)v.x;
b[ks][1] = (int)v.y;
}
};
/* The weight and the first tile's activation fragments are asked for a unit ahead (16-token
* tile: 2-3 % behind without), each further tile's before the WMMA steps of the tile
* before it. */
typename D::Raw cur = D::fetch(c, rt, kph, lane, kph < c.nkb), nxt;
i2v bq[2][8], bn[8];
if (kph < c.nkb) bload(0u, kph, bq[0]);
for (uint32_t kb = kph; kb < c.nkb; kb += KW) {
if (kb + KW < c.nkb) {
nxt = D::fetch(c, rt, kb + KW, lane, true);
bload(0u, kb + KW, bn);
}
uint32_t w[16];
D::rows(cur, c, 1.0f, w);
Stage8 a8[2];
frag(w, s_tr + wave * kTrBytes, lane, a8);
const float fb = fold_f32<F>(c, row0, kb);
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
if (j * kRows < nrows) {
if (j + 1u < NT && (j + 1u) * kRows < nrows) bload(j + 1u, kb, bq[(j + 1u) & 1u]);
f8v raw = __builtin_bit_cast(f8v, (i8v)(kRbBias));
#pragma unroll
for (uint32_t ks = 0; ks < kBlock / kK; ++ks)
raw = mma8<true>(frag_of(a8[ks / 4u], ks % 4u), bq[j & 1u][ks], raw);
const float sb = fb * xsr[j][kb >> ash];
corr[j] += sb;
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
out[j][t] = __builtin_fmaf(raw[t], sb, out[j][t]);
}
}
if (++nflush == kRbFlush) {
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
out[j][t] = __builtin_fmaf(-kRbBiasF, corr[j], out[j][t]);
corr[j] = 0.0f;
}
nflush = 0;
}
cur = nxt;
#pragma unroll
for (uint32_t ks = 0; ks < 8; ++ks) bq[0][ks] = bn[ks];
}
}
#pragma unroll
for (uint32_t j = 0; j < NT; ++j)
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) out[j][t] = __builtin_fmaf(-kRbBiasF, corr[j], out[j][t]);
if constexpr (KW > 1u) {
/* each wave's partials in its own tile, behind its last transpose's reads */
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront", "local");
__builtin_amdgcn_wave_barrier();
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) red(wave)[t * kWave + lane] = out[0][t];
__syncthreads();
if (kph != 0u) return;
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
float a = 0.0f;
#pragma unroll
for (uint32_t w = 0; w < KW; ++w) a += red(rtb * KW + w)[t * kWave + lane];
out[0][t] = a;
}
}
const uint32_t a0 = acc_row(lane, 0);
float rsc[8];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) rsc[t] = pad ? 0.0f : row_scale<F>(c, row0 + a0 + t);
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
const uint32_t rj = j * kRows + col;
if (rj < nrows) {
float v[8];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) v[t] = okr[j] ? out[j][t] * rsc[t] : 0.0f;
*(uint4*)(Y + (size_t)(rs + rj) * y_ld + part * fy + tin * 16u + a0) =
make_uint4(bf16x2_rne(v[0], v[1]), bf16x2_rne(v[2], v[3]),
bf16x2_rne(v[4], v[5]), bf16x2_rne(v[6], v[7]));
}
}
};
/* A wave whose tile is all of its K (KW 1) takes TPW tiles in turn: the run search and the
* rows above are paid once for them, which a narrow-K projection (two or three units a tile)
* otherwise pays as a third of its work. */
for (uint32_t tw = 0; tw < TPW; ++tw) tile((blockIdx.y * RTB + rtb) * TPW + tw);
}
/* The kernel around the body, whose blocks return where their work ends: CH `r4dchain` is the
* chained form (r4d_chain.h), every block waiting before its first read and adding once after
* its last write. */
template <class F, uint32_t KW, uint32_t RTB, bool MAP, uint32_t NT, uint32_t TPW, class CH>
__global__ __launch_bounds__(KW * RTB * kWave) R4D_WAVES(8)
void moe_iqr_kernel(R4D_MOEIQR_PARAMS) {
if (CH::on) r4d_chain_wait();
moe_iqr_body<F, KW, RTB, MAP, NT, TPW>(X, XS, c_0, c_1, c_2, c_3, sorted, off, Y, map, T, fy,
n_expert, inv_k, x_ld, xs_ld, y_ld, mode, run_tiles,
inv_ft);
if (CH::on) r4d_chain_done();
}
#undef R4D_MOEIQR_PARAMS
/* Token tiles a block of the run map's grid: a run of up to 64 rows decodes its expert once. */
constexpr uint32_t kMapTiles = 4;
/* The routed rows between which a narrow-K wave takes two weight tiles. Flash-Next's down
* projection (2560 x 384:256, 512 experts, top 10), us a launch at one tile -> two: 10 rows 11.1 ->
* 11.9 (too few waves to fill the card), 20 rows level, 30 rows 21.1 -> 20.3, 80 rows 48.0 -> 44.1,
* 160 rows 88.1 -> 78.4, 240 rows 134.8 -> 129.2, and 320 to 480 rows 4-6 % slower again. */
constexpr uint32_t kTwoTileMinRows = 24, kTwoTileMaxRows = 256;
/* The routed rows from which a wide-K tile is one wave's instead of four waves' share: fewer waves
* pay the run search and the partial sum through LDS, once enough runs fill the card. Flash-Next's
* gate_up (768:512 x 2560), us a launch at four waves -> one: 10 rows 15.5 -> 16.3, 20 rows 24.8 ->
* 24.2, 40 rows 46.3 -> 41.0, 80 rows 81.7 -> 69.7, 160 rows 188 -> 168, 320 rows 380 -> 332,
* 640 rows 642 -> 522. */
constexpr uint32_t kOneWaveMinRows = 20;
/* The forms built: the computed trellis under one f32 scale a row at two to six bits. */
#define R4D_MOEIQR_FORMS(X) \
X(2, 15) X(2, 16) X(3, 16) X(4, 16) X(5, 16) X(6, 16)
struct Launch {
const int8_t* x;
const float* xs;
IqrCls c[4];
const int32_t *sorted, *off;
uint16_t* y;
uint32_t* map;
uint32_t T, N, n_expert, inv_k, x_ld, xs_ld, y_ld, mode, run_tiles, inv_ft;
uint32_t gx, nkb;
bool chain; /* the chained form (r4d_chain.h) */
};
template <class F>
int launch_form(const Launch& g, RadStream stream) {
int rc;
#define R4D_MOEIQR_E(kw_, rtb_, map_, nt_, tpw_, ch_) \
rc = R4D_EMIT(stream, (moe_iqr_kernel<F, kw_, rtb_, map_, nt_, tpw_, ch_>), \
dim3(g.gx, g.N / (16u * rtb_ * tpw_)), dim3(kw_ * rtb_ * kWave), 0, g.x, g.xs, \
g.c[0], g.c[1], g.c[2], g.c[3], g.sorted, g.off, g.y, (const uint32_t*)g.map, \
g.T, g.N / (g.mode >> 8), g.n_expert, g.inv_k, g.x_ld, g.xs_ld, g.y_ld, g.mode, \
g.run_tiles, g.inv_ft)
#define R4D_MOEIQR_GO(kw_, rtb_, map_, nt_, tpw_) \
do { if (g.chain) R4D_MOEIQR_E(kw_, rtb_, map_, nt_, tpw_, r4dchain); \
else R4D_MOEIQR_E(kw_, rtb_, map_, nt_, tpw_, R4dUnchained); } while (0)
/* The run map's grid (prefill): a wave a weight tile down all of its K, four tiles a block,
* kMapTiles token tiles a decode. The decode grid: a wave a tile and a block four, except that
* a wide K (eight 128-K blocks and up) under kOneWaveMinRows routed rows is shared between
* four waves a tile, and a narrow one between kTwoTileMinRows and kTwoTileMaxRows rows gives a
* wave two tiles in turn and a block eight. */
const bool wide_k = g.nkb >= 8u && (g.T < kOneWaveMinRows || (g.N / 16u) % 4u);
const bool two = !wide_k && g.nkb < 8u && g.N % (16u * 8u) == 0u &&
g.T >= kTwoTileMinRows && g.T <= kTwoTileMaxRows;
if (g.map) R4D_MOEIQR_GO(1u, 4u, true, kMapTiles, 1u);
else if (wide_k) R4D_MOEIQR_GO(4u, 1u, false, 1u, 1u);
else if (!two) R4D_MOEIQR_GO(1u, 4u, false, 1u, 1u);
else R4D_MOEIQR_GO(1u, 4u, false, 1u, 2u);
#undef R4D_MOEIQR_GO
#undef R4D_MOEIQR_E
return rc;
}
/* moe_gemm_q's operands (r4d_moe.hip's moe_gemm_launch): [0] a [1] a_scale [2] w [3] w_scale
* [4] sorted [5] off, then the further classes' tables and y. */
int moe_iqr_launch(const RadArgs* a, RadStream stream, int ncls) {
if (ncls != 2 && ncls != 4) return R4D_NO(RAD_E_INVAL);
const RadTensor* Aq = r4d_opt(a, 0);
const RadTensor* As = r4d_opt(a, 1);
const RadTensor* sorted = r4d_opt(a, 4);
const RadTensor* off = r4d_opt(a, 5);
const RadTensor* Wc[4] = { r4d_opt(a, 2), r4d_opt(a, 6),
ncls == 4 ? r4d_opt(a, 8) : nullptr,
ncls == 4 ? r4d_opt(a, 10) : nullptr };
const RadTensor* Wsc[4] = { r4d_opt(a, 3), r4d_opt(a, 7),
ncls == 4 ? r4d_opt(a, 9) : nullptr,
ncls == 4 ? r4d_opt(a, 11) : nullptr };
const RadTensor* Y = r4d_opt(a, ncls == 4 ? 12 : 8);
if (!Aq || !As || !sorted || !off || !Y) return R4D_NO(RAD_E_INVAL);
if (!Aq->data || !As->data || !sorted->data || !off->data || !Y->data)
return R4D_NO(RAD_E_INVAL);
static const char* const kNk[4][2] = { { "N", "K" }, { "N_1", "K_1" }, { "N_2", "K_2" },
{ "N_3", "K_3" } };
long long Nc[4] = { 0, 0, 0, 0 }, Kc[4] = { 0, 0, 0, 0 };
Nc[0] = r4d_geti_or(a, "N", 0);
Kc[0] = r4d_geti_or(a, "K", 0);
for (int q = 1; q < ncls; ++q) {
Nc[q] = r4d_geti_or(a, ncls == 4 ? kNk[q][0] : "N_odd", Nc[0]);
Kc[q] = r4d_geti_or(a, ncls == 4 ? kNk[q][1] : "K_odd", Kc[0]);
}
const long long parts = r4d_geti_or(a, "parts", 1);
const long long n_expert = r4d_geti_or(a, "n_expert", 0);
const long long top_k = r4d_geti_or(a, "top_k", 0);
if (parts <= 0 || parts > 255 || n_expert <= 0 || top_k <= 0) return R4D_NO(RAD_E_SHAPE);
if (n_expert > (long long)kMaxExpert) return R4D_NO(RAD_E_UNSUPPORTED);
if (r4d_geti_or(a, "group", kBlock) != (long long)kBlock) return R4D_NO(RAD_E_SHAPE);
const long long a_group = r4d_geti_or(a, "a_group", kBlock);
if (a_group != (long long)kBlock && a_group != 2 * (long long)kBlock)
return R4D_NO(RAD_E_UNSUPPORTED);
/* Every class holds one form: the tables' dtype is the layout's word (r4d_iqr.h). */
const uint32_t wdt = Wc[0] ? Wc[0]->dtype : 0u;
if (!is_weight_dtype(wdt)) return R4D_NO(RAD_E_DTYPE);
const uint32_t word_ = wdt & kWordMask;
const Form fm = form(word_);
if (fm.kind != kTrellisMad || fm.scale != kRowF32 || fm.lrb != 0 || fm.lrun < 4)
return R4D_NO(RAD_E_DTYPE);
const long long run = (long long)1 << fm.lrun;
long long N = 0, K = 0;
Launch g{};
for (int q = 0; q < ncls; ++q) {
const long long cnt = (n_expert + ncls - 1 - q) / ncls;
if (!Wc[q] || !Wsc[q] || Nc[q] <= 0 || Kc[q] <= 0) return R4D_NO(RAD_E_INVAL);
if (Wc[q]->dtype != wdt || Wsc[q]->dtype != (R4D_DT_IQR_S | word_))
return R4D_NO(RAD_E_DTYPE);
/* Pointer tables, one entry an expert (the core's weight_table_tensor). */
if (Wc[q]->rank != 3 || Wsc[q]->rank != 3 || Wc[q]->stride[0] != 0 ||
Wsc[q]->stride[0] != 0 || Wc[q]->shape[0] < cnt || Wsc[q]->shape[0] < cnt ||
(cnt > 0 && (!Wc[q]->data || !Wsc[q]->data)))
return R4D_NO(RAD_E_SHAPE);
/* A part of a class is whole 16-row tiles and whole trellis runs; K whole 128s and whole
* activation scale groups. */
if (Kc[q] % a_group || Nc[q] % (16 * parts) || (Nc[q] / parts) % run)
return R4D_NO(RAD_E_SHAPE);
g.c[q].w = (const void* const*)Wc[q]->data;
g.c[q].s = (const void* const*)Wsc[q]->data;
g.c[q].n = (uint32_t)Nc[q];
g.c[q].fc = (uint32_t)(Nc[q] / parts);
g.c[q].pad_ = 0;
g.c[q].k = (uint32_t)Kc[q];
if (Nc[q] > N) N = Nc[q];
if (Kc[q] > K) K = Kc[q];
}
for (int q = ncls; q < 4; ++q) g.c[q] = g.c[0];
if (Aq->dtype != RAD_I8 || As->dtype != RAD_F32 || Y->dtype != RAD_BF16 ||
sorted->dtype != RAD_I32 || off->dtype != RAD_I32)
return R4D_NO(RAD_E_DTYPE);
long long T = 0, M = 0, Ms = 0;
const long long y_ld = r4d_rows_pitch(Y, N, &T);
if (y_ld < 0 || T <= 0) return R4D_NO(RAD_E_STRIDE);
const long long a_ld = r4d_rows_pitch(Aq, K, &M);
if (a_ld < 0 || M <= 0) return R4D_NO(RAD_E_STRIDE);
const long long as_ld = r4d_rows_pitch(As, K / a_group, &Ms);
if (as_ld < 0 || Ms < M) return R4D_NO(RAD_E_STRIDE);
if (r4d_numel(sorted) < T || r4d_numel(off) < n_expert + 1) return R4D_NO(RAD_E_SHAPE);
const char* ord = r4d_gets(a, "a_order");
const bool a_sorted = ord && !std::strcmp(ord, "sorted");
if (ord && !a_sorted && std::strcmp(ord, "token")) return R4D_NO(RAD_E_UNSUPPORTED);
if (M < (a_sorted ? T : (T + top_k - 1) / top_k)) return R4D_NO(RAD_E_SHAPE);
g.nkb = (uint32_t)(K / kBlock);
const bool band = r4d_moe_in_decode_band(T, n_expert);
/* a narrow-K projection and the run map's grid take four weight tiles a block */
if (((!band || g.nkb < 8u) && (N / 16) % 4) || (N / parts) % 16) return R4D_NO(RAD_E_SHAPE);
g.x = (const int8_t*)Aq->data;
g.xs = (const float*)As->data;
g.sorted = (const int32_t*)sorted->data;
g.off = (const int32_t*)off->data;
g.y = (uint16_t*)Y->data;
g.T = (uint32_t)T;
g.N = (uint32_t)N;
g.n_expert = (uint32_t)n_expert;
if (top_k * T > (long long)1 << 31) return R4D_NO(RAD_E_SHAPE);
g.inv_k = top_k == 1 ? 0u : (uint32_t)(((uint64_t)1 << 32) / (uint64_t)top_k + 1u);
g.x_ld = (uint32_t)a_ld;
g.xs_ld = (uint32_t)as_ld;
g.y_ld = (uint32_t)y_ld;
g.run_tiles = (uint32_t)(run / 16);
/* a part's tiles as a reciprocal (slot_token's bound: a tile index is far below 2^32 / tiles) */
if (parts > 1 && N / parts < 32) return R4D_NO(RAD_E_SHAPE);
g.inv_ft = parts > 1 ? (uint32_t)(((uint64_t)1 << 32) / (uint64_t)(N / parts / 16) + 1u) : 0u;
const uint32_t cshift = ncls == 4 ? 2u : 1u;
g.mode = (a_sorted ? 1u : 0u) | cshift << 1 | (a_group == 2 * (long long)kBlock ? 8u : 0u) |
(uint32_t)parts << 8;
if (band) {
g.map = nullptr;
/* A tile of r rows holds at most r runs, so T slots serve every tile: slot x is run
* x % 16 of tile x / 16, and the last tile's slots end with its rows. */
g.gx = (uint32_t)T;
/* The band's one launch has a chained form; the run map's two launches stay plain. */
g.chain = r4d_geti_or(a, "chain", 0) != 0;
} else {
const long long cap = r4d_moe_blockmap_cap(T, n_expert, kRows * kMapTiles);
if (!a->scratch || a->scratch_bytes < r4d_moe_blockmap_bytes(cap))
return R4D_NO(RAD_E_SCRATCH);
g.map = (uint32_t*)a->scratch;
const int rc = r4d_moe_blockmap_emit(stream, g.off, g.n_expert, g.T, kRows * kMapTiles,
(uint32_t)cap, g.map);
if (rc != RAD_OK) return rc;
g.gx = (uint32_t)cap;
}
int rc = R4D_NO(RAD_E_DTYPE);
#define R4D_MOEIQR_CASE(b_, l_) \
if (fm.bits == b_ && fm.L == l_) \
rc = launch_form<FormT<kTrellisMad, b_, 0, l_, 0, kRowF32>>(g, stream);
R4D_MOEIQR_FORMS(R4D_MOEIQR_CASE)
#undef R4D_MOEIQR_CASE
if (rc != RAD_OK) return rc;
R4D_MOEIQR_CHK();
return RAD_OK;
}
int64_t moe_iqr_scratch(const RadArgs* a) {
const long long n_expert = r4d_geti_or(a, "n_expert", 0);
const long long top_k = r4d_geti_or(a, "top_k", 0);
const long long M = r4d_geti_or(a, "M", 0);
if (n_expert <= 0 || n_expert > (long long)kMaxExpert || top_k <= 0 || M <= 0) return 0;
const long long T = M * top_k;
if (r4d_moe_in_decode_band(T, n_expert)) return 0;
return r4d_moe_blockmap_bytes(r4d_moe_blockmap_cap(T, n_expert, kRows * kMapTiles));
}
} // namespace
extern "C" int r4d_rad_moe_gemm_iqr(const RadArgs* a, RadStream s) {
return moe_iqr_launch(a, s, 2);
}
extern "C" int r4d_rad_moe_gemm_iqr_mod4(const RadArgs* a, RadStream s) {
return moe_iqr_launch(a, s, 4);
}
extern "C" int64_t r4d_rad_moe_gemm_iqr_scratch(const RadArgs* a) { return moe_iqr_scratch(a); }
File diff suppressed because it is too large. Load diff
+187 -20
View File
@@ -19,6 +19,7 @@
// change to make if a model hashes at prefill width with many more heads.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_chain.h"
#include "r4d_emit.h"
#include <cstdint>
@@ -47,15 +48,15 @@ enum { kNgMaxShift = 8, kNgThreads = 256 };
*
* At decode this op's cost is the dispatch itself (flat from M=1 to M=512), so avoiding a second
* launch for the write-back is most of the saving. */
__global__ __launch_bounds__(kNgThreads) void ngram_ids_kernel(
const int32_t* __restrict__ tok, int32_t* __restrict__ state,
const int32_t* __restrict__ cu, const long long* __restrict__ mult,
const long long* __restrict__ vsz, const long long* __restrict__ off,
const int32_t* __restrict__ sidx, const int32_t* __restrict__ hini,
const int32_t* __restrict__ nacc, int32_t* __restrict__ ids,
uint32_t heads, uint32_t ngram, uint32_t per, uint32_t W,
long long eos, uint32_t ids_ld, int32_t* __restrict__ ahead, uint32_t n_ahead,
uint32_t ahead_ld) {
#define NGRAM_IDS_PARAMS \
const int32_t* __restrict__ tok, int32_t* __restrict__ state, \
const int32_t* __restrict__ cu, const long long* __restrict__ mult, \
const long long* __restrict__ vsz, const long long* __restrict__ off, \
const int32_t* __restrict__ sidx, const int32_t* __restrict__ hini, \
const int32_t* __restrict__ nacc, int32_t* __restrict__ ids, uint32_t heads, \
uint32_t ngram, uint32_t per, uint32_t W, long long eos, uint32_t ids_ld, \
int32_t* __restrict__ ahead, uint32_t n_ahead, uint32_t ahead_ld
__device__ __forceinline__ void ngram_ids_body(NGRAM_IDS_PARAMS) {
const uint32_t s = blockIdx.y;
const uint32_t bos = (uint32_t)cu[s];
@@ -146,6 +147,111 @@ __global__ __launch_bounds__(kNgThreads) void ngram_ids_kernel(
for (uint32_t k = 0; k < ctx; ++k) win[k] = (int32_t)keep[k];
}
/* The kernel around the body, whose blocks return where their work ends: CH `r4dchain` is the
* chained form (r4d_chain.h). */
template <class CH>
__global__ __launch_bounds__(kNgThreads)
void ngram_ids_kernel(NGRAM_IDS_PARAMS) {
if (CH::on) r4d_chain_wait();
ngram_ids_body(tok, state, cu, mult, vsz, off, sidx, hini, nacc, ids, heads, ngram, per, W, eos, ids_ld, ahead, n_ahead, ahead_ld);
if (CH::on) r4d_chain_done();
}
#undef NGRAM_IDS_PARAMS
/* ngram_hint: the row ids of each sequence's NEWEST token on a draft head's pass, ahead of the
* verify step that will run it, so the rows can be fetched while the head drafts.
*
* A verify step's rows are the token the last verify chose and the head's proposals. The head
* proposes one a pass: its history pass ends at the chosen token, each later round reads the
* proposal before it. So all but the last proposal are known a pass or more before ngram_ids
* hashes them, and a table read from a drive has that long to deliver their rows.
*
* One thread a sequence. `tail` holds, per state slot, the `ngram - 1` committed ids up to the
* chosen token and the same count of ids up to the newest proposal, each newest last:
*
* hist the pass's last row is the chosen token; rows at its position are repeats of it
* (the history pass pads a run to the furthest the verify could have committed), and
* the rows before them hold the ids committed just before, in order. Ids further back
* come from the committed tail. Both tails then end at the chosen token.
* else the row is the proposal before this round's; the ids before it are the chain tail,
* which then ends at it.
*
* The hash is ngram_ids'. The ids are a hint: a slot whose tail belongs to another request (the
* first pass after a prompt) hashes other history and names rows nobody reads, which costs their
* fetch and nothing else, so there is no cold-window rule here. */
#define NGRAM_HINT_PARAMS \
const int32_t* __restrict__ tok, const int32_t* __restrict__ pos, \
const int32_t* __restrict__ cu, const long long* __restrict__ mult, \
const long long* __restrict__ vsz, const long long* __restrict__ off, \
const int32_t* __restrict__ sidx, int32_t* __restrict__ tail, int32_t* __restrict__ ids, \
uint32_t n_seq, uint32_t heads, uint32_t ngram, uint32_t per, long long eos, \
uint32_t ids_ld, uint32_t hist, uint32_t slots
__device__ __forceinline__ void ngram_hint_body(NGRAM_HINT_PARAMS) {
const uint32_t s = blockIdx.x * kNgThreads + threadIdx.x;
if (s >= n_seq) return;
const uint32_t bos = (uint32_t)cu[s], eot = (uint32_t)cu[s + 1];
const int32_t slot = sidx ? sidx[s] : (int32_t)s;
int32_t* const row = ids + (long long)s * ids_ld;
/* A sequence with nothing to hint still gets ids a gather can read: its heads' first rows. */
if (eot <= bos || slot < 0) {
for (uint32_t h = 0; h < heads; ++h) row[h] = (int32_t)off[h];
return;
}
const uint32_t ctx = ngram - 1u;
/* Two slots that meet in `tail` (a state slot past its rows) swap hints, no more. */
int32_t* const commit = tail + (long long)((uint32_t)slot % slots) * 2 * ctx;
int32_t* const chain = commit + ctx;
/* `back[k]` is the id k + 1 places before the newest. */
const uint32_t last = eot - 1u;
const long long x = (long long)tok[last];
long long back[kNgMaxShift];
if (hist) {
uint32_t first = last;
const int32_t at = pos[last];
while (first > bos && pos[first - 1u] == at) --first;
const uint32_t have = first - bos;
for (uint32_t k = 0; k < ctx; ++k)
back[k] = k < have ? (long long)tok[first - 1u - k]
: (long long)commit[ctx - 1u - (k - have)];
} else {
for (uint32_t k = 0; k < ctx; ++k) back[k] = (long long)chain[ctx - 1u - k];
}
for (uint32_t k = 0; k < ctx; ++k) {
const int32_t v = k + 1u < ctx ? (int32_t)back[ctx - 2u - k] : (int32_t)x;
if (hist) commit[k] = v;
chain[k] = v;
}
long long sh[kNgMaxShift];
sh[0] = x;
bool cut = false;
for (uint32_t k = 1; k < ngram; ++k) {
if (cut || sh[k - 1] == eos) { cut = true; sh[k] = eos; continue; }
sh[k] = back[k - 1u];
}
long long mixed = 0;
for (uint32_t k = 0; k < ngram; ++k) {
const long long term = ng_wrap_mul(sh[k], mult[k]);
mixed = k == 0 ? term : (mixed ^ term);
if (k == 0) continue;
for (uint32_t j = 0; j < per; ++j) {
const uint32_t h = (k - 1u) * per + j;
row[h] = (int32_t)(ng_floor_mod(mixed, vsz[h]) + off[h]);
}
}
}
template <class CH>
__global__ __launch_bounds__(kNgThreads)
void ngram_hint_kernel(NGRAM_HINT_PARAMS) {
if (CH::on) r4d_chain_wait();
ngram_hint_body(tok, pos, cu, mult, vsz, off, sidx, tail, ids, n_seq, heads, ngram, per, eos,
ids_ld, hist, slots);
if (CH::on) r4d_chain_done();
}
#undef NGRAM_HINT_PARAMS
} // namespace
enum { NG_TOK = 0, NG_STATE, NG_CU, NG_MULT, NG_VSZ, NG_OFF, NG_CIDX, NG_HINIT, NG_NACC, NG_IDS,
@@ -206,15 +312,76 @@ extern "C" int r4d_rad_ngram_ids(const RadArgs* a, RadStream stream) {
* any one sequence's; a short sequence's extra blocks find their rows past its end. A
* per-sequence count would mean reading `cu` on the host. */
const uint32_t tiles = (uint32_t)((T + A + kNgThreads - 1) / kNgThreads);
return R4D_EMIT(stream, ngram_ids_kernel, dim3(tiles, (uint32_t)N), dim3(kNgThreads), 0,
(const int32_t*)r4d_addr(tok), (int32_t*)r4d_addr(st),
(const int32_t*)r4d_addr(cu), (const long long*)r4d_addr(mult),
(const long long*)r4d_addr(vsz), (const long long*)r4d_addr(off),
cidx ? (const int32_t*)r4d_addr(cidx) : nullptr,
hini ? (const int32_t*)r4d_addr(hini) : nullptr,
nacc ? (const int32_t*)r4d_addr(nacc) : nullptr,
(int32_t*)r4d_addr(ids), (uint32_t)heads, (uint32_t)ngram,
(uint32_t)per, (uint32_t)W, eos, (uint32_t)ids_ld,
A > 0 ? (int32_t*)r4d_addr(ahd) : nullptr, (uint32_t)A,
(uint32_t)ahead_ld);
#define R4D_NGI(CH_) \
R4D_EMIT(stream, ngram_ids_kernel<CH_>, dim3(tiles, (uint32_t)N), dim3(kNgThreads), \
0, \
(const int32_t*)r4d_addr(tok), (int32_t*)r4d_addr(st), \
(const int32_t*)r4d_addr(cu), (const long long*)r4d_addr(mult), \
(const long long*)r4d_addr(vsz), (const long long*)r4d_addr(off), \
cidx ? (const int32_t*)r4d_addr(cidx) : nullptr, \
hini ? (const int32_t*)r4d_addr(hini) : nullptr, \
nacc ? (const int32_t*)r4d_addr(nacc) : nullptr, \
(int32_t*)r4d_addr(ids), (uint32_t)heads, (uint32_t)ngram, \
(uint32_t)per, (uint32_t)W, eos, (uint32_t)ids_ld, \
A > 0 ? (int32_t*)r4d_addr(ahd) : nullptr, (uint32_t)A, \
(uint32_t)ahead_ld)
const int rc = r4d_geti_or(a, "chain", 0) != 0 && T <= 64 ? R4D_NGI(r4dchain)
: R4D_NGI(R4dUnchained);
#undef R4D_NGI
return rc;
}
enum { NH_TOK = 0, NH_POS, NH_CU, NH_MULT, NH_VSZ, NH_OFF, NH_CIDX, NH_TAIL, NH_IDS };
extern "C" int r4d_rad_ngram_hint(const RadArgs* a, RadStream stream) {
const RadTensor* tok = r4d_opt(a, NH_TOK);
const RadTensor* pos = r4d_opt(a, NH_POS);
const RadTensor* cu = r4d_opt(a, NH_CU);
const RadTensor* mult = r4d_opt(a, NH_MULT);
const RadTensor* vsz = r4d_opt(a, NH_VSZ);
const RadTensor* off = r4d_opt(a, NH_OFF);
const RadTensor* cidx = r4d_opt(a, NH_CIDX);
const RadTensor* tail = r4d_opt(a, NH_TAIL);
const RadTensor* ids = r4d_opt(a, NH_IDS);
if (!tok || !pos || !cu || !mult || !vsz || !off || !tail || !ids) return R4D_NO(RAD_E_INVAL);
if (tok->dtype != RAD_I32 || pos->dtype != RAD_I32 || cu->dtype != RAD_I32 ||
tail->dtype != RAD_I32 || ids->dtype != RAD_I32 || (cidx && cidx->dtype != RAD_I32))
return R4D_NO(RAD_E_DTYPE);
if (mult->dtype != RAD_I64 || vsz->dtype != RAD_I64 || off->dtype != RAD_I64)
return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(tok) || !r4d_contig(pos) || !r4d_contig(cu) || !r4d_contig(tail))
return R4D_NO(RAD_E_STRIDE);
const long long heads = r4d_geti_or(a, "heads", 0);
const long long ngram = r4d_geti_or(a, "ngram", 0);
const long long eos = r4d_geti_or(a, "eos", -1);
const long long hist = r4d_geti_or(a, "hist", 0);
if (heads <= 0 || ngram < 2 || eos < 0) return R4D_NO(RAD_E_SHAPE);
if (ngram > kNgMaxShift) return R4D_NO(RAD_E_UNSUPPORTED);
if (heads % (ngram - 1)) return R4D_NO(RAD_E_SHAPE);
const long long per = heads / (ngram - 1);
/* A row of ids a sequence, counted from the operand (`M` is ranged). */
const long long N = r4d_numel(cu) - 1;
long long rows = 0;
const long long ids_ld = r4d_rows_pitch(ids, heads, &rows);
if (ids_ld < 0 || N <= 0 || rows < N) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(mult) < ngram || r4d_numel(vsz) < heads || r4d_numel(off) < heads)
return R4D_NO(RAD_E_SHAPE);
if (cidx && r4d_numel(cidx) < N) return R4D_NO(RAD_E_SHAPE);
const long long slots = r4d_numel(tail) / (2 * (ngram - 1));
if (slots < 1) return R4D_NO(RAD_E_SHAPE);
const uint32_t blocks = (uint32_t)((N + kNgThreads - 1) / kNgThreads);
#define R4D_NGH(CH_) \
R4D_EMIT(stream, ngram_hint_kernel<CH_>, dim3(blocks), dim3(kNgThreads), 0, \
(const int32_t*)r4d_addr(tok), (const int32_t*)r4d_addr(pos), \
(const int32_t*)r4d_addr(cu), (const long long*)r4d_addr(mult), \
(const long long*)r4d_addr(vsz), (const long long*)r4d_addr(off), \
cidx ? (const int32_t*)r4d_addr(cidx) : nullptr, (int32_t*)r4d_addr(tail), \
(int32_t*)r4d_addr(ids), (uint32_t)N, (uint32_t)heads, (uint32_t)ngram, \
(uint32_t)per, eos, (uint32_t)ids_ld, (uint32_t)(hist ? 1 : 0), (uint32_t)slots)
const int rc = r4d_geti_or(a, "chain", 0) != 0 ? R4D_NGH(r4dchain) : R4D_NGH(R4dUnchained);
#undef R4D_NGH
return rc;
}
+46 -13
View File
@@ -26,6 +26,8 @@
* the bf16-rounded norm, a scale of amax * (1 / 448) per 128 columns (1 for an all-zero group),
* value times reciprocal clamped to +-448, one v_cvt_pk_fp8_f32. Element i is thread i % 256 at
* slot i / 256, so a group is four waves at one slot: a wave max, then the four.
* norm_add_norm_route_i8g writes the experts' input as rmsnorm_had_quant_i8g does instead: int8
* codes of the bf16-rounded norm rotated by a 128-wide Hadamard, a scale of amax * (1 / 127).
*
* One 256-thread block per row: a decode step is a handful of rows, so the row is latency bound
* and three block reductions beat seven launches. Values a later stage reuses stay in registers
@@ -42,6 +44,7 @@
#include "r4d_plugin.h"
#include "r4d_launch.h"
#include "r4d_q8.h" // norm_add_norm_route_i8g's rotated int8 codes
#include "rad_plugin.h"
namespace r4d_join {
@@ -114,11 +117,15 @@ struct NormArgs {
};
/* t = norm(a) * w_a; x += t; y = norm(x) * w_y -- and with ROUTE, from the same norm of x, the
* router's input norm(x) * w_r * mult and the experts' norm(x) * w_e as E4M3 codes and scales */
template <int PER, bool ROUTE>
* router's input norm(x) * w_r * mult and the experts' norm(x) * w_e as codes and scales: E4M3
* (ROUTE 1), or at ROUTE 2 had_quant_act_i8g's rotated int8. The rotation's butterfly wants a
* group in one wave, four columns a lane, where this kernel holds a column a thread, so the
* experts' bf16 row goes through LDS to that mapping (r4d_q8.h, q8_row_had_i8g). */
template <int PER, int ROUTE>
__global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) {
__shared__ float lds[kWaves];
__shared__ float gmax[ROUTE ? PER * kWaves : 1];
__shared__ float gmax[ROUTE == 1 ? PER * kWaves : 1];
__shared__ uint16_t erow[ROUTE == 2 ? PER * kThreads : 1];
const int tid = (int)threadIdx.x, n = A.n;
const long long m = (long long)blockIdx.x;
const uint16_t* ar = A.a + m * A.a_ld;
@@ -164,13 +171,20 @@ __global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) {
yr[i] = f2bf((xv[k] * sx) * wy[k]);
if constexpr (ROUTE) {
rr[i] = f2bf(((xv[k] * sx) * wr[k]) * A.mult);
av[k] = rbf((xv[k] * sx) * we[k]); /* the experts' row, as quantised */
const uint16_t he = f2bf((xv[k] * sx) * we[k]);
av[k] = bf2f(he); /* the experts' row, as quantised */
if constexpr (ROUTE == 2) erow[i] = he;
}
} else if constexpr (ROUTE) {
av[k] = 0.0f;
}
}
if constexpr (ROUTE) {
if constexpr (ROUTE == 2) {
__syncthreads();
q8_row_had_i8g<kThreads>(erow, (signed char*)(A.q + m * A.q_ld), A.qs + m * A.qs_ld,
(uint32_t)n);
}
if constexpr (ROUTE == 1) {
/* group 2k + tid / 128 at slot k is waves 0..3 or 4..7: each wave's max, then its four */
const int wave = tid >> 5, half = tid >> 7;
#pragma unroll
@@ -326,16 +340,19 @@ int r4d_rad_norm_add_norm_bf16(const RadArgs* a, RadStream stream) {
P.w0 = (const float*)Wa->data; P.w1 = (const float*)Wy->data;
P.n = (int)n; P.eps = eps;
if (n <= (int64_t)kThreads * 12)
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<12, false>), dim3((unsigned)M), dim3(kThreads),
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<12, 0>), dim3((unsigned)M), dim3(kThreads),
(hipStream_t)stream, P);
else
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<kMaxPer, false>), dim3((unsigned)M),
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<kMaxPer, 0>), dim3((unsigned)M),
dim3(kThreads), (hipStream_t)stream, P);
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
/* operands: a, w_a, x (inout), w_y, y, w_r, r, w_e, q, qs */
int r4d_rad_norm_add_norm_route_bf16(const RadArgs* a, RadStream stream) {
} /* extern "C" */
/* operands: a, w_a, x (inout), w_y, y, w_r, r, w_e, q, qs; `i8` is norm_add_norm_route_i8g, whose
* q is int8 */
static int norm_add_norm_route(const RadArgs* a, RadStream stream, bool i8) {
using namespace r4d_join;
if (!a || a->n_t < 10) return RAD_E_INVAL;
int64_t n = 0;
@@ -351,7 +368,7 @@ int r4d_rad_norm_add_norm_route_bf16(const RadArgs* a, RadStream stream) {
int64_t ra = 0, la = 0, rx = 0, lx = 0, ry = 0, ly = 0, rr = 0, lr = 0, rq = 0, lq = 0,
rs = 0, ls = 0;
if (!rows_of(A_, n, &ra, &la) || !rows_of(X, n, &rx, &lx) || !rows_of(Y, n, &ry, &ly) ||
!rows_of(R, n, &rr, &lr) || !rows_as(Q, RAD_F8E4M3, n, &rq, &lq) ||
!rows_of(R, n, &rr, &lr) || !rows_as(Q, i8 ? RAD_I8 : RAD_F8E4M3, n, &rq, &lq) ||
!rows_as(S, RAD_F32, n / 128, &rs, &ls))
return RAD_E_SHAPE;
const int64_t M = rx; /* the step's rows: the stream's view */
@@ -368,15 +385,31 @@ int r4d_rad_norm_add_norm_route_bf16(const RadArgs* a, RadStream stream) {
P.w2 = (const float*)Wr->data; P.w3 = (const float*)We->data;
P.mult = (float)rad_args_getf_or(a, "mult", 1.0);
P.n = (int)n; P.eps = eps;
if (n <= (int64_t)kThreads * 12)
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<12, true>), dim3((unsigned)M), dim3(kThreads),
const bool narrow = n <= (int64_t)kThreads * 12;
if (narrow && i8)
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<12, 2>), dim3((unsigned)M), dim3(kThreads),
(hipStream_t)stream, P);
else if (narrow)
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<12, 1>), dim3((unsigned)M), dim3(kThreads),
(hipStream_t)stream, P);
else if (i8)
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<kMaxPer, 2>), dim3((unsigned)M),
dim3(kThreads), (hipStream_t)stream, P);
else
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<kMaxPer, true>), dim3((unsigned)M),
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<kMaxPer, 1>), dim3((unsigned)M),
dim3(kThreads), (hipStream_t)stream, P);
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
extern "C" {
int r4d_rad_norm_add_norm_route_bf16(const RadArgs* a, RadStream stream) {
return norm_add_norm_route(a, stream, false);
}
int r4d_rad_norm_add_norm_route_i8g_bf16(const RadArgs* a, RadStream stream) {
return norm_add_norm_route(a, stream, true);
}
/* operands: d, w_d, r, w_r, w_j, x (inout), s, w_n?, y? -- the last two both or neither */
int r4d_rad_join_add_scale_bf16(const RadArgs* a, RadStream stream) {
using namespace r4d_join;
+28
View File
@@ -0,0 +1,28 @@
/* r4d_par.h -- the load-time relayouts' split of one weight over the host's cores. */
#pragma once
#include <algorithm>
#include <thread>
#include <vector>
namespace r4d_par {
/* Runs f(lo, hi) over [0, n) in parallel chunks, one thread for every `per_thread` items' worth of
* work and at most 16. A model's weights relayout at load, gigabytes of them, so a large one is
* split over the host's cores; the loader already runs several relayouts side by side, so a small
* one stays on the calling thread rather than starting threads that would only contend. */
template <typename F>
void par_for(long long n, long long per_thread, F f) {
const long long hc = std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
const long long nt = std::max(1ll, std::min(hc, n / std::max(1ll, per_thread)));
if (nt == 1) {
f(0ll, n);
return;
}
const long long per = (n + nt - 1) / nt;
std::vector<std::thread> th;
for (long long lo = 0; lo < n; lo += per) th.emplace_back(f, lo, std::min(n, lo + per));
for (std::thread& t : th) t.join();
}
} // namespace r4d_par
+40 -22
View File
@@ -29,6 +29,7 @@
// on `hist < kPcBT`, asserted below.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_chain.h"
#include "r4d_common.h"
#include <cstdint>
@@ -54,16 +55,16 @@ __device__ __forceinline__ float pc_silu(float z) { return z / (1.0f + expf(-z))
/* SILU is ple_conv's activation; causal_conv1d (LFM2's short convolution) is the same window with
* no activation, no residual and dilation one. */
#define PLE_CONV_PARAMS \
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, \
uint16_t* __restrict__ cs, const int32_t* __restrict__ cu, \
const uint16_t* __restrict__ resid, const int32_t* __restrict__ sidx, \
const int32_t* __restrict__ hini, const int32_t* __restrict__ nacc, \
uint16_t* __restrict__ y, const uint16_t* __restrict__ bias, uint32_t n, uint32_t wid, \
uint32_t dil, uint32_t hist, uint32_t xld, uint32_t rld, uint32_t yld, uint32_t wld, \
long long cs_slot, long long cs_ch, long long cs_tok, long long state_len
template <bool SILU>
__global__ __launch_bounds__(kPcThreads) void ple_conv_kernel(
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
uint16_t* __restrict__ cs, const int32_t* __restrict__ cu,
const uint16_t* __restrict__ resid, const int32_t* __restrict__ sidx,
const int32_t* __restrict__ hini, const int32_t* __restrict__ nacc,
uint16_t* __restrict__ y, const uint16_t* __restrict__ bias,
uint32_t n, uint32_t wid, uint32_t dil, uint32_t hist,
uint32_t xld, uint32_t rld, uint32_t yld, uint32_t wld,
long long cs_slot, long long cs_ch, long long cs_tok, long long state_len) {
__device__ __forceinline__ void ple_conv_body(PLE_CONV_PARAMS) {
const uint32_t c = blockIdx.x * kPcThreads + threadIdx.x;
if (c >= n) return;
@@ -151,6 +152,18 @@ __global__ __launch_bounds__(kPcThreads) void ple_conv_kernel(
if (i < hist) dst[(size_t)i * cs_tok] = keep[i];
}
/* The kernel around the body, whose blocks return where their work ends: CH `r4dchain` is the
* chained form (r4d_chain.h), taken at decode heights. */
template <bool SILU, class CH>
__global__ __launch_bounds__(kPcThreads)
void ple_conv_kernel(PLE_CONV_PARAMS) {
if (CH::on) r4d_chain_wait();
ple_conv_body<SILU>(x, w, cs, cu, resid, sidx, hini, nacc, y, bias, n, wid, dil, hist, xld, rld,
yld, wld, cs_slot, cs_ch, cs_tok, state_len);
if (CH::on) r4d_chain_done();
}
#undef PLE_CONV_PARAMS
enum { PC_X = 0, PC_W, PC_CS, PC_CU, PC_RESID, PC_CIDX, PC_HINIT, PC_NACC, PC_Y };
/* ple_conv_bias: ple_conv's operands with `b`, the per-channel bias inside the silu (Mamba-2's
* conv1d), before `y`. */
@@ -216,19 +229,24 @@ int conv_launch(const RadArgs* a, RadStream s, bool silu, const RadTensor* x, co
const uint32_t cb = (uint32_t)((n + kPcThreads - 1) / kPcThreads);
const uint32_t tb = (uint32_t)((T + kPcBT - 1) / kPcBT);
const auto kernel = silu ? ple_conv_kernel<true> : ple_conv_kernel<false>;
hipLaunchKernelGGL(kernel, dim3(cb, tb, (uint32_t)N), dim3(kPcThreads), 0, (hipStream_t)s,
(const uint16_t*)r4d_addr(x), (const uint16_t*)r4d_addr(w),
have_cs ? (uint16_t*)r4d_addr(cs) : nullptr,
(const int32_t*)r4d_addr(cu),
resid ? (const uint16_t*)r4d_addr(resid) : nullptr,
cidx ? (const int32_t*)r4d_addr(cidx) : nullptr,
hini ? (const int32_t*)r4d_addr(hini) : nullptr,
nacc ? (const int32_t*)r4d_addr(nacc) : nullptr,
(uint16_t*)r4d_addr(y), b ? (const uint16_t*)r4d_addr(b) : nullptr,
(uint32_t)n, (uint32_t)wid, (uint32_t)dil,
(uint32_t)hist, (uint32_t)xld, (uint32_t)rld, (uint32_t)yld, (uint32_t)wld,
cs_slot, cs_ch, cs_tok, state_len);
const bool chain = r4d_geti_or(a, "chain", 0) != 0 && T <= 64;
#define R4D_PC(S_, CH_) \
hipLaunchKernelGGL((ple_conv_kernel<S_, CH_>), dim3(cb, tb, (uint32_t)N), \
dim3(kPcThreads), 0, (hipStream_t)s, \
(const uint16_t*)r4d_addr(x), (const uint16_t*)r4d_addr(w), \
have_cs ? (uint16_t*)r4d_addr(cs) : nullptr, \
(const int32_t*)r4d_addr(cu), \
resid ? (const uint16_t*)r4d_addr(resid) : nullptr, \
cidx ? (const int32_t*)r4d_addr(cidx) : nullptr, \
hini ? (const int32_t*)r4d_addr(hini) : nullptr, \
nacc ? (const int32_t*)r4d_addr(nacc) : nullptr, \
(uint16_t*)r4d_addr(y), b ? (const uint16_t*)r4d_addr(b) : nullptr, \
(uint32_t)n, (uint32_t)wid, (uint32_t)dil, \
(uint32_t)hist, (uint32_t)xld, (uint32_t)rld, (uint32_t)yld, (uint32_t)wld, \
cs_slot, cs_ch, cs_tok, state_len)
if (silu) { if (chain) R4D_PC(true, r4dchain); else R4D_PC(true, R4dUnchained); }
else { if (chain) R4D_PC(false, r4dchain); else R4D_PC(false, R4dUnchained); }
#undef R4D_PC
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
+32 -15
View File
@@ -26,6 +26,7 @@
// property to check a fused kernel against, never one to fold.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_chain.h"
#include "r4d_common.h"
#include <cstdint>
@@ -57,13 +58,14 @@ __device__ __forceinline__ float pg_reduce(float v, float* lds) {
return r;
}
__global__ __launch_bounds__(kPgThreads) void ple_gate_kernel(
const uint16_t* __restrict__ k, const uint16_t* __restrict__ q,
const uint16_t* __restrict__ v, const float* __restrict__ wk,
const float* __restrict__ wq, const float* __restrict__ wc,
uint16_t* __restrict__ gv, uint16_t* __restrict__ gvn,
uint32_t n, uint32_t hc, uint32_t k_ld, uint32_t q_ld, uint32_t v_ld,
uint32_t g_ld, uint32_t gn_ld, float eps, float wadd, float geps, uint32_t per_thread) {
#define PLE_GATE_PARAMS \
const uint16_t* __restrict__ k, const uint16_t* __restrict__ q, \
const uint16_t* __restrict__ v, const float* __restrict__ wk, \
const float* __restrict__ wq, const float* __restrict__ wc, uint16_t* __restrict__ gv, \
uint16_t* __restrict__ gvn, uint32_t n, uint32_t hc, uint32_t k_ld, uint32_t q_ld, \
uint32_t v_ld, uint32_t g_ld, uint32_t gn_ld, float eps, float wadd, float geps, \
uint32_t per_thread
__device__ __forceinline__ void ple_gate_body(PLE_GATE_PARAMS) {
__shared__ float lds[kPgThreads];
/* At most 16 elements per thread: n <= 16 * kPgThreads = 4096, which the row constrains. */
@@ -126,6 +128,17 @@ __global__ __launch_bounds__(kPgThreads) void ple_gate_kernel(
}
}
/* The kernel around the body, whose blocks return where their work ends: CH `r4dchain` is the
* chained form (r4d_chain.h), taken at decode heights. */
template <class CH>
__global__ __launch_bounds__(kPgThreads)
void ple_gate_kernel(PLE_GATE_PARAMS) {
if (CH::on) r4d_chain_wait();
ple_gate_body(k, q, v, wk, wq, wc, gv, gvn, n, hc, k_ld, q_ld, v_ld, g_ld, gn_ld, eps, wadd, geps, per_thread);
if (CH::on) r4d_chain_done();
}
#undef PLE_GATE_PARAMS
enum { PG_K = 0, PG_Q, PG_V, PG_WK, PG_WQ, PG_WC, PG_GV, PG_GVN };
} // namespace
@@ -169,13 +182,17 @@ extern "C" int r4d_rad_ple_gate(const RadArgs* a, RadStream s) {
if (r4d_numel(wk) < hn || r4d_numel(wq) < hn || r4d_numel(wc) < hn)
return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(ple_gate_kernel, dim3((uint32_t)(T * hc)), dim3(kPgThreads), 0,
(hipStream_t)s,
(const uint16_t*)r4d_addr(k), (const uint16_t*)r4d_addr(q),
(const uint16_t*)r4d_addr(v), (const float*)r4d_addr(wk),
(const float*)r4d_addr(wq), (const float*)r4d_addr(wc),
(uint16_t*)r4d_addr(gv), (uint16_t*)r4d_addr(gvn),
(uint32_t)n, (uint32_t)hc, (uint32_t)k_ld, (uint32_t)q_ld, (uint32_t)v_ld,
(uint32_t)g_ld, (uint32_t)gn_ld, eps, wadd, geps, (uint32_t)per_thread);
#define R4D_PG(CH_) \
hipLaunchKernelGGL(ple_gate_kernel<CH_>, dim3((uint32_t)(T * hc)), dim3(kPgThreads), 0, \
(hipStream_t)s, \
(const uint16_t*)r4d_addr(k), (const uint16_t*)r4d_addr(q), \
(const uint16_t*)r4d_addr(v), (const float*)r4d_addr(wk), \
(const float*)r4d_addr(wq), (const float*)r4d_addr(wc), \
(uint16_t*)r4d_addr(gv), (uint16_t*)r4d_addr(gvn), \
(uint32_t)n, (uint32_t)hc, (uint32_t)k_ld, (uint32_t)q_ld, (uint32_t)v_ld, \
(uint32_t)g_ld, (uint32_t)gn_ld, eps, wadd, geps, (uint32_t)per_thread)
if (r4d_geti_or(a, "chain", 0) != 0 && T <= 64) R4D_PG(r4dchain);
else R4D_PG(R4dUnchained);
#undef R4D_PG
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
+110 -140
View File
@@ -112,92 +112,87 @@ enum {
extern "C" {
/* -- attention (r4d_attn_*.hip) -- */
int r4d_rad_attn_prefill_h256_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8_qk8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8_pv8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8_qk8pv8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_fp8v4(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8v4(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8v4_qk8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8v4_pv8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8v4_qk8pv8(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_v4_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_k6v4(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_k6v4(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_k6v4_qk8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_k6v4_pv8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_k6v4_qk8pv8(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_k6_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_bf16 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_bf16 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_i8_scratch(const RadArgs*);
int64_t r4d_rad_attn_decode_h256_scratch(const RadArgs*);
/* The prefill rows' KV-split partials (r4d_attn_paged_h256_gqa6.hip, prefill_scratch), by cache
* row: fp8 and bf16, fp8_v4, k6_v4. */
int64_t r4d_rad_attn_prefill_h256_scratch(const RadArgs*);
int64_t r4d_rad_attn_prefill_h256_v4_scratch(const RadArgs*);
int64_t r4d_rad_attn_prefill_h256_k6_scratch(const RadArgs*);
/* The i8 cache on the same geometry (int8 K and V, an f16 scale each per token and head). */
int r4d_rad_attn_prefill_h256_i8(const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_i8_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_i8(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_i8_scratch(const RadArgs*);
int64_t r4d_rad_attn_decode_h128_scratch(const RadArgs*);
/* Gemma 4 dense sliding window (r4d_attn_paged_h256_gqa2.hip): head_dim 256, 2 queries per KV
* head. Both bands: decode (q_len*gqa <= 64, verify width 32 against the gqa6 leg's 10) and
* windowed prefill (the gqa6 leg's r4d_attn_prefill_kernel with WIN on). */
int r4d_rad_attn_prefill_h256_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_gqa2_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa2_i8_scratch(const RadArgs*);
int r4d_rad_attn_prefill_h256_gqa2_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa2_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa2_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa2_i8_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa2_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs*);
/* Gemma 3 sliding window (r4d_attn_paged_h128_gqa2w.hip): head_dim 128, 2 queries per KV head,
* window >= 1. Decode (q_len*gqa <= 64) and windowed prefill, as the h256/gqa2 pair above. */
int r4d_rad_attn_prefill_h128_gqa2w_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h128_gqa2w_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h128_gqa2w_bf16 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa2w_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa2w_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa2w_i8_scratch(const RadArgs*);
int r4d_rad_attn_decode_h128_gqa2w_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa2w_scratch(const RadArgs*);
/* attn_paged_qrow on the split-KV decode kernel: the h256/gqa2 decode with q at its own pitch, and
* head_dim 128 at gqa 8 as the gqa-4 kernel with two query groups a kv head (R4DArgs::kv_rep). */
int r4d_rad_attn_qrow_decode_h256_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_qrow_decode_h256_gqa2_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_qrow_decode_h256_gqa2_i8_scratch(const RadArgs*);
int r4d_rad_attn_qrow_decode_h256_gqa2_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_qrow_decode_h256_gqa2_scratch(const RadArgs*);
int r4d_rad_attn_qrow_h128_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_qrow_h128_gqa8_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_qrow_h128_gqa8_i8_scratch(const RadArgs*);
int r4d_rad_attn_qrow_h128_gqa8_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_qrow_h128_gqa8_scratch(const RadArgs*);
/* Paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV head, any window, causal or not
* (r4d_attn_paged_window.hip): one entry point per geometry and cache dtype, every q_len and any q
* row pitch, so they serve both attn_paged and attn_paged_qrow. */
int r4d_rad_attn_window_h128_gqa1_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h128_gqa1_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h128_gqa1_i8 (const RadArgs*, RadStream);
/* The same kernels under attn_paged_sink (a sink logit a query head). */
int r4d_rad_attn_window_sink_h128_gqa8_bf16 (const RadArgs*, RadStream);
int r4d_rad_attn_window_sink_h128_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_sink_h128_gqa8_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_sink_h128_gqa16_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_sink_h128_gqa16_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_sink_h128_gqa16_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa1_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa1_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa1_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa2_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa2_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_tree_h256_gqa2_i8(const RadArgs*, RadStream);
int r4d_rad_attn_window_ahead_h256_gqa2_i8(const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa4_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa4_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa4_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa8_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa8_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa1_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa1_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa1_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa2_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa2_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa4_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa4_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa4_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa8_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa8_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_tree_h512_gqa8_i8(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa16_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa16_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa16_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_window_h128_scratch(const RadArgs*);
int64_t r4d_rad_attn_window_h256_scratch(const RadArgs*);
int64_t r4d_rad_attn_window_h512_scratch(const RadArgs*);
#define R4D_ATTN_ANCHOR_DECL(HD, G) \
int r4d_rad_attn_anchor_window_h##HD##_gqa##G##_bf16kv(const RadArgs*, RadStream); \
int r4d_rad_attn_anchor_window_h##HD##_gqa##G##_fp8kv(const RadArgs*, RadStream);
int r4d_rad_attn_anchor_window_h##HD##_gqa##G##_i8kv(const RadArgs*, RadStream);
R4D_ATTN_ANCHOR_DECL(128, 1)
R4D_ATTN_ANCHOR_DECL(256, 1) R4D_ATTN_ANCHOR_DECL(256, 2) R4D_ATTN_ANCHOR_DECL(256, 4)
R4D_ATTN_ANCHOR_DECL(256, 8)
@@ -208,11 +203,11 @@ int r4d_rad_dflash_markov_greedy(const RadArgs*, RadStream);
int r4d_rad_dflash_markov_greedy_f32(const RadArgs*, RadStream);
/* attn_paged_qrow_tree (docs/OPS.md): the h256/gqa2 split-KV decode and the windowed kernels with a
* tree verify's mask from operand 8, `spec_parent`. */
int r4d_rad_attn_qrow_tree_decode_h256_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_qrow_tree_decode_h256_gqa2_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_qrow_tree_decode_h256_gqa2_bf16(const RadArgs*, RadStream);
#define R4D_WIN_TREE_DECL(HD, G) \
int r4d_rad_attn_window_tree_h##HD##_gqa##G##_bf16(const RadArgs*, RadStream); \
int r4d_rad_attn_window_tree_h##HD##_gqa##G##_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_tree_h##HD##_gqa##G##_i8 (const RadArgs*, RadStream);
R4D_WIN_TREE_DECL(256, 1) R4D_WIN_TREE_DECL(256, 2) R4D_WIN_TREE_DECL(256, 4) R4D_WIN_TREE_DECL(256, 8)
R4D_WIN_TREE_DECL(512, 1) R4D_WIN_TREE_DECL(512, 2) R4D_WIN_TREE_DECL(512, 4) R4D_WIN_TREE_DECL(512, 8)
#undef R4D_WIN_TREE_DECL
@@ -220,7 +215,7 @@ R4D_WIN_TREE_DECL(512, 1) R4D_WIN_TREE_DECL(512, 2) R4D_WIN_TREE_DECL(512, 4) R4
* window that bounds the keys behind only. */
#define R4D_WIN_AHEAD_DECL(HD, G) \
int r4d_rad_attn_window_ahead_h##HD##_gqa##G##_bf16(const RadArgs*, RadStream); \
int r4d_rad_attn_window_ahead_h##HD##_gqa##G##_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_ahead_h##HD##_gqa##G##_i8 (const RadArgs*, RadStream);
R4D_WIN_AHEAD_DECL(256, 1) R4D_WIN_AHEAD_DECL(256, 2) R4D_WIN_AHEAD_DECL(256, 4) R4D_WIN_AHEAD_DECL(256, 8)
#undef R4D_WIN_AHEAD_DECL
/* dflash_tree (r4d_dflash_tree_bf16.hip): dflash_select's lattice grown best-first into a tree. */
@@ -238,6 +233,7 @@ int r4d_rad_lili_walk (const RadArgs*, RadStream);
* each routing weight by its expert's scale (r4d_expert_scale_bf16.hip). */
int r4d_rad_norm_add_norm_bf16 (const RadArgs*, RadStream);
int r4d_rad_norm_add_norm_route_bf16(const RadArgs*, RadStream);
int r4d_rad_norm_add_norm_route_i8g_bf16(const RadArgs*, RadStream);
int r4d_rad_join_add_scale_bf16 (const RadArgs*, RadStream);
int r4d_rad_expert_scale_bf16 (const RadArgs*, RadStream);
/* Runtime LoRA's two halves, each row's adapter named by its slot (r4d_lora_bf16.hip): the scalar
@@ -267,7 +263,7 @@ int r4d_rad_chan_stats (const RadArgs*, RadStream);
int r4d_rad_attn_dense_wide (const RadArgs*, RadStream);
/* The image generator's other ops (r4d_gen.hip). */
int r4d_rad_ln_mod (const RadArgs*, RadStream);
int r4d_rad_ln_mod_quant_fp8 (const RadArgs*, RadStream);
int r4d_rad_ln_mod_had_quant_i8g (const RadArgs*, RadStream);
int r4d_rad_gate_add (const RadArgs*, RadStream);
int r4d_rad_timestep_embed (const RadArgs*, RadStream);
int r4d_rad_gather_rows2 (const RadArgs*, RadStream);
@@ -314,8 +310,8 @@ int r4d_rad_int_affine (const RadArgs*, RadStream);
int r4d_rad_sub_i32 (const RadArgs*, RadStream);
/* r4d_video.hip */
int r4d_rad_rms_mod (const RadArgs*, RadStream);
int r4d_rad_rms_mod_quant_fp8 (const RadArgs*, RadStream);
int r4d_rad_rms_mod_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_rms_mod_had_quant_i8g (const RadArgs*, RadStream);
int r4d_rad_flow_x0_step (const RadArgs*, RadStream);
int r4d_rad_flow_res_multistep (const RadArgs*, RadStream);
int r4d_rad_patch_unfold (const RadArgs*, RadStream);
@@ -359,102 +355,105 @@ int64_t r4d_rad_quant_cols_fp8_scratch(const RadArgs*);
/* Eight queries per KV head (r4d_attn_paged_gqa8.hip): the routed 35B-A3B at head_dim 256 and
* MiniCPM5-2B at 128. A decode workgroup holds 64 rows of q_len*gqa, so the verify width (the
* row's constraint value) is 8, against the gqa6 leg's 10. */
int r4d_rad_attn_prefill_h256_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_gqa8_bf16(const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa8_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa8_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa8_scratch(const RadArgs*);
int r4d_rad_attn_prefill_h128_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h128_gqa8_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa8_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa8_scratch(const RadArgs*);
/* The i8 cache at head_dim 128 (R4D_ATTN_I8 in r4d_attn_paged_gqa8.hip). */
int r4d_rad_attn_prefill_h128_gqa8_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa8_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa8_i8_scratch(const RadArgs*);
/* SEVEN queries a KV head, head_dim 128 -- Nanbeige4.3-33B (56 over 8). Same body at 21 warps and
* a 63-row decode cap (r4d_attn_paged_h128_gqa7.hip). */
int r4d_rad_attn_prefill_h128_gqa7_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h128_gqa7_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h128_gqa7_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa7_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa7_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa7_i8_scratch(const RadArgs*);
int r4d_rad_attn_decode_h128_gqa7_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa7_scratch(const RadArgs*);
/* ONE query a KV head, head_dim 128 -- plain MHA, the Unlimited-OCR decoder (10 over 10). Both
* legs from the generic body instantiated at ratio 1 (r4d_attn_paged_h128_gqa1.hip). */
int r4d_rad_attn_prefill_h128_gqa1_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h128_gqa1_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h128_gqa1_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa1_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa1_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa1_i8_scratch(const RadArgs*);
int r4d_rad_attn_decode_h128_gqa1_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa1_scratch(const RadArgs*);
/* Four queries per KV head, head_dim 256 only (Qwen3.5-0.8B); same body, another instantiation
* (r4d_attn_paged_h256_gqa4.hip). */
int r4d_rad_attn_prefill_h256_gqa4_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_gqa4_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa4_i8_scratch(const RadArgs*);
int r4d_rad_attn_prefill_h256_gqa4_bf16(const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa4_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa4_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa4_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa4_i8_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa4_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa4_scratch(const RadArgs*);
/* ...and its head_dim 64 prefill leg, LFM2's geometry, serving every query length. */
int r4d_rad_attn_prefill_h64_gqa4_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h64_gqa4_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h64_gqa4_bf16(const RadArgs*, RadStream);
/* Two queries per KV head at head_dim 128 (Qwen3-1.7B, Qwen3-ASR's decoder): the gqa8 body at
* gqa 2 (r4d_attn_paged_h128_gqa2.hip). */
int r4d_rad_attn_prefill_h128_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h128_gqa2_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h128_gqa2_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa2_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa2_i8_scratch(const RadArgs*);
int r4d_rad_attn_decode_h128_gqa2_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa2_scratch(const RadArgs*);
/* Sixteen queries per KV head at head_dim 128 (Nemotron-H): the gqa8 body at gqa 16
* (r4d_attn_paged_h128_gqa16.hip). */
int r4d_rad_attn_prefill_h128_gqa16_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h128_gqa16_i8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h128_gqa16_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa16_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa16_i8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa16_i8_scratch(const RadArgs*);
int r4d_rad_attn_decode_h128_gqa16_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa16_scratch(const RadArgs*);
/* Twelve queries per KV head, head_dim 256 only: Qwen3.8-Flash-Next's QSA layers. Same body,
* another instantiation (r4d_attn_paged_h256_gqa12.hip). */
int r4d_rad_attn_prefill_h256_gqa12_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_gqa12_bf16(const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa12_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa12_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa12_bf16 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa12_fp8(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa12_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_ghq_h256_gqa12_bf16(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa12_scratch(const RadArgs*);
/* Six queries per KV head, head_dim 256, paged block 4: the same QSA layers at four ranks, with
* the KV head replicated across a rank pair. The verify width is 64/6 = 10 against gqa12's 5,
* the decode rows' constraint value. */
int r4d_rad_attn_prefill_h256_gqa6_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_gqa6_bf16(const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa6_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa6_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa6_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa6_scratch(const RadArgs*);
/* The same two merges with the output gate and the quantiser, at the four-rank ratio. The body
* instantiates these at every ratio (`R4D_ATTN_GQA` pastes them), so this needed a row, not a
* kernel; see attn_decode_gq_h256_gqa6_fp8kv. */
int r4d_rad_attn_decode_gq_h256_gqa6_fp8(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa6_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_ghq_h256_gqa6_bf16(const RadArgs*, RadStream);
/* The fp8_v4 and k6_v4 caches on both: prefill, decode, and decode with the gate and quantiser in
* the merge (R4D_ATTN_V4 in r4d_attn_paged_gqa8.hip). */
int r4d_rad_attn_prefill_h256_gqa12_fp8v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa12_fp8v4_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa12_fp8v4(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa12_fp8v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa12_fp8v4_scratch(const RadArgs*);
int r4d_rad_attn_prefill_h256_gqa12_k6v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa12_k6v4_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa12_k6v4(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa12_k6v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa12_k6v4_scratch(const RadArgs*);
int r4d_rad_attn_prefill_h256_gqa6_fp8v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa6_fp8v4_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa6_fp8v4(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa6_fp8v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa6_fp8v4_scratch(const RadArgs*);
int r4d_rad_attn_prefill_h256_gqa6_k6v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa6_k6v4_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa6_k6v4(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa6_k6v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa6_k6v4_scratch(const RadArgs*);
/* The i8 cache on the same two (gqa 12, and gqa 6 at 4-token pages) and at gqa 8 with 16-token
* pages (Qwen3.6-35B-A3B): prefill, decode, and decode with the gate and quantiser in the merge
* (`_gq`: gate_quant_fp8's codes, `_ghq`: gate_had_quant_i8g's). */
int r4d_rad_attn_prefill_h256_gqa12_i8(const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa12_i8_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa12_i8(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa12_i8(const RadArgs*, RadStream);
int r4d_rad_attn_decode_ghq_h256_gqa12_i8(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa12_i8_scratch(const RadArgs*);
int r4d_rad_attn_prefill_h256_gqa6_i8(const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa6_i8_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa6_i8(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa6_i8(const RadArgs*, RadStream);
int r4d_rad_attn_decode_ghq_h256_gqa6_i8(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa6_i8_scratch(const RadArgs*);
int r4d_rad_attn_prefill_h256_gqa8_i8(const RadArgs*, RadStream);
int64_t r4d_rad_attn_prefill_h256_gqa8_i8_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_gqa8_i8(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa8_i8(const RadArgs*, RadStream);
int r4d_rad_attn_decode_ghq_h256_gqa8_i8(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa8_i8_scratch(const RadArgs*);
/* -- gated delta net (r4d_gdn_*.hip) -- */
int r4d_rad_gdn_chunk_scan (const RadArgs*, RadStream);
@@ -478,9 +477,6 @@ int r4d_rad_mhc_pre_partial(const RadArgs*, RadStream);
int r4d_rad_mhc_pre_finish(const RadArgs*, RadStream);
int r4d_rad_kda_update(const RadArgs*, RadStream);
int r4d_rad_ssd_update(const RadArgs*, RadStream);
int r4d_rad_moe_mxfp4(const RadArgs*, RadStream);
int r4d_rad_layout_moe_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_mhc_post(const RadArgs*, RadStream);
int r4d_rad_mhc_contract(const RadArgs*, RadStream);
int r4d_rad_mtp_enter (const RadArgs*, RadStream);
@@ -536,7 +532,6 @@ int r4d_rad_gemm_w5a16_m64 (const RadArgs*, RadStream);
int r4d_rad_gemm_w4a16asym_m64(const RadArgs*, RadStream);
int r4d_rad_gemm_w4a8i8_tiled(const RadArgs*, RadStream);
int r4d_rad_gemm_w5a8i8_tiled(const RadArgs*, RadStream);
int r4d_rad_givens_dense_quant(const RadArgs*, RadStream);
int r4d_rad_gemm_w8a16_m64 (const RadArgs*, RadStream);
int r4d_rad_gemm_w4a8_m64 (const RadArgs*, RadStream);
int r4d_rad_gemm_w4a8_tiled (const RadArgs*, RadStream);
@@ -550,21 +545,12 @@ int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs*);
int r4d_rad_gemm_mxfp4a8_decode(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs*);
int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs*, RadStream);
int r4d_rad_gemm_mxfp4a8_gated(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_mxfp4a8_gated_scratch(const RadArgs*);
/* M2XFP4 (the paper's weight-side Sg-EM): the same GEMM bands at the m2xfp4 encoding, one meta
* plane more (r4d_layout.cpp, m2xfp4). */
int r4d_rad_gemm_m2xfp4a8_tiled(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_m2xfp4a8_tiled_scratch(const RadArgs*);
int r4d_rad_gemm_m2xfp4a8_decode(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_m2xfp4a8_decode_scratch(const RadArgs*);
int r4d_rad_gemm_mxfp4a8_gated_wide(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_mxfp4a8_gated_wide_scratch(const RadArgs*);
int r4d_rad_dequant_w4 (const RadArgs*, RadStream);
int r4d_rad_rowtopk (const RadArgs*, RadStream);
int64_t r4d_rad_rowtopk_scratch(const RadArgs*);
int r4d_rad_rowtopk_merge (const RadArgs*, RadStream);
int r4d_rad_logit_rerank (const RadArgs*, RadStream);
int r4d_rad_logit_rerank_i8 (const RadArgs*, RadStream);
/* -- the routed mixture of experts (r4d_moe.hip) --
@@ -582,7 +568,6 @@ int r4d_rad_router_gemm_topk_scatter_init(const RadParam*, int, int rank, int w
void r4d_rad_router_gemm_topk_scatter_fini(void*);
int r4d_rad_router_gemm_topk_scatter(const RadArgs*, RadStream);
int64_t r4d_rad_moe_scatter_scratch(const RadArgs*);
int r4d_rad_moe_gemm_q (const RadArgs*, RadStream);
/* Scratch for the run map that aligns the prefill form. Zero in the decode band and for a shape
* whose parameters do not describe one, so a caller that never asks still gets a correct uniform
* grid. */
@@ -593,8 +578,14 @@ int64_t r4d_rad_moe_gemm_w4a8_scratch(const RadArgs*);
int r4d_rad_moe_gemm_w4a8 (const RadArgs*, RadStream);
/* `moe_gemm_q_mod4`: the same two kernels over four classes of experts, by the expert's number
* mod 4. The scratch hooks are the two-class ones. */
int r4d_rad_moe_gemm_q_mod4 (const RadArgs*, RadStream);
int r4d_rad_moe_gemm_w4a8_mod4 (const RadArgs*, RadStream);
/* The grouped GEMM against an int8 activation (the iu8 WMMA): int8 experts with a bf16 scale per
* (row, 128 of K), and the four-bit experts' stored planes read at int8 levels. The scratch hooks
* are the E4M3 rows'. */
int r4d_rad_moe_gemm_i8a8 (const RadArgs*, RadStream);
int r4d_rad_moe_gemm_i8a8_mod4 (const RadArgs*, RadStream);
int r4d_rad_moe_gemm_w4a8i8 (const RadArgs*, RadStream);
int r4d_rad_moe_gemm_w4a8i8_mod4 (const RadArgs*, RadStream);
/* `moe_gemm` at bf16: one weight table of the checkpoint's row-major planes, no scales. Same
* grouping and three forms; its scratch hook sizes the same run map. */
int r4d_rad_moe_gemm_bf16 (const RadArgs*, RadStream);
@@ -626,24 +617,13 @@ int r4d_rad_gdn_gated_norm_hq_i8 (const RadArgs*, RadStream);
int r4d_rad_qk_norm_rope_gate (const RadArgs*, RadStream);
int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs*, RadStream);
int r4d_rad_qk_norm_rope_gate_kv_store_streamed(const RadArgs*, RadStream);
int r4d_rad_qk_norm_rope_gate_kv_store_fp8v4(const RadArgs*, RadStream);
int r4d_rad_qk_norm_rope_gate_kv_store_k6v4(const RadArgs*, RadStream);
int r4d_rad_rope_table (const RadArgs*, RadStream);
/* -- block-scaled fp8, and the device sampler (r4d_gemm_fp8*.hip / r4d_fp8_layout.cpp) --
*
* These return a negative code instead of throwing, unlike the rest of libr4d's GEMMs, so their
* shims carry no R4D_TRY. */
int r4d_rad_gemm_fp8a16_m1 (const RadArgs*, RadStream);
int r4d_rad_gemm_fp8a8_m16 (const RadArgs*, RadStream);
int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs*, RadStream);
int r4d_rad_gemm_fp8a8_gated_wide(const RadArgs*, RadStream);
/* `gemm_nt_q_short`: the narrow row with the short-prompt split rule (narrow_ksplit). */
int r4d_rad_gemm_fp8a8_m16_short(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_fp8a8_m16_short_scratch(const RadArgs*);
int r4d_rad_gemm_fp8a8_bias_m16(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_fp8a8_m16_scratch(const RadArgs*);
int r4d_rad_gemm_fp8a8_tiled(const RadArgs*, RadStream);
int r4d_rad_gemm_i8a8_m16 (const RadArgs*, RadStream);
int64_t r4d_rad_gemm_i8a8_m16_scratch(const RadArgs*);
int r4d_rad_logits_gemm_i8(const RadArgs*, RadStream);
@@ -662,6 +642,10 @@ int r4d_rad_gemm_iqr_gated(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_iqr_gated_scratch(const RadArgs*);
int r4d_rad_gemm_iqr_tiled(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_iqr_tiled_scratch(const RadArgs*);
/* The routed experts as IQR weights, a run's rows against each decoded tile (r4d_moe_iqr.hip). */
int r4d_rad_moe_gemm_iqr(const RadArgs*, RadStream);
int r4d_rad_moe_gemm_iqr_mod4(const RadArgs*, RadStream);
int64_t r4d_rad_moe_gemm_iqr_scratch(const RadArgs*);
int r4d_rad_quant_act_i8g(const RadArgs*, RadStream);
int r4d_rad_had_quant_act_i8g(const RadArgs*, RadStream);
int r4d_rad_quant_act_fp8 (const RadArgs*, RadStream);
@@ -687,7 +671,6 @@ int r4d_rad_kv_store_streamed(const RadArgs*, RadStream);
int r4d_rad_qsa_tail_store (const RadArgs*, RadStream);
int r4d_rad_qsa_work (const RadArgs*, RadStream);
int r4d_rad_sample_chain (const RadArgs*, RadStream);
int r4d_rad_logits_gemm_fp8 (const RadArgs*, RadStream);
/* -- what each weight-reading kernel stores, from a weight's canonical planes --
*
@@ -708,6 +691,8 @@ R4D_HOOKS(i8_block)
R4D_HOOKS(iqr)
R4D_HOOKS(iqr_logits)
R4D_HOOKS(iqr_vocab)
R4D_HOOKS(moe_iqr)
R4D_HOOKS(moe_iqr_mod4)
R4D_HOOKS(fp8_logits)
R4D_HOOKS(i8_logits)
R4D_HOOKS(hc_e4m3)
@@ -717,8 +702,6 @@ R4D_HOOKS(w2a8)
R4D_HOOKS(moe_w4)
R4D_HOOKS(moe_w4_mod4)
#undef R4D_HOOKS
int r4d_rad_layout_fp8_rowmajor(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
/* embed_lookup_bf16's check that its table is plain bf16 (r4d_fp8_layout.cpp), and the IQR
* table's hooks and gather (r4d_iqr_layout.cpp, r4d_iqr_embed.hip). */
int r4d_rad_layout_embed_bf16(const RadParam*, int, int, const RadEncoding*, const int*,
@@ -730,10 +713,14 @@ int r4d_rad_relayout_iqr_embed(const RadParam*, int, int, const RadEncoding*, co
int r4d_rad_embed_lookup_iqr(const RadArgs*, RadStream);
int r4d_rad_layout_embed_q(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_layout_moe_fp8(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_layout_moe_fp8_mod4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
/* The grouped GEMM's int8 experts: codes and the bf16 scale per (row, 128 of K) row-major as
* stored, `i8a8h` from an encoding rotated 128 wide and `i8a8` from one that is not. */
int r4d_rad_layout_i8_rowmajor(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_layout_moe_i8(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_layout_moe_i8_mod4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_layout_w8a16(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_layout_w8a8(const RadParam*, int, int, const RadEncoding*, const int*,
@@ -800,20 +787,6 @@ int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const in
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_layout_mxfp4_gated(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_mxfp4_gated(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_layout_m2xfp4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_m2xfp4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_layout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_unrelayout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*,
const void*, int64_t, const RadTensor*, int);
/* -- the small bf16 model ops (r4d_model_bf16.hip) --
*
@@ -824,6 +797,7 @@ int r4d_rad_embed_lookup (const RadArgs*, RadStream);
* memory over the link. */
int r4d_rad_embed_lookup_q (const RadArgs*, RadStream);
int r4d_rad_ngram_ids (const RadArgs*, RadStream);
int r4d_rad_ngram_hint (const RadArgs*, RadStream);
int r4d_rad_ple_gate (const RadArgs*, RadStream);
int r4d_rad_ple_conv (const RadArgs*, RadStream);
int r4d_rad_ple_conv_bias (const RadArgs*, RadStream);
@@ -867,14 +841,9 @@ int r4d_rad_scale (const RadArgs*, RadStream);
int r4d_rad_silu_mul (const RadArgs*, RadStream);
int r4d_rad_swiglu_clamped(const RadArgs*, RadStream);
int r4d_rad_swiglu_step(const RadArgs*, RadStream);
int r4d_rad_swiglu_clamped_quant_fp8(const RadArgs*, RadStream);
int r4d_rad_dsa_pool(const RadArgs*, RadStream);
int r4d_shape_dsa_pool(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_dsa_query(const RadArgs*, RadStream);
int r4d_rad_fp8_f32scale(const RadArgs*, RadStream);
int r4d_rad_moe_fp8_f32scale(const RadArgs*, RadStream);
int r4d_layout_fp8_f32scale(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_shape_dsa_query(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_gemm_nt_f32(const RadArgs*, RadStream);
int r4d_shape_gemm_nt_f32(const RadParam*, int, int, RadOpdDesc*);
@@ -918,8 +887,7 @@ int r4d_rad_gemm_nt_bias (const RadArgs*, RadStream);
int r4d_rad_gemm_f32_nt_bias(const RadArgs*, RadStream);
int r4d_rad_kv_store (const RadArgs*, RadStream);
int r4d_rad_kv_store_fp8 (const RadArgs*, RadStream);
int r4d_rad_kv_store_fp8v4 (const RadArgs*, RadStream);
int r4d_rad_kv_store_k6v4 (const RadArgs*, RadStream);
int r4d_rad_kv_store_i8 (const RadArgs*, RadStream);
int r4d_rad_logits_gemm (const RadArgs*, RadStream);
int r4d_rad_logits_gemm_cols(const RadArgs*, RadStream);
@@ -968,7 +936,6 @@ int r4d_shape_mhc_pre_partial(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mhc_pre_finish(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_kda_update(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_ssd_update(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_moe_mxfp4(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mhc_post(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mhc_contract(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mtp_enter (const RadParam*, int, int operand, RadOpdDesc*);
@@ -1034,6 +1001,8 @@ int r4d_shape_router_gemm_topk_scatter(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_moe_scatter (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_moe_gemm_q (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_moe_gemm_q_mod4(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_moe_gemm_i8 (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_moe_gemm_i8_mod4(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_moe_gather (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_scale_rows (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_scale (const RadParam*, int, int operand, RadOpdDesc*);
@@ -1099,6 +1068,7 @@ int r4d_fuse_qk_norm_rope_gate_kv_store_streamed(const RadParam*, int, uint64_t,
int r4d_fuse_ar_rmsnorm_quant_fp8(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_ar_gather_hc_write (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_attn_paged_gate_quant(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_attn_paged_gate_had_quant(const RadParam*, int, uint64_t, int, RadFuseStep*);
} /* extern "C" */
+23
View File
@@ -12,6 +12,7 @@
#include <hip/hip_runtime.h>
#include <cstdint>
#include "r4d_common.h" // r4d_wave_max, for q8_row_i8g
#include "r4d_fwht.h" // the rotation q8_row_had_i8g puts before the absmax
template <bool I8>
__device__ __forceinline__ constexpr float q8_top() {
@@ -65,3 +66,25 @@ __device__ __forceinline__ void q8_row_i8g(const uint16_t* row, signed char* __r
*(uint32_t*)(q + c0) = q8_pack4<true>(v[0], v[1], v[2], v[3], 1.0f / sc);
}
}
// q8_row_i8g with the 128-wide Hadamard between the staged values and the absmax: the codes
// had_quant_act_i8g writes over the same bf16 row (r4d_fwht_wave's mapping is this one's, a wave a
// group and four consecutive columns a lane), for a producer whose row crossed threads on the way
// (norm_add_norm_route_i8g). The caller publishes `row` behind a barrier first.
template <uint32_t THR>
__device__ __forceinline__ void q8_row_had_i8g(const uint16_t* row, signed char* __restrict__ q,
float* __restrict__ s, uint32_t n) {
const uint32_t lane = threadIdx.x & 31u, wave = threadIdx.x >> 5;
for (uint32_t kb = wave; kb < n / 128u; kb += THR / 32u) {
const uint32_t c0 = kb * 128u + lane * 4u;
float v[4];
#pragma unroll
for (int j = 0; j < 4; ++j) v[j] = __uint_as_float((uint32_t)row[c0 + j] << 16);
r4d_fwht_wave<128>(v, (int)lane);
float m = fmaxf(fmaxf(fabsf(v[0]), fabsf(v[1])), fmaxf(fabsf(v[2]), fabsf(v[3])));
m = r4d_wave_max(m);
const float sc = m > 0.0f ? m * (1.0f / q8_top<true>()) : 1.0f;
if (lane == 0) s[kb] = sc;
*(uint32_t*)(q + c0) = q8_pack4<true>(v[0], v[1], v[2], v[3], 1.0f / sc);
}
}
+169 -282
View File
@@ -18,8 +18,8 @@
//
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "rad_yarn.h"
#include <hip/hip_bf16.h>
@@ -43,15 +43,13 @@
// Cost: at rot 64 the rotary partner is in another wave. The lane re-derives it instead of an LDS
// exchange: it loads the partner's input (an L1-hot read) and norms it with the block's `inv`.
/* The paged cache the KV form writes: kv_store's operands and parameters in one argument, to stay
* inside the emitter's parameter budget. Only the E4M3 form reads the descales. */
* inside the emitter's parameter budget. */
struct QkKvStore {
const __hip_bfloat16* v;
const int32_t* slot;
void* cache;
int v_pitch, block_size, n_blocks;
float k_inv, v_inv;
int row; /* fp8_v4 / k6_v4: a token's bytes in a page, 25 or 22 * HD / 16 */
/* QK_KV_STREAMED only: the group's host mirror and per-layer residency map, as
/* The streamed forms only: the group's host mirror and per-layer residency map, as
* kv_store_streamed takes them (libr4d/r4d_model_bf16.hip). `blocks` is the mirror's block
* count (the id space) while `n_blocks` stays the ring depth. */
const int32_t* res;
@@ -59,23 +57,23 @@ struct QkKvStore {
int blocks;
};
/* The cache forms KV selects. The two streamed forms are the same store into two planes, E4M3
* and bf16. */
enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2, QK_KV_F8V4 = 3, QK_KV_K6V4 = 4,
QK_KV_STREAMED = 5, QK_KV_STREAMED_BF16 = 6 };
/* The cache forms KV selects: bf16 or the int8 cache, each resident or streamed (the same store
* into the host mirror and, where the block is resident, the ring). */
enum { QK_KV_NONE = 0, QK_KV_BF16 = 2, QK_KV_STREAMED_BF16 = 6, QK_KV_I8 = 7,
QK_KV_STREAMED_I8 = 8 };
/* KV folds kv_store in: a k head's block, holding the token's rotated k one element per lane, also
* writes that element and the head's v element into the cache at the token's slot, as E4M3 with
* kv_store_fp8's arithmetic or as bf16 like kv_store_bf16 (see the store at the end). */
* writes that element and the head's v element into the cache at the token's slot, as bf16 like
* kv_store_bf16 or as the int8 cache's codes like kv_store_i8 (see the store at the end). */
#define R4D_QK_NORM_ROPE_GATE_PARAMS \
const __hip_bfloat16* __restrict__ QG, const __hip_bfloat16* __restrict__ K, \
__hip_bfloat16* __restrict__ QO, __hip_bfloat16* __restrict__ KO, \
__hip_bfloat16* __restrict__ GO, const void* __restrict__ WQ, \
const void* __restrict__ WK, const void* __restrict__ CS, const void* __restrict__ POS, \
long cs_rows, int nq, int nkv, int rot, float eps, float wadd, int qg_pitch, \
int k_pitch, int cs_f32, int pos_i64, int w_f32, QkKvStore kvs
template <int HD, int KV = QK_KV_NONE>
__device__ __forceinline__ void r4d_qk_norm_rope_gate_kernel_body(
const __hip_bfloat16* __restrict__ QG, const __hip_bfloat16* __restrict__ K,
__hip_bfloat16* __restrict__ QO, __hip_bfloat16* __restrict__ KO,
__hip_bfloat16* __restrict__ GO,
const void* __restrict__ WQ, const void* __restrict__ WK,
const void* __restrict__ CS, const void* __restrict__ POS, long cs_rows,
int nq, int nkv, int rot, float eps, float wadd,
int qg_pitch, int k_pitch, int cs_f32, int pos_i64, int w_f32, QkKvStore kvs) {
__device__ __forceinline__ void r4d_qk_norm_rope_gate_body(R4D_QK_NORM_ROPE_GATE_PARAMS) {
constexpr int THR = 256;
__shared__ float lds[THR / 32];
const int tok = blockIdx.x, h = blockIdx.y;
@@ -148,158 +146,116 @@ __device__ __forceinline__ void r4d_qk_norm_rope_gate_kernel_body(
if (t < HD) {
out[t] = __float2bfloat16(res);
// `gate_out` is optional: a caller that reads the gate straight from the interleaved projection
// (the fp8 block, via gate_quant_fp8) passes none.
// passes none.
if (!isk && GO) GO[((size_t)tok * nq + lh) * HD + t] = in[HD + t];
}
// The cache write kv_store would make next, from the same bytes: the rotated k as just stored
// and the v row as the projection left it. The E4M3 form scales by the inverse descale, clamps
// (v_cvt_pk_fp8_f32 returns NaN out of range) and converts each element on its own, so one
// element a lane gives the same byte. The bf16 form stores the values as kv_store_bf16 does.
// Layout [n_blocks, kv_heads, block_size, 2*head_dim], k then v; a negative or out-of-range slot
// stores nothing.
if constexpr (KV != QK_KV_NONE) {
// and the v row as the projection left it. Layout [n_blocks, kv_heads, block_size, row], k then
// v; a negative or out-of-range slot stores nothing.
//
// A streamed group's cache is the ring and its truth is the host mirror: the token goes to the
// mirror's block row always and to the ring slot only where the residency map says the block is
// resident, exactly as kv_store_streamed writes it (libref/ref_attn.cpp states why the test
// belongs in the writer). The block id bounds the mirror, the map bounds the ring, and a slot
// names a ring block only through `res`.
if constexpr (KV == QK_KV_I8 || KV == QK_KV_STREAMED_I8) {
// The int8 cache (kv_store_i8's bytes): the head's k and v each as int8 codes against one f16
// scale, the head's absmax / 127, taken over the block through LDS. `isk` is uniform over the
// block, so every thread of a k head's block meets the barrier.
if (isk) {
__shared__ float s_m[2][THR / 32];
const bool in = t < HD;
const float kf = in ? __bfloat162float(__float2bfloat16(res)) : 0.0f;
const float vf =
in ? __bfloat162float(kvs.v[(size_t)tok * kvs.v_pitch + (size_t)lh * HD + t]) : 0.0f;
float km = r4d_wave_max(fabsf(kf)), vm = r4d_wave_max(fabsf(vf));
if ((t & 31) == 0) { s_m[0][t >> 5] = km; s_m[1][t >> 5] = vm; }
__syncthreads();
km = 0.0f; vm = 0.0f;
#pragma unroll
for (int wv = 0; wv < THR / 32; ++wv) {
km = fmaxf(km, s_m[0][wv]);
vm = fmaxf(vm, s_m[1][wv]);
}
const int32_t sl = kvs.slot[tok];
constexpr bool STREAMED = KV == QK_KV_STREAMED_I8;
const uint32_t id_space = (uint32_t)(STREAMED ? kvs.blocks : kvs.n_blocks);
if (in && sl >= 0 && (uint32_t)sl / (uint32_t)kvs.block_size < id_space) {
const uint32_t blk = (uint32_t)sl / (uint32_t)kvs.block_size;
const uint32_t off = (uint32_t)sl % (uint32_t)kvs.block_size;
const size_t rowb = (size_t)(2 * HD + 4);
const __fp16 k16 = (__fp16)fminf(km / 127.0f, 515.0f);
const __fp16 v16 = (__fp16)fminf(vm / 127.0f, 515.0f);
const float ksc = (float)k16, vsc = (float)v16;
const float kr = ksc > 0.0f ? rintf(kf / ksc) : 0.0f;
const float vr = vsc > 0.0f ? rintf(vf / vsc) : 0.0f;
const unsigned char kc = (unsigned char)(signed char)(int)fminf(fmaxf(kr, -127.0f), 127.0f);
const unsigned char vc = (unsigned char)(signed char)(int)fminf(fmaxf(vr, -127.0f), 127.0f);
auto put = [&](unsigned char* c) {
c[t] = kc;
c[HD + t] = vc;
if (t == 0) {
*(uint16_t*)(c + 2 * HD) = __builtin_bit_cast(uint16_t, k16);
*(uint16_t*)(c + 2 * HD + 2) = __builtin_bit_cast(uint16_t, v16);
}
};
if constexpr (STREAMED) {
const size_t o = ((size_t)lh * kvs.block_size + off) * rowb;
const size_t brow = (size_t)nkv * kvs.block_size * rowb;
put((unsigned char*)kvs.host + (size_t)blk * brow + o);
const int32_t rs = kvs.res[blk];
if (rs >= 0 && (uint32_t)rs < (uint32_t)kvs.n_blocks)
put((unsigned char*)kvs.cache + (size_t)rs * brow + o);
} else {
put((unsigned char*)kvs.cache + (((size_t)blk * nkv + lh) * kvs.block_size + off) * rowb);
}
}
}
} else if constexpr (KV != QK_KV_NONE) {
if (isk && t < HD) {
const int32_t sl = kvs.slot[tok];
/* A streamed group's cache is the ring and its truth is the host mirror: the token goes to
* the mirror's block row ALWAYS and to the ring slot only where the residency map says the
* block is resident, exactly as kv_store_streamed writes it (libref/ref_attn.cpp states why
* the test belongs in the writer). The block id bounds the mirror, the map bounds the ring,
* and a slot names a ring block only through `res`. */
if constexpr (KV == QK_KV_STREAMED || KV == QK_KV_STREAMED_BF16) {
const size_t rowb = (size_t)(2 * HD);
const __hip_bfloat16 kb = __float2bfloat16(res);
const __hip_bfloat16 vb = kvs.v[(size_t)tok * kvs.v_pitch + (size_t)lh * HD + t];
if constexpr (KV == QK_KV_STREAMED_BF16) {
if (sl >= 0 && (uint32_t)sl / (uint32_t)kvs.block_size < (uint32_t)kvs.blocks) {
const uint32_t blk = (uint32_t)sl / (uint32_t)kvs.block_size;
const uint32_t off = (uint32_t)sl % (uint32_t)kvs.block_size;
/* One element of each plane. The mirror and the ring are byte planes of the same paged
* layout and `block_bytes` is their pitch, so a bf16 element is two bytes at twice the
* fp8 offset. */
const size_t EB = KV == QK_KV_STREAMED_BF16 ? 2 : 1;
const size_t rowb = (size_t)(2 * HD) * EB;
const size_t at = ((size_t)blk * nkv * kvs.block_size + off) * rowb +
(size_t)lh * kvs.block_size * rowb;
const __hip_bfloat16 kb = __float2bfloat16(res);
const __hip_bfloat16 vb = kvs.v[(size_t)tok * kvs.v_pitch + (size_t)lh * HD + t];
const size_t o = ((size_t)lh * kvs.block_size + off) * rowb;
const size_t brow = (size_t)nkv * kvs.block_size * rowb;
__hip_bfloat16* const m = (__hip_bfloat16*)kvs.host + (size_t)blk * brow + o;
m[t] = kb;
m[HD + t] = vb;
const int32_t rs = kvs.res[blk];
unsigned char* const m = (unsigned char*)kvs.host + at;
unsigned char* const c =
(rs >= 0 && (uint32_t)rs < (uint32_t)kvs.n_blocks)
? (unsigned char*)kvs.cache +
(((size_t)rs * nkv * kvs.block_size + off) * rowb +
(size_t)lh * kvs.block_size * rowb)
: nullptr;
if constexpr (KV == QK_KV_STREAMED_BF16) {
/* kv_store_bf16 writes the values themselves: no descales. */
*(__hip_bfloat16*)(m + EB * t) = kb;
*(__hip_bfloat16*)(m + EB * (HD + t)) = vb;
if (c) {
*(__hip_bfloat16*)(c + EB * t) = kb;
*(__hip_bfloat16*)(c + EB * (HD + t)) = vb;
}
} else {
const float kf = __bfloat162float(kb) * kvs.k_inv;
const float vf = __bfloat162float(vb) * kvs.v_inv;
const int pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf, -448.0f), 448.0f), 0.0f,
0, false);
const int pv = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(vf, -448.0f), 448.0f), 0.0f,
0, false);
m[t] = (unsigned char)(pk & 0xFF);
m[HD + t] = (unsigned char)(pv & 0xFF);
if (c) {
c[t] = (unsigned char)(pk & 0xFF);
c[HD + t] = (unsigned char)(pv & 0xFF);
}
if (rs >= 0 && (uint32_t)rs < (uint32_t)kvs.n_blocks) {
__hip_bfloat16* const c = (__hip_bfloat16*)kvs.cache + (size_t)rs * brow + o;
c[t] = kb;
c[HD + t] = vb;
}
}
} else if (sl >= 0 && (uint32_t)sl / (uint32_t)kvs.block_size < (uint32_t)kvs.n_blocks) {
const uint32_t blk = (uint32_t)sl / (uint32_t)kvs.block_size;
const uint32_t off = (uint32_t)sl % (uint32_t)kvs.block_size;
const size_t rowb = (KV == QK_KV_F8V4 || KV == QK_KV_K6V4) ? (size_t)kvs.row : (size_t)(2 * HD);
const size_t at = ((size_t)blk * nkv * kvs.block_size + off) * rowb +
(size_t)lh * kvs.block_size * rowb;
const __hip_bfloat16 kb = __float2bfloat16(res);
const __hip_bfloat16 vb = kvs.v[(size_t)tok * kvs.v_pitch + (size_t)lh * HD + t];
if constexpr (KV == QK_KV_BF16) {
__hip_bfloat16* c = (__hip_bfloat16*)kvs.cache + at;
c[t] = kb;
c[HD + t] = vb;
} else if constexpr (KV == QK_KV_F8V4 || KV == QK_KV_K6V4) {
// fp8_v4: K as the E4M3 form writes it. k6_v4: K as int6 in groups of 32 (one wave)
// with an f16 scale, absmax / 31, in kv_store_k6v4's layout. V as int4 in groups of 32
// with an f16 scale, absmax / 7. The even lane of a pair writes the pair's nibble byte.
unsigned char* c = (unsigned char*)kvs.cache + at;
const float kf = __bfloat162float(kb) * kvs.k_inv;
constexpr int voff = KV == QK_KV_K6V4 ? HD * 3 / 4 : HD;
constexpr int vsoff = KV == QK_KV_K6V4 ? HD * 21 / 16 : HD * 3 / 2;
if constexpr (KV == QK_KV_K6V4) {
float kmax = fabsf(kf);
for (int m = 16; m >= 1; m >>= 1) kmax = fmaxf(kmax, __shfl_xor(kmax, m, 32));
const __fp16 k16 = (__fp16)fminf(kmax / 31.0f, 2112.0f); // finite codes, as kv_store_k6v4
const float ksc = (float)k16;
const float r = ksc > 0.0f ? rintf(kf / ksc) : 0.0f;
const int q = ((int)fminf(fmaxf(r, -31.0f), 31.0f)) & 0x3F;
const int qn = __shfl_xor(q & 15, 1, 32);
if ((t & 1) == 0) c[t / 2] = (unsigned char)((q & 15) | (qn << 4));
// High bits: a pair's four into bits 0-3 at its even lane, then the pair eight dims on
// into bits 4-7; lane 2j of a 16-dim chunk writes byte j.
const int h01 = (q >> 4) | (__shfl_xor(q >> 4, 1, 32) << 2);
const int hb = h01 | (__shfl_xor(h01, 8, 32) << 4);
if ((t & 1) == 0 && (t & 15) < 8) c[HD / 2 + (t / 16) * 4 + (t & 7) / 2] = (unsigned char)hb;
if ((t & 31) == 0) *(uint16_t*)(c + HD * 5 / 4 + (t / 32) * 2) = __builtin_bit_cast(uint16_t, k16);
} else {
const int pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf, -448.0f), 448.0f), 0.0f,
0, false);
c[t] = (unsigned char)(pk & 0xFF);
}
const float vf = __bfloat162float(vb) * kvs.v_inv;
float amax = fabsf(vf);
for (int m = 16; m >= 1; m >>= 1) amax = fmaxf(amax, __shfl_xor(amax, m, 32));
const __fp16 s16 = (__fp16)fminf(amax / 7.0f, 8188.0f); // finite codes, as kv_store_fp8v4
const float sc = (float)s16;
const float r = sc > 0.0f ? rintf(vf / sc) : 0.0f;
const int q = ((int)fminf(fmaxf(r, -7.0f), 7.0f)) & 0xF;
const int qn = __shfl_xor(q, 1, 32);
if ((t & 1) == 0) c[voff + t / 2] = (unsigned char)(q | (qn << 4));
if ((t & 31) == 0) *(uint16_t*)(c + vsoff + (t / 32) * 2) = __builtin_bit_cast(uint16_t, s16);
} else {
unsigned char* c = (unsigned char*)kvs.cache + at;
const float kf = __bfloat162float(kb) * kvs.k_inv;
const float vf = __bfloat162float(vb) * kvs.v_inv;
const int pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf, -448.0f), 448.0f), 0.0f,
0, false);
const int pv = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(vf, -448.0f), 448.0f), 0.0f,
0, false);
c[t] = (unsigned char)(pk & 0xFF);
c[HD + t] = (unsigned char)(pv & 0xFF);
}
__hip_bfloat16* c = (__hip_bfloat16*)kvs.cache + at;
c[t] = kb;
c[HD + t] = vb;
}
}
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <int HD, int KV = QK_KV_NONE>
__global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
const __hip_bfloat16* __restrict__ QG, const __hip_bfloat16* __restrict__ K,
__hip_bfloat16* __restrict__ QO, __hip_bfloat16* __restrict__ KO,
__hip_bfloat16* __restrict__ GO,
const void* __restrict__ WQ, const void* __restrict__ WK,
const void* __restrict__ CS, const void* __restrict__ POS, long cs_rows,
int nq, int nkv, int rot, float eps, float wadd,
int qg_pitch, int k_pitch, int cs_f32, int pos_i64, int w_f32, QkKvStore kvs) {
r4d_qk_norm_rope_gate_kernel_body<HD, KV>(QG, K, QO, KO, GO, WQ, WK, CS, POS, cs_rows, nq, nkv, rot, eps, wadd, qg_pitch, k_pitch, cs_f32, pos_i64, w_f32, kvs);
}
template <int HD, int KV = QK_KV_NONE>
__global__ __launch_bounds__(256) void r4dchain_qk_norm_rope_gate(
const __hip_bfloat16* __restrict__ QG, const __hip_bfloat16* __restrict__ K,
__hip_bfloat16* __restrict__ QO, __hip_bfloat16* __restrict__ KO,
__hip_bfloat16* __restrict__ GO,
const void* __restrict__ WQ, const void* __restrict__ WK,
const void* __restrict__ CS, const void* __restrict__ POS, long cs_rows,
int nq, int nkv, int rot, float eps, float wadd,
int qg_pitch, int k_pitch, int cs_f32, int pos_i64, int w_f32, QkKvStore kvs) {
r4d_chain_wait();
r4d_qk_norm_rope_gate_kernel_body<HD, KV>(QG, K, QO, KO, GO, WQ, WK, CS, POS, cs_rows, nq, nkv, rot, eps, wadd, qg_pitch, k_pitch, cs_f32, pos_i64, w_f32, kvs);
r4d_chain_done();
// The kernel around the body: CH `r4dchain` is the chained form (r4d_chain.h).
template <int HD, int KV, class CH>
__global__ __launch_bounds__(256)
void r4d_qk_norm_rope_gate_kernel(R4D_QK_NORM_ROPE_GATE_PARAMS) {
if (CH::on) r4d_chain_wait();
r4d_qk_norm_rope_gate_body<HD, KV>(QG, K, QO, KO, GO, WQ, WK, CS, POS, cs_rows, nq, nkv, rot, eps,
wadd, qg_pitch, k_pitch, cs_f32, pos_i64, w_f32, kvs);
if (CH::on) r4d_chain_done();
}
#undef R4D_QK_NORM_ROPE_GATE_PARAMS
// ============================================================ the cos/sin table
//
@@ -315,9 +271,10 @@ __global__ __launch_bounds__(256) void r4dchain_qk_norm_rope_gate(
// bit-identical: `1.0f / powf(theta, 2i/den)` with `den` the ladder's width (`rot` for `rotary`,
// `head_dim` for `head`), the position divided by `rscale` in f32, `sincosf`, and the products
// consumed in f32 by the caller. Changing any of it changes the model's output.
__global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel(
const void* __restrict__ POS, void* __restrict__ CS, long rows, int rot, int den, float theta,
float rscale, int cs_f32, int pos_i64, RadYarn yarn) {
#define R4D_QK_ROPE_TABLE_PARAMS \
const void* __restrict__ POS, void* __restrict__ CS, long rows, int rot, int den, \
float theta, float rscale, int cs_f32, int pos_i64, RadYarn yarn
__device__ __forceinline__ void r4d_qk_rope_table_body(R4D_QK_ROPE_TABLE_PARAMS) {
const int m = blockIdx.x;
const long pp = pos_i64 ? ((const long*)POS)[m] : (long)((const int*)POS)[m];
// A padded row addresses no table row, and a position at or past the table's height writes
@@ -342,6 +299,16 @@ __global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel(
}
}
// The kernel around the body: CH `r4dchain` is the chained form (r4d_chain.h).
template <class CH>
__global__ __launch_bounds__(64)
void r4d_qk_rope_table_kernel(R4D_QK_ROPE_TABLE_PARAMS) {
if (CH::on) r4d_chain_wait();
r4d_qk_rope_table_body(POS, CS, rows, rot, den, theta, rscale, cs_f32, pos_i64, yarn);
if (CH::on) r4d_chain_done();
}
#undef R4D_QK_ROPE_TABLE_PARAMS
// The two launches, as the plugin ABI's RadLaunchFn. See the note at the head of
// r4d_quant_act_i8.hip on the argument list and status return.
enum { QK_QGATE = 0, QK_K, QK_COSSIN, QK_POS, QK_WQ, QK_WK, QK_QOUT, QK_KOUT, QK_GOUT,
@@ -350,6 +317,7 @@ enum { QK_QGATE = 0, QK_K, QK_COSSIN, QK_POS, QK_WQ, QK_WK, QK_QOUT, QK_KOUT, QK
/* The body of both forms; KVF is the kv_store fold and `kvs` its cache, already checked. */
template <int KVF>
static int qk_body(const RadArgs* args, RadStream stream, const QkKvStore& kvs) {
const bool chain = r4d_geti_or(args, "chain", 0) != 0; // the chained form (r4d_chain.h)
const RadTensor* qg = r4d_opt(args, QK_QGATE);
const RadTensor* k = r4d_opt(args, QK_K);
const RadTensor* cs = r4d_opt(args, QK_COSSIN);
@@ -403,15 +371,14 @@ static int qk_body(const RadArgs* args, RadStream stream, const QkKvStore& kvs)
const int nh = (int)(nq + nkv);
// One block per (token, head), 256 threads, one element per lane. The width is fixed at 256, not
// fitted to the head count, so the sum of squares matches r4d_rmsnorm_bf16 (see the kernel).
/* The chained form (r4d_chain.h) where the row resolved with `chain`. */
const bool ch = r4d_geti_or(args, "chain", 0) != 0 && r4d_chain_rows_ok(M);
#define R4D_QKG_L(H) emit_rc = R4D_EMIT(stream, (ch ? &r4dchain_qk_norm_rope_gate<H, KVF> \
: &r4d_qk_norm_rope_gate_kernel<H, KVF>), \
#define R4D_QKG_E(H, CH_) emit_rc = R4D_EMIT(stream, (r4d_qk_norm_rope_gate_kernel<H, KVF, CH_>), \
dim3((int)M, nh), dim3(256), 0, (const __hip_bfloat16*)r4d_p(qg), \
(const __hip_bfloat16*)r4d_p(k), (__hip_bfloat16*)r4d_wp(qo), (__hip_bfloat16*)r4d_wp(ko), \
(__hip_bfloat16*)r4d_wp(go), r4d_p(wq), r4d_p(wk), r4d_p(cs), r4d_p(po), (long)cs_rows, \
(int)nq, (int)nkv, (int)rot, eps, wadd, (int)qg_pitch, (int)k_pitch, cs_f32, pos_i64, w_f32, \
kvs)
#define R4D_QKG_L(H) \
do { if (chain) R4D_QKG_E(H, r4dchain); else R4D_QKG_E(H, R4dUnchained); } while (0)
int emit_rc = RAD_OK;
switch (hd) {
case 64: R4D_QKG_L(64); break;
@@ -419,6 +386,7 @@ static int qk_body(const RadArgs* args, RadStream stream, const QkKvStore& kvs)
default: R4D_QKG_L(256); break;
}
#undef R4D_QKG_L
#undef R4D_QKG_E
return emit_rc;
}
@@ -427,81 +395,39 @@ extern "C" int r4d_rad_qk_norm_rope_gate(const RadArgs* args, RadStream stream)
}
/* The prologue with the KV store folded in: qk_norm_rope_gate's operands, then kv_store's `v`,
* `slot_mapping` and `kv_cache`, and its parameters. The cache is E4M3 or bf16 as `kv_dtype`
* names, checked as kv_store checks it, one slot per prologue row. The k kv_store would read is the
* prologue's own output, so it is not a separate operand. */
extern "C" int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs* args, RadStream stream) {
const RadTensor* k = r4d_opt(args, QK_K);
const RadTensor* qg = r4d_opt(args, QK_QGATE);
const RadTensor* v = r4d_opt(args, QK_V);
const RadTensor* sm = r4d_opt(args, QK_SLOT);
const RadTensor* kv = r4d_opt(args, QK_CACHE);
if (!k || !v || !sm || !kv) return R4D_NO(RAD_E_INVAL);
const char* kvd = r4d_gets(args, "kv_dtype");
const uint32_t want = kvd ? rad_dtype_parse(kvd) : (uint32_t)RAD_DT_INVALID;
if (v->dtype != RAD_BF16 || sm->dtype != RAD_I32 || kv->dtype != want ||
(kv->dtype != RAD_F8E4M3 && kv->dtype != RAD_BF16))
return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(sm) || !r4d_contig(kv)) return R4D_NO(RAD_E_STRIDE);
const long long hd = r4d_geti_or(args, "head_dim", 0);
const long long nkv = r4d_geti_or(args, "n_head_kv", 0);
const long long bs = r4d_geti_or(args, "block_size", 0);
if (hd <= 0 || nkv <= 0 || bs <= 0) return R4D_NO(RAD_E_SHAPE);
if (kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs || kv->shape[3] != 2 * hd)
return R4D_NO(RAD_E_SHAPE);
const long long M = qg ? qg->shape[0] : k->shape[0];
long long Mv = 0;
const long long v_ld = r4d_rows_pitch(v, nkv * hd, &Mv);
if (v_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (Mv < M || r4d_numel(sm) != M) return R4D_NO(RAD_E_SHAPE);
const double ks = r4d_getf(args, "k_scale", 1.0);
const double vs = r4d_getf(args, "v_scale", 1.0);
if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL);
QkKvStore kvs{};
kvs.v = (const __hip_bfloat16*)r4d_p(v);
kvs.slot = (const int32_t*)r4d_p(sm);
kvs.cache = r4d_wp(kv);
kvs.v_pitch = (int)v_ld;
kvs.block_size = (int)bs;
kvs.n_blocks = (int)kv->shape[0];
kvs.k_inv = 1.0f / (float)ks;
kvs.v_inv = 1.0f / (float)vs;
return kv->dtype == RAD_BF16 ? qk_body<QK_KV_BF16>(args, stream, kvs)
: qk_body<QK_KV_FP8>(args, stream, kvs);
}
/* The prologue with the streamed store folded in (docs/OPS.md "kv_store_streamed"): each token's
* rotated k and its v go to the mirror's block row always and to `kv_cache[res[block]]` only where
* the block is resident, one launch where qk_norm_rope_gate + kv_store_streamed were two. The bytes
* are the pair's: `k_out`'s bf16 value is what the conversion reads, and both planes share one
* layout. E4M3, or bf16 storing the values themselves. */
extern "C" int r4d_rad_qk_norm_rope_gate_kv_store_streamed(const RadArgs* args, RadStream stream) {
* `slot_mapping` and `kv_cache`, and its parameters. The cache is bf16 or the int8 cache
* ([n_blocks, kv_heads, block_size, 2 * HD + 4] bytes) as `kv_dtype` names, checked as kv_store
* checks it, one slot per prologue row. The k kv_store would read is the prologue's own output, so
* it is not a separate operand. `streamed` adds the residency map and the host mirror (docs/OPS.md
* "kv_store_streamed"): each token's rotated k and its v go to the mirror's block row always and
* to `kv_cache[res[block]]` only where the block is resident, one launch where qk_norm_rope_gate +
* kv_store_streamed were two, and the same bytes. */
static int qk_kv_store(const RadArgs* args, RadStream stream, bool streamed) {
const RadTensor* k = r4d_opt(args, QK_K);
const RadTensor* qg = r4d_opt(args, QK_QGATE);
const RadTensor* v = r4d_opt(args, QK_V);
const RadTensor* sm = r4d_opt(args, QK_SLOT);
const RadTensor* kv = r4d_opt(args, QK_CACHE);
const RadTensor* res = r4d_opt(args, QK_RES);
const RadTensor* ho = r4d_opt(args, QK_HOST);
if (!k || !v || !sm || !kv || !res || !ho) return R4D_NO(RAD_E_INVAL);
const RadTensor* res = streamed ? r4d_opt(args, QK_RES) : nullptr;
const RadTensor* ho = streamed ? r4d_opt(args, QK_HOST) : nullptr;
if (!k || !v || !sm || !kv || (streamed && (!res || !ho))) return R4D_NO(RAD_E_INVAL);
const char* kvd = r4d_gets(args, "kv_dtype");
const uint32_t want = kvd ? rad_dtype_parse(kvd) : (uint32_t)RAD_DT_INVALID;
if (v->dtype != RAD_BF16 || sm->dtype != RAD_I32 || kv->dtype != want ||
(kv->dtype != RAD_F8E4M3 && kv->dtype != RAD_BF16) || res->dtype != RAD_I32 ||
ho->dtype != RAD_U8)
(kv->dtype != RAD_I8 && kv->dtype != RAD_BF16))
return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(sm) || !r4d_contig(kv) || !r4d_contig(res) || !r4d_contig(ho) ||
ho->rank != 2)
if (streamed && (res->dtype != RAD_I32 || ho->dtype != RAD_U8)) return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(sm) || !r4d_contig(kv)) return R4D_NO(RAD_E_STRIDE);
if (streamed && (!r4d_contig(res) || !r4d_contig(ho) || ho->rank != 2))
return R4D_NO(RAD_E_STRIDE);
const bool i8 = kv->dtype == RAD_I8;
const long long hd = r4d_geti_or(args, "head_dim", 0);
const long long nkv = r4d_geti_or(args, "n_head_kv", 0);
const long long bs = r4d_geti_or(args, "block_size", 0);
if (hd <= 0 || nkv <= 0 || bs <= 0) return R4D_NO(RAD_E_SHAPE);
if (kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs || kv->shape[3] != 2 * hd)
const long long rowe = i8 ? 2 * hd + 4 : 2 * hd; /* a token's row in a head, in elements */
if (kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs || kv->shape[3] != rowe)
return R4D_NO(RAD_E_SHAPE);
const long long M = qg ? qg->shape[0] : k->shape[0];
long long Mv = 0;
@@ -509,61 +435,6 @@ extern "C" int r4d_rad_qk_norm_rope_gate_kv_store_streamed(const RadArgs* args,
if (v_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (Mv < M || r4d_numel(sm) != M) return R4D_NO(RAD_E_SHAPE);
/* One block of one layer: the mirror's row pitch and the ring's slot pitch are the same bytes,
* so the store addresses both with one row arithmetic. */
const long long row = nkv * bs * 2 * hd * (kv->dtype == RAD_BF16 ? 2 : 1);
const long long blocks = ho->shape[0], slots = kv->shape[0];
if (blocks <= 0 || slots <= 0 || row <= 0) return R4D_NO(RAD_E_SHAPE);
if (ho->shape[1] != row || ho->stride[0] != row) return R4D_NO(RAD_E_STRIDE);
if (r4d_numel(res) < blocks) return R4D_NO(RAD_E_SHAPE);
const double ks = r4d_getf(args, "k_scale", 1.0);
const double vs = r4d_getf(args, "v_scale", 1.0);
if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL);
QkKvStore kvs{};
kvs.v = (const __hip_bfloat16*)r4d_p(v);
kvs.slot = (const int32_t*)r4d_p(sm);
kvs.cache = r4d_wp(kv);
kvs.v_pitch = (int)v_ld;
kvs.block_size = (int)bs;
kvs.n_blocks = (int)slots;
kvs.k_inv = 1.0f / (float)ks;
kvs.v_inv = 1.0f / (float)vs;
kvs.res = (const int32_t*)r4d_p(res);
kvs.host = r4d_wp(ho);
kvs.blocks = (int)blocks;
return kv->dtype == RAD_BF16 ? qk_body<QK_KV_STREAMED_BF16>(args, stream, kvs)
: qk_body<QK_KV_STREAMED>(args, stream, kvs);
}
/* The fp8_v4 and k6_v4 forms: the same operands, the cache [n_blocks, kv_heads, block_size,
* 25 or 22 * HD / 16] E4M3-typed bytes (fp8_v4: E4M3 K; k6_v4: int6 K; both int4 V, f16 scales). */
static int qk_kv_q4(const RadArgs* args, RadStream stream, int k6) {
const long long r16 = k6 ? 22 : 25;
const RadTensor* k = r4d_opt(args, QK_K);
const RadTensor* qg = r4d_opt(args, QK_QGATE);
const RadTensor* v = r4d_opt(args, QK_V);
const RadTensor* sm = r4d_opt(args, QK_SLOT);
const RadTensor* kv = r4d_opt(args, QK_CACHE);
if (!k || !v || !sm || !kv) return R4D_NO(RAD_E_INVAL);
if (v->dtype != RAD_BF16 || sm->dtype != RAD_I32 || kv->dtype != RAD_F8E4M3)
return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(sm) || !r4d_contig(kv)) return R4D_NO(RAD_E_STRIDE);
const long long hd = r4d_geti_or(args, "head_dim", 0);
const long long nkv = r4d_geti_or(args, "n_head_kv", 0);
const long long bs = r4d_geti_or(args, "block_size", 0);
if (hd <= 0 || nkv <= 0 || bs <= 0 || hd % 32) return R4D_NO(RAD_E_SHAPE);
if (kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs || kv->shape[3] != hd * r16 / 16)
return R4D_NO(RAD_E_SHAPE);
const long long M = qg ? qg->shape[0] : k->shape[0];
long long Mv = 0;
const long long v_ld = r4d_rows_pitch(v, nkv * hd, &Mv);
if (v_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (Mv < M || r4d_numel(sm) != M) return R4D_NO(RAD_E_SHAPE);
const double ks = r4d_getf(args, "k_scale", 1.0);
const double vs = r4d_getf(args, "v_scale", 1.0);
if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL);
QkKvStore kvs{};
kvs.v = (const __hip_bfloat16*)r4d_p(v);
kvs.slot = (const int32_t*)r4d_p(sm);
@@ -571,16 +442,27 @@ static int qk_kv_q4(const RadArgs* args, RadStream stream, int k6) {
kvs.v_pitch = (int)v_ld;
kvs.block_size = (int)bs;
kvs.n_blocks = (int)kv->shape[0];
kvs.k_inv = 1.0f / (float)ks;
kvs.v_inv = 1.0f / (float)vs;
kvs.row = (int)(hd * r16 / 16);
return k6 ? qk_body<QK_KV_K6V4>(args, stream, kvs) : qk_body<QK_KV_F8V4>(args, stream, kvs);
if (!streamed)
return i8 ? qk_body<QK_KV_I8>(args, stream, kvs) : qk_body<QK_KV_BF16>(args, stream, kvs);
/* One block of one layer: the mirror's row pitch and the ring's slot pitch are the same bytes,
* so the store addresses both with one row arithmetic. */
const long long row = nkv * bs * rowe * (i8 ? 1 : 2);
const long long blocks = ho->shape[0];
if (blocks <= 0 || kvs.n_blocks <= 0 || row <= 0) return R4D_NO(RAD_E_SHAPE);
if (ho->shape[1] != row || ho->stride[0] != row) return R4D_NO(RAD_E_STRIDE);
if (r4d_numel(res) < blocks) return R4D_NO(RAD_E_SHAPE);
kvs.res = (const int32_t*)r4d_p(res);
kvs.host = r4d_wp(ho);
kvs.blocks = (int)blocks;
return i8 ? qk_body<QK_KV_STREAMED_I8>(args, stream, kvs)
: qk_body<QK_KV_STREAMED_BF16>(args, stream, kvs);
}
extern "C" int r4d_rad_qk_norm_rope_gate_kv_store_fp8v4(const RadArgs* args, RadStream stream) {
return qk_kv_q4(args, stream, 0);
extern "C" int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs* args, RadStream stream) {
return qk_kv_store(args, stream, false);
}
extern "C" int r4d_rad_qk_norm_rope_gate_kv_store_k6v4(const RadArgs* args, RadStream stream) {
return qk_kv_q4(args, stream, 1);
extern "C" int r4d_rad_qk_norm_rope_gate_kv_store_streamed(const RadArgs* args, RadStream stream) {
return qk_kv_store(args, stream, true);
}
// The cos/sin plane the fused prologue reads: one launch a step, against `rope`'s one per layer.
@@ -622,7 +504,12 @@ extern "C" int r4d_rad_rope_table(const RadArgs* args, RadStream stream) {
const float rscale = (float)r4d_getf(args, "scale", 1.0);
const RadYarn yarn = rad_yarn_args(args);
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return R4D_NO(RAD_E_INVAL);
return R4D_EMIT(stream, r4d_qk_rope_table_kernel, dim3((int)M), dim3(64), 0,
r4d_p(po), r4d_wp(cs), (long)(r4d_numel(cs) / rot), (int)rot, (int)den, theta,
rscale, cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0, yarn);
#define R4D_RT(CH_) \
R4D_EMIT(stream, r4d_qk_rope_table_kernel<CH_>, dim3((int)M), dim3(64), 0, \
r4d_p(po), r4d_wp(cs), (long)(r4d_numel(cs) / rot), (int)rot, (int)den, theta, \
rscale, cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0, yarn)
const int rc = r4d_geti_or(args, "chain", 0) != 0 && M <= 64 ? R4D_RT(r4dchain)
: R4D_RT(R4dUnchained);
#undef R4D_RT
return rc;
}
+46 -49
View File
@@ -25,12 +25,12 @@
//
// `qkv_norm_rope_kv_store` is the same launch followed by `kv_store`: the block of a k head (and of
// a v head) ends holding its token's finished head, so it also writes it into the paged cache at
// the token's slot, converted as kv_store converts it (E4M3: times the inverse descale, clamped to
// +-448, v_cvt_pk_fp8_f32 four columns a lane; bf16: the values as they are). The head is staged in
// LDS for that, since the fp8 store packs four neighbouring columns a lane. Byte-identical to the
// pair at either cache width; the k, v and q rows are still written, as the pair leaves them.
// the token's slot, converted as kv_store converts it (the int8 cache: the head's codes against its
// absmax / 127 as an f16, kv_store_i8's bytes; bf16: the values as they are). The head is staged in
// LDS for that, since the int8 store takes the head's absmax first. Byte-identical to the pair at
// either cache; the k, v and q rows are still written, as the pair leaves them.
//
// Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip.
// Returns a negative code instead of throwing: a kernel entry point has no caller to catch.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
@@ -88,27 +88,29 @@ __device__ __forceinline__ void rotate(const uint16_t* __restrict__ nb, uint16_t
}
}
// One head into the paged cache at element offset `off` (r4d_model_bf16.hip's kv_store kernels):
// KV 1 an E4M3 cache, four columns a lane as kv_store_fp8_kernel converts them; KV 2 a bf16 cache,
// the values as they are. `src` is the head in LDS, complete before the call.
// One head into the paged cache (r4d_model_bf16.hip's kv_store kernels). `src` is the head in LDS,
// complete before the call. KV 2, a bf16 cache: the values as they are, at element offset `off`.
// KV 1, the int8 cache: the head's int8 codes at byte offset `off` and its f16 scale (absmax / 127,
// the codes taken against the rounded scale) at byte offset `soff`, as kv_store_i8 writes them;
// `red` is a wave's slot each for the block's absmax, and the call holds a barrier, so the whole
// block makes it.
template <uint32_t HD, int KV>
__device__ __forceinline__ void kv_put(void* __restrict__ kv, size_t off,
const uint16_t* __restrict__ src, float inv) {
__device__ __forceinline__ void kv_put(void* __restrict__ kv, size_t off, size_t soff,
const uint16_t* __restrict__ src, float* red) {
const uint32_t t = threadIdx.x;
if (KV == 1) {
if (t < HD / 4) {
const uint32_t d = t * 4u;
float f[4];
const float f = bf2f(src[t]);
float am = r4d_wave_max(fabsf(f));
if ((t & 31u) == 0u) red[t >> 5] = am;
__syncthreads();
am = 0.0f;
#pragma unroll
for (int e = 0; e < 4; ++e) f[e] = bf2f(src[d + (uint32_t)e]) * inv;
// clamped because v_cvt_pk_fp8_f32 returns NaN out of range instead of saturating
int pk = 0;
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(f[0], -448.0f), 448.0f),
fminf(fmaxf(f[1], -448.0f), 448.0f), pk, false);
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(f[2], -448.0f), 448.0f),
fminf(fmaxf(f[3], -448.0f), 448.0f), pk, true);
*(uint32_t*)((uint8_t*)kv + off + d) = (uint32_t)pk;
}
for (uint32_t w = 0; w < HD / kWave; ++w) am = fmaxf(am, red[w]);
const __fp16 s16 = (__fp16)fminf(am / 127.0f, 515.0f);
const float sc = (float)s16;
const float r = sc > 0.0f ? rintf(f / sc) : 0.0f;
((uint8_t*)kv)[off + t] = (uint8_t)(int8_t)(int)fminf(fmaxf(r, -127.0f), 127.0f);
if (t == 0u) *(uint16_t*)((uint8_t*)kv + soff) = __builtin_bit_cast(uint16_t, s16);
} else if (KV == 2) {
for (uint32_t i = t; i < HD; i += HD) ((uint16_t*)kv)[off + i] = src[i];
}
@@ -117,9 +119,10 @@ __device__ __forceinline__ void kv_put(void* __restrict__ kv, size_t off,
// blockIdx.y: [0, nq) a query head, [nq, nq+nkv) a key head (and with VK its value, from the raw
// key), [nq+nkv, nq+2nkv) a value head normalised in place (without VK).
//
// KV 1 or 2 also stores each k and v head into the paged cache [n_blocks, nkv, block_size, 2*HD]
// at slot[m] (k at column 0, v at HD), for rows m < n_slot whose slot is in range; KV 0 stores
// nothing and ignores the cache arguments.
// KV 1 or 2 also stores each k and v head into the paged cache [n_blocks, nkv, block_size, row] at
// slot[m] (k at column 0, v at HD; row 2*HD, or 2*HD + 4 at the int8 cache, whose two scales
// follow the codes), for rows m < n_slot whose slot is in range; KV 0 stores nothing and ignores
// the cache arguments.
// The body: its blocks return early (rows past the cliff, value heads), so the chained form
// (r4d_chain.h) wraps it below rather than bracketing it in place.
template <uint32_t HD, bool WF32, bool VK, int KV>
@@ -130,7 +133,7 @@ __device__ __forceinline__ void qkv_norm_rope_body(
uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd,
uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos,
uint32_t m_rows, const int32_t* __restrict__ slot, void* __restrict__ kvc, uint32_t n_slot,
uint32_t block_size, uint32_t n_blocks, float k_inv, float v_inv, uint32_t vnorm) {
uint32_t block_size, uint32_t n_blocks, uint32_t vnorm) {
__shared__ float l1[HD / kWave], l2[HD / kWave];
__shared__ uint16_t nb[HD];
__shared__ uint16_t sb[KV ? HD : 1]; // the head this block stores
@@ -141,7 +144,8 @@ __device__ __forceinline__ void qkv_norm_rope_body(
// rope rotates only the rows its positions cover; a row past them is normed and not rotated
const float p0 = m < n_pos ? (float)pos[m] / div : 0.0f;
// The row's cache slot, as kv_store reads it: a negative or out-of-range slot stores nothing.
// Uniform over the block, so the barriers below are too.
// Uniform over the block, so the barriers below are too. ROW is a token's row in a head.
constexpr size_t ROW = KV == 1 ? 2 * HD + 4 : 2 * HD;
size_t base = 0;
bool put = false;
if (KV && m < n_slot) {
@@ -149,10 +153,10 @@ __device__ __forceinline__ void qkv_norm_rope_body(
if (sl >= 0 && (uint32_t)sl / block_size < n_blocks) {
put = true;
base = ((size_t)((uint32_t)sl / block_size) * nkv * block_size +
(size_t)((uint32_t)sl % block_size)) * 2 * HD;
(size_t)((uint32_t)sl % block_size)) * ROW;
}
}
const size_t head_step = (size_t)block_size * 2 * HD;
const size_t head_step = (size_t)block_size * ROW;
if (hh >= nq + nkv) { // a value head, in place: rmsnorm_p (or, without v_norm, only stored)
const uint32_t h = hh - nq - nkv;
@@ -170,7 +174,8 @@ __device__ __forceinline__ void qkv_norm_rope_body(
}
if (KV && put) {
__syncthreads();
kv_put<HD, KV>(kvc, base + (size_t)h * head_step + HD, sb, v_inv);
const size_t r0 = base + (size_t)h * head_step;
kv_put<HD, KV>(kvc, r0 + HD, r0 + 2 * HD + 2, sb, l1);
}
return;
}
@@ -200,8 +205,9 @@ __device__ __forceinline__ void qkv_norm_rope_body(
else for (uint32_t i = t; i < HD; i += HD) { x[i] = nb[i]; if (st) st[i] = nb[i]; }
if (KV && !isq && put) {
__syncthreads(); // the stored head (and VK's value) complete in LDS
kv_put<HD, KV>(kvc, base + (size_t)h * head_step, sb, k_inv);
if (VK) kv_put<HD, KV>(kvc, base + (size_t)h * head_step + HD, vb, v_inv);
const size_t r0 = base + (size_t)h * head_step;
kv_put<HD, KV>(kvc, r0, r0 + 2 * HD, sb, l1);
if (VK) kv_put<HD, KV>(kvc, r0 + HD, r0 + 2 * HD + 2, vb, l2);
}
}
@@ -211,9 +217,9 @@ __device__ __forceinline__ void qkv_norm_rope_body(
uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd, \
uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos, \
uint32_t m_rows, const int32_t* __restrict__ slot, void* __restrict__ kvc, uint32_t n_slot, \
uint32_t block_size, uint32_t n_blocks, float k_inv, float v_inv, uint32_t vnorm
uint32_t block_size, uint32_t n_blocks, uint32_t vnorm
#define R4D_QNR_ARGS q, k, v, pos, qw, kw, nq, nkv, pq, pk, pv, q_ld, k_ld, v_ld, eps, wadd, rot, nfreq, \
den, theta, rscale, n_pos, m_rows, slot, kvc, n_slot, block_size, n_blocks, k_inv, v_inv, vnorm
den, theta, rscale, n_pos, m_rows, slot, kvc, n_slot, block_size, n_blocks, vnorm
// The plain kernel, and the chained one (r4dchain*, r4d_chain.h) wrapping the same body.
template <uint32_t HD, bool WF32, bool VK, int KV>
__global__ __launch_bounds__(HD) void qkv_norm_rope_kernel(R4D_QNR_PARAMS) {
@@ -299,34 +305,25 @@ static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store)
const bool chain = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; /* RadKernelChainFn, decode */
// The store's geometry, checked as kv_store_geom checks it (r4d_model_bf16.hip).
int kvw = 0; // 0 none, 1 E4M3, 2 bf16
int kvw = 0; // 0 none, 1 the int8 cache, 2 bf16
const RadTensor* sm = nullptr;
const RadTensor* kv = nullptr;
long long bs = 0, nblk = 0, nslot = 0;
float kinv = 1.0f, vinv = 1.0f;
if (store) {
sm = r4d_opt(a, QN_SLOT);
kv = r4d_opt(a, QN_CACHE);
if (!sm || !kv) return R4D_NO(RAD_E_INVAL);
if (sm->dtype != RAD_I32 || !r4d_contig(sm) || !r4d_contig(kv)) return R4D_NO(RAD_E_STRIDE);
if (kv->dtype == RAD_I8) kvw = 1;
else if (kv->dtype == RAD_BF16) kvw = 2;
else return R4D_NO(RAD_E_DTYPE);
bs = r4d_geti_or(a, "block_size", 0);
if (bs <= 0 || kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs ||
kv->shape[3] != 2 * hd)
kv->shape[3] != (kvw == 1 ? 2 * hd + 4 : 2 * hd))
return R4D_NO(RAD_E_SHAPE);
nblk = kv->shape[0];
nslot = r4d_numel(sm);
if (nslot <= 0 || nslot > M) return R4D_NO(RAD_E_SHAPE);
if (kv->dtype == RAD_F8E4M3) {
const double ks = r4d_getf(a, "k_scale", 1.0), vs = r4d_getf(a, "v_scale", 1.0);
if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL);
kinv = 1.0f / (float)ks;
vinv = 1.0f / (float)vs;
kvw = 1;
} else if (kv->dtype == RAD_BF16) {
kvw = 2;
} else {
return R4D_NO(RAD_E_DTYPE);
}
}
#define R4D_QNR_T(HD, WF, VK, KV) emit_rc = chain ? R4D_QNR_C(HD, WF, VK, KV, true) : R4D_QNR_C(HD, WF, VK, KV, false)
@@ -335,7 +332,7 @@ static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store)
r4d_p(qw), r4d_p(kw), (uint32_t)nq, (uint32_t)nkv, pq, pk, pv, (uint32_t)q_ld, (uint32_t)k_ld, \
(uint32_t)v_ld, eps, wadd, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp, \
(uint32_t)M, (const int32_t*)(sm ? r4d_p(sm) : nullptr), (void*)(kv ? r4d_wp(kv) : nullptr), \
(uint32_t)nslot, (uint32_t)bs, (uint32_t)nblk, kinv, vinv, (uint32_t)(vn ? 1 : 0))
(uint32_t)nslot, (uint32_t)bs, (uint32_t)nblk, (uint32_t)(vn ? 1 : 0))
#define R4D_QNR_KV(HD, WF, VK) \
do { if (kvw == 1) R4D_QNR_T(HD, WF, VK, 1); else if (kvw == 2) R4D_QNR_T(HD, WF, VK, 2); \
else R4D_QNR_T(HD, WF, VK, 0); } while (0)
+30 -32
View File
@@ -28,9 +28,9 @@
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_chain.h"
#include "rad_yarn.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_common.h" // r4d_wave_sum
#include <hip/hip_runtime.h>
@@ -55,12 +55,13 @@ __device__ __forceinline__ int qbk_comp(int mode, int i, int s0, int s1, int s2)
return i < s0 ? 0 : (i < s0 + s1 ? 1 : 2);
}
__device__ __forceinline__ void qsa_block_key_kernel_body(
const uint16_t* __restrict__ k, const float* __restrict__ w,
const int32_t* __restrict__ page, const int32_t* __restrict__ bpos,
uint16_t* __restrict__ out,
int n, int ratio, int rot, float eps, float wadd, float theta, float rscale,
long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc, RadYarn yarn) {
#define QSA_BLOCK_KEY_PARAMS \
const uint16_t* __restrict__ k, const float* __restrict__ w, \
const int32_t* __restrict__ page, const int32_t* __restrict__ bpos, \
uint16_t* __restrict__ out, int n, int ratio, int rot, float eps, float wadd, \
float theta, float rscale, long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, \
int s2, int bstep, int mc, RadYarn yarn
__device__ __forceinline__ void qsa_block_key_body(QSA_BLOCK_KEY_PARAMS) {
__shared__ float sh[kMaxN];
__shared__ float red[kMaxN / 32];
@@ -125,25 +126,17 @@ __device__ __forceinline__ void qsa_block_key_kernel_body(
((__hip_bfloat16*)out)[(size_t)orow * o_ld + t] = __float2bfloat16(res);
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
__global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel(
const uint16_t* __restrict__ k, const float* __restrict__ w,
const int32_t* __restrict__ page, const int32_t* __restrict__ bpos,
uint16_t* __restrict__ out,
int n, int ratio, int rot, float eps, float wadd, float theta, float rscale,
long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc, RadYarn yarn) {
qsa_block_key_kernel_body(k, w, page, bpos, out, n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld, o_ld, mode, s0, s1, s2, bstep, mc, yarn);
}
__global__ __launch_bounds__(kMaxN) void r4dchain_qsa_block_key(
const uint16_t* __restrict__ k, const float* __restrict__ w,
const int32_t* __restrict__ page, const int32_t* __restrict__ bpos,
uint16_t* __restrict__ out,
int n, int ratio, int rot, float eps, float wadd, float theta, float rscale,
long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc, RadYarn yarn) {
r4d_chain_wait();
qsa_block_key_kernel_body(k, w, page, bpos, out, n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld, o_ld, mode, s0, s1, s2, bstep, mc, yarn);
r4d_chain_done();
/* The kernel around the body, whose blocks and threads return where their work ends: CH `r4dchain`
* is the chained form (r4d_chain.h). */
template <class CH>
__global__ __launch_bounds__(kMaxN)
void qsa_block_key_kernel(QSA_BLOCK_KEY_PARAMS) {
if (CH::on) r4d_chain_wait();
qsa_block_key_body(k, w, page, bpos, out, n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld,
o_ld, mode, s0, s1, s2, bstep, mc, yarn);
if (CH::on) r4d_chain_done();
}
#undef QSA_BLOCK_KEY_PARAMS
} // namespace
@@ -157,7 +150,7 @@ static int r4d_qsa_block_key_bf16_emit(long k, long w, long page, long bpos, lon
int n, int ratio, int rot, float eps, float wadd,
float theta, float rscale, long long pos0, int k_ld,
int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc,
RadStream stream, RadYarn yarn) {
RadStream stream, RadYarn yarn, bool chain) {
if (!k || !w || !out || (pos0 < 0 && !bpos)) return R4D_NO(RAD_E_INVAL);
if (M <= 0 || n <= 0 || n > kMaxN || ratio <= 0) return R4D_NO(RAD_E_SHAPE);
if (rot < 0 || rot > n || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
@@ -165,10 +158,15 @@ static int r4d_qsa_block_key_bf16_emit(long k, long w, long page, long bpos, lon
if (!o_ld) o_ld = n;
/* n threads rounded up to whole waves for the block reduction (extra threads contribute 0). */
const int thr = ((n + 31) / 32) * 32;
return R4D_EMIT(stream, g_r4d_chain_arg ? &r4dchain_qsa_block_key : &qsa_block_key_kernel, dim3((unsigned)M), dim3((unsigned)thr), 0,
(const uint16_t*)k, (const float*)w, (const int32_t*)page,
(const int32_t*)bpos, (uint16_t*)out, n, ratio, rot, eps, wadd, theta, rscale,
pos0, k_ld, o_ld, mode, s0, s1, s2, bstep, mc, yarn);
/* Each form named at its own launch: a test reads the kernel a launch site names. */
#define R4D_QBKEY(CH_) \
R4D_EMIT(stream, qsa_block_key_kernel<CH_>, dim3((unsigned)M), dim3((unsigned)thr), 0, \
(const uint16_t*)k, (const float*)w, (const int32_t*)page, (const int32_t*)bpos, \
(uint16_t*)out, n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld, o_ld, mode, \
s0, s1, s2, bstep, mc, yarn)
const int rc = chain ? R4D_QBKEY(r4dchain) : R4D_QBKEY(R4dUnchained);
#undef R4D_QBKEY
return rc;
}
// ============================================================== the plugin ABI entry point
@@ -238,12 +236,12 @@ extern "C" int r4d_rad_qsa_block_key(const RadArgs* a, RadStream stream) {
if (!rad_yarn_valid(yarn) ||
(yarn.factor != 0.0f && (rot <= 0 || r4d_getf(a, "scale", 1.0) != 1.0)))
return R4D_NO(RAD_E_INVAL);
const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0);
return r4d_qsa_block_key_bf16_emit(
r4d_addr(k), r4d_addr(w), r4d_addr(pg), r4d_addr(bp), r4d_addr(o),
(int)M, (int)n, (int)ratio, (int)rot,
(float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 1.0),
(float)r4d_getf(a, "theta", 10000.0), (float)r4d_getf(a, "scale", 1.0),
pos0, (int)kp, (int)op, mode, sec[0], sec[1], sec[2], bstep, mc, stream, yarn);
pos0, (int)kp, (int)op, mode, sec[0], sec[1], sec[2], bstep, mc, stream, yarn,
r4d_geti_or(a, "chain", 0) != 0);
}
+26 -29
View File
@@ -19,8 +19,8 @@
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "r4d_gdn_wmma.h"
@@ -242,12 +242,13 @@ constexpr long long kMxWavesTarget = 4096;
* heads) would otherwise dominate. */
constexpr long long kMxMinTiles = 4;
#define QSA_SCORE_MX_PARAMS \
const unsigned short* __restrict__ q, const unsigned short* __restrict__ bk, \
const int32_t* __restrict__ bt, const int32_t* __restrict__ cu, \
const int32_t* __restrict__ nc, float* __restrict__ out, int M, int nb, int nseq, \
int tpw, int q_ld, int bk_ld, int bt_ld, int out_ld, int vec
template <int HEADS>
__device__ __forceinline__ void qsa_score_mx_kernel_body(
const unsigned short* __restrict__ q, const unsigned short* __restrict__ bk,
const int32_t* __restrict__ bt, const int32_t* __restrict__ cu,
const int32_t* __restrict__ nc, float* __restrict__ out,
int M, int nb, int nseq, int tpw, int q_ld, int bk_ld, int bt_ld, int out_ld, int vec) {
__device__ __forceinline__ void qsa_score_mx_body(QSA_SCORE_MX_PARAMS) {
const int lane = threadIdx.x & (kWave - 1), wave = threadIdx.x >> 5;
const int half = lane >> 4, col = lane & 15;
@@ -335,25 +336,17 @@ __device__ __forceinline__ void qsa_score_mx_kernel_body(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <int HEADS>
__global__ __launch_bounds__(kMxWaves * kWave) void qsa_score_mx_kernel(
const unsigned short* __restrict__ q, const unsigned short* __restrict__ bk,
const int32_t* __restrict__ bt, const int32_t* __restrict__ cu,
const int32_t* __restrict__ nc, float* __restrict__ out,
int M, int nb, int nseq, int tpw, int q_ld, int bk_ld, int bt_ld, int out_ld, int vec) {
qsa_score_mx_kernel_body<HEADS>(q, bk, bt, cu, nc, out, M, nb, nseq, tpw, q_ld, bk_ld, bt_ld, out_ld, vec);
}
template <int HEADS>
__global__ __launch_bounds__(kMxWaves * kWave) void r4dchain_qsa_score_mx(
const unsigned short* __restrict__ q, const unsigned short* __restrict__ bk,
const int32_t* __restrict__ bt, const int32_t* __restrict__ cu,
const int32_t* __restrict__ nc, float* __restrict__ out,
int M, int nb, int nseq, int tpw, int q_ld, int bk_ld, int bt_ld, int out_ld, int vec) {
r4d_chain_wait();
qsa_score_mx_kernel_body<HEADS>(q, bk, bt, cu, nc, out, M, nb, nseq, tpw, q_ld, bk_ld, bt_ld, out_ld, vec);
r4d_chain_done();
/* The kernel around the body, whose blocks and threads return where their work ends: CH `r4dchain`
* is the chained form (r4d_chain.h). */
template <int HEADS, class CH>
__global__ __launch_bounds__(kMxWaves * kWave)
void qsa_score_mx_kernel(QSA_SCORE_MX_PARAMS) {
if (CH::on) r4d_chain_wait();
qsa_score_mx_body<HEADS>(q, bk, bt, cu, nc, out, M, nb, nseq, tpw, q_ld, bk_ld, bt_ld, out_ld,
vec);
if (CH::on) r4d_chain_done();
}
#undef QSA_SCORE_MX_PARAMS
/* Form override for tests (r4d_selftest compares the two): 0 = automatic, 1 = scalar,
* 2 = matrix. Like r4d_gemm_fp8a8_pin_mw. */
@@ -371,7 +364,8 @@ extern "C" void r4d_qsa_score_pin_form(int form) { g_qsa_form = form; }
// out [M][nb] f32, `out_ld` elements a row (0 = nb)
static int r4d_qsa_score_bf16_emit(long q, long bk, long bt, long cu, long nc, long out,
int M, int n, int heads, int nb, int nseq,
int q_ld, int bk_ld, int bt_ld, int out_ld, RadStream stream) {
int q_ld, int bk_ld, int bt_ld, int out_ld, RadStream stream,
bool chain) {
int emit_rc = RAD_OK;
if (!q || !bk || !bt || !cu || !nc || !out) return R4D_NO(RAD_E_INVAL);
if (M <= 0 || n <= 0 || heads <= 0 || nb <= 0 || nseq <= 0) return R4D_NO(RAD_E_SHAPE);
@@ -394,12 +388,14 @@ static int r4d_qsa_score_bf16_emit(long q, long bk, long bt, long cu, long nc, l
if (tpw < kMxMinTiles) tpw = kMxMinTiles;
const unsigned gx = (unsigned)((tiles + tpw * kMxWaves - 1) / (tpw * kMxWaves));
const int vec = (out_ld % 4 == 0) && ((out & 15) == 0);
#define RAD_QSA_MX(H) \
emit_rc = R4D_EMIT(stream, (g_r4d_chain_arg ? &r4dchain_qsa_score_mx<H> : &qsa_score_mx_kernel<H>), dim3(gx, (unsigned)qt), \
#define RAD_QSA_MX_E(H, CH_) \
emit_rc = R4D_EMIT(stream, (qsa_score_mx_kernel<H, CH_>), dim3(gx, (unsigned)qt), \
dim3(kMxWaves * kWave), 0, (const unsigned short*)q, \
(const unsigned short*)bk, \
(const int32_t*)bt, (const int32_t*)cu, (const int32_t*)nc, \
(float*)out, M, nb, nseq, (int)tpw, q_ld, bk_ld, bt_ld, out_ld, vec)
#define RAD_QSA_MX(H) \
do { if (chain) RAD_QSA_MX_E(H, r4dchain); else RAD_QSA_MX_E(H, R4dUnchained); } while (0)
switch (heads) {
case 1: RAD_QSA_MX(1); break;
case 2: RAD_QSA_MX(2); break;
@@ -408,6 +404,7 @@ static int r4d_qsa_score_bf16_emit(long q, long bk, long bt, long cu, long nc, l
default: return R4D_NO(RAD_E_SHAPE);
}
#undef RAD_QSA_MX
#undef RAD_QSA_MX_E
return emit_rc;
}
const unsigned nbg = (unsigned)((nb + kWaves * kBPW - 1) / (kWaves * kBPW));
@@ -482,10 +479,10 @@ extern "C" int r4d_rad_qsa_score(const RadArgs* a, RadStream stream) {
const long long qp = r4d_row_pitch(q), kp = r4d_row_pitch(bk);
const long long tp = r4d_row_pitch(bt), op = r4d_row_pitch(o);
if (qp < 0 || kp < 0 || tp < 0 || op < 0) return R4D_NO(RAD_E_STRIDE);
const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0);
return r4d_qsa_score_bf16_emit(r4d_addr(q), r4d_addr(bk), r4d_addr(bt), r4d_addr(cu),
r4d_addr(nc), r4d_addr(o),
(int)M, (int)n, (int)heads, (int)nb, (int)nseq,
(int)qp, (int)kp, (int)tp, (int)op, stream);
(int)qp, (int)kp, (int)tp, (int)op, stream,
r4d_geti_or(a, "chain", 0) != 0);
}
+222 -167
View File
@@ -19,8 +19,8 @@
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_emit.h"
#include "r4d_launch.h" // R4D_DYN_LDS
#include "r4d_common.h" // the DPP wave scans
@@ -129,13 +129,14 @@ __device__ __forceinline__ void counts_before(const uint32_t* wsum, int lane, in
* block table and complete-block count. The per-query bound is (pos + 1) / ratio: block b is
* entirely in the query's past when b * ratio + ratio - 1 <= pos. At decode this equals the
* sequence's complete count. */
#define QSA_SELECT_PARAMS \
const float* __restrict__ score, const int32_t* __restrict__ bt, \
const int32_t* __restrict__ nc, const int32_t* __restrict__ pos, \
const int32_t* __restrict__ cu, int32_t* __restrict__ sel, int32_t* __restrict__ nsel, \
int32_t* __restrict__ seqused, int nb, int topk, int ratio, int nseq, int s_ld, \
int t_ld, int o_ld, int cap
template <bool Signed>
__device__ __forceinline__ void qsa_select_kernel_body(
const float* __restrict__ score, const int32_t* __restrict__ bt,
const int32_t* __restrict__ nc, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu,
int32_t* __restrict__ sel, int32_t* __restrict__ nsel, int32_t* __restrict__ seqused,
int nb, int topk, int ratio, int nseq, int s_ld, int t_ld, int o_ld, int cap) {
__device__ __forceinline__ void qsa_select_body(QSA_SELECT_PARAMS) {
__shared__ uint32_t hist[kBins];
__shared__ uint32_t suf[kBins];
@@ -295,27 +296,17 @@ __device__ __forceinline__ void qsa_select_kernel_body(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <bool Signed>
__global__ __launch_bounds__(kThreads) void qsa_select_kernel(
const float* __restrict__ score, const int32_t* __restrict__ bt,
const int32_t* __restrict__ nc, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu,
int32_t* __restrict__ sel, int32_t* __restrict__ nsel, int32_t* __restrict__ seqused,
int nb, int topk, int ratio, int nseq, int s_ld, int t_ld, int o_ld, int cap) {
qsa_select_kernel_body<Signed>(score, bt, nc, pos, cu, sel, nsel, seqused, nb, topk, ratio, nseq, s_ld, t_ld, o_ld, cap);
}
template <bool Signed>
__global__ __launch_bounds__(kThreads) void r4dchain_qsa_select(
const float* __restrict__ score, const int32_t* __restrict__ bt,
const int32_t* __restrict__ nc, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu,
int32_t* __restrict__ sel, int32_t* __restrict__ nsel, int32_t* __restrict__ seqused,
int nb, int topk, int ratio, int nseq, int s_ld, int t_ld, int o_ld, int cap) {
r4d_chain_wait();
qsa_select_kernel_body<Signed>(score, bt, nc, pos, cu, sel, nsel, seqused, nb, topk, ratio, nseq, s_ld, t_ld, o_ld, cap);
r4d_chain_done();
/* The kernel around the body, whose blocks and threads return where their work ends: CH `r4dchain`
* is the chained form (r4d_chain.h). */
template <bool Signed, class CH>
__global__ __launch_bounds__(kThreads)
void qsa_select_kernel(QSA_SELECT_PARAMS) {
if (CH::on) r4d_chain_wait();
qsa_select_body<Signed>(score, bt, nc, pos, cu, sel, nsel, seqused, nb, topk, ratio, nseq, s_ld,
t_ld, o_ld, cap);
if (CH::on) r4d_chain_done();
}
#undef QSA_SELECT_PARAMS
/* ===================================================== the wide-launch path, for a prefill chunk
*
@@ -814,8 +805,16 @@ constexpr int32_t kParOver = 1 << 30;
* hide LDS and global latency (24 VGPRs, so occupancy is not the limit). The bin scan stays at
* 256 threads. */
constexpr int kMergeThreads = 1024;
/* The local pass has many more workgroups (48 at the decode shape), so a narrower block. */
constexpr int kLocalThreads = 512;
/* The local pass has many more workgroups (a query's chunks times the query rows), so a narrower
* block -- except where the grid is small enough to sit on the card at once: up to
* kLocalWideGrid workgroups (four verify rows over as many as kParWMax chunks) the wide block
* hides the same latencies as the merge's. At 95K tokens of context, one sequence under the draft
* head, the twelve local launches of a verify pass take 105 us wide against 126 (and 209 at 256
* threads). */
constexpr int kLocalThreads = 512, kLocalWideThreads = 1024;
constexpr int kLocalWideGrid = 64;
static_assert(kParCap / kLocalThreads <= 32 && kLdsCap / kMergeThreads <= 32,
"a thread's run of keys is a 32-bit mask (run_take)");
/* Chunks for a block list of nb (at most kParWMax). Both kernels index the scratch at the fixed
* kParWMax stride, so they agree regardless of this value. */
@@ -874,76 +873,77 @@ __device__ __forceinline__ void radix_thresh(const uint32_t* __restrict__ key, i
}
}
/* The qualifying set by prefix count, in two layouts.
/* The qualifying set by prefix count.
*
* The merge must reproduce the single-workgroup kernel's table exactly (entries above the
* threshold first, ties last): the attention sums pages in table order and float addition is not
* associative. The local pass instead writes in block order, since the merge's tie rule reads it
* that way. Slots come from workgroup prefix counts, never from scheduling. */
struct ParEmit {
uint32_t* wsum; /* [kWaves] scratch for the wave prefix */
uint32_t* sh_hi; /* running count of entries above the threshold */
uint32_t* sh_ord; /* running count of entries taken, in block order */
uint32_t taken_eq; /* ties taken so far; per thread, and uniform by induction */
uint32_t T, need;
bool all; /* below the top-k: everything live is in */
};
struct ParTake {
bool hi, take;
uint32_t slot_hi, slot_ord, rank_eq;
* that way. Slots come from workgroup prefix counts, never from scheduling.
*
* A thread owns `run` consecutive keys of the list in LDS (threads in order, so block order holds)
* and classes them into bit masks; three workgroup prefixes over the per-thread counts then place
* every key, two barriers each whatever the list's length (a prefix per NT keys of the list costs
* five barriers a round, eight rounds for a chunk). `run` is at most 32. */
struct RunTake {
uint32_t hi, eq, take; /* bit j: this thread's key j is above the threshold, a tie
* at it, taken */
uint32_t rank_eq; /* ties ahead of this thread's first key */
uint32_t slot_hi, slot_take; /* above-threshold and taken keys ahead of it */
uint32_t n_hi, n_take; /* the workgroup's totals */
};
/* One ballot, one wave prefix, one workgroup prefix. `*run` is the running total, advanced by
* thread 0. */
/* The exclusive workgroup prefix of a per-thread count, and the total. */
template <int NT>
__device__ __forceinline__ uint32_t par_scan(ParEmit& e, bool p, int lane, int wave,
uint32_t* run, uint32_t base0, uint32_t* total) {
__device__ __forceinline__ uint32_t run_prefix(uint32_t mine, uint32_t* wsum, int lane, int wave,
uint32_t* total) {
constexpr int NW = NT / kWave;
const unsigned long long mk = __ballot(p);
const uint32_t rk = (uint32_t)__popcll(mk & ((1ull << lane) - 1ull));
if (lane == 0) e.wsum[wave] = (uint32_t)__popcll(mk);
const uint32_t inc = r4d_wave_prefix_u32(mine, lane);
if (lane == kWave - 1) wsum[wave] = inc;
__syncthreads();
uint32_t before, tot;
counts_before<NW>(e.wsum, lane, wave, &before, &tot);
const uint32_t base = base0 + before;
counts_before<NW>(wsum, lane, wave, &before, &tot);
__syncthreads();
if (total) *total = tot;
if (run && threadIdx.x == 0) *run += tot;
return base + rk;
*total = tot;
return before + inc - mine;
}
/* WantHi / WantOrd select which slots are computed: each par_scan costs a ballot and two
* barriers, the merge reads only slot_hi and rank_eq, and the local pass only slot_ord. The
* branches are compile-time, so every thread takes the same path and the barriers inside are
* legal. `take` depends on rank_eq, which is always computed first. */
template <bool WantHi, bool WantOrd, int NT>
__device__ __forceinline__ ParTake par_take(ParEmit& e, uint32_t k, int lane, int wave) {
ParTake r{};
r.hi = k != 0u && (e.all || k > e.T);
const bool eq = k != 0u && !e.all && k == e.T;
uint32_t tot_e = 0;
r.rank_eq = par_scan<NT>(e, eq, lane, wave, nullptr, e.taken_eq, &tot_e);
r.take = r.hi || (eq && r.rank_eq < e.need);
if (WantHi) r.slot_hi = par_scan<NT>(e, r.hi, lane, wave, e.sh_hi, *e.sh_hi, nullptr);
if (WantOrd) r.slot_ord = par_scan<NT>(e, r.take, lane, wave, e.sh_ord, *e.sh_ord, nullptr);
e.taken_eq += tot_e;
__syncthreads();
/* `all`: below the top-k, everything live is in. Else keys above `T` are in and the first `need`
* ties at `T` in list order. */
template <int NT>
__device__ __forceinline__ RunTake run_take(const uint32_t* __restrict__ key, int n, int run,
uint32_t T, uint32_t need, bool all, uint32_t* wsum,
int lane, int wave) {
RunTake r{};
const int i0 = (int)threadIdx.x * run;
for (int j = 0; j < run; ++j) {
const uint32_t k = i0 + j < n ? key[i0 + j] : 0u;
if (k != 0u && (all || k > T)) r.hi |= 1u << j;
if (k != 0u && !all && k == T) r.eq |= 1u << j;
}
uint32_t n_eq = 0;
r.rank_eq = run_prefix<NT>((uint32_t)__builtin_popcount(r.eq), wsum, lane, wave, &n_eq);
/* The ties this thread may take: the first `need - rank_eq` of its own. */
uint32_t left = r.rank_eq < need ? need - r.rank_eq : 0u, eq_take = 0u;
for (int j = 0; j < run && left > 0u; ++j)
if ((r.eq >> j) & 1u) { eq_take |= 1u << j; --left; }
r.take = r.hi | eq_take;
r.slot_hi = run_prefix<NT>((uint32_t)__builtin_popcount(r.hi), wsum, lane, wave, &r.n_hi);
r.slot_take = run_prefix<NT>((uint32_t)__builtin_popcount(r.take), wsum, lane, wave, &r.n_take);
return r;
}
/* ---- pass one: every chunk's own top-k, as (key, block index) in block order. */
template <bool Signed>
__global__ __launch_bounds__(kLocalThreads) void qsa_local_kernel(
const float* __restrict__ score, const int32_t* __restrict__ bt,
const int32_t* __restrict__ nc, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu,
uint32_t* __restrict__ ck, int32_t* __restrict__ ci, int32_t* __restrict__ cc,
int nb, int topk, int ratio, int nseq, int s_ld, int t_ld, int chunk) {
#define QSA_LOCAL_PARAMS \
const float* __restrict__ score, const int32_t* __restrict__ bt, \
const int32_t* __restrict__ nc, const int32_t* __restrict__ pos, \
const int32_t* __restrict__ cu, \
uint32_t* __restrict__ ck, int32_t* __restrict__ ci, int32_t* __restrict__ cc, \
int nb, int topk, int ratio, int nseq, int s_ld, int t_ld, int chunk
template <bool Signed, int LT>
__device__ __forceinline__ void qsa_local_body(QSA_LOCAL_PARAMS) {
constexpr int LT = kLocalThreads;
__shared__ uint32_t hist[kBins], suf[kBins], wsum[LT / kWave];
__shared__ uint32_t sh_T, sh_need, sh_hi, sh_ord;
__shared__ uint32_t sh_T, sh_need;
__shared__ int sh_seq;
R4D_DYN_LDS(uint32_t, sh_key);
@@ -968,41 +968,68 @@ __global__ __launch_bounds__(kLocalThreads) void qsa_local_kernel(
const float* sc = score + (size_t)m * s_ld;
const int32_t* tb = bt + (size_t)seq * t_ld;
for (int i = t; i < cn; i += LT) sh_key[i] = keyof<Signed>(sc[lo + i], tb[lo + i]);
/* A thread's scores and pages (every LT-th of the chunk) are all loaded before the first key
* is staged: one round trip instead of one a key. */
{
constexpr int kPre = kParCap / LT;
float sv[kPre];
int32_t pv[kPre];
#pragma unroll
for (int u = 0; u < kPre; ++u) {
const int i = t + u * LT;
sv[u] = 0.0f; pv[u] = -1;
if (i < cn) { sv[u] = sc[lo + i]; pv[u] = tb[lo + i]; }
}
#pragma unroll
for (int u = 0; u < kPre; ++u) {
const int i = t + u * LT;
if (i < cn) sh_key[i] = keyof<Signed>(sv[u], pv[u]);
}
}
__syncthreads();
ParEmit e{ wsum, &sh_hi, &sh_ord, 0u, 0u, 0u, cn <= topk };
if (!e.all) {
const bool all = cn <= topk;
uint32_t T = 0u, need = 0u;
if (!all) {
radix_thresh<LT>(sh_key, cn, (uint32_t)topk, true, hist, suf, wsum, &sh_T, &sh_need);
e.T = sh_T; e.need = sh_need;
T = sh_T; need = sh_need;
}
/* A threshold means more than topk live keys here, so more than topk in the whole list. */
const bool over = !e.all && e.T != 0u;
if (t == 0) { sh_hi = 0; sh_ord = 0; }
__syncthreads();
const bool over = !all && T != 0u;
/* In block order: the merge breaks ties by block index. */
uint32_t* dk = ck + (size_t)(m * kParWMax + c) * topk;
int32_t* di = ci + (size_t)(m * kParWMax + c) * topk;
for (int i0 = 0; i0 < cn; i0 += LT) {
const int i = i0 + t;
const uint32_t k = i < cn ? sh_key[i] : 0u;
const ParTake r = par_take<false, true, LT>(e, k, lane, wave);
if (r.take && r.slot_ord < (uint32_t)topk) {
dk[r.slot_ord] = k;
/* Store the page, not the block index: resolving it here spreads the dependent load
* over many workgroups instead of the merge's few. The merge breaks ties by list
* position (block-ordered), never by index. A taken candidate has k != 0, so its
* page is live. */
di[r.slot_ord] = tb[lo + i];
}
const int run = (cn + LT - 1) / LT;
const RunTake r = run_take<LT>(sh_key, cn, run, T, need, all, wsum, lane, wave);
for (int j = 0; j < run; ++j) {
if (!((r.take >> j) & 1u)) continue;
const uint32_t slot = r.slot_take + (uint32_t)__builtin_popcount(r.take & ((1u << j) - 1u));
if (slot >= (uint32_t)topk) continue;
const int i = t * run + j;
dk[slot] = sh_key[i];
/* Store the page, not the block index: resolving it here spreads the dependent load
* over many workgroups instead of the merge's few. The merge breaks ties by list
* position (block-ordered), never by index. A taken candidate has k != 0, so its
* page is live. */
di[slot] = tb[lo + i];
}
if (t == 0) cc[(size_t)m * kParWMax + c] =
(int32_t)(sh_ord < (uint32_t)topk ? sh_ord : (uint32_t)topk) | (over ? kParOver : 0);
(int32_t)(r.n_take < (uint32_t)topk ? r.n_take : (uint32_t)topk) | (over ? kParOver : 0);
}
/* The kernel around the body, whose blocks return where their chunk is empty: CH `r4dchain` is the
* chained form (r4d_chain.h). */
template <bool Signed, int LT, class CH>
__global__ __launch_bounds__(LT) void qsa_local_kernel(QSA_LOCAL_PARAMS) {
if (CH::on) r4d_chain_wait();
qsa_local_body<Signed, LT>(score, bt, nc, pos, cu, ck, ci, cc, nb, topk, ratio, nseq, s_ld,
t_ld, chunk);
if (CH::on) r4d_chain_done();
}
#undef QSA_LOCAL_PARAMS
/* ---- pass two: merge the chunk lists and emit the page-id table. */
template <bool Signed>
template <bool Signed, class CH>
__global__ __launch_bounds__(kMergeThreads) void qsa_merge_kernel(
const uint32_t* __restrict__ ck, const int32_t* __restrict__ ci,
const int32_t* __restrict__ cc, const int32_t* __restrict__ bt,
@@ -1010,10 +1037,12 @@ __global__ __launch_bounds__(kMergeThreads) void qsa_merge_kernel(
const int32_t* __restrict__ cu,
int32_t* __restrict__ sel, int32_t* __restrict__ nsel, int32_t* __restrict__ seqused,
int nb, int topk, int ratio, int nseq, int t_ld, int o_ld, int nchunk) {
/* CH `r4dchain` is the chained form (r4d_chain.h): no block or thread returns before the end. */
if (CH::on) r4d_chain_wait();
constexpr int NT = kMergeThreads;
__shared__ uint32_t hist[kBins], suf[kBins], wsum[NT / kWave];
__shared__ uint32_t sh_T, sh_need, sh_hi, sh_ord, sh_tot, sh_over;
__shared__ uint32_t sh_T, sh_need, sh_tot, sh_over;
__shared__ int sh_seq, sh_off[kParWMax + 1];
R4D_DYN_LDS(uint32_t, sh_key);
@@ -1031,27 +1060,41 @@ __global__ __launch_bounds__(kMergeThreads) void qsa_merge_kernel(
int n = nc[seq] < nb ? nc[seq] : nb;
if (own < n) n = own;
/* Chunk offsets, serially on one thread (nchunk <= 16). */
if (t == 0) {
int s = 0;
uint32_t over = 0;
for (int c = 0; c < nchunk; ++c) {
const int32_t v = cc[(size_t)m * kParWMax + c];
over |= (v & kParOver) ? 1u : 0u;
sh_off[c] = s;
s += v & ~kParOver;
}
sh_off[nchunk] = s;
sh_tot = (uint32_t)s;
sh_over = over;
/* Chunk offsets: the first wave loads a chunk's count a lane and takes their prefix, one
* round trip for all of them (nchunk <= kParWMax lanes). */
{
const int32_t v = t < nchunk ? cc[(size_t)m * kParWMax + t] : 0;
const uint32_t cnt = (uint32_t)(v & ~kParOver);
const uint32_t inc = r4d_wave_prefix_u32(cnt, lane);
const unsigned long long ov = __ballot(t < nchunk && (v & kParOver) != 0);
if (t < nchunk) sh_off[t] = (int)(inc - cnt);
if (t == nchunk - 1) { sh_off[nchunk] = (int)inc; sh_tot = inc; }
if (t == 0) sh_over = ov != 0ull ? 1u : 0u;
}
__syncthreads();
const int tot = (int)sh_tot;
for (int c = 0; c < nchunk; ++c) {
const int base = sh_off[c], cnt = sh_off[c + 1] - base;
const uint32_t* src = ck + (size_t)(m * kParWMax + c) * topk;
for (int i = t; i < cnt; i += NT) sh_key[base + i] = src[i];
/* The candidates into LDS in list order. A thread's keys (every NT-th of the list) are all
* loaded before the first is stored: one round trip, where a pass per chunk made one for each
* of the nchunk lists. */
{
constexpr int kPre = kLdsCap / NT;
uint32_t kv[kPre];
#pragma unroll
for (int u = 0; u < kPre; ++u) {
const int i = t + u * NT;
kv[u] = 0u;
if (i < tot) {
int c = nchunk - 1;
while (c > 0 && sh_off[c] > i) --c;
kv[u] = ck[(size_t)(m * kParWMax + c) * topk + (i - sh_off[c])];
}
}
#pragma unroll
for (int u = 0; u < kPre; ++u) {
const int i = t + u * NT;
if (i < tot) sh_key[i] = kv[u];
}
}
__syncthreads();
@@ -1059,32 +1102,36 @@ __global__ __launch_bounds__(kMergeThreads) void qsa_merge_kernel(
* most topk blocks, or topk or fewer live. With no chunk over topk the candidates are every
* live key, so their count is the live count; a chunk over topk means more than topk live,
* and then exactly topk candidates are the top-k, whose ties go last. */
ParEmit e{ wsum, &sh_hi, &sh_ord, 0u, 0u, 0u, n <= topk || (!sh_over && tot <= topk) };
if (!e.all) {
const bool all = n <= topk || (!sh_over && tot <= topk);
uint32_t T = 0u, need = 0u;
if (!all) {
radix_thresh<NT>(sh_key, tot, (uint32_t)topk, false, hist, suf, wsum, &sh_T, &sh_need);
e.T = sh_T; e.need = sh_need;
T = sh_T; need = sh_need;
}
if (t == 0) { sh_hi = 0; sh_ord = 0; }
__syncthreads();
const int32_t* tb = bt + (size_t)seq * t_ld;
int32_t* ou = sel + (size_t)m * o_ld;
for (int i0 = 0; i0 < tot; i0 += NT) {
const int i = i0 + t;
const uint32_t k = i < tot ? sh_key[i] : 0u;
const ParTake r = par_take<true, false, NT>(e, k, lane, wave);
if (r.take) {
/* The candidate's chunk, from the offsets. */
int c = nchunk - 1;
while (c > 0 && sh_off[c] > i) --c;
/* Already a page (resolved by the local pass); tb is still needed for the partial
* page. */
const int32_t page = ci[(size_t)(m * kParWMax + c) * topk + (i - sh_off[c])];
/* The single-workgroup kernel's layout: above the threshold first, ties last. */
if (r.hi) { if (r.slot_hi < (uint32_t)topk) ou[r.slot_hi] = page; }
else { ou[(uint32_t)topk - e.need + r.rank_eq] = page; }
const int run = (tot + NT - 1) / NT;
const RunTake r = run_take<NT>(sh_key, tot, run, T, need, all, wsum, lane, wave);
for (int j = 0; j < run; ++j) {
if (!((r.take >> j) & 1u)) continue;
const int i = t * run + j;
/* The candidate's chunk, from the offsets. */
int c = nchunk - 1;
while (c > 0 && sh_off[c] > i) --c;
/* Already a page (resolved by the local pass); tb is still needed for the partial
* page. */
const int32_t page = ci[(size_t)(m * kParWMax + c) * topk + (i - sh_off[c])];
/* The single-workgroup kernel's layout: above the threshold first, ties last. */
const uint32_t below = (1u << j) - 1u;
if ((r.hi >> j) & 1u) {
const uint32_t slot = r.slot_hi + (uint32_t)__builtin_popcount(r.hi & below);
if (slot < (uint32_t)topk) ou[slot] = page;
} else {
ou[(uint32_t)topk - need + r.rank_eq + (uint32_t)__builtin_popcount(r.eq & below)] = page;
}
}
const uint32_t n_hi = r.n_hi;
/* The partial page, appended last, as in the single-workgroup kernel. */
if (t == 0) {
@@ -1092,7 +1139,7 @@ __global__ __launch_bounds__(kMergeThreads) void qsa_merge_kernel(
* table is full (ties fill it), and the merged count can fall short, which would let the
* padding loop overwrite ties with -1. The exception is the same as there: topk or
* fewer live blocks, all of them emitted. */
uint32_t out = e.all ? sh_hi : (uint32_t)topk;
uint32_t out = all ? n_hi : (uint32_t)topk;
const int32_t part = (n < nb && (p + 1) % ratio != 0) ? tb[n] : -1;
if (part >= 0) ou[out++] = part;
for (uint32_t i = out; i < (uint32_t)(topk + 1); ++i) ou[i] = -1;
@@ -1101,6 +1148,7 @@ __global__ __launch_bounds__(kMergeThreads) void qsa_merge_kernel(
: (out - 1) * (uint32_t)ratio + (uint32_t)(p % ratio) + 1u);
seqused[m] = su;
}
if (CH::on) r4d_chain_done();
}
} // namespace
@@ -1124,7 +1172,8 @@ template <bool Signed>
static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long cu, long sel,
long nsel, long seqused, int M, int nb, int topk, int ratio,
int nseq, int s_ld, int t_ld, int o_ld,
void* scratch, long long scratch_bytes, RadStream stream) {
void* scratch, long long scratch_bytes, RadStream stream,
bool chain) {
if (!score || !bt || !nc || !cu || !sel || !nsel || !seqused) return R4D_NO(RAD_E_INVAL);
if (M <= 0 || nb <= 0 || topk <= 0 || ratio <= 0 || nseq <= 0) return R4D_NO(RAD_E_SHAPE);
if (!s_ld) s_ld = nb;
@@ -1143,19 +1192,30 @@ static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long
uint32_t* ck = (uint32_t*)scratch;
int32_t* ci = (int32_t*)(ck + (size_t)kParM * kParWMax * topk);
int32_t* cc = ci + (size_t)kParM * kParWMax * topk;
const int rc = R4D_EMIT(stream, qsa_local_kernel<Signed>,
dim3((unsigned)nchunk, (unsigned)M), dim3(kLocalThreads),
(size_t)chunk * sizeof(uint32_t),
(const float*)score, (const int32_t*)bt, (const int32_t*)nc,
(const int32_t*)pos, (const int32_t*)cu, ck, ci, cc, nb, topk,
ratio, nseq, s_ld, t_ld, chunk);
/* Each form named at its own launch, as below. */
#define R4D_QLOC(LT_, CH_) \
R4D_EMIT(stream, (qsa_local_kernel<Signed, LT_, CH_>), \
dim3((unsigned)nchunk, (unsigned)M), dim3(LT_), \
(size_t)chunk * sizeof(uint32_t), \
(const float*)score, (const int32_t*)bt, (const int32_t*)nc, \
(const int32_t*)pos, (const int32_t*)cu, ck, ci, cc, nb, topk, \
ratio, nseq, s_ld, t_ld, chunk)
#define R4D_QMRG(CH_) \
R4D_EMIT(stream, (qsa_merge_kernel<Signed, CH_>), dim3((unsigned)M), \
dim3(kMergeThreads), (size_t)nchunk * topk * sizeof(uint32_t), \
(const uint32_t*)ck, (const int32_t*)ci, (const int32_t*)cc, \
(const int32_t*)bt, (const int32_t*)nc, (const int32_t*)pos, \
(const int32_t*)cu, (int32_t*)sel, (int32_t*)nsel, (int32_t*)seqused, \
nb, topk, ratio, nseq, t_ld, o_ld, nchunk)
const bool wide = (long)M * nchunk <= kLocalWideGrid;
const int rc = wide ? (chain ? R4D_QLOC(kLocalWideThreads, r4dchain)
: R4D_QLOC(kLocalWideThreads, R4dUnchained))
: (chain ? R4D_QLOC(kLocalThreads, r4dchain)
: R4D_QLOC(kLocalThreads, R4dUnchained));
if (rc != RAD_OK) return rc;
return R4D_EMIT(stream, qsa_merge_kernel<Signed>, dim3((unsigned)M), dim3(kMergeThreads),
(size_t)nchunk * topk * sizeof(uint32_t), (const uint32_t*)ck,
(const int32_t*)ci, (const int32_t*)cc, (const int32_t*)bt,
(const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu,
(int32_t*)sel, (int32_t*)nsel, (int32_t*)seqused,
nb, topk, ratio, nseq, t_ld, o_ld, nchunk);
return chain ? R4D_QMRG(r4dchain) : R4D_QMRG(R4dUnchained);
#undef R4D_QLOC
#undef R4D_QMRG
}
/* A wide launch (prefill chunk, key cache off) takes the wide kernel. */
@@ -1171,19 +1231,15 @@ static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long
/* Never more than the table width. */
int cap = (M <= kCacheMaxM) ? lds_cap_of() : 0;
if (cap > nb) cap = nb;
/* Two launch sites rather than a choice of kernel inside one: each names its kernel alone, and
* the emulator test reads the plain one's name (tests/r4d_emu/test_qsa.cpp). */
if (g_r4d_chain_arg)
return R4D_EMIT(stream, r4dchain_qsa_select<Signed>, dim3((unsigned)M), dim3(kThreads),
(size_t)cap * sizeof(uint32_t), (const float*)score, (const int32_t*)bt,
(const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu,
(int32_t*)sel, (int32_t*)nsel,
(int32_t*)seqused, nb, topk, ratio, nseq, s_ld, t_ld, o_ld, cap);
return R4D_EMIT(stream, qsa_select_kernel<Signed>, dim3((unsigned)M), dim3(kThreads),
(size_t)cap * sizeof(uint32_t), (const float*)score, (const int32_t*)bt,
(const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu,
(int32_t*)sel, (int32_t*)nsel,
(int32_t*)seqused, nb, topk, ratio, nseq, s_ld, t_ld, o_ld, cap);
/* Each form named at its own launch: a test reads the kernel a launch site names. */
#define R4D_QSEL(CH_) \
R4D_EMIT(stream, (qsa_select_kernel<Signed, CH_>), dim3((unsigned)M), dim3(kThreads), \
(size_t)cap * sizeof(uint32_t), (const float*)score, (const int32_t*)bt, \
(const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu, (int32_t*)sel, \
(int32_t*)nsel, (int32_t*)seqused, nb, topk, ratio, nseq, s_ld, t_ld, o_ld, cap)
const int rc = chain ? R4D_QSEL(r4dchain) : R4D_QSEL(R4dUnchained);
#undef R4D_QSEL
return rc;
}
extern "C" void r4d_qsa_select_pin_form(int form) { g_qsa_select_form = form; }
@@ -1199,7 +1255,6 @@ enum { QL_SCORE = 0, QL_BT = 1, QL_NC = 2, QL_POS = 3, QL_CU = 4, QL_SEL = 5, QL
QL_SEQ = 7 };
extern "C" int r4d_rad_qsa_select(const RadArgs* a, RadStream stream) {
const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0);
const RadTensor* sc = r4d_opt(a, QL_SCORE);
const RadTensor* bt = r4d_opt(a, QL_BT);
const RadTensor* nc = r4d_opt(a, QL_NC);
@@ -1235,6 +1290,6 @@ extern "C" int r4d_rad_qsa_select(const RadArgs* a, RadStream stream) {
r4d_addr(cu), r4d_addr(se), r4d_addr(ns), r4d_addr(su),
(int)M, (int)nb, (int)topk, (int)ratio, (int)nseq,
(int)sp, (int)tp, (int)op, a->scratch, a->scratch_bytes,
stream);
stream, r4d_geti_or(a, "chain", 0) != 0);
}
+29 -29
View File
@@ -21,8 +21,8 @@
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_emit.h"
#include <hip/hip_runtime.h>
#include <cstdint>
@@ -31,11 +31,12 @@ namespace {
constexpr int kThreads = 256;
__device__ __forceinline__ void qsa_tail_store_kernel_body(
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 slots, int k_ld, int s_slot, int s_row, int sidx_ld) {
#define QSA_TAIL_STORE_PARAMS \
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 slots, int k_ld, \
int s_slot, int s_row, int sidx_ld
__device__ __forceinline__ void qsa_tail_store_body(QSA_TAIL_STORE_PARAMS) {
const int t = (int)blockIdx.x;
if (t >= T) return;
@@ -60,23 +61,17 @@ __device__ __forceinline__ void qsa_tail_store_kernel_body(
for (int d = (int)threadIdx.x; d < n; d += kThreads) state[dst + d] = k[src + d];
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
__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 slots, int k_ld, int s_slot, int s_row, int sidx_ld) {
qsa_tail_store_kernel_body(k, pos, cu, sidx, state, T, n, ring, seqs, slots, k_ld, s_slot, s_row, sidx_ld);
}
__global__ __launch_bounds__(kThreads) void r4dchain_qsa_tail_store(
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 slots, int k_ld, int s_slot, int s_row, int sidx_ld) {
r4d_chain_wait();
qsa_tail_store_kernel_body(k, pos, cu, sidx, state, T, n, ring, seqs, slots, k_ld, s_slot, s_row, sidx_ld);
r4d_chain_done();
/* The kernel around the body, whose blocks and threads return where their work ends: CH `r4dchain`
* is the chained form (r4d_chain.h). */
template <class CH>
__global__ __launch_bounds__(kThreads)
void qsa_tail_store_kernel(QSA_TAIL_STORE_PARAMS) {
if (CH::on) r4d_chain_wait();
qsa_tail_store_body(k, pos, cu, sidx, state, T, n, ring, seqs, slots, k_ld, s_slot, s_row,
sidx_ld);
if (CH::on) r4d_chain_done();
}
#undef QSA_TAIL_STORE_PARAMS
} // namespace
@@ -88,16 +83,21 @@ __global__ __launch_bounds__(kThreads) void r4dchain_qsa_tail_store(
// keep their contents
static int r4d_qsa_tail_store_bf16_emit(long k, long pos, long cu, long sidx, long state, int T,
int n, int ring, int seqs, int slots, int k_ld, int s_slot,
int s_row, int sidx_ld, RadStream stream) {
int s_row, int sidx_ld, RadStream stream,
bool chain) {
if (!k || !pos || !cu || !sidx || !state) return R4D_NO(RAD_E_INVAL);
if (T <= 0 || n <= 0 || ring <= 0 || seqs <= 0 || slots <= 0) return R4D_NO(RAD_E_SHAPE);
if (!k_ld) k_ld = n;
if (!s_row) s_row = n;
if (!sidx_ld) sidx_ld = 1;
return R4D_EMIT(stream, g_r4d_chain_arg ? &r4dchain_qsa_tail_store : &qsa_tail_store_kernel, dim3((unsigned)T), dim3(kThreads), 0,
(const uint16_t*)k, (const int32_t*)pos, (const int32_t*)cu,
(const int32_t*)sidx, (uint16_t*)state, T, n, ring, seqs, slots, k_ld, s_slot,
s_row, sidx_ld);
/* Each form named at its own launch: a test reads the kernel a launch site names. */
#define R4D_QTAIL(CH_) \
R4D_EMIT(stream, qsa_tail_store_kernel<CH_>, dim3((unsigned)T), dim3(kThreads), 0, \
(const uint16_t*)k, (const int32_t*)pos, (const int32_t*)cu, (const int32_t*)sidx, \
(uint16_t*)state, T, n, ring, seqs, slots, k_ld, s_slot, s_row, sidx_ld)
const int rc = chain ? R4D_QTAIL(r4dchain) : R4D_QTAIL(R4dUnchained);
#undef R4D_QTAIL
return rc;
}
// ============================================================== the plugin ABI entry point
@@ -132,10 +132,10 @@ extern "C" int r4d_rad_qsa_tail_store(const RadArgs* a, RadStream stream) {
const long long kp = r4d_row_pitch(k);
if (kp < 0) return R4D_NO(RAD_E_STRIDE);
if (k->dtype != RAD_BF16 || st->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0);
return r4d_qsa_tail_store_bf16_emit(r4d_addr(k), r4d_addr(po), r4d_addr(cu), r4d_addr(sx),
r4d_addr(st), (int)T, (int)n, (int)ring, (int)seqs,
(int)st->shape[0], (int)kp, (int)st->stride[0],
(int)st->stride[2], (int)sxp, stream);
(int)st->stride[2], (int)sxp, stream,
r4d_geti_or(a, "chain", 0) != 0);
}
+34 -43
View File
@@ -20,8 +20,8 @@
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_emit.h"
#include <hip/hip_runtime.h>
#include <cstdint>
@@ -33,15 +33,15 @@ constexpr int kThreads = 128;
* row constraint on the declared seqs (rad-convert declares 256, which must still resolve). */
constexpr int kMaxSeq = 256;
__device__ __forceinline__ void qsa_work_kernel_body(
const uint16_t* __restrict__ k, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu, const uint16_t* __restrict__ state,
const int32_t* __restrict__ sidx, const int32_t* __restrict__ bt,
uint16_t* __restrict__ stage, int32_t* __restrict__ page, int32_t* __restrict__ bpos,
int32_t* __restrict__ nc,
int n, int ratio, int ring, int seqs, int max_work, int k_ld, int s_slot, int s_row,
int sidx_ld, int bt_ld, int g_ld, const int32_t* __restrict__ rope, int rplane,
int bstep) {
#define QSA_WORK_PARAMS \
const uint16_t* __restrict__ k, const int32_t* __restrict__ pos, \
const int32_t* __restrict__ cu, const uint16_t* __restrict__ state, \
const int32_t* __restrict__ sidx, const int32_t* __restrict__ bt, \
uint16_t* __restrict__ stage, int32_t* __restrict__ page, int32_t* __restrict__ bpos, \
int32_t* __restrict__ nc, int n, int ratio, int ring, int seqs, int max_work, int k_ld, \
int s_slot, int s_row, int sidx_ld, int bt_ld, int g_ld, \
const int32_t* __restrict__ rope, int rplane, int bstep
__device__ __forceinline__ void qsa_work_body(QSA_WORK_PARAMS) {
const int w = (int)blockIdx.x;
/* Complete blocks per sequence (needed by the scorer and the selection), written by the first
@@ -114,31 +114,17 @@ __device__ __forceinline__ void qsa_work_kernel_body(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
__global__ __launch_bounds__(kThreads) void qsa_work_kernel(
const uint16_t* __restrict__ k, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu, const uint16_t* __restrict__ state,
const int32_t* __restrict__ sidx, const int32_t* __restrict__ bt,
uint16_t* __restrict__ stage, int32_t* __restrict__ page, int32_t* __restrict__ bpos,
int32_t* __restrict__ nc,
int n, int ratio, int ring, int seqs, int max_work, int k_ld, int s_slot, int s_row,
int sidx_ld, int bt_ld, int g_ld, const int32_t* __restrict__ rope, int rplane,
int bstep) {
qsa_work_kernel_body(k, pos, cu, state, sidx, bt, stage, page, bpos, nc, n, ratio, ring, seqs, max_work, k_ld, s_slot, s_row, sidx_ld, bt_ld, g_ld, rope, rplane, bstep);
}
__global__ __launch_bounds__(kThreads) void r4dchain_qsa_work(
const uint16_t* __restrict__ k, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu, const uint16_t* __restrict__ state,
const int32_t* __restrict__ sidx, const int32_t* __restrict__ bt,
uint16_t* __restrict__ stage, int32_t* __restrict__ page, int32_t* __restrict__ bpos,
int32_t* __restrict__ nc,
int n, int ratio, int ring, int seqs, int max_work, int k_ld, int s_slot, int s_row,
int sidx_ld, int bt_ld, int g_ld, const int32_t* __restrict__ rope, int rplane,
int bstep) {
r4d_chain_wait();
qsa_work_kernel_body(k, pos, cu, state, sidx, bt, stage, page, bpos, nc, n, ratio, ring, seqs, max_work, k_ld, s_slot, s_row, sidx_ld, bt_ld, g_ld, rope, rplane, bstep);
r4d_chain_done();
/* The kernel around the body, whose blocks and threads return where their work ends: CH `r4dchain`
* is the chained form (r4d_chain.h). */
template <class CH>
__global__ __launch_bounds__(kThreads)
void qsa_work_kernel(QSA_WORK_PARAMS) {
if (CH::on) r4d_chain_wait();
qsa_work_body(k, pos, cu, state, sidx, bt, stage, page, bpos, nc, n, ratio, ring, seqs,
max_work, k_ld, s_slot, s_row, sidx_ld, bt_ld, g_ld, rope, rplane, bstep);
if (CH::on) r4d_chain_done();
}
#undef QSA_WORK_PARAMS
} // namespace
@@ -158,7 +144,7 @@ static int r4d_qsa_work_bf16_emit(long k, long pos, long cu, long state, long si
long stage, long page, long bpos, long nc, int n, int ratio,
int ring, int seqs, int max_work, int k_ld, int s_slot,
int s_row, int sidx_ld, int bt_ld, int g_ld, long rope,
int rplane, int bstep, RadStream stream) {
int rplane, int bstep, RadStream stream, bool chain) {
if (!k || !pos || !cu || !state || !sidx || !bt || !stage || !page || !bpos || !nc)
return R4D_NO(RAD_E_INVAL);
if (n <= 0 || ratio <= 0 || ring < ratio || seqs <= 0 || max_work <= 0 || seqs > kMaxSeq)
@@ -167,12 +153,17 @@ static int r4d_qsa_work_bf16_emit(long k, long pos, long cu, long state, long si
if (!s_row) s_row = n;
if (!g_ld) g_ld = n;
if (!sidx_ld) sidx_ld = 1;
return R4D_EMIT(stream, g_r4d_chain_arg ? &r4dchain_qsa_work : &qsa_work_kernel, dim3((unsigned)max_work), dim3(kThreads), 0,
(const uint16_t*)k, (const int32_t*)pos, (const int32_t*)cu,
(const uint16_t*)state, (const int32_t*)sidx, (const int32_t*)bt,
(uint16_t*)stage, (int32_t*)page, (int32_t*)bpos, (int32_t*)nc, n, ratio,
ring, seqs, max_work, k_ld, s_slot, s_row, sidx_ld, bt_ld, g_ld,
(const int32_t*)rope, rplane, bstep);
/* Each form named at its own launch: a test reads the kernel a launch site names. */
#define R4D_QWORK(CH_) \
R4D_EMIT(stream, qsa_work_kernel<CH_>, dim3((unsigned)max_work), dim3(kThreads), 0, \
(const uint16_t*)k, (const int32_t*)pos, (const int32_t*)cu, \
(const uint16_t*)state, (const int32_t*)sidx, (const int32_t*)bt, \
(uint16_t*)stage, (int32_t*)page, (int32_t*)bpos, (int32_t*)nc, n, ratio, ring, \
seqs, max_work, k_ld, s_slot, s_row, sidx_ld, bt_ld, g_ld, (const int32_t*)rope, \
rplane, bstep)
const int rc = chain ? R4D_QWORK(r4dchain) : R4D_QWORK(R4dUnchained);
#undef R4D_QWORK
return rc;
}
// ============================================================== the plugin ABI entry point
@@ -238,12 +229,12 @@ extern "C" int r4d_rad_qsa_work(const RadArgs* a, RadStream stream) {
const long long bp2 = r4d_row_pitch(bt), sp = r4d_row_pitch(st);
if (kp < 0 || bp2 < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE);
if (k->dtype != RAD_BF16 || tl->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0);
return r4d_qsa_work_bf16_emit(r4d_addr(k), r4d_addr(po), r4d_addr(cu), r4d_addr(tl),
r4d_addr(sx), r4d_addr(bt), r4d_addr(st), r4d_addr(pg),
r4d_addr(bp), r4d_addr(nc), (int)n, (int)ratio, (int)ring,
(int)seqs, (int)mw, (int)kp, (int)tl->stride[0],
(int)tl->stride[2], (int)sxp, (int)bp2, (int)sp,
r4d_addr(rp), rp ? (int)rp->shape[1] : 0, (int)bstep, stream);
r4d_addr(rp), rp ? (int)rp->shape[1] : 0, (int)bstep, stream,
r4d_geti_or(a, "chain", 0) != 0);
}
+62 -57
View File
@@ -47,10 +47,15 @@ constexpr uint32_t kGroup = 128;
//
// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); no block returns
// early. quant_act_fp8_kernel and r4dchain_quant_act_fp8 below are the plain and chained forms.
template <bool ROT, bool I8 = false, bool CHAIN = false>
//
// SUB is the 128-column blocks one scale covers: 1, or 2 for IQ8R's 256-wide group (int8 only),
// where a wave owns both blocks of a group, rotates each on its own (the rotation stays 128 wide)
// and takes the amax over the pair. `nkb` counts scale groups.
template <bool ROT, bool I8 = false, bool CHAIN = false, uint32_t SUB = 1>
__device__ __forceinline__ void quant_act_fp8_body(
const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s,
uint32_t K, uint32_t nkb, uint32_t x_ld, uint32_t q_ld, uint32_t s_ld) {
static_assert(SUB == 1 || (SUB == 2 && I8), "a 256 group is the int8 quantiser's");
if (CHAIN) r4d_chain_wait();
const uint32_t row = blockIdx.x;
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
@@ -58,57 +63,64 @@ __device__ __forceinline__ void quant_act_fp8_body(
const size_t qrow = (size_t)row * q_ld;
for (uint32_t kb = wave; kb < nkb; kb += kWaves) {
const uint32_t c0 = kb * kGroup + lane * 4u;
float v[4];
float v[SUB][4];
float m = 0.0f;
#pragma unroll
for (int j = 0; j < 4; ++j) {
const uint32_t c = c0 + (uint32_t)j;
v[j] = c < K ? __uint_as_float((uint32_t)x[xrow + c] << 16) : 0.0f;
}
// The rotated launcher requires K % 128 == 0: a partial block would rotate real values
// with padding zeros, and the weight has no matching block.
if constexpr (ROT) r4d_fwht_wave<(int)kGroup>(v, (int)lane);
for (uint32_t h = 0; h < SUB; ++h) {
const uint32_t c0 = (kb * SUB + h) * kGroup + lane * 4u;
#pragma unroll
for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j]));
for (int j = 0; j < 4; ++j) {
const uint32_t c = c0 + (uint32_t)j;
v[h][j] = c < K ? __uint_as_float((uint32_t)x[xrow + c] << 16) : 0.0f;
}
// The rotated launcher requires K % 128 == 0: a partial block would rotate real values
// with padding zeros, and the weight has no matching block.
if constexpr (ROT) r4d_fwht_wave<(int)kGroup>(v[h], (int)lane);
#pragma unroll
for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[h][j]));
}
m = r4d_wave_max(m);
constexpr float kTop = I8 ? 127.0f : 448.0f;
const float sc = m > 0.0f ? m * (1.0f / kTop) : 1.0f;
if (lane == 0) s[(size_t)row * s_ld + kb] = sc;
const float inv = 1.0f / sc;
int pk = 0;
if constexpr (I8) {
uint32_t b = 0;
#pragma unroll
for (int j = 0; j < 4; ++j) {
const int c = (int)rintf(fminf(fmaxf(v[j] * inv, -127.0f), 127.0f));
b |= ((uint32_t)c & 0xFFu) << (8 * j);
for (uint32_t h = 0; h < SUB; ++h) {
const uint32_t c0 = (kb * SUB + h) * kGroup + lane * 4u;
int pk = 0;
if constexpr (I8) {
uint32_t b = 0;
#pragma unroll
for (int j = 0; j < 4; ++j) {
const int c = (int)rintf(fminf(fmaxf(v[h][j] * inv, -127.0f), 127.0f));
b |= ((uint32_t)c & 0xFFu) << (8 * j);
}
pk = (int)b;
} else {
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[h][0] * inv, -448.0f), 448.0f),
fminf(fmaxf(v[h][1] * inv, -448.0f), 448.0f),
pk, false);
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[h][2] * inv, -448.0f), 448.0f),
fminf(fmaxf(v[h][3] * inv, -448.0f), 448.0f),
pk, true);
}
pk = (int)b;
} else {
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[0] * inv, -448.0f), 448.0f),
fminf(fmaxf(v[1] * inv, -448.0f), 448.0f), pk,
false);
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[2] * inv, -448.0f), 448.0f),
fminf(fmaxf(v[3] * inv, -448.0f), 448.0f), pk,
true);
// A ragged last group is written zero-padded; the GEMM's bounds guard keeps the
// padding out of the accumulators. The caller must own K rounded up to 4 bytes of `q`.
if (c0 < K) *(uint32_t*)(q + qrow + c0) = (uint32_t)pk;
}
// A ragged last group is written zero-padded; the GEMM's bounds guard keeps the padding out
// of the accumulators. The caller must own K rounded up to 4 bytes of `q`.
if (c0 < K) *(uint32_t*)(q + qrow + c0) = (uint32_t)pk;
}
if (CHAIN) r4d_chain_done();
}
#define R4D_QAF_PARAMS const uint16_t* __restrict__ x, uint8_t* __restrict__ q, \
float* __restrict__ s, uint32_t K, uint32_t nkb, uint32_t x_ld, uint32_t q_ld, uint32_t s_ld
template <bool ROT, bool I8 = false>
template <bool ROT, bool I8 = false, uint32_t SUB = 1>
__global__ __launch_bounds__(kThreads) void quant_act_fp8_kernel(R4D_QAF_PARAMS) {
quant_act_fp8_body<ROT, I8, false>(x, q, s, K, nkb, x_ld, q_ld, s_ld);
quant_act_fp8_body<ROT, I8, false, SUB>(x, q, s, K, nkb, x_ld, q_ld, s_ld);
}
template <bool ROT, bool I8 = false>
template <bool ROT, bool I8 = false, uint32_t SUB = 1>
__global__ __launch_bounds__(kThreads) void r4dchain_quant_act_fp8(R4D_QAF_PARAMS) {
quant_act_fp8_body<ROT, I8, true>(x, q, s, K, nkb, x_ld, q_ld, s_ld);
quant_act_fp8_body<ROT, I8, true, SUB>(x, q, s, K, nkb, x_ld, q_ld, s_ld);
}
#undef R4D_QAF_PARAMS
@@ -121,29 +133,33 @@ extern "C" int r4d_quant_act_fp8_group(void) { return (int)kGroup; }
// s [M][ceil(K/128)] f32, `s_ld` elements a row (0 = ceil(K/128))
//
// `rot` runs the 128-wide Hadamard first and additionally requires K % 128 == 0 (see the kernel).
// `wide` (int8 only): one scale per 256 columns (IQ8R), K a multiple of 256, `s` [M][K/256].
static int quant_act_fp8_launch(long a, long q, long s, int M, int K,
int x_ld, int q_ld, int s_ld, RadStream stream, bool rot,
bool i8 = false, bool chain = false) {
bool i8 = false, bool chain = false, bool wide = false) {
int emit_rc = RAD_OK;
if (!a || !q || !s) return -1;
if (M <= 0 || K <= 0) return -2;
if (K % 4) return -3; // a lane owns four columns; see the kernel
if (rot && (K % (int)kGroup)) return -5;
if (wide && (!i8 || K % (2 * (int)kGroup))) return -5;
if (!x_ld) x_ld = K;
if (!q_ld) q_ld = K;
const int nkb = (K + (int)kGroup - 1) / (int)kGroup;
const int grp = wide ? 2 * (int)kGroup : (int)kGroup;
const int nkb = (K + grp - 1) / grp;
if (!s_ld) s_ld = nkb;
/* The chained form at decode heights, where the row resolved with `chain`. */
const bool ch = chain && M <= 64;
#define R4D_QA(ROT_, I8_) \
(ch ? R4D_EMIT(stream, (r4dchain_quant_act_fp8<ROT_, I8_>), dim3((uint32_t)M), \
#define R4D_QA(ROT_, I8_, SUB_) \
(ch ? R4D_EMIT(stream, (r4dchain_quant_act_fp8<ROT_, I8_, SUB_>), dim3((uint32_t)M), \
dim3(kThreads), 0, (const uint16_t*)a, (uint8_t*)q, (float*)s, (uint32_t)K, \
(uint32_t)nkb, (uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld) \
: R4D_EMIT(stream, (quant_act_fp8_kernel<ROT_, I8_>), dim3((uint32_t)M), \
: R4D_EMIT(stream, (quant_act_fp8_kernel<ROT_, I8_, SUB_>), dim3((uint32_t)M), \
dim3(kThreads), 0, (const uint16_t*)a, (uint8_t*)q, (float*)s, (uint32_t)K, \
(uint32_t)nkb, (uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld))
if (i8) emit_rc = rot ? R4D_QA(true, true) : R4D_QA(false, true);
else emit_rc = rot ? R4D_QA(true, false) : R4D_QA(false, false);
if (wide) emit_rc = rot ? R4D_QA(true, true, 2u) : R4D_QA(false, true, 2u);
else if (i8) emit_rc = rot ? R4D_QA(true, true, 1u) : R4D_QA(false, true, 1u);
else emit_rc = rot ? R4D_QA(true, false, 1u) : R4D_QA(false, false, 1u);
#undef R4D_QA
if (emit_rc != RAD_OK) return -4;
return (hipGetLastError() != hipSuccess) ? -4 : 0;
@@ -155,12 +171,6 @@ extern "C" int r4d_quant_act_fp8(long a, long q, long s, int M, int K,
(RadStream)(uintptr_t)stream, false);
}
extern "C" int r4d_had_quant_act_fp8(long a, long q, long s, int M, int K,
int x_ld, int q_ld, int s_ld, long stream) {
return quant_act_fp8_launch(a, q, s, M, K, x_ld, q_ld, s_ld,
(RadStream)(uintptr_t)stream, true);
}
// ============================================================== the plugin ABI entry points
//
// The shared operand reader is r4d_fp8_args.h; see libr4d/r4d_args.h.
@@ -177,17 +187,20 @@ static int rad_quant_act_fp8(const RadArgs* a, RadStream stream, bool rot, bool
* `q` and `sc` are written for the GEMM and stay rank 2. */
if (x->rank < 2 || q->rank != 2 || sc->rank != 2) return R4D_NO(RAD_E_SHAPE);
const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1);
const long long grp = r4d_quant_act_fp8_group();
/* The group is fixed by the weight's scale grid: 128, or 256 for the int8 quantisers (IQ8R).
* Any other declared group is refused. */
const long long g0 = r4d_quant_act_fp8_group();
const long long grp = r4d_geti_or(a, "group", g0);
const bool wide = i8 && grp == R4D_I8_GROUP_WIDE;
if (grp != g0 && !wide) return R4D_NO(RAD_E_SHAPE);
const long long nkb = (K + grp - 1) / grp;
/* The group is fixed by the checkpoint's scale grid; a different declared group is refused. */
if (r4d_geti_or(a, "group", grp) != grp) return R4D_NO(RAD_E_SHAPE);
if (q->shape[0] != M || q->shape[1] != K) return R4D_NO(RAD_E_SHAPE);
if (sc->shape[0] != M || sc->shape[1] != nkb) return R4D_NO(RAD_E_SHAPE);
const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc);
if (xp < 0 || qp < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE);
const int e = quant_act_fp8_launch(r4d_addr(x), r4d_addr(q), r4d_addr(sc), (int)M, (int)K,
(int)xp, (int)qp, (int)sp, stream, rot, i8,
r4d_geti_or(a, "chain", 0) != 0);
r4d_geti_or(a, "chain", 0) != 0, wide);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
@@ -195,14 +208,6 @@ extern "C" int r4d_rad_quant_act_fp8(const RadArgs* a, RadStream stream) {
return rad_quant_act_fp8(a, stream, false);
}
/* The rotated form is a separate op, not a parameter: it writes different numbers, so a swapped
* graph would still run as a different model. The op name pairs with the weight's layout tag in
* arch/common/rad_block_moe_fp8.h. It pairs only with the `w4a8h` expert plane; any consumer not
* rotated at convert reads it as noise. */
extern "C" int r4d_rad_had_quant_act_fp8(const RadArgs* a, RadStream stream) {
return rad_quant_act_fp8(a, stream, true);
}
/* The int8 pair, for the int8 trunk GEMMs (gemm_i8a8_*). Separate ops for the same reason as the
* rotated form: different numbers in a buffer of the same shape. */
extern "C" int r4d_rad_quant_act_i8g(const RadArgs* a, RadStream stream) {
+20 -4
View File
@@ -78,10 +78,11 @@ __global__ __launch_bounds__(THR) void r4dchain_quant_act_i8(
// membership is unchanged.
#define R4D_QAI8_MAXG 256
#define R4D_QUANT_ACT_I8_ASUM_PARAMS \
const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, \
float* __restrict__ S, float* __restrict__ Asum, int K, int group, int Mpad
template <int THR>
__global__ __launch_bounds__(THR) void r4d_quant_act_i8_asum_kernel(
const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S,
float* __restrict__ Asum, int K, int group, int Mpad) {
__device__ __forceinline__ void r4d_quant_act_i8_asum_body(R4D_QUANT_ACT_I8_ASUM_PARAMS) {
const int row = blockIdx.x;
const __hip_bfloat16* a = A + (size_t)row * K;
signed char* q = Q + (size_t)row * K;
@@ -119,6 +120,17 @@ __global__ __launch_bounds__(THR) void r4d_quant_act_i8_asum_kernel(
Asum[(size_t)g * Mpad + row] = (float)gs[g];
}
// The kernel around the body: CH `r4dchain` is the chained form (r4d_chain.h), taken at decode
// heights.
template <int THR, class CH>
__global__ __launch_bounds__(THR)
void r4d_quant_act_i8_asum_kernel(R4D_QUANT_ACT_I8_ASUM_PARAMS) {
if (CH::on) r4d_chain_wait();
r4d_quant_act_i8_asum_body<THR>(A, Q, S, Asum, K, group, Mpad);
if (CH::on) r4d_chain_done();
}
#undef R4D_QUANT_ACT_I8_ASUM_PARAMS
// The plugin ABI entry point (RadLaunchFn); a refused shape is a status code, not a throw. See
// libr4d/r4d_args.h.
//
@@ -173,9 +185,12 @@ extern "C" int r4d_rad_quant_act_i8(const RadArgs* args, RadStream stream) {
const long long mpad = ((M + 15) / 16) * 16;
if (r4d_numel(as) < (K / group) * mpad) return R4D_NO(RAD_E_SCRATCH);
#define R4D_QAI8A_LAUNCH(T) emit_rc = R4D_EMIT(stream, (r4d_quant_act_i8_asum_kernel<T>), \
const bool chain = r4d_geti_or(args, "chain", 0) != 0 && M <= 64;
#define R4D_QAI8A_CH(T, CH_) R4D_EMIT(stream, (r4d_quant_act_i8_asum_kernel<T, CH_>), \
dim3((int)M), dim3(T), 0, (const __hip_bfloat16*)r4d_p(x), (signed char*)r4d_wp(q), \
(float*)r4d_wp(sc), (float*)r4d_wp(as), (int)K, (int)group, (int)mpad)
#define R4D_QAI8A_LAUNCH(T) emit_rc = chain ? R4D_QAI8A_CH(T, r4dchain) \
: R4D_QAI8A_CH(T, R4dUnchained)
switch (thr) {
case 128: R4D_QAI8A_LAUNCH(128); break;
case 256: R4D_QAI8A_LAUNCH(256); break;
@@ -184,5 +199,6 @@ extern "C" int r4d_rad_quant_act_i8(const RadArgs* args, RadStream stream) {
default: return R4D_NO(RAD_E_INVAL);
}
#undef R4D_QAI8A_LAUNCH
#undef R4D_QAI8A_CH
return emit_rc;
}
+14 -8
View File
@@ -346,7 +346,9 @@ __device__ __forceinline__ unsigned int arq8_load_acq(const unsigned int* p) {
return __hip_atomic_load(p, __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_SYSTEM);
}
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, bool GRP = false>
// CH `r4dchain`: the chained form (r4d_chain.h); no block returns early.
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, bool GRP = false,
class CH = R4dUnchained>
__global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32,
@@ -354,6 +356,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags,
unsigned int* seq_ctrs, int M, uint32_t n, float eps, float wadd, uint32_t r_ld, uint32_t y_ld,
int slot_stride16, int drain, int acq, unsigned int nbw, long stage) {
if (CH::on) r4d_chain_wait();
extern __shared__ uint16_t ybuf[];
__shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave];
__shared__ unsigned int s_seq, s_slot;
@@ -420,6 +423,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
wadd, s1, ybuf, l2, lm);
__syncthreads(); /* the planes and ybuf are re-used by the next row this block owns */
}
if (CH::on) r4d_chain_done();
}
// ---------------------------------------------------------------------------------------------
@@ -1009,13 +1013,14 @@ extern "C" int r4d_rad_rmsnorm_quant_i8g(const RadArgs* a, RadStream stream) {
// double-buffered scratch, the per-block flags and the device-resident sequence counters -- and the
// rest is the junction's. `x` is the message and takes no pitch; `nblocks` is clamped to M (a block
// owns whole rows). `grp` takes quant_act_i8g's grid (ar_rmsnorm_quant_i8g): `s` is [M][n / 128]
// and n a multiple of 128. Returns 0, or a negative code for a shape it does not serve.
// and n a multiple of 128. `chain` takes the chained form (r4d_chain.h), which the launch has at
// the decode width of 1024 threads. Returns 0, or a negative code for a shape it does not serve.
extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags,
long my_flags, long seq_ctrs, long slot_stride16,
long x, long res, long w, long wp, long sc, int sc_f32,
long y, long q, long s, int M, int n, float eps, float wadd,
int w_f32, int r_ld, int y_ld, long stream, int nblocks,
int drain, int acq, int grp, long stage) {
int drain, int acq, int grp, long stage, int chain) {
if (!x || !w || !q || !s) return -1;
if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1;
if (M <= 0 || n <= 0) return -2;
@@ -1030,8 +1035,8 @@ extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long
if (nb > nbw) nb = nbw;
const int thr = r4d_act_threads(M, n);
const size_t lds = (size_t)n * sizeof(uint16_t);
#define R4D_ARQ8_T(WF, RS, PO, SC, T, G) \
hipLaunchKernelGGL((ar_rmsnorm_quant_i8_kernel<WF, RS, PO, SC, T, G>), dim3((uint32_t)nb), \
#define R4D_ARQ8_T(WF, RS, PO, SC, T, G, CH) \
hipLaunchKernelGGL((ar_rmsnorm_quant_i8_kernel<WF, RS, PO, SC, T, G, CH>), dim3((uint32_t)nb), \
dim3(T), lds, (hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, \
(const void*)w, (const void*)wp, (const void*)sc, (uint32_t)sc_f32, \
(signed char*)q, (float*)s, (uint16_t*)y, (int4*)peer_scratch, \
@@ -1040,9 +1045,10 @@ extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long
wadd, (uint32_t)r_ld, (uint32_t)y_ld, (int)slot_stride16, drain, acq, \
(unsigned)nbw, stage)
#define R4D_ARQ8(WF, RS, PO, SC, G) \
do { if (thr == 1024) R4D_ARQ8_T(WF, RS, PO, SC, 1024, G); \
else if (thr == 512) R4D_ARQ8_T(WF, RS, PO, SC, 512, G); \
else R4D_ARQ8_T(WF, RS, PO, SC, 256, G); } while (0)
do { if (thr == 1024 && chain) R4D_ARQ8_T(WF, RS, PO, SC, 1024, G, r4dchain); \
else if (thr == 1024) R4D_ARQ8_T(WF, RS, PO, SC, 1024, G, R4dUnchained); \
else if (thr == 512) R4D_ARQ8_T(WF, RS, PO, SC, 512, G, R4dUnchained); \
else R4D_ARQ8_T(WF, RS, PO, SC, 256, G, R4dUnchained); } while (0)
#define R4D_ARQ8_W(WF, G) \
do { if (!res) R4D_ARQ8(WF, false, false, false, G); \
else if (!wp && !sc) R4D_ARQ8(WF, true, false, false, G); \
+818 -1145
View File
File diff suppressed because it is too large. Load diff
+127 -25
View File
@@ -206,25 +206,39 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4dchain_rowtopk
// An empty slot is not token `off`. A chunk that ran out of candidates leaves a zero key; OI gets
// column 0 for it, without the offset, so a pad cannot look like this rank's first real token. The
// pair plane writes -1, the sentinel the merge drops (not -INFINITY, a valid masked logit).
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below.
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. PT is a lane's
// list, at least R (see the header): 32 serves every R, and a launch for R <= 8 or R <= 16 takes
// the shorter list, whose insert and whose round's shift are that much shorter. The output is the
// same for any PT >= R.
template <int PT>
__device__ __forceinline__ void r4d_rowtopk_stage2_body(
const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI,
float* __restrict__ OP, int off, int R, int n) {
const int m = blockIdx.x;
const int lane = threadIdx.x;
unsigned long long t[R4D_TOPK_PT2];
unsigned long long t[PT];
#pragma unroll
for (int q = 0; q < R4D_TOPK_PT2; q++) t[q] = 0ull;
for (int q = 0; q < PT; q++) t[q] = 0ull;
// The key decides, as in stage 1 (see tk_insert). A NaN a chunk handed on displaced a real
// candidate, so dropping it here can leave the row short of R; the pad filling the gap is what
// the merge reports as id -1. An empty slot's key is 0 and never places.
// UNROLL keys are loaded before the first is placed, as in stage 1: one load a pass would put a
// memory latency between consecutive inserts. A lane places its keys in the same order.
const unsigned long long* p = P + (size_t)m * n;
for (int i = lane; i < n; i += R4D_TOPK_WAVE) tk_insert<R4D_TOPK_PT2>(t, p[i]);
int i = lane;
for (; i + (R4D_TOPK_UNROLL - 1) * R4D_TOPK_WAVE < n; i += R4D_TOPK_UNROLL * R4D_TOPK_WAVE) {
unsigned long long k[R4D_TOPK_UNROLL];
#pragma unroll
for (int u = 0; u < R4D_TOPK_UNROLL; u++) k[u] = p[i + u * R4D_TOPK_WAVE];
#pragma unroll
for (int u = 0; u < R4D_TOPK_UNROLL; u++) tk_insert<PT>(t, k[u]);
}
for (; i < n; i += R4D_TOPK_WAVE) tk_insert<PT>(t, p[i]);
for (int r = 0; r < R; r++) {
const unsigned long long w = tk_round<R4D_TOPK_PT2>(t);
const unsigned long long w = tk_round<PT>(t);
if (lane == 0) {
// A zero key is an empty slot, not a real column.
const float v = w ? tk_val(w) : -INFINITY;
@@ -239,16 +253,18 @@ __device__ __forceinline__ void r4d_rowtopk_stage2_body(
}
}
}
template <int PT>
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_stage2_kernel(
const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI,
float* __restrict__ OP, int off, int R, int n) {
r4d_rowtopk_stage2_body(P, OV, OI, OP, off, R, n);
r4d_rowtopk_stage2_body<PT>(P, OV, OI, OP, off, R, n);
}
template <int PT>
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4dchain_rowtopk_stage2(
const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI,
float* __restrict__ OP, int off, int R, int n) {
r4d_chain_wait();
r4d_rowtopk_stage2_body(P, OV, OI, OP, off, R, n);
r4d_rowtopk_stage2_body<PT>(P, OV, OI, OP, off, R, n);
r4d_chain_done();
}
@@ -293,10 +309,14 @@ static int rowtopk_bf16_sharded_emit(long y, long partial, long outv, long outi,
}
#undef R4D_TK_S1
if (emit_rc != RAD_OK) return emit_rc;
return R4D_EMIT(stream, (chain ? r4dchain_rowtopk_stage2 : r4d_rowtopk_stage2_kernel), dim3(M),
dim3(R4D_TOPK_WAVE), 0,
(const unsigned long long*)partial, (float*)outv, (int*)outi,
(float*)outp, off, R, nch * RC);
#define R4D_TK_S2(PT) R4D_EMIT(stream, (chain ? r4dchain_rowtopk_stage2<PT> \
: r4d_rowtopk_stage2_kernel<PT>), dim3(M), \
dim3(R4D_TOPK_WAVE), 0, \
(const unsigned long long*)partial, (float*)outv, (int*)outi, \
(float*)outp, off, R, nch * RC)
const int rc2 = R <= 8 ? R4D_TK_S2(8) : R <= 16 ? R4D_TK_S2(16) : R4D_TK_S2(R4D_TOPK_PT2);
#undef R4D_TK_S2
return rc2;
}
// ============================================================ the vocab-parallel merge
@@ -376,14 +396,16 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4dchain_rowtopk_merge(
// row's bf16 scale per 128 columns in its tail) with int8 codes instead of E4M3. The drafter
// rescores against whichever head the trunk's logits GEMM reads, so an int8 head needs this form.
#define R4D_RERANK_WPB 8 // waves a block: 256 threads, and R <= 32 so a wave takes <= 4
#define R4D_RERANK_U 5 // 512-column steps a lane has in flight: all of K = 2560
/* TB > 0: an IQR head (r4d_iqr.h's lm form), TB-bit codes then the row's scales, the table of 2^TB
* int8 entries after the last row. */
#define R4D_LOGIT_RERANK_PARAMS \
const unsigned short* __restrict__ X, const int* __restrict__ IN, \
const unsigned char* __restrict__ W, int* __restrict__ OI, float* __restrict__ OV, \
float* __restrict__ OP, int R, long K, long voff, long nv, long w_ld
template <bool I8, uint32_t TB = 0>
__global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_RERANK_WPB) void r4d_logit_rerank_kernel(
const unsigned short* __restrict__ X, const int* __restrict__ IN,
const unsigned char* __restrict__ W, int* __restrict__ OI, float* __restrict__ OV,
float* __restrict__ OP, int R, long K, long voff, long nv, long w_ld) {
__device__ __forceinline__ void r4d_logit_rerank_body(R4D_LOGIT_RERANK_PARAMS) {
__shared__ float s_sc[R4D_TOPK_PT2];
__shared__ int s_id[R4D_TOPK_PT2];
@@ -406,7 +428,76 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_RERANK_WPB) void r4d_logit_rera
const unsigned short* const sr = (const unsigned short*)(wr + (TB ? K / 8 * TB : K));
[[maybe_unused]] const int8_t* const tab =
(const int8_t*)(W + ((size_t)nv * w_ld + 255) / 256 * 256);
for (long k = lane; k < K; k += R4D_TOPK_WAVE) {
/* At K a multiple of 512 a lane takes sixteen consecutive columns of every 512, all in one
* scale block: their products sum from zero in column order and the block's scale multiplies
* that partial sum, the same arithmetic for every code form (an IQR head's scores are the
* int8 head's to the bit). Byte codes on aligned planes load whole: R4D_RERANK_U steps are
* in flight before the first is summed, where a column at a time is 80 loads in series at
* K = 2560, each waiting for the last. */
const bool ord = (K & 511) == 0;
bool vec = false;
if constexpr (TB == 0) vec = ord && ((size_t)X & 15) == 0 && ((size_t)W & 7) == 0;
if constexpr (TB == 0) {
for (long k0 = 16 * lane; vec && k0 < K; k0 += 512 * R4D_RERANK_U) {
uint2 c[R4D_RERANK_U][2];
uint4 xv[R4D_RERANK_U][2];
uint32_t sv[R4D_RERANK_U];
#pragma unroll
for (int u = 0; u < R4D_RERANK_U; u++) {
const long k = k0 + 512 * u;
if (k < K) {
const uint2* const pc = (const uint2*)(wr + k);
const uint4* const px = (const uint4*)(xr + k);
c[u][0] = pc[0]; c[u][1] = pc[1];
xv[u][0] = px[0]; xv[u][1] = px[1];
sv[u] = sr[k / 128];
}
}
#pragma unroll
for (int u = 0; u < R4D_RERANK_U; u++) {
if (k0 + 512 * u < K) {
const uint32_t cw[4] = { c[u][0].x, c[u][0].y, c[u][1].x, c[u][1].y };
const uint32_t xw[8] = { xv[u][0].x, xv[u][0].y, xv[u][0].z, xv[u][0].w,
xv[u][1].x, xv[u][1].y, xv[u][1].z, xv[u][1].w };
float part = 0.0f;
#pragma unroll
for (int d = 0; d < 4; d++) {
float f[4];
if constexpr (I8) {
#pragma unroll
for (int q = 0; q < 4; q++) f[q] = (float)((int)(cw[d] << (24 - 8 * q)) >> 24);
} else {
const v2f lo = r4d_fp8::e4m3_pk<false>(cw[d]), hi = r4d_fp8::e4m3_pk<true>(cw[d]);
f[0] = lo.x; f[1] = lo.y; f[2] = hi.x; f[3] = hi.y;
}
part = fmaf(f[0], __uint_as_float(xw[2 * d] << 16), part);
part = fmaf(f[1], __uint_as_float(xw[2 * d] & 0xffff0000u), part);
part = fmaf(f[2], __uint_as_float(xw[2 * d + 1] << 16), part);
part = fmaf(f[3], __uint_as_float(xw[2 * d + 1] & 0xffff0000u), part);
}
acc = fmaf(part, r4d_fp8::bscale(sv[u]), acc);
}
}
}
}
for (long k0 = 16 * lane; ord && !vec && k0 < K; k0 += 512) {
float part = 0.0f;
#pragma unroll
for (int q = 0; q < 16; q++) {
const long k = k0 + q;
float c;
if constexpr (TB != 0) {
const long bit = k * (long)TB;
const uint32_t wv = (uint32_t)wr[bit >> 3] | (uint32_t)wr[(bit >> 3) + 1] << 8;
c = (float)tab[(wv >> (bit & 7)) & ((1u << TB) - 1u)];
} else {
c = I8 ? (float)(int8_t)wr[k] : r4d_fp8::e4m3((uint32_t)wr[k]);
}
part = fmaf(c, bf16_to_f32(xr[k]), part);
}
acc = fmaf(part, r4d_fp8::bscale(sr[k0 / 128]), acc);
}
for (long k = ord ? K : lane; k < K; k += R4D_TOPK_WAVE) {
float c;
if constexpr (TB != 0) {
const long bit = k * (long)TB;
@@ -446,25 +537,39 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_RERANK_WPB) void r4d_logit_rera
}
}
// The kernel around the body: CH `r4dchain` is the chained form (r4d_chain.h), taken at decode
// heights.
template <bool I8, uint32_t TB, class CH>
__global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_RERANK_WPB)
void r4d_logit_rerank_kernel(R4D_LOGIT_RERANK_PARAMS) {
if (CH::on) r4d_chain_wait();
r4d_logit_rerank_body<I8, TB>(X, IN, W, OI, OV, OP, R, K, voff, nv, w_ld);
if (CH::on) r4d_chain_done();
}
#undef R4D_LOGIT_RERANK_PARAMS
static int logit_rerank_emit(long x, long idx_in, long head, long outi, long outv, long outp,
int M, int R, long K, long voff, long nv, RadStream stream,
bool i8, uint32_t tb = 0) {
bool i8, uint32_t tb = 0, bool chain = false) {
r4d_iqr::Form tf;
tf.bits = tb;
const long w_ld = tb ? (long)r4d_iqr::lm_row(tf, K) : r4d_fp8::lm_row_bytes(K);
// R <= PT2 makes the re-sort exact for any scores (one lane holds the whole answer), so it is
// checked, not clamped.
if (M < 1 || R < 1 || K < 1 || nv < 1 || R > R4D_TOPK_PT2) return R4D_NO(RAD_E_SHAPE);
#define R4D_RERANK_CH(I8, TB, CH_) \
R4D_EMIT(stream, (r4d_logit_rerank_kernel<I8, TB, CH_>), dim3(M), \
dim3(R4D_TOPK_WAVE * R4D_RERANK_WPB), 0, (const unsigned short*)x, \
(const int*)idx_in, (const unsigned char*)head, (int*)outi, (float*)outv, \
(float*)outp, R, K, voff, nv, w_ld)
#define R4D_RERANK_EMIT(I8, TB) \
R4D_EMIT(stream, (r4d_logit_rerank_kernel<I8, TB>), dim3(M), dim3(R4D_TOPK_WAVE * R4D_RERANK_WPB), \
0, (const unsigned short*)x, (const int*)idx_in, (const unsigned char*)head, \
(int*)outi, \
(float*)outv, (float*)outp, R, K, voff, nv, w_ld)
(chain ? R4D_RERANK_CH(I8, TB, r4dchain) : R4D_RERANK_CH(I8, TB, R4dUnchained))
const int rc = tb == 2u ? R4D_RERANK_EMIT(true, 2) : tb == 3u ? R4D_RERANK_EMIT(true, 3)
: tb == 4u ? R4D_RERANK_EMIT(true, 4) : tb == 5u ? R4D_RERANK_EMIT(true, 5)
: tb == 6u ? R4D_RERANK_EMIT(true, 6)
: i8 ? R4D_RERANK_EMIT(true, 0) : R4D_RERANK_EMIT(false, 0);
#undef R4D_RERANK_EMIT
#undef R4D_RERANK_CH
return rc;
}
@@ -632,10 +737,7 @@ static int rad_logit_rerank(const RadArgs* a, RadStream stream, bool i8, bool iq
return logit_rerank_emit(r4d_addr(x), r4d_addr(in), r4d_addr(w), r4d_addr(idx), r4d_addr(val),
pr ? r4d_addr(pr) : 0, (int)M, (int)R, (long)K, (long)voff, (long)NV,
stream, i8, tb);
}
extern "C" int r4d_rad_logit_rerank(const RadArgs* a, RadStream stream) {
return rad_logit_rerank(a, stream, false);
stream, i8, tb, r4d_geti_or(a, "chain", 0) != 0 && M <= 64);
}
extern "C" int r4d_rad_logit_rerank_i8(const RadArgs* a, RadStream stream) {
return rad_logit_rerank(a, stream, true);
+2111 -2951
View File
File diff suppressed because it is too large. Load diff
+33 -89
View File
@@ -389,29 +389,6 @@ extern "C" int r4d_shape_gemm_nt_bias(const RadParam* p, int n_p, int operand, R
R4D_PICK(l);
}
extern "C" int r4d_shape_moe_mxfp4(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K");
const int64_t N1 = rad_param_geti(p, n_p, "N_odd", N), K1 = rad_param_geti(p, n_p, "K_odd", K);
const int64_t ne = pi(p, n_p, "n_expert"), top = pi(p, n_p, "top_k");
const char* order = rad_param_gets(p, n_p, "a_order", "");
const int64_t ar = !std::strcmp(order, "sorted") ? M * top : M;
const int64_t nk = std::max(K, K1), nn = std::max(N, N1);
RadOpdDesc s0 = opd((uint32_t)RAD_U8, (ne + 1) / 2, N, K / 32);
RadOpdDesc s1 = opd((uint32_t)RAD_U8, ne / 2, N1, K1 / 32);
s0.fill = s1.fill = RAD_FILL_INDEX;
s0.idx_const = s1.idx_const = 127;
const RadOpdDesc l[] = { opd((uint32_t)RAD_F8E4M3, ar, nk),
opd((uint32_t)RAD_F32, ar, nk / 128),
opd((uint32_t)RAD_FP4E2M1, (ne + 1) / 2, N, K),
s0,
opd_idx(M * top, 0, M * top),
opd_idx(ne + 1, 0, M * top + 1),
opd((uint32_t)RAD_FP4E2M1, ne / 2, N1, K1),
s1,
opd((uint32_t)RAD_BF16, M * top, nn) };
R4D_PICK(l);
}
extern "C" int r4d_shape_kda_update(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const char* form = rad_param_gets(p, n_p, "state_form", "");
if (!std::strcmp(form, "anchor")) return RAD_E_UNSUPPORTED;
@@ -1382,7 +1359,7 @@ extern "C" int r4d_shape_ar_rmsnorm_had_quant_i8g(const RadParam* p, int n_p, in
const int64_t M = pi(p, n_p, "M");
const int64_t n = pi(p, n_p, "n");
const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK);
if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED;
if (g != R4D_FP8_BLOCK && g != R4D_I8_GROUP_WIDE) return RAD_E_UNSUPPORTED;
const RadOpdDesc l[] = {
opd((uint32_t)RAD_BF16, M, n), /* inout: the message and the input */
opd((uint32_t)RAD_BF16, M, n),
@@ -1447,55 +1424,6 @@ extern "C" int r4d_shape_gemm_nt_q(const RadParam* p, int n_p, int operand,
R4D_PICK(l);
}
/* gemm_nt_q_bias at fp8a8: gemm_nt_q's fp8 operands, a bf16 bias per output column, then y. The
* libref description matches it (ref_gemm_nt_q_bias_shape). */
extern "C" int r4d_shape_gemm_nt_q_bias(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t N = pi(p, n_p, "N");
const int64_t K = pi(p, n_p, "K");
const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK);
const char* q = r4d_pgets(p, n_p, "dtype");
if (!q || std::strcmp(q, "fp8a8") || g != R4D_FP8_BLOCK || K <= 0 || N <= 0)
return RAD_E_UNSUPPORTED;
const int64_t kb = (K + g - 1) / g, nb = (N + g - 1) / g;
const RadOpdDesc l[] = {
opd((uint32_t)RAD_F8E4M3, M, K),
opd((uint32_t)RAD_F32, M, kb),
opd((uint32_t)RAD_F8E4M3, N, K),
opd((uint32_t)RAD_BF16, nb, kb),
opd((uint32_t)RAD_BF16, N),
opd((uint32_t)RAD_BF16, M, N),
};
R4D_PICK(l);
}
/* The same GEMM with the SwiGLU and the quantiser in its epilogue. `N` is the weight's rows, gate
* then up, so the quantiser's outputs are N/2 wide (hence a schema of its own). */
extern "C" int r4d_shape_gemm_nt_q_gated(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t N = pi(p, n_p, "N");
const int64_t K = pi(p, n_p, "K");
const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK);
const char* q = r4d_pgets(p, n_p, "dtype");
if (!q || std::strcmp(q, "fp8a8") || g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED;
if (N <= 0 || N % 2 || K <= 0) return RAD_E_UNSUPPORTED;
const int64_t nout = N / 2;
const int64_t kb = (K + g - 1) / g;
const RadOpdDesc l[] = {
opd((uint32_t)RAD_F8E4M3, M, K),
opd((uint32_t)RAD_F32, M, kb),
opd((uint32_t)RAD_F8E4M3, N, K),
opd((uint32_t)RAD_BF16, (N + g - 1) / g, kb),
opd((uint32_t)RAD_F8E4M3, M, nout),
opd((uint32_t)RAD_F32, M, (nout + g - 1) / g),
opd((uint32_t)RAD_BF16, M, nout),
};
R4D_PICK(l);
}
/* dequant_w4 -- the packed 4-bit weight back to row-major bf16 (shim in r4d_dequant_w4_bf16.hip).
*
* The one packed weight a public dtype sizes exactly: RAD_I4 is four bits per element, so [N, K]
@@ -1644,7 +1572,9 @@ extern "C" int r4d_shape_moe_scatter_inv(const RadParam* p, int n_p, int operand
R4D_PICK(l);
}
extern "C" int r4d_shape_moe_gemm_q(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
/* `i8`: moe_gemm_i8a8's operands, int8 codes on both sides and the weight's scale per (row, group
* of K). */
static int moe_gemm_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out, bool i8) {
const int64_t M = pi(p, n_p, "M");
const int64_t N0 = pi(p, n_p, "N"), K0 = pi(p, n_p, "K");
const int64_t N1 = pi(p, n_p, "N_odd", N0), K1 = pi(p, n_p, "K_odd", K0);
@@ -1661,27 +1591,34 @@ extern "C" int r4d_shape_moe_gemm_q(const RadParam* p, int n_p, int operand, Rad
* in scatter order ("sorted"). */
const char* ord = rad_param_gets(p, n_p, "a_order", nullptr);
const int64_t AR = (ord && !std::strcmp(ord, "sorted")) ? M * k : M;
const uint32_t C = i8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3;
auto srows = [&](int64_t n) { return i8 ? n : (n + g - 1) / g; };
const int64_t ag = pi(p, n_p, "a_group", g) > 0 ? pi(p, n_p, "a_group", g) : g;
const RadOpdDesc l[] = {
opd((uint32_t)RAD_F8E4M3, AR, K), /* a -- see `a_order` */
opd((uint32_t)RAD_F32, AR, (K + g - 1) / g), /* a_scale */
opd(C, AR, K), /* a -- see `a_order` */
opd((uint32_t)RAD_F32, AR, (K + ag - 1) / ag), /* a_scale */
/* The weight operands are tables when issued, described here as one stacked plane; a
* fixture cannot hold a pointer array, and the kernel reads both forms (r4d_moe.hip,
* wtab_at). */
opd((uint32_t)RAD_F8E4M3, ne0, N0, K0), /* w -- the even experts */
opd((uint32_t)RAD_BF16, ne0, (N0 + g - 1) / g, (K0 + g - 1) / g), /* w_scale */
opd(C, ne0, N0, K0), /* w -- the even experts */
opd((uint32_t)RAD_BF16, ne0, srows(N0), (K0 + g - 1) / g), /* w_scale */
opd_idx(M * k, 0, M * k, -1), /* sorted_tok */
opd_idx(ne + 1, 0, M * k + 1, -1), /* expert_offset -- see the note above */
opd((uint32_t)RAD_F8E4M3, ne1, N1, K1), /* w_odd -- the odd experts */
opd((uint32_t)RAD_BF16, ne1, (N1 + g - 1) / g, (K1 + g - 1) / g), /* w_odd_scale */
opd(C, ne1, N1, K1), /* w_odd -- the odd experts */
opd((uint32_t)RAD_BF16, ne1, srows(N1), (K1 + g - 1) / g), /* w_odd_scale */
opd(D, M * k, N), /* y, in sorted order */
};
R4D_PICK(l);
}
extern "C" int r4d_shape_moe_gemm_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return moe_gemm_q_shape(p, n_p, operand, out, true);
}
/* The four-class form: class q holds the experts e with e % 4 == q at [N_q, K_q], defaulting to
* class 0's, ceil((n - q) / 4) of them; `y` follows the last class. */
extern "C" int r4d_shape_moe_gemm_q_mod4(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
static int moe_gemm_q_mod4_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out,
bool i8) {
const int64_t M = pi(p, n_p, "M");
int64_t Nc[4], Kc[4];
Nc[0] = pi(p, n_p, "N");
@@ -1705,13 +1642,16 @@ extern "C" int r4d_shape_moe_gemm_q_mod4(const RadParam* p, int n_p, int operand
const uint32_t D = dt_act(p, n_p, "dtype");
const char* ord = rad_param_gets(p, n_p, "a_order", nullptr);
const int64_t AR = (ord && !std::strcmp(ord, "sorted")) ? M * k : M;
auto wq = [&](int q) { return opd((uint32_t)RAD_F8E4M3, nq[q], Nc[q], Kc[q]); };
const uint32_t C = i8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3;
auto wq = [&](int q) { return opd(C, nq[q], Nc[q], Kc[q]); };
const int64_t ag = pi(p, n_p, "a_group", g) > 0 ? pi(p, n_p, "a_group", g) : g;
auto sq = [&](int q) {
return opd((uint32_t)RAD_BF16, nq[q], (Nc[q] + g - 1) / g, (Kc[q] + g - 1) / g);
return opd((uint32_t)RAD_BF16, nq[q], i8 ? Nc[q] : (Nc[q] + g - 1) / g,
(Kc[q] + g - 1) / g);
};
const RadOpdDesc l[] = {
opd((uint32_t)RAD_F8E4M3, AR, K), /* a -- see `a_order` */
opd((uint32_t)RAD_F32, AR, (K + g - 1) / g), /* a_scale */
opd(C, AR, K), /* a -- see `a_order` */
opd((uint32_t)RAD_F32, AR, (K + ag - 1) / ag), /* a_scale */
wq(0), sq(0), /* w, w_scale -- class 0 */
opd_idx(M * k, 0, M * k, -1), /* sorted_tok */
opd_idx(ne + 1, 0, M * k + 1, -1), /* expert_offset */
@@ -1720,6 +1660,10 @@ extern "C" int r4d_shape_moe_gemm_q_mod4(const RadParam* p, int n_p, int operand
};
R4D_PICK(l);
}
extern "C" int r4d_shape_moe_gemm_i8_mod4(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
return moe_gemm_q_mod4_shape(p, n_p, operand, out, true);
}
extern "C" int r4d_shape_moe_gather(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
@@ -2183,7 +2127,7 @@ extern "C" int r4d_shape_rmsnorm_had_quant_i8g(const RadParam* p, int n_p, int o
const int64_t n = pi(p, n_p, "n");
const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK);
const uint32_t D = dt_act(p, n_p, "dtype");
if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED;
if (g != R4D_FP8_BLOCK && g != R4D_I8_GROUP_WIDE) return RAD_E_UNSUPPORTED;
const RadOpdDesc l[] = {
opd(D, M, n),
opd(D, M, n),
@@ -2202,7 +2146,7 @@ extern "C" int r4d_shape_gated_had_quant_i8g(const RadParam* p, int n_p, int ope
const int64_t n = pi(p, n_p, "n");
const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK);
const uint32_t D = dt_act(p, n_p, "dtype");
if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED;
if (g != R4D_FP8_BLOCK && g != R4D_I8_GROUP_WIDE) return RAD_E_UNSUPPORTED;
const RadOpdDesc l[] = {
opd(D, M, 2 * n), /* gate then up in one buffer */
opd((uint32_t)RAD_I8, M, n),
@@ -2219,7 +2163,7 @@ extern "C" int r4d_shape_gate_quant_fp8(const RadParam* p, int n_p, int operand,
const int64_t n = pi(p, n_p, "n");
const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK);
const uint32_t D = dt_act(p, n_p, "dtype");
if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED;
if (g != R4D_FP8_BLOCK && g != R4D_I8_GROUP_WIDE) return RAD_E_UNSUPPORTED;
/* A row is a (token, head) pair: `M` is tokens * n_head and `n` is head_dim, so the gate is a
* fixed stride inside the [q|gate] projection and the scale plane lands where the out
* projection reads it. In the engine the gate is a column slice; described flat. */
+48 -17
View File
@@ -79,8 +79,13 @@ __device__ __forceinline__ float rdv(const float*, float v) { return v; }
constexpr int kRmChunks = 4; // 8-wide chunks a thread keeps: n <= kT * 8 * 4 = 8192
// QMODE: 0 writes the bf16 chain to `z`, 1 also quantises it to E4M3 (q, scale), 2 to int8, the
// two differing only in r4d_q8.h's `q8_top` and `q8_pack4`.
template <bool GATED, int QMODE>
// two differing only in r4d_q8.h's `q8_top` and `q8_pack4`. 3 is rms_mod_had_quant_i8g,
// had_quant_act_i8g's quantiser: the bf16-rounded chain rotated by the 128-wide Hadamard where it
// lies, eight columns a lane and sixteen lanes a block (strides 1, 2, 4 in the lane, then 8 to 64
// across lanes, r4d_fwht_wave's order, so the sums are the standalone kernel's), then int8 codes
// under one scale per (row, 128 * SUB): SUB 2 is IQ8R's 256-wide group, a whole wave. `z` receives
// the unrotated chain.
template <bool GATED, int QMODE, int SUB = 1>
__global__ __launch_bounds__(kT) void rms_mod_kernel(
const uint16_t* __restrict__ yd, const uint16_t* __restrict__ g, const uint16_t* __restrict__ s,
const uint16_t* __restrict__ w, const int* __restrict__ cu, uint16_t* __restrict__ x,
@@ -159,6 +164,23 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel(
}
if (z) st8(z + (size_t)r * z_ld + i, o);
if (QMODE) {
if constexpr (QMODE == 3) {
#pragma unroll
for (int h = 1; h < 8; h <<= 1) {
#pragma unroll
for (int j = 0; j < 8; ++j)
if ((j & h) == 0) {
const float a = o[j], b = o[j + h];
o[j] = a + b;
o[j + h] = a - b;
}
}
const int lane = (int)threadIdx.x & 31;
r4d_fwht_xstage<8, 1>(o, lane);
r4d_fwht_xstage<8, 2>(o, lane);
r4d_fwht_xstage<8, 4>(o, lane);
r4d_fwht_xstage<8, 8>(o, lane);
}
float m = 0.0f;
#pragma unroll
for (int j = 0; j < 8; ++j) m = fmaxf(m, fabsf(o[j]));
@@ -166,12 +188,13 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel(
m = fmaxf(m, r4d_xor_lane<4>(m));
m = fmaxf(m, r4d_xor_lane<2>(m));
m = fmaxf(m, r4d_xor_lane<1>(m));
const float sc = m > 0.0f ? m * (1.0f / q8_top<QMODE == 2>()) : 1.0f;
if constexpr (SUB == 2) m = fmaxf(m, r4d_xor_lane<16>(m));
const float sc = m > 0.0f ? m * (1.0f / q8_top<QMODE >= 2>()) : 1.0f;
const float inv = 1.0f / sc;
if ((threadIdx.x & 15) == 0) qs[(size_t)r * qs_ld + i / 128] = sc;
if ((threadIdx.x & (16 * SUB - 1)) == 0) qs[(size_t)r * qs_ld + i / (128 * SUB)] = sc;
*(uint2*)(q + (size_t)r * q_ld + i) =
make_uint2(q8_pack4<QMODE == 2>(o[0], o[1], o[2], o[3], inv),
q8_pack4<QMODE == 2>(o[4], o[5], o[6], o[7], inv));
make_uint2(q8_pack4<QMODE >= 2>(o[0], o[1], o[2], o[3], inv),
q8_pack4<QMODE >= 2>(o[4], o[5], o[6], o[7], inv));
}
}
}
@@ -610,7 +633,8 @@ int parse_f32_list(const char* s, float* out, int max) {
// ============================================================== the plugin ABI entry points
// rms_mod (QUANT false: y, g, s, w, cu, x, z) and rms_mod_quant_fp8 (y, g, s, w, cu, x, q, scale,
// z), one shim.
// z), one shim. qmode 2 is rms_mod_quant_i8 and 3 rms_mod_had_quant_i8g, whose `group` is 128 or
// 256 with n whole groups.
static int rms_mod_launch(const RadArgs* a, RadStream st, int qmode) {
const RadTensor *y = r4d_opt(a, 0), *g = r4d_opt(a, 1), *sc = r4d_opt(a, 2);
const RadTensor *w = r4d_opt(a, 3), *cu = r4d_opt(a, 4), *x = r4d_opt(a, 5);
@@ -625,11 +649,12 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, int qmode) {
if (gated && (!y || !g)) return R4D_NO(RAD_E_INVAL);
if (!is_bf16(x) || !is_bf16(sc) || (w && !is_bf16(w)) || !is_i32(cu) ||
(gated && (!is_bf16(y) || !is_bf16(g))) || (z && !is_bf16(z)) ||
(qmode && (q->dtype != (qmode == 2 ? RAD_I8 : RAD_F8E4M3) || qs->dtype != RAD_F32)))
(qmode && (q->dtype != (qmode >= 2 ? RAD_I8 : RAD_F8E4M3) || qs->dtype != RAD_F32)))
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0);
const long long grp = qmode ? r4d_geti_or(a, "group", 0) : 128;
if (n <= 0 || (n & 7) || n > (long long)kT * 8 * kRmChunks ||
(qmode && (n % 128 || r4d_geti_or(a, "group", 0) != 128)))
(qmode && (n % grp || (grp != 128 && !(qmode == 3 && grp == 256)))))
return R4D_NO(RAD_E_SHAPE);
long long rx = 0, xl = 0, ry = 0, yl = 0, rg = 0, gl = 0, rs = 0, sl = 0, rz = 0, zl = 0;
long long rq = 0, rqs = 0, ql = 0, qsl = 0;
@@ -640,7 +665,7 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, int qmode) {
return R4D_NO(RAD_E_STRIDE);
if (qmode) {
ql = r4d_rows_pitch(q, n, &rq);
qsl = r4d_rows_pitch(qs, n / 128, &rqs);
qsl = r4d_rows_pitch(qs, n / grp, &rqs);
if (ql < 0 || (ql & 7) || ((uintptr_t)q->data & 7) || qsl < 0) return R4D_NO(RAD_E_STRIDE);
}
const long long n_seq = r4d_numel(cu) - 1, rows = qmode ? rq : rz;
@@ -658,8 +683,8 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, int qmode) {
const int layer = nk && !std::strcmp(nk, "layer");
const int none = nk && !std::strcmp(nk, "none");
if ((nk && !layer && !none && std::strcmp(nk, "rms")) || (none && w)) return R4D_NO(RAD_E_INVAL);
#define R4D_RMQ(G, Q) \
hipLaunchKernelGGL((rms_mod_kernel<G, Q>), dim3((unsigned)rows), dim3(kT), 0, \
#define R4D_RMQ(G, Q, ...) \
hipLaunchKernelGGL((rms_mod_kernel<G, Q, ##__VA_ARGS__>), dim3((unsigned)rows), dim3(kT), 0, \
(hipStream_t)st, G ? (const uint16_t*)y->data : nullptr, \
G ? (const uint16_t*)g->data : nullptr, (const uint16_t*)sc->data, \
w ? (const uint16_t*)w->data : nullptr, (const int*)cu->data, \
@@ -668,7 +693,13 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, int qmode) {
z ? (uint16_t*)z->data : nullptr, (int)n, (int)n_seq, eps, (int)yl, \
(int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl, wadd, once, layer, \
none, cm ? (const int*)cm->data : nullptr)
if (qmode == 2) {
if (qmode == 3 && grp == 256) {
if (gated) R4D_RMQ(true, 3, 2);
else R4D_RMQ(false, 3, 2);
} else if (qmode == 3) {
if (gated) R4D_RMQ(true, 3);
else R4D_RMQ(false, 3);
} else if (qmode == 2) {
if (gated) R4D_RMQ(true, 2);
else R4D_RMQ(false, 2);
} else if (qmode == 1) {
@@ -684,14 +715,14 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, int qmode) {
extern "C" int r4d_rad_rms_mod(const RadArgs* a, RadStream s) { return rms_mod_launch(a, s, 0); }
extern "C" int r4d_rad_rms_mod_quant_fp8(const RadArgs* a, RadStream s) {
return rms_mod_launch(a, s, 1);
}
extern "C" int r4d_rad_rms_mod_quant_i8(const RadArgs* a, RadStream s) {
return rms_mod_launch(a, s, 2);
}
extern "C" int r4d_rad_rms_mod_had_quant_i8g(const RadArgs* a, RadStream s) {
return rms_mod_launch(a, s, 3);
}
extern "C" int r4d_rad_flow_x0_step(const RadArgs* a, RadStream s) {
const RadTensor *v = r4d_opt(a, 0), *t = r4d_opt(a, 1), *sg = r4d_opt(a, 2);
const RadTensor *sgn = r4d_opt(a, 3), *x = r4d_opt(a, 4);