Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
+70
-98
@@ -1,17 +1,15 @@
|
||||
# THE ARCHITECTURES libr4d SERVES, declared here and nowhere else. Its kernels are written for
|
||||
# RDNA4: wave32, the gfx12 WMMA fragment layouts, and gfx12-only instructions such as
|
||||
# global_load_tr_b128. Compiled for anything else they would launch and compute garbage, so the
|
||||
# coverage is a property of the library and the library is what states it.
|
||||
# libr4d serves RDNA4 only, declared here and nowhere else. Its kernels rely on wave32, the gfx12
|
||||
# WMMA fragment layouts and gfx12-only instructions such as global_load_tr_b128; built for other
|
||||
# targets they would compute garbage.
|
||||
#
|
||||
# A build targeting other cards skips libr4d and keeps going. What it gets is an engine with no
|
||||
# device kernel library for that card, which REFUSES TO SERVE an op only a reference library
|
||||
# implements unless --debug-accept-reference-kernels is passed (spec §17) -- an unserved card that
|
||||
# says so, rather than a project that will not configure. Supplying a kernel library for that card
|
||||
# is the supported answer, and it is the same one an out-of-tree author gives.
|
||||
# A build targeting other cards skips libr4d. The engine then has no device kernel library for that
|
||||
# card and refuses ops only a reference library implements, unless
|
||||
# --debug-accept-reference-kernels is passed (spec §17). The supported fix is a kernel library for
|
||||
# that card.
|
||||
#
|
||||
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
|
||||
# radiance (`cmake -S libr4d -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`, with the HIP compiler
|
||||
# named as for the tree) -- the same rad_add_plugin either way (cmake/RadAddPlugin.cmake).
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S libr4d -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`, naming the HIP compiler as for
|
||||
# the tree); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(libr4d LANGUAGES CXX HIP)
|
||||
@@ -26,87 +24,72 @@ if(NOT R4D_GPU_TARGETS)
|
||||
return()
|
||||
endif()
|
||||
|
||||
# The libr4d kernel plugin, and THE ONLY BUILD libr4d HAS: this list is the definition of its
|
||||
# translation units.
|
||||
# R4D_UNITS is the definitive list of libr4d's device translation units, as "unit|extra flags".
|
||||
# The GDN chunk scan needs -mcumode. The quantised GEMMs' group sizes are source constants, not
|
||||
# build options: the host packer reads r4d_args.h and the units their own defaults, which must
|
||||
# agree (r4d_gemm_args.h static_asserts the w4 and w8 groups).
|
||||
#
|
||||
# THE PER-UNIT FLAGS ARE NOT DECORATION: the GDN chunk scan needs -mcumode, and every quantised
|
||||
# GEMM needs its group size, which must match the group the weights were packed at or the kernel
|
||||
# reads the wrong scales.
|
||||
#
|
||||
# Every unit is compiled -ffp-contract=off. The quantised all-reduce REQUIRES it: it sums two
|
||||
# dequantised products per element, the two ranks see the products in the opposite order, and
|
||||
# contracting either into an FMA makes them disagree by ~1 ULP -- which breaks the replicated-state
|
||||
# invariant. For the rest it is reproducibility: the costs the kernels' comments state hold at
|
||||
# this setting.
|
||||
# Every unit is compiled -ffp-contract=off. The quantised all-reduce requires it: the two ranks sum
|
||||
# two dequantised products per element in opposite order, and an FMA on either side makes them
|
||||
# differ by ~1 ULP, breaking the replicated-state invariant. Elsewhere it keeps results and the
|
||||
# costs quoted in kernel comments reproducible.
|
||||
|
||||
# ONE DIRECTORY: the kernels and libr4d's own declaration -- the row table, the layouts -- live
|
||||
# together. There is no launch adapter between the plugin ABI and the kernels: every entry point
|
||||
# takes `(const RadArgs*, RadStream)` and sits beside the kernel it launches.
|
||||
#
|
||||
# THIS PLUGIN LINKS rad_abi AND NOTHING ELSE: it is a standalone plugin built on abi/, exactly like
|
||||
# one written out of tree.
|
||||
|
||||
# The weight group size, as the DEVICE units see it. It is NOT one variable covering both sides:
|
||||
# the packer is r4d_layout.cpp, a host source in R4D_DECLARATION below, which no -D here reaches --
|
||||
# it reads R4D_W4_GROUP from r4d_args.h, a hardcoded 128. So changing this alone re-groups the
|
||||
# kernel and leaves the packer at 128, which is precisely the silently-wrong-output the single
|
||||
# variable was supposed to rule out.
|
||||
# CHANGING THE GROUP MEANS CHANGING BOTH, and the enum is the one that decides what is on disk.
|
||||
set(RAD_W4_GROUP 128 CACHE STRING "libr4d quantised-weight group size (must match R4D_W4_GROUP in r4d_args.h)")
|
||||
# Kernels and libr4d's declaration (row table, layouts) share one directory. There is no launch
|
||||
# adapter: every entry point takes `(const RadArgs*, RadStream)` and sits beside its kernel. The
|
||||
# plugin links rad_abi only, like one written out of tree.
|
||||
|
||||
set(R4D_UNITS
|
||||
"r4d_attn_paged_h256_gqa6|"
|
||||
"r4d_attn_paged_h128_gqa4|"
|
||||
# Gemma 4 dense sliding window: head_dim 256, 2 queries per KV head, windowed decode and
|
||||
# prefill. The windowed twin of the drafter leg above.
|
||||
# prefill.
|
||||
"r4d_attn_paged_h256_gqa2|"
|
||||
# Eight queries per KV head, at both head widths: the routed 35B-A3B is 16 over 2 at 256
|
||||
# and MiniCPM5-2B is 16 over 2 at 128. Same device code, different instantiations.
|
||||
# Eight queries per KV head, one body instantiated at head_dim 256 (the routed 35B-A3B) and 128
|
||||
# (MiniCPM5-2B).
|
||||
"r4d_attn_paged_gqa8|"
|
||||
# Twelve, head_dim 256 only: Qwen3.8-Flash-Next's QSA layers are 24 over 2. Four lines that
|
||||
# set the ratio and include the unit above, which is the parameterised body.
|
||||
# The gqa12, gqa4 and gqa6_bs4 units set the ratio and include the parameterised body above.
|
||||
# gqa12, head_dim 256: Qwen3.8-Flash-Next's QSA layers (24 query heads over 2).
|
||||
"r4d_attn_paged_h256_gqa12|"
|
||||
# Four, head_dim 256: Qwen3.5-0.8B is 8 over 2 at the 27B's head width. Again the body above
|
||||
# with the ratio set.
|
||||
# gqa4, head_dim 256: Qwen3.5-0.8B (8 over 2).
|
||||
"r4d_attn_paged_h256_gqa4|"
|
||||
# Six, head_dim 256 and the same 4-token page: the same QSA layers at four ranks, where each KV
|
||||
# head is replicated across a rank pair. Again four lines that set the ratio and include the body.
|
||||
# gqa6, head_dim 256, 4-token page: the same QSA layers at four ranks, each KV head replicated
|
||||
# across a rank pair.
|
||||
"r4d_attn_paged_h256_gqa6_bs4|"
|
||||
# head_dim 256 and 512 at 1, 2, 4 or 8 queries per KV head with ANY window: Gemma 4's sliding
|
||||
# (h256/gqa2, window 1024) and full (h512, gqa 8 at TP1/TP2) layers. One kernel a geometry for
|
||||
# every q_len, reading q at any row pitch, which is what attn_paged_qrow is.
|
||||
# head_dim 256 and 512 at 1, 2, 4 or 8 queries per KV head with any window: Gemma 4's sliding
|
||||
# (h256/gqa2, window 1024) and full (h512, gqa 8 at TP1/TP2) layers. One kernel per geometry
|
||||
# covers every q_len and reads q at any row pitch (attn_paged_qrow).
|
||||
"r4d_attn_paged_window|"
|
||||
# Two queries per KV head at head_dim 128 only (Qwen3-1.7B's 16 over 8, Qwen3-ASR's decoder):
|
||||
# the gqa8 body with the ratio set.
|
||||
"r4d_attn_paged_h128_gqa2|"
|
||||
"r4d_attn_vit_h72_bf16|"
|
||||
# An encoder's dense attention (bidirectional, GQA in the workgroup, a two-sided window) and
|
||||
# the small ops around it: act_mul, seg_mean, qk_norm_rope with a v norm, the f32 widening.
|
||||
"r4d_attn_dense_bf16|"
|
||||
"r4d_encoder_bf16|"
|
||||
# The image generator: attention over a paged prefix and the pass's own rows, the causal
|
||||
# head_dim-128 dense form and the 1152-wide decoder head; and the sampler, adaptive norm,
|
||||
# implicit-GEMM convolution and pixel ops around them.
|
||||
# The image generator: attention over a paged prefix plus the pass's own rows, the causal
|
||||
# head_dim-128 dense form and the 1152-wide decoder head; plus the sampler, adaptive norm,
|
||||
# implicit-GEMM convolution and pixel ops.
|
||||
"r4d_attn_gen|"
|
||||
"r4d_gen|"
|
||||
# The vision tower's own small ops: layer norm, the learned-grid position embedding, and the
|
||||
# biased GEMM with a linear layer's activation and residual in its store.
|
||||
# Vision tower ops: layer norm, the learned-grid position embedding, and the biased GEMM with
|
||||
# activation and residual fused into its store.
|
||||
"r4d_vit_bf16|"
|
||||
"r4d_gdn_chunk_scan_k128_v128_c64_bf16|-mcumode"
|
||||
"r4d_gdn_conv_w4_h128_bf16|"
|
||||
"r4d_gdn_kkt_solve_k128_c64_bf16|"
|
||||
"r4d_gdn_recurrent_update_k128_v128_bf16_fp32state|"
|
||||
"r4d_gdn_gated_rmsnorm_h128_bf16|"
|
||||
# The gated residual, which is what a hyper-connection model has instead of a pre-norm and a
|
||||
# residual add. ONE unit: hc_read is two launches behind one entry point, because the mix
|
||||
# depends on every column of the low-rank waist and a kernel boundary is the grid-wide
|
||||
# barrier that says so.
|
||||
# The hyper-connection gated residual (in place of pre-norm plus residual add). hc_read is two
|
||||
# launches behind one entry point: the mix depends on every column of the low-rank waist, so it
|
||||
# needs a grid-wide barrier.
|
||||
"r4d_hc_bf16|"
|
||||
"r4d_ngram_ids|"
|
||||
"r4d_ple_gate_bf16|"
|
||||
"r4d_ple_conv_bf16|"
|
||||
# The all-reduce family is ONE unit and not one per kernel: they share a single instance --
|
||||
# peer scratch, IPC-equivalent pointers, per-block flags, device sequence counters -- and one
|
||||
# rendezvous that establishes it across every rank before the first launch. Splitting the entry
|
||||
# points across the six kernel units would put that state in a header and give each unit its own
|
||||
# copy of it, which is the one thing it must not have.
|
||||
# The all-reduce kernels share one instance (peer scratch, IPC-equivalent pointers, per-block
|
||||
# flags, device sequence counters) set up by one rendezvous across ranks, so all entry points
|
||||
# live in r4d_ar_entry. Spreading them across the kernel units would give each its own copy.
|
||||
"r4d_ar_entry|"
|
||||
"r4d_ar_gather_2rank|"
|
||||
"r4d_ar_gather_Nrank|"
|
||||
@@ -118,23 +101,22 @@ set(R4D_UNITS
|
||||
"r4d_gemm_bf16_nt_m16|"
|
||||
"r4d_gemm_bf16_nt_m64|"
|
||||
"r4d_gemm_bf16_nt_tiled|"
|
||||
"r4d_gemm_w4a16_nt_m64|-DR4D_GEMM_W4_GROUP=${RAD_W4_GROUP}"
|
||||
"r4d_gemm_w5a16_nt_m64|-DR4D_GEMM_W4_GROUP=${RAD_W4_GROUP}"
|
||||
"r4d_gemm_w4a16_nt_m64|"
|
||||
"r4d_gemm_w5a16_nt_m64|"
|
||||
"r4d_gemm_wpa8i8_tiled|"
|
||||
"r4d_givens_dense|"
|
||||
"r4d_gemm_w8a16_nt_m64|-DR4D_GEMM_W8_GROUP=${RAD_W4_GROUP}"
|
||||
"r4d_gemm_w2a8_nt|-DR4D_GEMM_W2A8_GROUP=${RAD_W4_GROUP}"
|
||||
"r4d_gemm_w4a8_nt_m64|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}"
|
||||
"r4d_gemm_w8a8_nt_m64|-DR4D_GEMM_W8A8_GROUP=${RAD_W4_GROUP}"
|
||||
"r4d_gemm_w8a8_tiled|-DR4D_GEMM_W8A8_GROUP=${RAD_W4_GROUP}"
|
||||
"r4d_gemm_w4a8_tiled|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}"
|
||||
"r4d_gemm_w4a8_prefill|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}"
|
||||
"r4d_gemm_w8a16_nt_m64|"
|
||||
"r4d_gemm_w2a8_nt|"
|
||||
"r4d_gemm_w4a8_nt_m64|"
|
||||
"r4d_gemm_w8a8_nt_m64|"
|
||||
"r4d_gemm_w8a8_tiled|"
|
||||
"r4d_gemm_w4a8_tiled|"
|
||||
"r4d_gemm_w4a8_prefill|"
|
||||
"r4d_gemm_mxfp4a8_nt_m64|"
|
||||
"r4d_gemm_mxfp4a8_tiled|"
|
||||
"r4d_gemm_mxfp4a8_decode|"
|
||||
# Block-scaled FP8 -- the format Qwen3.8-27B-FP8 ships in.
|
||||
# No -D: the 128x128 block is a property of the checkpoint on disk and not a quantiser choice
|
||||
# like RAD_W4_GROUP, so it is a constant in the source and the entry points reject a mismatch.
|
||||
# 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_quant_act_fp8|"
|
||||
@@ -163,14 +145,14 @@ set(R4D_UNITS
|
||||
"r4d_rowtopk_bf16|"
|
||||
# The vocab-sharded draft head's cross-rank top-1, one id a row.
|
||||
"r4d_pair_argmax_f32|"
|
||||
# Gemma 4's two sandwich-norm joins (norm_add_norm, norm_add_norm_route, join_add_scale) and
|
||||
# expert_scale: each one kernel for a chain of small ones.
|
||||
# Gemma 4's sandwich-norm joins (norm_add_norm, norm_add_norm_route, join_add_scale) and
|
||||
# expert_scale, each one kernel for a chain of small ones.
|
||||
"r4d_norm_join_bf16|"
|
||||
"r4d_expert_scale_bf16|"
|
||||
"r4d_dflash_conv_t2_g16_bf16|"
|
||||
"r4d_dflash_select_bf16|"
|
||||
# The routed mixture of experts: router, scatter, the grouped block-scaled fp8 GEMM and
|
||||
# gather, in one unit because the other three exist only to feed the GEMM.
|
||||
# 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|"
|
||||
)
|
||||
|
||||
@@ -193,16 +175,9 @@ foreach(u ${R4D_UNITS})
|
||||
list(APPEND R4D_SRC "${src}")
|
||||
endforeach()
|
||||
|
||||
# THE HOST SOURCES IN libr4d/ ARE DECLARATION. There is no launch adapter: every entry point
|
||||
# takes `(const RadArgs*, RadStream)` and lives beside the kernel it launches, in libr4d.
|
||||
# These are the plugin's statements ABOUT those kernels -- the row table, the weight layouts and
|
||||
# their relayouts, the operand descriptions, the fusion claims -- and all of them are PURE HOST
|
||||
# C++ that include neither r4d.h nor hip_runtime.h.
|
||||
#
|
||||
# That split is what lets the tables a transcription error hides in be compiled and read on a box
|
||||
# with no ROCm, and it is why an operand description (answered before anything is allocated) and a
|
||||
# declared fusion (a statement about the op vocabulary, answered with no tensors in hand) belong
|
||||
# here rather than in a translation unit that needs a compiler for the card.
|
||||
# The host sources are declaration only: the row table, weight layouts and relayouts, operand
|
||||
# descriptions and fusion claims. They are pure host C++ that includes neither r4d.h nor
|
||||
# hip_runtime.h, so these tables compile and can be inspected without ROCm.
|
||||
set(R4D_DECLARATION r4d_rows.cpp r4d_layout.cpp r4d_fp8_layout.cpp r4d_shapes.cpp r4d_fuse.cpp)
|
||||
|
||||
rad_add_plugin(libr4d kernels
|
||||
@@ -211,18 +186,15 @@ rad_add_plugin(libr4d kernels
|
||||
GPU_TARGETS ${R4D_GPU_TARGETS}
|
||||
INCLUDES ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
# The catalogue dump: prints every row and, on a card, calls each launch with a minimal valid
|
||||
# input. This is how a transcription error in the constraint table is found -- otherwise it is
|
||||
# invisible until a model silently picks the wrong kernel. It dlopens the plugin rather than
|
||||
# linking it, because an undefined symbol in the .so is itself one of the things being tested.
|
||||
# Catalogue dump: prints every row and, on a card, calls each launch with a minimal valid input, to
|
||||
# catch transcription errors in the constraint table. It dlopens the plugin so an undefined symbol
|
||||
# in the .so is caught too.
|
||||
add_executable(r4d_selftest ${CMAKE_CURRENT_SOURCE_DIR}/r4d_selftest.cpp)
|
||||
# It dlopens the plugin but allocates the device buffers it feeds the kernels itself, so it needs
|
||||
# the HIP runtime even though it links no kernel.
|
||||
# Links the HIP runtime to allocate the device buffers it feeds the kernels.
|
||||
target_link_libraries(r4d_selftest PRIVATE radiance::abi ${CMAKE_DL_LIBS} ${RAD_HIP_RUNTIME})
|
||||
target_include_directories(r4d_selftest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
set_target_properties(r4d_selftest PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
|
||||
# libr4d is built at -std=c++17: at C++20 clang tightens the address-space check on
|
||||
# __builtin_amdgcn_global_load_tr_b128_v8i16 in r4d_common.h, and C++17 is the configuration every
|
||||
# cost stated in the kernels' comments was taken in.
|
||||
# C++17: at C++20 clang tightens the address-space check on
|
||||
# __builtin_amdgcn_global_load_tr_b128_v8i16 in r4d_common.h. Kernel cost figures are for C++17.
|
||||
set_target_properties(libr4d PROPERTIES HIP_STANDARD 17 HIP_STANDARD_REQUIRED ON)
|
||||
+69
-67
@@ -1,121 +1,123 @@
|
||||
# libr4d
|
||||
|
||||
R4D is a library of specialized HIP kernels for **gfx1201 (RDNA4, Radeon AI PRO R9700)**.
|
||||
|
||||
It is built by the radiance engine, which is its only consumer: `libr4d/CMakeLists.txt` names
|
||||
every translation unit and the per-unit flags each one needs.
|
||||
libr4d is radiance's kernel library for RDNA4 (gfx12, developed on gfx1201, the Radeon AI PRO
|
||||
R9700): specialised HIP kernels behind a plain C ABI ([`r4d.h`](r4d.h)) and the kernel-plugin rows
|
||||
the engine selects from (`r4d_rows.cpp`). `libr4d/CMakeLists.txt` names every translation unit and
|
||||
the per-unit flags each needs.
|
||||
|
||||
## Naming
|
||||
|
||||
An entry point is
|
||||
|
||||
```
|
||||
<family>_<op>_<the geometry it is compiled for>
|
||||
r4d_<family>_<op>_<the geometry it is compiled for>
|
||||
```
|
||||
|
||||
and the geometry is not decoration. These are specialised kernels: every dimension in the name is a
|
||||
compile-time constant, and the entry point **rejects a mismatch rather than 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 a different head size needs a new instantiation, which gets
|
||||
its own name beside this one -- no existing name has to change to make room for it, and no caller
|
||||
can pick up a kernel that does not fit by accident.
|
||||
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
|
||||
instantiation under its own name, so no existing name changes and no caller can pick up a kernel
|
||||
that does not fit.
|
||||
|
||||
Dimensions that are the same across the whole library discriminate nothing between entry points and
|
||||
so stay out of the names: the paged block size (16), the query dtype (bf16 everywhere) and the
|
||||
target architecture. They are reported by the `r4d_*_dims()` accessors in
|
||||
[`r4d.h`](r4d.h) and by the `RadKernelInfo` rows in `r4d_rows.cpp`.
|
||||
Dimensions that are the same across the whole library stay out of the names: the paged block size
|
||||
(16), the query dtype (bf16) and the target architecture. The `r4d_*_dims()` accessors in
|
||||
[`r4d.h`](r4d.h) and the `RadKernelInfo` rows in `r4d_rows.cpp` report them.
|
||||
|
||||
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, up to 64 query rows |
|
||||
| `attn_decode_h256_gqa6_scratch_bytes` / `attn_decode_h128_gqa4_scratch_bytes` | how many bytes of split-KV scratch a given launch needs — ask before allocating; the split count is chosen from the geometry |
|
||||
| `attn_decode_h256_gqa6_fp8kv` / `..._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` | 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 |
|
||||
| `gdn_kkt_solve_k128_c64_bf16` | `A = (I + strict_lower(diag(beta) K K^T e^dg))^-1` per chunk of 64 -- the gram and its triangular inverse, without the fp32 gram ever reaching memory |
|
||||
| `gdn_chunk_scan_k128_v128_c64_bf16` | gated-delta-net chunked scan -- WY recompute, state recurrence and output in one kernel; head_k 128, head_v 128, chunk 64 |
|
||||
| `gdn_conv_prep_w4_h128_bf16` | 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 |
|
||||
| `gdn_kkt_solve_k128_c64_bf16` | `A = (I + strict_lower(diag(beta) K K^T e^dg))^-1` per chunk of 64: the gram and its triangular inverse, without the fp32 gram reaching memory |
|
||||
| `gdn_chunk_scan_k128_v128_c64_bf16` | gated-delta-net chunked scan: WY recompute, state recurrence and output in one kernel; head_k 128, head_v 128, chunk 64 |
|
||||
| `gdn_conv_update_w4_h128_bf16` | the same convolution for a decode step: a rolling speculative window over the conv state cache, writing q/k/v directly |
|
||||
| `gdn_recurrent_update_k128_v128_bf16_fp32state` | the decode-time recurrent delta-rule update against the paged fp32 state cache, gating and qk l2norm included |
|
||||
| `gdn_gated_rmsnorm_h128_bf16` | gated rms norm over a 128-channel row, `out = rms(x) . w . act(z)` |
|
||||
| `gdn_gated_rmsnorm_h128_bf16` | gated RMS norm over a 128-channel row, `out = rms(x) . w . act(z)` |
|
||||
| `ar_oneshot_2rank_exact` | one-shot push all-reduce over P2P, exactly 2 ranks, exact bf16/fp16/fp32 |
|
||||
| `ar_oneshot_2rank_wht6` | the same handshake with a Walsh-Hadamard-rotated 6-bit wire payload (lossy) |
|
||||
| `gemm_bf16_nt_m16` | skinny bf16 GEMM, `C[M,N] = A[M,K] @ W[N,K]^T`, M ≤ 16, split-K. **Superseded on every shape measured by the WMMA row below**, which the shim forwards to — its accumulators are registers indexed by row, so it falls off a cliff past 8 rows and is several times slower at M = 16. `R4D_BF16_M16=1` reaches it. |
|
||||
| `gemm_bf16_nt_m64` | the same GEMM for M ≤ 64, one 16x16x16 WMMA per row tile per 16 of K |
|
||||
| `gemm_w4a16_nt_m64` | the same GEMM with a **4-bit weight** — asymmetric scale and integer zero per 128 K, pre-permuted offline into WMMA fragment order so the weight path is one `global_load_b128` per lane per four k steps, f16 activations, bf16 out |
|
||||
| `gemm_w4a8_nt_m64` | the 4-bit weight against an **int8 activation** through `v_wmma_i32_16x16x16_iu8` — twice the matrix rate of the f16 form. Symmetric scale per 128 K; the skinny decode kernel, M ≤ 64, per-shape (WV, SK, MB, NPW, NT) bands |
|
||||
| `gemm_bf16_nt_m16` | the M ≤ 16 band (the MoE router gate), forwarded to `gemm_bf16_nt_m64`; no kernel of its own |
|
||||
| `gemm_bf16_nt_m64` | skinny bf16 GEMM, `C[M,N] = A[M,K] @ W[N,K]^T`, one 16x16x16 WMMA per row tile per 16 of K, split-K; any M, with `gemm_bf16_nt_tiled` taking M > 64 where N ≥ 128 |
|
||||
| `gemm_w4a16_nt_m64` | the same GEMM with a 4-bit weight: f16 scale and integer zero per 128 K, pre-permuted offline into WMMA fragment order so the weight path is one `global_load_b128` per lane per four k steps; f16 activations, bf16 out |
|
||||
| `gemm_w4a8_nt_m64` | the 4-bit weight against an int8 activation through `v_wmma_i32_16x16x16_iu8`, twice the matrix rate of the f16 form. Symmetric scale per 128 K; the skinny decode kernel, M ≤ 64, tunable over `wv`, `sk`, `mb`, `npw`, `nt` |
|
||||
| `gemm_w4a8_asym_nt_m64` | the same with an asymmetric grid: unsigned B fragment, per-group zero from the scale dword's high half, minus the activation's per-group row sums |
|
||||
| `gemm_w4a8_tiled` | the prefill/large-M sibling, block tile 128x256, BK=64 double-buffered through registers; variant-indexed tile table |
|
||||
| `gemm_w4a8_tiled` | the large-M sibling: block tile 128x256 by default (a `tile` axis selects other compiled arms), BK = 64 double-buffered in LDS |
|
||||
| `gemm_w4a8_asym_tiled` | the asymmetric grid at the tiled shape |
|
||||
| `gemm_w4a8_prefill` | a second large-M W4A8 kernel, outranking `gemm_w4a8_tiled` in the M > 64 band; a tuned pick that names no prefill variant falls back to the tiled one |
|
||||
| `gemm_w4a8_prefill` | a second large-M W4A8 kernel for the symmetric grid, ranked above `gemm_w4a8_tiled` |
|
||||
| `gemm_w8a8_nt_m64` | int8 weight against int8 activation, skinny; the promoted (8-bit) linears of a mixed-precision artifact |
|
||||
| `gemm_w8a8_tiled` | the prefill sibling of the above |
|
||||
| `gemm_w8a16_nt_m64` | 8-bit weight, f16 activation, skinny |
|
||||
| `gemm_w2a8_nt` | 2-bit weight against int8 activation — the fast draft head |
|
||||
| `gemm_w2a8_nt` | 2-bit weight against int8 activation: the DFlash2 draft head |
|
||||
| `gemm_mxfp4a8_nt_m64` | OCP-MXFP4 weight, fp8 activation, skinny |
|
||||
| `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_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; `attn_h128_gqa4_have_prefill()` reports 0 so a caller routes long queries to its own fallback |
|
||||
| `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 |
|
||||
| `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 |
|
||||
| `dequant_w4_bf16` | unpack a 4-bit fragment-ordered weight back to bf16 |
|
||||
| `quant_act_i8` / `quant_act_i8_asum` | per-row int8 activation quantiser, **fragment-ordered** for the r4d GEMMs (see the warning below); the `_asum` form also emits the per-group row sums the asymmetric GEMMs need |
|
||||
| `had_quant_act_i8` | the same with a block Walsh-Hadamard rotation first — the rotation is what makes one scale per row viable |
|
||||
| `dequant_w4_bf16` | unpacks a 4-bit fragment-ordered weight back to bf16 |
|
||||
| `quant_act_i8` / `quant_act_i8_asum` | per-row int8 activation quantiser, in the r4d GEMMs' fragment byte order; the `_asum` form also emits the per-group row sums the asymmetric GEMMs need |
|
||||
| `had_quant_act_i8` | the same with a block Walsh-Hadamard rotation first, which is what makes one scale per row viable |
|
||||
| `rmsnorm_had_quant_i8` | residual add, RMS norm, rotate and quantise in one kernel |
|
||||
| `ar_ln_had_quant_i8` | **the all-reduce and the norm that always follows it, fused**: the peer's contribution is a second operand on the norm's load, so the all-reduce's bf16 output never exists. Exact bf16 or rotated 6-bit wire (`wire`) |
|
||||
| `ar_ln_had_quant_i8` | the all-reduce fused with the norm that follows it: the peer's contribution is a second operand on the norm's load, so the all-reduce's bf16 output never exists. Exact bf16 or rotated 6-bit wire (`wire`) |
|
||||
| `gated_had_quant_i8` | `silu(a)*b` or `sigmoid(a)*b`, then the same rotation and quantiser |
|
||||
| `gdn_gated_norm_had_quant_i8` | the gdn gated norm with the rotation and quantiser fused onto it |
|
||||
| `qk_norm_rope_gate` | q/k rms-norm, rope and the attention gate in one kernel |
|
||||
| `gdn_gated_norm_had_quant_i8` | the GDN gated norm with the rotation and quantiser fused onto it |
|
||||
| `qk_norm_rope_gate` | q/k RMS norm, rope and the attention gate in one kernel |
|
||||
| `ar_oneshot_{3,4,8}rank_exact`, `ar_twoshot_{3,4,8}rank_exact`, `ar_twoshot_{3,4}rank_ti8`, `ar_gather_3rank` | the wider-world collectives (TP3/TP4/TP8), exact and int8-wire |
|
||||
| `p2p_copy2d`, `p2p_copy2d_kernel`, `p2p_fence` | strided peer device-to-device copy, through the copy engines or a kernel |
|
||||
## Asking the library instead of remembering
|
||||
|
||||
A geometry could be written down three times: in the entry point's name, in the check the entry
|
||||
point rejects a mismatch on, and again in whatever caller decided it was allowed to make the call.
|
||||
The third copy is the one that drifts, so the constraints are DATA rather than prose, and they live
|
||||
where the answers are used rather than in this library's own registry.
|
||||
## Constraints as data
|
||||
|
||||
`libr4d/r4d_rows.cpp` carries one `RadKernelInfo` row per kernel, with its geometry written as
|
||||
`RadConstraint`s as well as in prose, and the engine's selector reads those rows to decide which
|
||||
kernel serves a band — so a caller never has to know a geometry in order to ask for one.
|
||||
`rad-kbench` tests the rows against the reference kernels, and `r4d_selftest` calls every launch
|
||||
with a minimal valid input, which is how a transcription error in a constraint is found.
|
||||
A geometry is stated in the entry point's name and in the check that rejects a mismatch. A third
|
||||
copy in each caller would drift, so the constraints are data in the rows the engine reads.
|
||||
|
||||
The kernels themselves are plain HIP behind the C ABI in [`r4d.h`](r4d.h) and know nothing about
|
||||
any of that.
|
||||
`r4d_rows.cpp` carries one `RadKernelInfo` row per kernel, its geometry written as `RadConstraint`s
|
||||
as well as in prose, and the engine's selector reads those rows to choose the kernel for a band; a
|
||||
caller never needs to know a geometry to ask for one. `rad-kbench` tests the rows against the
|
||||
reference kernels, and `r4d_selftest` calls every launch with a minimal valid input, which catches
|
||||
a transcription error in a constraint.
|
||||
|
||||
The kernels themselves are plain HIP behind the C ABI in [`r4d.h`](r4d.h) and know nothing of the
|
||||
rows.
|
||||
|
||||
## Building
|
||||
|
||||
There is no build here. `libr4d/CMakeLists.txt` is it -- see the engine's `build.sh`.
|
||||
libr4d builds inside radiance's tree (see `build.sh`) or on its own against an installed radiance
|
||||
(`cmake -S libr4d -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`). It is skipped when the build
|
||||
targets no gfx12 architecture.
|
||||
|
||||
Translation units are compiled separately and linked, so per-kernel target features stay scoped:
|
||||
`-mcumode` applies to `r4d_gdn_chunk_scan_k128_v128_c64_bf16.o` alone, and `-ffp-contract=off` is
|
||||
global because the rotated 6-bit all-reduce requires it (the two ranks fuse different products
|
||||
otherwise and diverge by ~1 ULP).
|
||||
Translation units are compiled separately and linked, so per-kernel flags stay scoped: `-mcumode`
|
||||
applies to `r4d_gdn_chunk_scan_k128_v128_c64_bf16` alone. `-ffp-contract=off` applies to every unit
|
||||
because the quantised all-reduce requires it: otherwise the two ranks fuse different products and
|
||||
diverge by about 1 ULP.
|
||||
|
||||
## Adding a kernel
|
||||
|
||||
1. Write the `.hip`; name the entry point for what it computes and the geometry it is compiled for.
|
||||
2. Declare it in `r4d.h`, and add a `_dims()` accessor if it has compiled-in geometry a caller
|
||||
should be able to read.
|
||||
3. Name the file after the entry point, geometry included; only shared machinery (`r4d_common.h`,
|
||||
`r4d_dt16.h`, `r4d_gdn_wmma.h`) is named for what it is, because it provides no kernel.
|
||||
3. Name the file after the entry point, geometry included. Only shared machinery that provides no
|
||||
kernel (`r4d_common.h`, `r4d_dt16.h`, `r4d_gdn_wmma.h`) is named for what it is.
|
||||
4. Add the translation unit to `R4D_UNITS` in `libr4d/CMakeLists.txt`, with any per-unit flags.
|
||||
5. Add a `RadKernelInfo` row in `libr4d/r4d_rows.cpp` and a shim beside it -- that row is what
|
||||
the engine's selector reads, so a kernel that is not in it is one no model can resolve to. Give
|
||||
it the `op` of the operation it implements, which it may share with other rows, and write its
|
||||
geometry as constraints as well as prose.
|
||||
6. Add a case to `libr4d/r4d_selftest.cpp` so the row is called at least once.
|
||||
5. Add a `RadKernelInfo` row in `libr4d/r4d_rows.cpp` whose launch is the
|
||||
`(const RadArgs*, RadStream)` entry beside the kernel. The selector reads only these rows, so a
|
||||
kernel without one cannot be resolved. Give it the `op` it implements (rows may share one) and
|
||||
write its geometry as constraints as well as prose.
|
||||
6. Add a case to `libr4d/r4d_selftest.cpp` so the row is called at least once; a row without one
|
||||
reports `no smoke case`.
|
||||
|
||||
## Notes for anyone reading the kernels
|
||||
## Notes on the kernels
|
||||
|
||||
Three properties of this architecture are assumed throughout and are not restated per kernel:
|
||||
Three properties of the architecture are assumed throughout and not restated per kernel:
|
||||
|
||||
* The wave32 WMMA fragment layout is `idx = lane % 16`, `k = 8*(e>>2) + 4*(lane>>4) + (e&3)`. Both
|
||||
A and B want K-contiguous rows, so swapping the operands of a WMMA transposes the result for free.
|
||||
* gfx1201 has no `v_cvt_pk_bf16_f32`, no direct-to-LDS, and no `ds_read_b64_tr_b16`. Packing bf16 is
|
||||
software, and the cheapest form is two adds plus a `v_perm_b32`.
|
||||
* LLVM single-buffers LDS and drains before every WMMA unless you tell it not to.
|
||||
`__builtin_amdgcn_sched_group_barrier` is the fix, and the granularity of the groups matters far
|
||||
more than their contents -- coarser is better, up to the point where the pattern asks for more
|
||||
A and B want K-contiguous rows, so swapping the operands of a WMMA transposes the result.
|
||||
* gfx1201 has no `v_cvt_pk_bf16_f32`, no direct-to-LDS and no `ds_read_b64_tr_b16`. Packing bf16 is
|
||||
software; the cheapest form is two adds plus a `v_perm_b32`.
|
||||
* LLVM single-buffers LDS and drains before every WMMA unless told otherwise.
|
||||
`__builtin_amdgcn_sched_group_barrier` fixes it, and the granularity of the groups matters more
|
||||
than their contents: coarser is better, up to the point where the pattern asks for more
|
||||
outstanding loads than the hardware can hold.
|
||||
+75
-81
@@ -1,10 +1,9 @@
|
||||
# libr4d/isa -- reading the machine code the kernels actually became
|
||||
# libr4d/isa: reading the machine code the kernels became
|
||||
|
||||
Seven scripts and four microbenchmarks. They exist because "this kernel is slow" and "this kernel
|
||||
is at the wall" look identical from a wall-clock timer, while the disassembly plus one calibration
|
||||
number tells them apart without a GPU run at all. The trace tools are the exception: they need the
|
||||
GPU, and they are the only instruments here that report the geometry a kernel was ACTUALLY launched
|
||||
with rather than the geometries it could have been.
|
||||
Nine scripts and four microbenchmarks. A wall-clock timer cannot tell "this kernel is slow" from
|
||||
"this kernel is at the memory wall"; the disassembly plus one calibration number can, without a GPU
|
||||
run. The trace tools are the exception: they need the GPU, and they are the only instruments here
|
||||
that report the geometry a kernel was launched with rather than every geometry it could have had.
|
||||
|
||||
BUILD=/path/to/build ./res.sh | head -40 # every kernel: vgpr/lds/scratch
|
||||
BUILD=... ./dis.sh r4d_gemm_fp8a8 ILb1ELb0ELj8ELj1ELj8ELj64ELb0E
|
||||
@@ -12,123 +11,118 @@ with rather than the geometries it could have been.
|
||||
./loop.sh # its K loop, classified
|
||||
./trace.sh traces/dec -- ./bin/radiance ... # then: ./tsum.sh traces/dec/k_kernel_trace.csv
|
||||
|
||||
`res.sh` prints the mangled name; the substring `dis.sh` takes is a template instantiation out of
|
||||
it, and the parameter order is in the kernel's own declaration (`gemm_fp8a8_kernel` is
|
||||
`<Full, AW, NT, MT, MW, FK, GATED>`, so `ILb1ELb0ELj8ELj1ELj8ELj64ELb0E` is the prefill tile).
|
||||
`loop.sh` anchors on `v_wmma` by default and takes the SMALLEST backward branch containing every
|
||||
anchor -- a plain largest-loop search finds the epilogue, which is a long unrolled store chain.
|
||||
`res.sh` prints mangled names; the substring `dis.sh` takes picks one template instantiation, and
|
||||
the parameter order is in the kernel's declaration (`gemm_fp8a8_kernel` is
|
||||
`<Full, AW, NT, MT, MW, FK, GATED, I8>`, so `ILb1ELb0ELj8ELj1ELj8ELj64ELb0E` is the prefill tile).
|
||||
`loop.sh` anchors on `v_wmma` by default and takes the smallest backward branch containing every
|
||||
anchor, because a largest-loop search finds the epilogue, a long unrolled store chain.
|
||||
|
||||
## The tools
|
||||
## Tools
|
||||
|
||||
| tool | what it answers |
|
||||
|---|---|
|
||||
| `co.sh` | extracts the gfx1201 code object out of one built `.hip.o`; everything else reads that |
|
||||
| `dis.sh` | disassembles ONE template instantiation out of one translation unit |
|
||||
| `co.sh` | extracts the gfx1201 code object from one built `.hip.o`; the other scripts read that |
|
||||
| `dis.sh` | disassembles one template instantiation from one translation unit |
|
||||
| `loop.sh` | isolates the working loop of that disassembly and classifies its body by instruction class |
|
||||
| `res.sh` | one row per device kernel in a build tree: VGPRs, SGPRs, LDS, scratch, spills, waves a SIMD, workgroup size |
|
||||
| `waterfall.sh` | every kernel that indexes a VGPR array with an index the compiler could not prove uniform |
|
||||
| `trace.sh` | runs a command under `rocprofv3 --kernel-trace` and leaves a CSV |
|
||||
| `tsum.sh` | summarises that CSV over a steady-state window: where device time goes, per (kernel, grid) |
|
||||
| `gaps.sh` | the other half -- where the device is IDLE, and which op it was waiting for |
|
||||
| `gaps.sh` | where the device is idle, and which op it was waiting for |
|
||||
| `rskew.sh` | per-kernel device time on each agent, and the skew between ranks |
|
||||
| `isarate.hip` | what one instruction slot is worth on gfx1201 (below) |
|
||||
| `graphrate.hip` | what a dispatch costs the HOST to submit, and what capturing a fixed sequence saves |
|
||||
| `graphrate.hip` | what a dispatch costs the host to submit, and what capturing a fixed sequence saves |
|
||||
| `launchreg.hip` + `launchreg_lib.hip` | whether a launch costs more when the module registers more kernels, and what crossing into a `.so` costs |
|
||||
| `blockcopy.hip` | contiguous versus scattered device-to-host copy, at KV-block granularity |
|
||||
|
||||
Each script's own header states its traps and how to read its output. The microbenchmarks are built
|
||||
by hand; the command line is in each file's header, and `build_launchreg.sh` builds the two-object
|
||||
pair the registration test needs.
|
||||
Each script's header states its traps and how to read its output. The microbenchmarks are built by
|
||||
hand: `clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 <name>.hip -o <name>` for `isarate`,
|
||||
`graphrate` and `blockcopy`, and `build_launchreg.sh` for the two-object launchreg pair.
|
||||
|
||||
## What an instruction slot is worth on gfx1201
|
||||
## Instruction slot cost on gfx1201
|
||||
|
||||
`isarate.hip` runs each instruction back to back in eight independent chains, so nothing stalls but
|
||||
issue. The ratio it reports is clock-independent, which is why it reads no clock.
|
||||
`isarate.hip` runs each instruction back to back in eight independent chains, so nothing stalls
|
||||
but issue. It reports a ratio, which is clock-independent, so it reads no clock.
|
||||
|
||||
**One `v_wmma_f32_16x16x16_fp8_fp8` costs about 12.9 plain VALU issue slots**, and that does not
|
||||
change when 36 KiB of LDS holds occupancy down to what a real prefill tile gets (at that occupancy
|
||||
it measures nearer 11.6, for a peak of about 434 TFLOP/s). So a kernel's ceiling is
|
||||
One `v_wmma_f32_16x16x16_fp8_fp8` costs about 12.9 plain VALU issue slots, and this holds with
|
||||
36 KiB of LDS limiting occupancy to what a real prefill tile gets (there it measures nearer 11.6,
|
||||
for a peak of about 434 TFLOP/s). A kernel's ceiling is therefore
|
||||
|
||||
TFLOP/s = 434 * wmma_slots / (wmma_slots + other_instructions_issued)
|
||||
|
||||
with `wmma_slots = 12.9 * (wmma count)`, both counts per loop iteration out of `loop.sh`.
|
||||
with `wmma_slots = 12.9 * (wmma count)`, both counts per loop iteration from `loop.sh`.
|
||||
|
||||
**It is a CEILING and not a prediction**, and the difference matters: a kernel cannot beat it, and a
|
||||
kernel far under it is under it for some other reason that then has to be found. Issue is frequently
|
||||
not the binding constraint. Cutting a kernel's non-WMMA instruction count by more than half can make
|
||||
it SLOWER, because the removed work was covering memory and LDS latency and its removal raises
|
||||
register pressure; and a memory-bound kernel moves by about a percent under the same cut. Use the
|
||||
model to rule a lever out, not to predict a gain.
|
||||
This is a ceiling, not a prediction. A kernel cannot beat it, and a kernel far below it is held
|
||||
back by something else. Issue is often not the binding constraint: cutting a kernel's non-WMMA
|
||||
instruction count by more than half can make it slower, because the removed work was covering
|
||||
memory and LDS latency and its removal raises register pressure, and a memory-bound kernel moves by
|
||||
about a percent under the same cut. Use the model to rule a lever out, not to predict a gain.
|
||||
|
||||
gfx1201 has **no dense 16x16x32 fp8 WMMA** -- `llvm-mc -mcpu=gfx1201` rejects it. The only 32-deep
|
||||
fp8 form is `v_swmmac_f32_16x16x32_fp8_fp8`, which is the 2:4 sparse one. The GEMMs here are already
|
||||
on the widest dense op that exists.
|
||||
gfx1201 has no dense 16x16x32 fp8 WMMA (`llvm-mc -mcpu=gfx1201` rejects it). The only 32-deep fp8
|
||||
form is `v_swmmac_f32_16x16x32_fp8_fp8`, the 2:4 sparse one, so the GEMMs here already use the
|
||||
widest dense op there is.
|
||||
|
||||
## The profiler: what works and what does not
|
||||
## The profiler
|
||||
|
||||
`rocprofv3 --pmc` does not work on this platform. Any counter set, any kernel filter, on this tree
|
||||
or on `isarate` alone: it collects, then hangs in `queue.cpp:939 Timeout while waiting for queue
|
||||
sync: 1 kernels still active` and aborts on SIGABRT. **There are no hardware counters**, so the
|
||||
dynamic instruction count is not directly observable -- `loop.sh` plus knowing which blocks are
|
||||
`rocprofv3 --pmc` does not work on this platform. With any counter set and any kernel filter, on
|
||||
this tree or on `isarate` alone, it collects, then hangs in `queue.cpp:939 Timeout while waiting
|
||||
for queue sync: 1 kernels still active` and aborts on SIGABRT. There are no hardware counters, so
|
||||
the dynamic instruction count is not directly observable; `loop.sh` plus knowing which blocks are
|
||||
predicated is how to get it.
|
||||
|
||||
`--kernel-trace` works, unmasked. The abort that names an unsupported agent
|
||||
`--kernel-trace` works without masking any device. The abort that names an unsupported agent
|
||||
|
||||
rocprofiler_iterate_agent_supported_counters failed for agent 3 (gfx1036)
|
||||
:: Agent HW architecture is not supported, no counter metrics found.
|
||||
|
||||
is **counter** enumeration and appears only under `--pmc`. It names a display GPU integrated on the
|
||||
CPU, which has no counter support; masking it does not make `--pmc` work, and `--kernel-trace` never
|
||||
needed it masked. `trace.sh` sets `ROCR_VISIBLE_DEVICES=0,1` only to pin the agent set and keep that
|
||||
line out of the log.
|
||||
comes from counter enumeration and appears only under `--pmc`. It names an integrated display GPU,
|
||||
which has no counter support; masking it does not make `--pmc` work. `trace.sh` sets
|
||||
`ROCR_VISIBLE_DEVICES=0,1` when it is unset, only to pin the agent set and keep that line out of
|
||||
the log. It runs `$ROCM/bin/rocprofv3`, with `ROCM` defaulting to `/opt/rocm`.
|
||||
|
||||
`rocprofv3` is not on `PATH`; it is `/opt/rocm/bin/rocprofv3`.
|
||||
|
||||
**A killed `rocprofv3` leaves a zombie that outlives its own `timeout`.** The hang is in
|
||||
finalisation, after the alarm has fired, so the child ignores the timeout and sits in queue-sync
|
||||
indefinitely. It does not hold CUs, so it does not poison a timing measurement -- but it does hold
|
||||
VRAM, which makes the *next* tool report allocation failures that read like miscompiled kernels.
|
||||
Always follow a `--pmc` attempt with `pkill -9 -f rocprofv3`; `trace.sh` does this itself.
|
||||
**A killed `rocprofv3` can outlive its own `timeout`.** The hang is in finalisation, after the
|
||||
alarm has fired, so the child ignores the timeout and waits in queue sync indefinitely. It holds no
|
||||
CUs, so it does not disturb a timing, but it holds VRAM, so the next tool reports allocation
|
||||
failures that look like miscompiled kernels. Follow a `--pmc` attempt with `pkill -9 -f rocprofv3`;
|
||||
`trace.sh` does this itself.
|
||||
|
||||
### Reading a trace
|
||||
|
||||
* Tracing costs about 2 us per dispatch per RANK. The ranks are separate host threads and inflate in
|
||||
parallel, so per-rank dispatches are what count, not the total.
|
||||
* Kernel **durations** are hardware timestamps and do not move under tracing. The **gaps** absorb the
|
||||
whole interception cost, so busy time is real and idle time is an upper bound. `tsum.sh` does that
|
||||
subtraction and prints both.
|
||||
* Generated text does not change under tracing, so a traced run can be pointed at a real serving
|
||||
* Tracing costs about 2 us per dispatch per rank. The ranks are separate host threads and slow down
|
||||
in parallel, so per-rank dispatch counts are what matter, not the total.
|
||||
* Kernel durations are hardware timestamps and do not change under tracing. The gaps absorb the
|
||||
whole interception cost, so busy time is real and idle time is an upper bound. `tsum.sh` does
|
||||
that subtraction and prints both.
|
||||
* Generated text does not change under tracing, so a traced run can use a real serving
|
||||
configuration rather than a proxy.
|
||||
* **Busy is not utilisation, and this is the easiest number here to misread.** A dispatch counts as
|
||||
busy if it is resident at all, so a 5 us kernel holding 1 of 64 CUs reads exactly like a GEMM
|
||||
saturating the card. "96% busy" says the step is almost never *waiting* for a launch. It says
|
||||
nothing about occupancy -- for that, read the blocks column, where anything under ~64 cannot fill
|
||||
the device however long it runs.
|
||||
* **A trace can go quiet and still look complete.** A run that idles before its workload records the
|
||||
startup and nothing else, and the CSV is well formed either way. Send the workload the moment
|
||||
* Busy is not utilisation. A dispatch counts as busy if it is resident at all, so a 5 us kernel on
|
||||
1 of 64 CUs reads the same as a GEMM saturating the card. "96% busy" says the step is almost never
|
||||
waiting for a launch, nothing about occupancy; for that, read the blocks column, where anything
|
||||
under ~64 cannot fill the device however long it runs.
|
||||
* A trace can go quiet and still look complete. A run that idles before its workload records the
|
||||
startup and nothing else, and the CSV is well formed either way. Send the workload as soon as
|
||||
health answers, keep the run short, and check `dispatches/step` in `tsum.sh`'s header against what
|
||||
the model should issue before believing any table built from it.
|
||||
the model should issue before trusting any table built from it.
|
||||
|
||||
## What the instruments say in general
|
||||
## General results
|
||||
|
||||
Two results recur often enough to be worth stating up front, because they decide which levers are
|
||||
worth pulling at all.
|
||||
Two results recur and decide which levers are worth pulling.
|
||||
|
||||
**Every dispatch costs a few microseconds before it does anything.** Across the shapes a decode step
|
||||
asks the narrow fp8 GEMM for, the time is not six different rates but one line,
|
||||
**Every dispatch has a fixed cost of a few microseconds.** Across the shapes a decode step asks of
|
||||
the narrow fp8 GEMM, the time follows one line,
|
||||
|
||||
t = fixed + bytes / achievable_stream_rate
|
||||
|
||||
with a fixed term of roughly 4.5 us and a stream rate near the card's achievable bandwidth. The same
|
||||
fixed cost shows on every small op -- rmsnorm, quant_act, add, gated_quant -- whatever it moves. So
|
||||
a "slow" small shape is usually a fixed cost failing to amortise, not a kernel with bandwidth left
|
||||
in it, and **fewer kernels** is the only lever that reaches it.
|
||||
fixed cost shows on every small op (rmsnorm, quant_act, add, gated_quant) whatever it moves. A
|
||||
"slow" small shape is usually a fixed cost that does not amortise, not a kernel with bandwidth left,
|
||||
and fewer kernels is the only lever that reaches it.
|
||||
|
||||
**Most of the weight-streaming kernels are at the memory wall.** A narrow GEMM whose K loop issues a
|
||||
few hundred instructions per few kilobytes of weight per wave has roughly four times more issue
|
||||
capacity than the card has bandwidth, and measures at the achievable stream rate. Assembly-level
|
||||
work on such a kernel is not worth doing; confirm the reading with `loop.sh` before spending any.
|
||||
**Most weight-streaming kernels are at the memory wall.** A narrow GEMM whose K loop issues a few
|
||||
hundred instructions per few kilobytes of weight per wave has about four times more issue capacity
|
||||
than the card has bandwidth, and runs at the achievable stream rate. Assembly-level work on such a
|
||||
kernel does not pay; confirm with `loop.sh` before starting.
|
||||
|
||||
**Read the kernel's own header before proposing anything about it.** Each hot kernel's source
|
||||
carries its own ablations, sweeps and rejected arms with the reason each was rejected, and the
|
||||
answer to most assembly-level ideas is already recorded there.
|
||||
**Read a kernel's own header before proposing changes to it.** Each hot kernel's source records
|
||||
its ablations, sweeps and rejected variants with the reason for each, and most assembly-level ideas
|
||||
are already answered there.
|
||||
@@ -1,13 +1,7 @@
|
||||
// WHAT A SCATTERED KV EVICTION COSTS.
|
||||
//
|
||||
// Pricing a host-tiered prefix cache from a bulk device-to-host bandwidth figure assumes the
|
||||
// context moves as ONE transfer. It does not: the prefix cache is block-granular, the blocks are
|
||||
// scattered through the paged pool, and a long context is many thousands of them. A scattered copy
|
||||
// is a different machine from a contiguous one, and any such estimate rests on which one it is.
|
||||
//
|
||||
// So: one contiguous copy of N*B bytes, against N separate copies of B bytes from scattered
|
||||
// offsets, against N copies issued back-to-back on one stream (the batched form a real eviction
|
||||
// would use).
|
||||
// Cost of a scattered KV eviction. The prefix cache is block-granular and its blocks are scattered
|
||||
// through the paged pool, so a bulk device-to-host bandwidth figure does not price it. Compares one
|
||||
// contiguous copy of N*B bytes, N copies of B bytes from scattered offsets with a sync after each,
|
||||
// and the same N copies issued back-to-back on one stream (the batched form an eviction would use).
|
||||
//
|
||||
// clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 blockcopy.hip -o blockcopy
|
||||
#include <hip/hip_runtime.h>
|
||||
@@ -35,8 +29,7 @@ int main(int argc, char** argv) {
|
||||
if (hipHostMalloc(&host, (size_t)bytes) != hipSuccess) { std::printf("hipHostMalloc failed\n"); return 1; }
|
||||
hipStream_t s; hipStreamCreate(&s);
|
||||
|
||||
/* SCATTERED, not sequential: a real pool hands out blocks in whatever order they were freed,
|
||||
* so the eviction walks them in an order uncorrelated with address. */
|
||||
/* Shuffled order: a pool hands out blocks in free order, uncorrelated with address. */
|
||||
std::vector<long long> order((size_t)n);
|
||||
for (long long i = 0; i < n; ++i) order[(size_t)i] = i;
|
||||
unsigned seed = 12345;
|
||||
|
||||
+38
-53
@@ -1,30 +1,25 @@
|
||||
// WHAT A DISPATCH COSTS THE HOST TO SUBMIT, and what capturing a fixed sequence saves.
|
||||
// Host cost of submitting a dispatch, and what capturing a fixed sequence saves.
|
||||
//
|
||||
// Capture is usually priced against the DEVICE-side gap between dependent kernels, which on this
|
||||
// part is well under a microsecond and not worth chasing. That is the wrong question for the MTP
|
||||
// draft loop. There the HOST is on the critical path: every pass embeds the token the previous
|
||||
// pass sampled, so nothing overlaps the submit, and the device sits idle for the whole of it. The
|
||||
// trunk never pays that, because it runs well over a thousand dispatches ahead of the device.
|
||||
// The device-side gap between dependent kernels is well under a microsecond on this part. In the
|
||||
// MTP draft loop the host is on the critical path instead: each pass embeds the token the previous
|
||||
// pass sampled, so nothing overlaps the submit and the device idles through it. The trunk runs
|
||||
// over a thousand dispatches ahead of the device and never pays this. So this times the submit
|
||||
// loop itself, separate from the sync.
|
||||
//
|
||||
// So this measures the HOST half: the wall time of the submit loop itself, separated from the sync.
|
||||
// Every arm runs once per iteration in one loop: clock and scheduler drift between runs exceeds
|
||||
// the differences being measured.
|
||||
//
|
||||
// EVERY ARM RUNS ONCE PER ITERATION, IN ONE LOOP. Clock and scheduler state drift between runs by
|
||||
// more than the differences being measured, so arms taken in sequence are not comparable to each
|
||||
// other; sharing one loop is what makes them comparable.
|
||||
//
|
||||
// individual 45 separate hipLaunchKernelGGL, one per op, as an uncaptured pass issues them.
|
||||
// graph one captured graph replayed. The floor, and unreachable: the pass is not static.
|
||||
// individual 45 separate hipLaunchKernelGGL, as an uncaptured pass issues them.
|
||||
// graph one captured graph replayed. The floor; unreachable, since the pass is not static.
|
||||
// graph+Kset replay after rewriting K nodes. About ten of the draft pass's 45 issues move an
|
||||
// operand pointer every step, and three of those (qsa_work, qsa_score, qsa_select)
|
||||
// also move a SHAPE, because the QSA extents grow with context and no arena
|
||||
// discipline makes them stand still. This is the shape a real implementation has.
|
||||
// graph+Kg+s the same with the params READ BACK from the node first, because the engine holds
|
||||
// no launch geometry of its own -- the shim marshals its own kernel arguments and
|
||||
// the runtime never sees the signature. If this costs what Kset costs, that
|
||||
// ignorance is free and the design needs no ABI change.
|
||||
// operand pointer every step, and three (qsa_work, qsa_score, qsa_select) also
|
||||
// move a shape, because the QSA extents grow with context.
|
||||
// graph+Kg+s the same, reading the params back from the node first, because the engine holds
|
||||
// no launch geometry (the shim marshals its own arguments). If this costs what
|
||||
// Kset costs, no ABI change is needed.
|
||||
// recap+updat re-issue the whole pass under capture and hipGraphExecUpdate the exec. Needs no
|
||||
// knowledge of which arg slot moved at all, so it is the smallest engine change --
|
||||
// if appending a node is cheap enough to pay for itself.
|
||||
// knowledge of which arg moved, so it is the smallest engine change, if appending
|
||||
// nodes is cheap enough.
|
||||
//
|
||||
// clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 graphrate.hip -o graphrate
|
||||
// ./graphrate 45 300 10
|
||||
@@ -38,11 +33,9 @@
|
||||
|
||||
__global__ void tiny(float* p) { if (threadIdx.x == 0) p[blockIdx.x] = 1.0f; }
|
||||
|
||||
/* THE SAME KERNEL WITH A REAL ARGUMENT LIST. An engine issue costs several times what `tiny`
|
||||
* above submits in, and the difference has two possible homes: HIP marshalling more arguments, or
|
||||
* the plugin shim's own prologue (band checks, grid derivation, the switch that picks a template
|
||||
* instantiation). They call for completely different work, so they have to be told apart. This
|
||||
* signature is r4d_qsa_score_bf16's, argument for argument: six pointers and nine scalars. */
|
||||
/* `tiny` with a real argument list, to separate HIP's argument marshalling from the shim's own
|
||||
* prologue (band checks, grid derivation, template switch) as the cause of an engine issue costing
|
||||
* several times `tiny`. The signature matches r4d_qsa_score_bf16: six pointers, nine scalars. */
|
||||
__global__ void fat(const float* q, const float* bk, const int* bt, const int* cu, const int* nc,
|
||||
float* out, int n, int heads, int nb, int nseq, int bpw, int q_ld, int bk_ld,
|
||||
int bt_ld, int out_ld) {
|
||||
@@ -50,12 +43,10 @@ __global__ void fat(const float* q, const float* bk, const int* bt, const int* c
|
||||
out[blockIdx.x] = (float)(n + heads + nb + nseq + bpw + q_ld + bk_ld + bt_ld + out_ld);
|
||||
}
|
||||
|
||||
/* A kernel SLOW ENOUGH TO BACK THE QUEUE UP. Every arm above syncs each iteration, so the command
|
||||
* ring is always empty and a submit only ever costs what the runtime spends writing it. A serving
|
||||
* engine is not in that state: the host runs far ahead of a device that is nearly always busy, and
|
||||
* a submit into a FULL ring waits for the device to retire a slot. If backpressure is what an
|
||||
* engine's launch cost actually is, then the shim prologue is not the story and no amount of
|
||||
* host-side tidying moves it. */
|
||||
/* Slow enough to back the queue up. The other arms sync each iteration, so the command ring is
|
||||
* empty and a submit costs only the runtime's write. A serving engine runs far ahead of a busy
|
||||
* device, and a submit into a full ring waits for the device to retire a slot; if that dominates,
|
||||
* host-side shim tidying cannot help. */
|
||||
__global__ void slow(float* p, int n) {
|
||||
float a = (float)threadIdx.x;
|
||||
for (int i = 0; i < n; ++i) a = fmaf(a, 1.0000001f, 1.0f);
|
||||
@@ -67,7 +58,7 @@ static double us_since(clk::time_point a, clk::time_point b) {
|
||||
return std::chrono::duration<double, std::micro>(b - a).count();
|
||||
}
|
||||
|
||||
/* The median, not the mean: one descheduled iteration is worth thirty clean ones to a mean. */
|
||||
/* Median, not mean: a single descheduled iteration skews a mean. */
|
||||
static double med(std::vector<double>& v) {
|
||||
if (v.empty()) return 0.0;
|
||||
std::sort(v.begin(), v.end());
|
||||
@@ -113,9 +104,8 @@ int main(int argc, char** argv) {
|
||||
std::vector<double> a_ind, a_fat, a_err, a_gra, a_set, a_gs, a_rec, a_cap, a_upd;
|
||||
a_ind.reserve(iters);
|
||||
|
||||
/* Warm the clocks, the runtime's lazy module load, and every path below. The cards
|
||||
* idle-suspend, so a timed loop that starts cold reads the governor ramping rather than the
|
||||
* steady-state rate -- worth most of a factor of two. */
|
||||
/* Warm the clocks, the runtime's lazy module load and every path below. The cards
|
||||
* idle-suspend, and a cold start times the clock governor ramping (up to ~2x). */
|
||||
for (int w = 0; w < 400; ++w) {
|
||||
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(tiny, dim3(1), dim3(64), 0, s, d);
|
||||
for (int i = 0; i < N; ++i)
|
||||
@@ -134,10 +124,9 @@ int main(int argc, char** argv) {
|
||||
hipGraphDestroy(g2);
|
||||
}
|
||||
|
||||
/* FOUR GRAPHS OVER THE SAME 45 NODES, because that is the shape the real pass has: three
|
||||
* all-reduces and a gather cut it into segments, and a graph launch costs about the same
|
||||
* whatever it contains. Whether that fixed cost, paid once per segment, eats the whole saving
|
||||
* is what decides whether capturing the pass pays at all. */
|
||||
/* Four graphs over the same 45 nodes: three all-reduces and a gather cut the real pass into
|
||||
* segments. A graph launch has a roughly fixed cost whatever it contains, paid per segment,
|
||||
* and that may eat the saving. */
|
||||
hipGraphExec_t gef[4] = {nullptr, nullptr, nullptr, nullptr};
|
||||
{
|
||||
const int seg[4] = {3, 17, 13, 12};
|
||||
@@ -161,10 +150,8 @@ int main(int argc, char** argv) {
|
||||
hipStreamSynchronize(s);
|
||||
a_ind.push_back(us_since(t0, t1));
|
||||
|
||||
/* ---- fifteen arguments, with the error check libr4d puts after every launch. There are
|
||||
* dozens of those call sites across the library and a single op's path can make several of
|
||||
* them. If hipGetLastError is a cheap TLS read this arm sits on top of the one above; if
|
||||
* it is not, it is a tax on every dispatch in the library. */
|
||||
/* ---- fifteen arguments plus the hipGetLastError check libr4d makes after every launch;
|
||||
* one op's path can make several. Prices that check against the plain 15-argument arm. */
|
||||
t0 = clk::now();
|
||||
for (int i = 0; i < N; ++i) {
|
||||
hipLaunchKernelGGL(fat, dim3(1), dim3(64), 0, s, d, d, (const int*)d,
|
||||
@@ -175,10 +162,9 @@ int main(int argc, char** argv) {
|
||||
hipStreamSynchronize(s);
|
||||
a_err.push_back(us_since(t0, t1));
|
||||
|
||||
/* ---- fifteen arguments through hipLaunchKernel + kernelParams: EXACTLY what a shim's
|
||||
* R4D_EMIT does on its LAUNCH path. Every ordinary dispatch pays this while a graph only
|
||||
* pays back on replay, so if this sits above `fat` the kernelParams path costs the normal
|
||||
* path more than it can save the captured one. */
|
||||
/* ---- fifteen arguments through hipLaunchKernel + kernelParams, as R4D_EMIT's launch path
|
||||
* does. Every ordinary dispatch pays this while a graph only pays back on replay, so if
|
||||
* it costs more than `fat` it loses more on the normal path than it saves on capture. */
|
||||
t0 = clk::now();
|
||||
for (int i = 0; i < N; ++i) {
|
||||
void* pv[15];
|
||||
@@ -202,7 +188,7 @@ int main(int argc, char** argv) {
|
||||
hipStreamSynchronize(s);
|
||||
a_fat.push_back(us_since(t0, t1));
|
||||
|
||||
/* ---- the same 45 nodes as FOUR graphs, plus the five dispatches the cuts leave behind */
|
||||
/* ---- the same 45 nodes as four graphs, plus the five dispatches the cuts leave behind */
|
||||
t0 = clk::now();
|
||||
for (int q = 0; q < 4; ++q) hipGraphLaunch(gef[q], s);
|
||||
for (int i = 0; i < 5; ++i) hipLaunchKernelGGL(tiny, dim3(1), dim3(64), 0, s, d);
|
||||
@@ -258,15 +244,14 @@ int main(int argc, char** argv) {
|
||||
a_rec.push_back(us_since(t0, t1));
|
||||
}
|
||||
|
||||
/* ---- SUBMIT UNDER BACKPRESSURE. The same launch, but the device cannot keep up, so the ring
|
||||
* fills and stays full. Reported per dispatch against the empty-ring arms above. */
|
||||
/* ---- Submit under backpressure: the device cannot keep up, so the ring stays full. */
|
||||
std::vector<double> a_bp;
|
||||
for (int w = 0; w < 20; ++w) {
|
||||
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(slow, dim3(8), dim3(256), 0, s, d, 4000);
|
||||
hipStreamSynchronize(s);
|
||||
}
|
||||
for (int it = 0; it < iters; ++it) {
|
||||
/* Do NOT sync: let the queue stay deep across iterations, the way a decode step does. */
|
||||
/* No sync: the queue stays deep across iterations, as in a decode step. */
|
||||
const auto t0 = clk::now();
|
||||
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(slow, dim3(8), dim3(256), 0, s, d, 4000);
|
||||
const auto t1 = clk::now();
|
||||
|
||||
+8
-12
@@ -1,14 +1,11 @@
|
||||
// What one instruction slot is worth on gfx1201, so that an instruction COUNT taken out of a
|
||||
// disassembly can be turned into a time.
|
||||
// Issue cost of one instruction slot on gfx1201, to turn an instruction count from a disassembly
|
||||
// into a time. A staged GEMM K tile is a few dozen v_wmma among several hundred other
|
||||
// instructions, so the wmma-to-VALU cost ratio decides whether trimming the rest pays; no public
|
||||
// table gives it for this part. Each instruction runs in independent back-to-back chains (issue
|
||||
// bound) and the rate is reported. The ratio is clock-independent, so no clock is read.
|
||||
//
|
||||
// A GEMM's staged K tile is a few dozen v_wmma inside several hundred other instructions, so
|
||||
// whether trimming the shell is worth anything depends entirely on what a wmma costs relative to a
|
||||
// plain VALU op -- and that ratio is not in any public table for this part. So measure it: run each
|
||||
// instruction back to back in independent chains (nothing to stall on but issue) and report the
|
||||
// rate. The RATIO is what matters and it is clock-independent, which is why no clock is read here.
|
||||
//
|
||||
// Occupancy is a parameter because a real tile kernel runs at 2 waves a SIMD (36864 B of LDS) and a
|
||||
// microbenchmark at 8 would answer a different question.
|
||||
// LDS is a parameter because occupancy matters: a tile kernel runs at 2 waves a SIMD (36864 B of
|
||||
// LDS), and 8 waves would answer a different question.
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
@@ -46,8 +43,7 @@ __global__ __launch_bounds__(256) void valu_rate(float* out, int iters) {
|
||||
float x0 = threadIdx.x, x1 = x0 + 1, x2 = x0 + 2, x3 = x0 + 3;
|
||||
float x4 = x0 + 4, x5 = x0 + 5, x6 = x0 + 6, x7 = x0 + 7;
|
||||
const float k = 1.0000001f;
|
||||
// Eight independent chains, eight ops an iteration -- the same shape as the wmma loop so the
|
||||
// two numbers differ only in the instruction being issued.
|
||||
// Same shape as the wmma loop (eight independent chains) so only the instruction differs.
|
||||
for (int i = 0; i < iters; ++i) {
|
||||
x0 *= k; x1 *= k; x2 *= k; x3 *= k; x4 *= k; x5 *= k; x6 *= k; x7 *= k;
|
||||
}
|
||||
|
||||
+15
-20
@@ -1,17 +1,14 @@
|
||||
// DOES A LAUNCH COST MORE WHEN THE MODULE REGISTERS MORE KERNELS, and does crossing into a shared
|
||||
// object cost anything at all?
|
||||
// Does a launch cost more when the module registers more kernels, and does crossing into a shared
|
||||
// object cost anything?
|
||||
//
|
||||
// The engine issues a launch for roughly twice what the same shape costs in a self-contained
|
||||
// binary, and the excess is roughly CONSTANT across kernels of very different shapes -- the
|
||||
// signature of a fixed per-issue tax rather than of anything a particular shim does. The error
|
||||
// check after every launch, a full command ring and the argument count together do not account for
|
||||
// it.
|
||||
// An engine launch costs roughly twice what the same shape costs in a self-contained binary, and
|
||||
// the excess is roughly constant across kernel shapes: a fixed per-issue tax. The per-launch error
|
||||
// check, a full command ring and the argument count do not account for it.
|
||||
//
|
||||
// The structural difference this isolates is the MODULE. libr4d is a .so holding every template
|
||||
// instantiation of every kernel, entered through a function pointer; a self-contained harness has
|
||||
// a handful of kernels compiled into the binary that launches them. HIP resolves a launch by
|
||||
// looking the host stub up in the table __hipRegisterFunction fills, so a bigger table is a
|
||||
// plausible tax -- and if it is the tax, the lever is fewer instantiations, not tidier shims.
|
||||
// This isolates the module. libr4d is a .so holding every kernel instantiation, entered through a
|
||||
// function pointer; a self-contained harness compiles a handful of kernels into the binary. HIP
|
||||
// resolves a launch by looking the host stub up in the table __hipRegisterFunction fills, so a
|
||||
// bigger table is a plausible tax, and then the lever is fewer instantiations.
|
||||
//
|
||||
// see build_launchreg.sh
|
||||
#include <hip/hip_runtime.h>
|
||||
@@ -65,13 +62,13 @@ int main(int argc, char** argv) {
|
||||
L->fn = (LaunchFn)dlsym(L->h, "lr_launch");
|
||||
L->dfn = (DistinctFn)dlsym(L->h, "lr_launch_distinct");
|
||||
CountFn c = (CountFn)dlsym(L->h, "lr_registered");
|
||||
if (!L->fn || !c) { std::printf("dlsym %s\n", L->path); return 1; }
|
||||
if (!L->fn || !L->dfn || !c) { std::printf("dlsym %s\n", L->path); return 1; }
|
||||
L->nreg = c();
|
||||
}
|
||||
std::printf("%d launches a sequence, %d iterations, medians\n", N, iters);
|
||||
std::printf(" few = %d instantiations, many = %d\n", few.nreg, many.nreg);
|
||||
|
||||
/* Warm every path: clocks, lazy module load for BOTH objects, and the code itself. */
|
||||
/* Warm every path: clocks, lazy module load for both objects, and the code itself. */
|
||||
for (int w = 0; w < 400; ++w) {
|
||||
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(local_k, dim3(1), dim3(64), 0, s, d);
|
||||
for (int i = 0; i < N; ++i) few.fn(d, s);
|
||||
@@ -107,12 +104,10 @@ int main(int argc, char** argv) {
|
||||
a_dist.push_back(us_since(t0, t1));
|
||||
}
|
||||
|
||||
/* ---- A SECOND SUBMITTING THREAD. The last structural difference between this harness and the
|
||||
* engine: --tp 2 runs two rank threads, each issuing onto its own stream, and every arm above
|
||||
* is single-threaded. If HIP takes a process-wide lock on the submit path then a launch costs
|
||||
* what it costs plus whatever the other rank is holding -- which would be a fixed tax, present
|
||||
* on every kernel however small, which is exactly the shape the excess has. The second
|
||||
* thread runs the identical loop on its OWN stream and is not measured; only rank 0 is. */
|
||||
/* ---- A second submitting thread. --tp 2 runs two rank threads, each issuing onto its own
|
||||
* stream. A process-wide lock on HIP's submit path would add a fixed tax to every launch,
|
||||
* the same shape as the excess. The second thread runs the same loop on its own stream and
|
||||
* is not measured; only rank 0 is. */
|
||||
hipStream_t s2;
|
||||
if (hipStreamCreate(&s2) != hipSuccess) { std::printf("second stream\n"); return 1; }
|
||||
std::atomic<bool> run{true};
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
// THE LIBRARY HALF of the registered-kernel test. Built twice, at -DNK=2 and -DNK=512, and
|
||||
// dlopen'd -- because that is libr4d's actual shape: a shared object holding every template
|
||||
// instantiation of every kernel, entered through a function pointer.
|
||||
//
|
||||
// Both builds launch THE SAME kernel, k<0>, with the same arguments. The only difference is how
|
||||
// many other instantiations sit in the module beside it.
|
||||
// Library half of the registered-kernel test, built at -DNK=2 and -DNK=512 and dlopen'd, which
|
||||
// matches libr4d's shape: one shared object holding every kernel instantiation, entered through a
|
||||
// function pointer. Both builds launch the same kernel k<0> with the same arguments; only the
|
||||
// number of other instantiations in the module differs.
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
template <int I>
|
||||
__global__ void k(float* p) { if (threadIdx.x == 0) p[blockIdx.x] = (float)I; }
|
||||
|
||||
/* The table exists to keep the instantiations alive. Without a use, the compiler drops every k<I>
|
||||
* that is never launched and both builds register one kernel. */
|
||||
/* Keeps the instantiations alive; without a use the compiler drops every unlaunched k<I>. */
|
||||
static const void* g_tab[NK];
|
||||
|
||||
template <int I>
|
||||
@@ -22,11 +19,9 @@ struct Reg<0> {
|
||||
static void go() { g_tab[0] = (const void*)k<0>; }
|
||||
};
|
||||
|
||||
/* A THUNK PER INSTANTIATION. The arms above launch one kernel over and over, which is the one
|
||||
* thing a decode step never does: it issues forty-five DIFFERENT kernels, each through its own
|
||||
* shim, each with its own argument buffer and its own host stub. Everything the tight loop keeps
|
||||
* in L1 -- the code, the stub, the args -- is cold on every one of those. This makes that
|
||||
* difference, and only that difference, measurable. */
|
||||
/* One thunk per instantiation. A decode step issues ~45 different kernels, each with its
|
||||
* own shim, argument buffer and host stub, so code, stub and args are cold on each launch; a
|
||||
* loop over one kernel keeps them in L1. lr_launch_distinct measures that difference. */
|
||||
typedef void (*Thunk)(float*, hipStream_t);
|
||||
template <int I>
|
||||
static void thunk(float* p, hipStream_t st) {
|
||||
|
||||
+389
-493
File diff suppressed because it is too large.
Load diff
+284
-427
File diff suppressed because it is too large.
Load diff
@@ -1,25 +1,18 @@
|
||||
// r4d_ar_gather_2rank.hip: r4d_ar_gather_2rank -- multi-block one-shot P2P all-GATHER, exactly two
|
||||
// ranks, for dual R9700 (gfx1201/RDNA4, PCIe).
|
||||
//
|
||||
// WHY IT EXISTS AS A KERNEL AND NOT AS A COPY. r4d_ar_oneshot_2rank_exact.hip says of
|
||||
// r4d_p2p_copy2d that a strided device-to-device copy "is what an ALL-GATHER between two ranks is
|
||||
// once the peer's buffer is IPC-mapped", and that is true of the DATA MOVEMENT and false of the
|
||||
// whole operation: a copy carries no handshake, so the reader has no way to know the writer's
|
||||
// bytes have landed. Ordering that with a separate fence plus a barrier collective is three
|
||||
// launches and a second rendezvous to keep aligned with this one. This is the same kernel as the
|
||||
// one-shot all-reduce with the reduction removed -- same push, same per-block flag protocol, same
|
||||
// double-buffered slot -- and it is a separate file rather than a template variant because the
|
||||
// all-reduce's shape (out is numel) and this one's (out is world_size * numel) differ.
|
||||
// A kernel rather than r4d_p2p_copy2d: a copy moves the data but carries no handshake, so the
|
||||
// reader cannot know the writer's bytes have landed, and ordering it with a fence plus a barrier
|
||||
// collective costs three launches and a second rendezvous. This is the one-shot all-reduce minus
|
||||
// the reduction (same push, per-block flag protocol and double-buffered slot); it is a separate
|
||||
// file because the output shapes differ (numel vs world_size * numel).
|
||||
//
|
||||
// WHAT IT IS FOR. The vocab-parallel sampler. lm_head is row-sharded, so each rank reduces its own
|
||||
// slice of the vocabulary to k candidates and only the CANDIDATE SETS are combined: at 4 rows and
|
||||
// 1024 candidates the message is 32 KiB, against the ~1 GiB a full-logits gather would move. The
|
||||
// payload is (u32 global token id, f32 logit) pairs, which is why this MOVES bytes and does not
|
||||
// sum them -- adding two f32 lanes would work on the logit and destroy the id, whose bit pattern
|
||||
// at any real vocabulary size is an f32 denormal.
|
||||
// Used by the vocab-parallel sampler. lm_head is row-sharded, so each rank reduces its vocabulary
|
||||
// slice to k candidates and only the candidate sets are combined (32 KiB at 4 rows x 1024
|
||||
// candidates, against ~1 GiB for full logits). The payload is (u32 token id, f32 logit) pairs,
|
||||
// so the bytes are moved, never summed.
|
||||
//
|
||||
// The element type is therefore irrelevant beyond its size: `dtype` is taken for symmetry with the
|
||||
// rest of the family and used only to turn n_elem into bytes.
|
||||
// `dtype` only converts n_elem to bytes.
|
||||
#include "r4d.h"
|
||||
#include "r4d_ar_seq.h"
|
||||
#include <cstdint>
|
||||
@@ -36,19 +29,16 @@ __device__ __forceinline__ unsigned int r4d_g_load_acq(const unsigned int* p) {
|
||||
return __hip_atomic_load(p, __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
|
||||
// WHERE A RANK'S WORDS LAND. `row16` is one ROW of this rank's contribution, in 16-byte words.
|
||||
// Where a rank's words land. `row16` is one row of this rank's contribution, in 16-byte words.
|
||||
//
|
||||
// row16 <= 0 or row16 == n16 -- one row: rank r's whole slice at r * n16, the plain
|
||||
// concatenation an all-gather is usually taken to mean.
|
||||
// otherwise -- ROW-INTERLEAVED: the input is [rows][row16] and the output is
|
||||
// [rows][world][row16], so row m carries every rank's words for
|
||||
// row16 <= 0 or row16 == n16 -- one row: rank r's whole slice at r * n16 (plain concatenation).
|
||||
// otherwise -- row-interleaved: input [rows][row16], output
|
||||
// [rows][world][row16], so row m holds every rank's words for
|
||||
// that row side by side.
|
||||
//
|
||||
// The second form is the one the vocab-parallel sampler needs and it is not a convenience. The
|
||||
// merge that consumes this reads ONE ROW of gathered candidates per sampled position, at a single
|
||||
// row stride; the concatenated form puts rank 1's row m a whole message away from rank 0's, which
|
||||
// no row stride can express. Interleaving here costs one division per word in a kernel that moves
|
||||
// 32 KiB and saves a transpose launch on the step path.
|
||||
// The vocab-parallel sampler's merge reads one row of gathered candidates per position at a single
|
||||
// row stride, which the concatenated form cannot express. Interleaving costs one division per word
|
||||
// and saves a transpose launch.
|
||||
__device__ __forceinline__ int r4d_g_dst(int k, int row16, int n16, int who) {
|
||||
if (row16 <= 0 || row16 >= n16) return who * n16 + k;
|
||||
const int m = k / row16, c = k - m * row16;
|
||||
@@ -56,7 +46,7 @@ __device__ __forceinline__ int r4d_g_dst(int k, int row16, int n16, int who) {
|
||||
}
|
||||
|
||||
// Block b owns words [start,end) of the 16B-word space and drives its own flag handshake; no
|
||||
// cross-block sync, exactly as in the all-reduce.
|
||||
// cross-block sync, as in the all-reduce.
|
||||
__global__ void r4d_ar_gather_2rank_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,
|
||||
@@ -73,8 +63,8 @@ __global__ void r4d_ar_gather_2rank_kernel(
|
||||
const int start = b * w;
|
||||
int end = start + w; if (end > n16) end = n16;
|
||||
|
||||
// push chunk -> peer slot, and place this rank's own slice while the push is in flight: it is a
|
||||
// local store that needs no handshake, so it costs nothing to hide here.
|
||||
// Push the chunk to the peer slot and place this rank's own slice (a local store, no handshake)
|
||||
// while the push is in flight.
|
||||
{
|
||||
int k = start + tid;
|
||||
for (; k + 3 * nt < end; k += 4 * nt) {
|
||||
@@ -87,8 +77,8 @@ __global__ void r4d_ar_gather_2rank_kernel(
|
||||
}
|
||||
for (; k < end; k += nt) { int4 v = in4[k]; ps[k] = v; out4[r4d_g_dst(k, row16, n16, rank)] = v; }
|
||||
}
|
||||
// Drain modes, identical to the all-reduce's: they order the pushes against the release flag so
|
||||
// the peer cannot see the flag before the data.
|
||||
// Drain modes, as in the all-reduce: order the pushes before the release flag so the peer cannot
|
||||
// see the flag before the data.
|
||||
if (drain == 1) __threadfence_system();
|
||||
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
|
||||
__syncthreads();
|
||||
@@ -96,8 +86,8 @@ __global__ void r4d_ar_gather_2rank_kernel(
|
||||
if (drain == 2) __threadfence_system();
|
||||
r4d_g_store_rel(&peer_flags[b], s);
|
||||
unsigned long long z = 0;
|
||||
// A handshake that cannot complete is a lockstep violation, and placing a slot the peer never
|
||||
// filled would pass stale bytes on as the peer's, so it traps instead.
|
||||
// A handshake that cannot complete is a lockstep violation; trap rather than pass on stale
|
||||
// bytes as the peer's.
|
||||
while (r4d_ar_seq_behind(r4d_g_load_acq(&my_flags[b]), s)) {
|
||||
if (++z > R4D_AR_GATHER_SPIN_MAX) __builtin_trap();
|
||||
}
|
||||
@@ -105,7 +95,7 @@ __global__ void r4d_ar_gather_2rank_kernel(
|
||||
__syncthreads();
|
||||
if (acq) __threadfence_system();
|
||||
|
||||
// The peer's slice, now staged in this rank's scratch, into the places that name it.
|
||||
// Place the peer's slice, now staged in this rank's scratch.
|
||||
{
|
||||
const int who = 1 - rank;
|
||||
int k = start + tid;
|
||||
@@ -128,9 +118,10 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo
|
||||
const long nbytes = (long)n_elem * esize;
|
||||
if (nbytes % 16 != 0) throw std::runtime_error("all_gather: n_elem*esize not 16B-aligned");
|
||||
if (rank != 0 && rank != 1) throw std::runtime_error("all_gather: rank must be 0 or 1");
|
||||
if (nbytes / 16 > slot_stride16) throw std::runtime_error("all_gather: message larger than a slot");
|
||||
const int n16 = (int)(nbytes / 16);
|
||||
// One row of this rank's contribution, in 16-byte words. Zero means "one row", which is the
|
||||
// plain concatenation; anything else has to divide evenly or a row would straddle a word.
|
||||
// One row of this rank's contribution, in 16-byte words. Zero means one row (plain
|
||||
// concatenation); otherwise rows must be whole 16-byte words and divide the message.
|
||||
long rowb = (long)row_elems * esize;
|
||||
if (row_elems > 0 && (rowb % 16 != 0 || nbytes % rowb != 0))
|
||||
throw std::runtime_error("all_gather: row is not a whole number of 16B words");
|
||||
@@ -139,8 +130,7 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo
|
||||
if (nb < 1) nb = 1;
|
||||
if (nb > n16) nb = n16;
|
||||
if (nb > R4D_AR_GATHER_MAX_BLOCKS) nb = R4D_AR_GATHER_MAX_BLOCKS;
|
||||
// The counter allocation's block capacity, shared with the all-reduce this rides beside
|
||||
// (r4d_ar_seq.h).
|
||||
// Block capacity of the counter allocation shared with the all-reduce (r4d_ar_seq.h).
|
||||
const unsigned nbw = (unsigned)r4d_ar_max_blocks();
|
||||
if ((unsigned)nb > nbw) nb = (int)nbw;
|
||||
int nt = (int)nthreads;
|
||||
|
||||
@@ -1,39 +1,32 @@
|
||||
// r4d_ar_gather_Nrank.hip: r4d_ar_gather_3rank, r4d_ar_gather_4rank, r4d_ar_gather_8rank -- one-shot P2P all-GATHER,
|
||||
// 4 or 8 ranks, gfx1201. WS is compile-time; the 2-rank gather keeps its own file, exactly as the
|
||||
// one-shot all-reduce's does.
|
||||
// 3, 4 or 8 ranks, gfx1201. WS is compile-time; the 2-rank gather has its own file, as does the
|
||||
// 2-rank one-shot all-reduce.
|
||||
//
|
||||
// WHY IT EXISTS. r4d_ar_gather_2rank.hip is the engine's only device all-gather and its handshake
|
||||
// is ONE PEER FLAG per block, not a tree (r4d_ar_entry.hip:492), so it is compiled for two ranks
|
||||
// and refuses every other width. The vocab-parallel sampler declares an all_gather whenever the
|
||||
// vocabulary is sharded, so at world 4 nothing but libref's host ref_all_gather resolves and the
|
||||
// serve is refused by name. This is the wide one-shot all-reduce with the reduction REMOVED: same
|
||||
// push, same per-block handshake, same double-buffered (parity, source) scratch, and the fp32 sum
|
||||
// replaced by placement.
|
||||
// r4d_ar_gather_2rank.hip handshakes with one peer flag per block, so it serves two ranks only. The
|
||||
// vocab-parallel sampler declares an all_gather whenever the vocabulary is sharded; without this
|
||||
// kernel only libref's host ref_all_gather resolves at wider worlds and the serve is refused. It is
|
||||
// the wide one-shot all-reduce with the reduction removed: same push, per-block handshake and
|
||||
// double-buffered (parity, source) scratch, with the fp32 sum replaced by placement.
|
||||
//
|
||||
// THE PAYLOAD IS MOVED AND NEVER SUMMED. What the sampler gathers is (u32 global token id, f32
|
||||
// logit) pairs; a token id's bit pattern read as f32 is a denormal, so adding two lanes would
|
||||
// work on the logit and destroy the id. `dtype` is taken for symmetry with the family and used
|
||||
// only to turn n_elem into bytes.
|
||||
// The payload is (u32 token id, f32 logit) pairs, so it is moved and never summed. `dtype` only
|
||||
// converts n_elem to bytes.
|
||||
//
|
||||
// THE PLACEMENT. row16 is one ROW of this rank's contribution in 16-byte words and r4d_g_dst_ws
|
||||
// says where a rank's words land: the plain concatenation when there is one row, and otherwise
|
||||
// ROW-INTERLEAVED -- input [rows][row16], output [rows][WS][row16] -- because the merge that
|
||||
// consumes this reads one row of gathered candidates per sampled position at a single row stride.
|
||||
// See r4d_ar_gather_2rank.hip, whose comment states why that is not a convenience.
|
||||
// Placement: row16 is one row of this rank's contribution in 16-byte words. r4d_g_dst_ws
|
||||
// concatenates when there is one row, and otherwise interleaves rows (input [rows][row16], output
|
||||
// [rows][WS][row16]) so the merge reads each position's candidates at a single row stride (see
|
||||
// r4d_ar_gather_2rank.hip).
|
||||
//
|
||||
// The IPC helpers and the handshake live in r4d_ar_wide.h; this unit links beside r4d_ar_entry.hip,
|
||||
// which owns the instance and the peer arrays.
|
||||
// The IPC helpers and the handshake live in r4d_ar_wide.h; r4d_ar_entry.hip owns the instance and
|
||||
// the peer arrays.
|
||||
#include "r4d.h"
|
||||
#include "r4d_ar_wide.h"
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
// The launchers this unit provides, in the family's shape: the peer arguments are ascending global
|
||||
// rank with the current rank removed, and `out` is world_size * n_elem elements. Declared extern
|
||||
// "C" here, at arm's length from the definitions below, so those definitions get C linkage; the
|
||||
// caller is r4d_ar_entry.hip, which owns the instance and repeats the two prototypes at its call
|
||||
// site (r4d.h declares the rest of the family and is not this unit's file).
|
||||
// Peer arguments are in ascending global rank with the current rank removed; `out` is
|
||||
// world_size * n_elem elements. Declared extern "C" here so the definitions below get C linkage;
|
||||
// r4d_ar_entry.hip repeats the prototypes at its call site, since r4d.h does not declare them.
|
||||
extern "C" void r4d_ar_gather_3rank(long peer_scratch0, long peer_scratch1,
|
||||
long peer_flags0, long peer_flags1,
|
||||
long my_scratch, long my_flags, long seq_ctrs,
|
||||
@@ -45,7 +38,8 @@ extern "C" void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long
|
||||
long my_scratch, long my_flags, long seq_ctrs,
|
||||
long slot_stride16, long inp, long out, long n_elem,
|
||||
long dtype, long rank, long row_elems, long stream,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub);
|
||||
long nblocks, long nthreads, long drain, long acq, long pub,
|
||||
long gate, long gate_ctr);
|
||||
extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
long peer_scratch3, long peer_scratch4, long peer_scratch5,
|
||||
long peer_scratch6, long peer_flags0, long peer_flags1,
|
||||
@@ -56,9 +50,8 @@ extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long
|
||||
long stream, long nblocks, long nthreads, long drain, long acq,
|
||||
long pub);
|
||||
|
||||
// WHERE A RANK'S WORDS LAND -- the 2-rank r4d_g_dst at a compile-time width. Named apart from it
|
||||
// on purpose: same rule, different WS, and two __device__ definitions of one name would be an ODR
|
||||
// violation between the two units.
|
||||
// Where a rank's words land: the 2-rank r4d_g_dst generalised to WS. Named differently because two
|
||||
// __device__ definitions of one name in the two units would violate the ODR.
|
||||
__device__ __forceinline__ int r4d_g_dst_ws(int k, int row16, int n16, int WS, int who) {
|
||||
if (row16 <= 0 || row16 >= n16) return who * n16 + k;
|
||||
const int m = k / row16, c = k - m * row16;
|
||||
@@ -66,20 +59,22 @@ __device__ __forceinline__ int r4d_g_dst_ws(int k, int row16, int n16, int WS, i
|
||||
}
|
||||
|
||||
// Block b owns words [start,end) of the 16B-word space and drives its own handshake; no cross-block
|
||||
// sync, exactly as in the all-reduce this rides beside.
|
||||
// sync, as in the all-reduce.
|
||||
template <int WS>
|
||||
__global__ void r4d_ar_gather_wide_kernel(
|
||||
const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers,
|
||||
const int4* __restrict__ my_base, int4* __restrict__ out4,
|
||||
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs,
|
||||
int n16, int slot_stride16, int rank, int row16, int drain, int acq, int pub) {
|
||||
int n16, int slot_stride16, int rank, int row16, int drain, int acq, int pub,
|
||||
long long* gate, unsigned int* gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
// The placement holds WS source words live per output word, so the 2x unroll spills at ws=8 --
|
||||
// the same ceiling the one-shot all-reduce draws for the same reason.
|
||||
// Placement holds WS source words live per output word, so the 2x unroll spills at ws=8 (same
|
||||
// limit as the one-shot all-reduce).
|
||||
constexpr int RU = (WS <= 4) ? 2 : 1;
|
||||
|
||||
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);
|
||||
r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int parity = (int)s_slot;
|
||||
@@ -88,18 +83,15 @@ __global__ void r4d_ar_gather_wide_kernel(
|
||||
const int start = b * w;
|
||||
int end = start + w; if (end > n16) end = n16;
|
||||
|
||||
// Every peer lays its scratch out identically, so one index serves all of them: the slot that
|
||||
// NAMES THE SOURCE RANK. We write our own words into the same slot number of every peer's
|
||||
// scratch, and every peer reads them out of the slot numbered by OUR rank.
|
||||
// Every peer lays its scratch out identically, with one slot per source rank. Our words go into
|
||||
// the slot numbered by our rank in every peer's scratch.
|
||||
int4* ps[NPEERS];
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p)
|
||||
ps[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16;
|
||||
|
||||
// push: 4x-unrolled, and the loaded words are reused across peers so the input is read once.
|
||||
// This rank's own slice is NOT placed here -- the pass after the handshake places every rank's
|
||||
// slice from one src[] table, and duplicating the local store to hide it here would be the only
|
||||
// thing the all-reduce's shape does not carry over.
|
||||
// Push, 4x unrolled; loaded words are reused across peers so the input is read once. This rank's
|
||||
// own slice is placed after the handshake with all the others, from one src[] table.
|
||||
{
|
||||
int k = start + tid;
|
||||
for (; k + 3 * nt < end; k += 4 * nt) {
|
||||
@@ -116,15 +108,16 @@ __global__ void r4d_ar_gather_wide_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// The wide family's own protocol: publish 2*seq to every peer's flag word [b][our rank], then
|
||||
// wait on our own [b][source] for every source. Flag values, parity and the slot guard are
|
||||
// r4d_ar_wide.h's, shared with the all-reduces this instance's buffers serve, and a handshake
|
||||
// that cannot complete traps rather than pass stale bytes on as a peer's.
|
||||
// Publish 2*seq to every peer's flag word [b][our rank], then wait on our own [b][source] for
|
||||
// every source. The protocol is r4d_ar_wide.h's, shared with the all-reduces on these buffers; a
|
||||
// handshake that cannot complete traps rather than pass on stale bytes.
|
||||
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s, drain, acq, pub);
|
||||
// One handshake, and the placement after it reads this card's scratch and input only: the last
|
||||
// block here ends the engine's hold, as in the one-shot all-reduce this rides beside.
|
||||
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
// The peers' slices, now staged in this rank's scratch, into the places that name them. Slot
|
||||
// [parity][our rank] of my own scratch is written by nobody, so -- exactly as in the all-reduce
|
||||
// -- the source that names OUR rank is the input itself and every lane is branch-free.
|
||||
// Place every rank's slice. Slot [parity][our rank] of our own scratch is never written, so, as
|
||||
// in the all-reduce, our rank's source is the input itself and the loop is branch-free.
|
||||
const int4* src[WS];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < WS; ++r)
|
||||
@@ -150,15 +143,14 @@ __global__ void r4d_ar_gather_wide_kernel(
|
||||
}
|
||||
|
||||
// --- host side ---
|
||||
// `row_elems` is the row width in ELEMENTS, 0 for the plain concatenation; the entry point has
|
||||
// already checked that it divides the message and is a whole number of 16-byte words, and it is
|
||||
// rechecked here because this is the half that throws.
|
||||
// `row_elems` is the row width in elements, 0 for plain concatenation. The entry point checks it
|
||||
// already; it is rechecked here because this is the half that throws.
|
||||
template <int WS>
|
||||
static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_flags, long my_scratch,
|
||||
long my_flags, long seq_ctrs, long slot_stride16, long inp,
|
||||
long out, long n_elem, long dtype, long rank, long row_elems,
|
||||
long stream_i, long nblocks, long nthreads, long drain, long acq,
|
||||
long pub) {
|
||||
long pub, long gate, long gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
static_assert(NPEERS <= R4D_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound");
|
||||
|
||||
@@ -200,9 +192,9 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla
|
||||
peers.rank[i] = (i < (int)rank) ? i : i + 1;
|
||||
}
|
||||
|
||||
// Same buffers, same rule as the all-reduce this shares an instance with: scratch backs 2*WS
|
||||
// slots of the declared stride, flags one word per (block, source rank), seq a handshake and a
|
||||
// parity word per block of capacity -- checked against the allocations, not the arguments.
|
||||
// As in the all-reduce sharing this instance, check against the allocations: scratch backs 2*WS
|
||||
// slots of the stride, flags one word per (block, source rank), seq a handshake and a parity
|
||||
// word per block of capacity.
|
||||
const long slot_bytes = 2L * WS * (long)slot_stride16 * 16;
|
||||
const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int);
|
||||
r4d_ar_check_extent(my_scratch, slot_bytes, "all_gather", "my_scratch");
|
||||
@@ -218,11 +210,10 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla
|
||||
r4d_ar_gather_wide_kernel<WS><<<nb, nt, 0, st>>>(
|
||||
(const int4*)inp, peers, (const int4*)my_scratch, (int4*)out, (unsigned int*)my_flags,
|
||||
(unsigned int*)seq_ctrs, n16, (int)slot_stride16, (int)rank, row16, (int)drain, (int)acq,
|
||||
(int)pub);
|
||||
(int)pub, (long long*)gate, (unsigned int*)gate_ctr);
|
||||
}
|
||||
|
||||
/* Three ranks: the same launch with two peers. The vocab-parallel sampler's gather at a world of
|
||||
* three (Qwen3.8-Flash-Next padded to 36 heads / 3 KV heads, docs/TP3.md) resolves here. */
|
||||
/* Three ranks, e.g. Qwen3.8-Flash-Next padded to 36 heads / 3 KV heads (docs/TP3.md). */
|
||||
void r4d_ar_gather_3rank(long peer_scratch0, long peer_scratch1,
|
||||
long peer_flags0, long peer_flags1, long my_scratch,
|
||||
long my_flags, long seq_ctrs, long slot_stride16, long inp, long out,
|
||||
@@ -230,19 +221,23 @@ void r4d_ar_gather_3rank(long peer_scratch0, long peer_scratch1,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub) {
|
||||
const long ps[2] = {peer_scratch0, peer_scratch1};
|
||||
const long pf[2] = {peer_flags0, peer_flags1};
|
||||
/* No link gate at three ranks: the row answers 1, the engine releases by barrier. */
|
||||
ar_gather_wide_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem,
|
||||
dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub);
|
||||
dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub,
|
||||
0L, 0L);
|
||||
}
|
||||
|
||||
void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
long peer_flags0, long peer_flags1, long peer_flags2, long my_scratch,
|
||||
long my_flags, long seq_ctrs, long slot_stride16, long inp, long out,
|
||||
long n_elem, long dtype, long rank, long row_elems, long stream,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub) {
|
||||
long nblocks, long nthreads, long drain, long acq, long pub, long gate,
|
||||
long gate_ctr) {
|
||||
const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2};
|
||||
const long pf[3] = {peer_flags0, peer_flags1, peer_flags2};
|
||||
ar_gather_wide_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem,
|
||||
dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub);
|
||||
dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub,
|
||||
gate, gate_ctr);
|
||||
}
|
||||
|
||||
void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
@@ -257,6 +252,8 @@ void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scrat
|
||||
peer_scratch4, peer_scratch5, peer_scratch6};
|
||||
const long pf[7] = {peer_flags0, peer_flags1, peer_flags2, peer_flags3,
|
||||
peer_flags4, peer_flags5, peer_flags6};
|
||||
/* No link gate at eight ranks: the row answers 1, the engine releases by barrier. */
|
||||
ar_gather_wide_launch<8>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem,
|
||||
dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub);
|
||||
dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub,
|
||||
0L, 0L);
|
||||
}
|
||||
+18
-21
@@ -1,17 +1,15 @@
|
||||
#pragma once
|
||||
// r4d_ar_hc.h: the per-word arithmetic of the all-reduces that end in the gated residual's write --
|
||||
// the MoE gather in front of the message and the hc write behind the reduction -- shared by the
|
||||
// exact kernels (r4d_ar_oneshot_2rank_exact.hip) and the rotated 6-bit ones
|
||||
// (r4d_ar_oneshot_2rank_wht6.hip). One copy of it is what makes the two wires' fused forms produce
|
||||
// the bytes of the same unfused chain: moe_gather, the all-reduce, hc_write.
|
||||
// r4d_ar_hc.h: per-word arithmetic of the all-reduces fused with the gated residual write: the MoE
|
||||
// gather before the message and the hc write after the reduction. Shared by the exact kernels
|
||||
// (r4d_ar_oneshot_2rank_exact.hip) and the rotated 6-bit ones (r4d_ar_oneshot_2rank_wht6.hip), so
|
||||
// both fused forms produce the same bytes as the unfused chain moe_gather, all-reduce, hc_write.
|
||||
//
|
||||
// A WORD is eight consecutive bf16 elements of one row -- a row is `n` elements and n is a multiple
|
||||
// A word is eight consecutive bf16 elements of one row. A row is `n` elements and n is a multiple
|
||||
// of eight, so a word never straddles a row.
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "r4d_gdn_wmma.h" // f2bf / bf2f: the gated residual's own bf16 arithmetic
|
||||
|
||||
// The LDS slot table's bounds: the rows one block of the table form covers, and the slots a row
|
||||
// holds.
|
||||
// LDS slot table bounds: rows per block, and slots per row.
|
||||
#define R4D_ARG_ROWS 8
|
||||
#define R4D_ARG_SLOTS 64
|
||||
|
||||
@@ -30,13 +28,13 @@ struct R4dArGather {
|
||||
int top_k, T, sig;
|
||||
};
|
||||
|
||||
// ONE WORD OF THE GATHER: y[row][i0 .. i0+8) = sum over the row's slots, ascending, of
|
||||
// w[row][j] * y_expert[slot][i0 ..], rounded to bf16, with the shared arm folded as moe_gather
|
||||
// folds it -- its narrows are round-to-nearest-even, not hc_write's.
|
||||
// One word of the gather: y[row][i0 .. i0+8) = sum over the row's slots, ascending, of
|
||||
// w[row][j] * y_expert[slot][i0 ..], rounded to bf16, with the shared arm folded in as moe_gather
|
||||
// does it. Its narrows are round-to-nearest-even, unlike hc_write's.
|
||||
//
|
||||
// With INV the slots come from the inverse table inv[token * top_k + slot] (the sorted row holding
|
||||
// it, or -1) and the weights and the gate from global memory; without it from the block's LDS
|
||||
// table, `r` being the row's index in it.
|
||||
// With INV, slots come from the inverse table inv[token * top_k + slot] (the sorted row holding
|
||||
// it, or -1) and weights and gate from global memory. Without it they come from the block's LDS
|
||||
// table, where `r` is the row's index.
|
||||
template <bool INV>
|
||||
__device__ __forceinline__ int4 r4d_ar_gather_word(const R4dArGather& G,
|
||||
const int* __restrict__ inv, const int* s_i,
|
||||
@@ -46,10 +44,9 @@ __device__ __forceinline__ int4 r4d_ar_gather_word(const R4dArGather& G,
|
||||
float acc[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) acc[e] = 0.0f;
|
||||
/* FOUR SLOTS' ROWS IN FLIGHT AT ONCE. Loaded one at a time behind the test for an empty slot,
|
||||
* each row's read waits for the one before it; so the four are issued first -- an empty slot
|
||||
* reads row 0, which is always there -- and then added in the same ascending order, the empty
|
||||
* ones skipped. */
|
||||
/* Four slot rows in flight at once: all four loads issue before any add, so they do not
|
||||
* serialise behind the empty-slot test. An empty slot reads row 0, which always exists, and is
|
||||
* skipped in the ascending add. */
|
||||
constexpr int kU = 4;
|
||||
for (int j0 = 0; j0 < K; j0 += kU) {
|
||||
int4 v[kU];
|
||||
@@ -92,9 +89,9 @@ __device__ __forceinline__ int4 r4d_ar_gather_word(const R4dArGather& G,
|
||||
return out;
|
||||
}
|
||||
|
||||
// ONE WORD OF THE WRITE: h[row][c*n + i0 ..] += inj[row][c] * y[row][i0 ..] for every stream c, in
|
||||
// hc_write's arithmetic (r4d_hc_bf16.hip) over `yv`, the reduced word as the bf16 the reduction
|
||||
// stored -- which is what hc_write reads back from memory.
|
||||
// One word of the write: h[row][c*n + i0 ..] += inj[row][c] * y[row][i0 ..] for every stream c, in
|
||||
// hc_write's arithmetic (r4d_hc_bf16.hip). `yv` is the reduced word as stored bf16, which is what
|
||||
// hc_write reads back from memory.
|
||||
__device__ __forceinline__ void r4d_ar_hc_write_word(const unsigned short* __restrict__ inj,
|
||||
unsigned short* __restrict__ h, int row,
|
||||
int i0, int n, int hc, long irow, long hrow,
|
||||
|
||||
@@ -1,44 +1,30 @@
|
||||
// r4d_ar_ln_had_quant_i8.hip -- r4d_ar_ln_had_quant_i8: the tensor-parallel all-reduce and the
|
||||
// residual add, RMS norm, block Hadamard and int8 quantiser that always follow it, in ONE kernel.
|
||||
// r4d_ar_ln_had_quant_i8.hip -- r4d_ar_ln_had_quant_i8: the tensor-parallel all-reduce plus the
|
||||
// residual add, RMS norm, block Hadamard and int8 quantiser that always follow it, in one kernel.
|
||||
//
|
||||
// WHY. Every row-parallel linear in the model is followed by an all-reduce, and every one of those
|
||||
// all-reduces is followed by a norm -- 128 of each on a 64-layer decode step, always adjacent and
|
||||
// always in that order:
|
||||
// Every row-parallel linear is followed by an all-reduce and then a norm (128 of each on a
|
||||
// 64-layer decode step):
|
||||
//
|
||||
// out_proj / o_proj / down_proj -> all_reduce -> (residual add, RMS norm, rotate, quantise)
|
||||
//
|
||||
// and the norm's output is the next quantised linear's A. A decode step is launch-bound: over a
|
||||
// thousand dispatches with ~2.3 us of unavoidable gap between each is several milliseconds of pure
|
||||
// gap, and the standalone norm is itself latency- rather than bandwidth-bound (4.1 us for an
|
||||
// 80 KiB row set, against a ~2.6 us launch floor). Merging the pair removes 128 dispatches AND
|
||||
// nearly all of the norm's fixed cost, because the norm's work is bolted onto a kernel that has
|
||||
// already paid it.
|
||||
// and the norm's output is the next quantised linear's A. Decode is launch-bound (~2.3 us gap per
|
||||
// dispatch), and the standalone norm is latency-bound (4.1 us for an 80 KiB row set against a
|
||||
// ~2.6 us launch floor). Fusing removes 128 dispatches and most of the norm's fixed cost. The
|
||||
// all-reduce output is never materialised: the peer's contribution is a second operand on the
|
||||
// norm's load, `t = mine + peer + residual`.
|
||||
//
|
||||
// The all-reduce OUTPUT never exists. In the unfused pair it is a bf16 [M, K] tensor written by
|
||||
// the all-reduce and read straight back by the norm; here the peer's contribution is simply a
|
||||
// second operand on the norm's load -- `t = mine + peer + residual` -- so the round trip is gone
|
||||
// as well.
|
||||
// Partition by row. r4d_ar_oneshot_2rank_exact gives each block a chunk of 16B words and an
|
||||
// independent flag with no grid barrier. A norm needs whole rows for its sum of squares, but rows
|
||||
// are contiguous, so giving block b a contiguous row range makes its words exactly those rows'
|
||||
// bytes. Both ranks derive the range from (M, gridDim.x), so the handshake stays per-block with no
|
||||
// grid barrier. This caps nb at M, which costs nothing here: the standalone all-reduce uses 4
|
||||
// blocks on an 80 KiB decode message and M is 8 or more.
|
||||
//
|
||||
// WHY THE PARTITION IS BY ROW. r4d_ar_oneshot_2rank_exact gives block b a contiguous chunk of 16B
|
||||
// WORDS and an independent flag, with no grid barrier anywhere: b pushes its chunk to the peer,
|
||||
// releases peer_flags[b], spins on my_flags[b], then reduces its own chunk. A norm cannot use that
|
||||
// partition -- a sum of squares closes only over a whole row -- but it does not need a grid barrier
|
||||
// either, because rows are contiguous: give block b a contiguous range of ROWS and its chunk of
|
||||
// words is exactly the bytes of those rows. Both ranks compute the same range from (M, gridDim.x),
|
||||
// so the handshake stays per-block and the kernel keeps the no-grid-barrier structure.
|
||||
//
|
||||
// The block count therefore has a ceiling the standalone all-reduce does not have (nb <= M), which
|
||||
// costs nothing at the sizes this runs at: the standalone all-reduce asks for 4 blocks on an 80 KiB
|
||||
// decode message and the row count is 8 or more. The number of threads actually pushing is n16
|
||||
// either way.
|
||||
//
|
||||
// Everything below the handshake is r4d_rmsnorm_had_quant_i8 unchanged -- the same one-pass
|
||||
// argument (the FWHT is linear and inv_rms is a per-row scalar, so the rotation runs before the
|
||||
// norm closes and the scale absorbs it), the same register staging rather than an LDS round trip,
|
||||
// the same `wadd` added inside the fp32 arithmetic for GemmaRMSNorm's `x_hat * (1 + w)`, and the
|
||||
// same optional unrotated bf16 output for a GDN block's bf16 in_proj_ba. The only change is that
|
||||
// the row is loaded from two places and that LDS is re-used across the rows a block owns, which
|
||||
// needs one more barrier per row.
|
||||
// Below the handshake this is r4d_rmsnorm_had_quant_i8: one pass (the FWHT is linear and inv_rms
|
||||
// is a per-row scalar, so the rotation runs before the norm closes and the scale absorbs it),
|
||||
// register staging, `wadd` inside the fp32 arithmetic for GemmaRMSNorm's `x_hat * (1 + w)`, and an
|
||||
// optional unrotated bf16 output for a GDN block's bf16 in_proj_ba. The differences: the row is
|
||||
// loaded from two places, and LDS is reused across a block's rows, which costs one more barrier
|
||||
// per row.
|
||||
#include "r4d.h"
|
||||
#include "r4d_ar_seq.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -47,14 +33,7 @@
|
||||
#include <cstdint>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
|
||||
// The compressed all-reduce this fuses stores its fp32 sum to a bf16 tensor and the norm reads
|
||||
// that back, so the fused kernel rounds the sum to bf16 too and reproduces the unfused pair's
|
||||
// output exactly. Build with -DARN_W6_MATCH=0 to keep the fp32 sum, which is strictly more
|
||||
// accurate and NOT token-exact against the pair.
|
||||
#ifndef ARN_W6_MATCH
|
||||
#define ARN_W6_MATCH 1
|
||||
#endif
|
||||
#include <string>
|
||||
|
||||
#define R4D_ARN_SPIN_MAX 4000000000ULL
|
||||
#define R4D_ARN_MAXVALS 72
|
||||
@@ -67,46 +46,38 @@ __device__ __forceinline__ unsigned int arn_load_acq(const unsigned int* p) {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// THE ROTATED 6-BIT WIRE. Same format and the same arithmetic as r4d_ar_oneshot_2rank_wht6 --
|
||||
// orthonormal Walsh-Hadamard over a group of 64, amax-scaled, 6 uniform bits plus a bf16 scale --
|
||||
// but packed at a CHUNK of 1024 elements instead of 2048, so that a chunk never straddles a row.
|
||||
// That is what lets the norm keep its row partition: block b owns rows [r0, r1), and because K is
|
||||
// a whole number of chunks its element range is a whole number of chunks too.
|
||||
// Rotated 6-bit wire: same format and arithmetic as r4d_ar_oneshot_2rank_wht6 (orthonormal
|
||||
// Walsh-Hadamard over groups of 64, amax-scaled, 6 uniform bits plus a bf16 scale), but packed in
|
||||
// chunks of ARN_CE elements instead of 2048 so a chunk never straddles a row. K is a whole number
|
||||
// of chunks, so a block's rows [r0, r1) are too, and the row partition holds.
|
||||
//
|
||||
// The wire is why this exists. Above ~200 KiB the message is bandwidth-bound and the compressed
|
||||
// payload is 2.6x smaller, which is worth far more than the launch the fusion saves. Carrying the
|
||||
// payload in here lets the two wins compose: a message large enough to want the compressed wire
|
||||
// still avoids a second dispatch and a bf16 round trip through memory.
|
||||
// Above ~200 KiB the message is bandwidth-bound and the compressed payload is 2.6x smaller, which
|
||||
// outweighs the saved launch; carrying it here gets both savings.
|
||||
//
|
||||
// The helpers are duplicated rather than included from r4d_ar_oneshot_2rank_wht6.h on purpose:
|
||||
// that header also carries the standalone kernel and its launcher, so including it would
|
||||
// instantiate a second copy of a shipped kernel in this translation unit.
|
||||
// The helpers are duplicated from r4d_ar_oneshot_2rank_wht6.h on purpose: that header also holds
|
||||
// the standalone kernel and launcher, which would be instantiated again in this unit.
|
||||
#define ARN_GROUP 64
|
||||
#define ARN_BITS 6
|
||||
#define ARN_EPL 8
|
||||
#define ARN_LPG (ARN_GROUP / ARN_EPL) // 8 lanes span one group
|
||||
#define ARN_WV 32
|
||||
#define ARN_GPW (ARN_WV * ARN_EPL / ARN_GROUP) // 4 groups per wave-iteration
|
||||
// GROUPS PER CHUNK, and the only real tuning knob on the wire. 8 here, against the standalone
|
||||
// kernel's 32: a wave owns a whole chunk, so the chunk size is what decides how many waves have
|
||||
// work. A 5120-group message is 160 chunks at 32 and 640 at 8, and the block count cannot make up
|
||||
// the difference, because every block pays its own flag round trip over the fabric -- raising the
|
||||
// count from 24 to 32 costs ~3%, to 64 ~4%, and to 160 ~24%. Shrinking the chunk buys the same
|
||||
// parallelism for nothing, and the wire's cost falls monotonically from 32 groups to 8.
|
||||
#ifndef ARN_CG
|
||||
// Groups per chunk, the wire's one tuning knob: 8 here against the standalone kernel's 32. A wave
|
||||
// owns a whole chunk, so chunk size sets how many waves have work (a 5120-group message is 160
|
||||
// chunks at 32, 640 at 8). More blocks cannot substitute, since each pays its own flag round trip
|
||||
// (24 -> 32 blocks costs ~3%, 64 ~4%, 160 ~24%). The wire's cost falls monotonically from 32 groups
|
||||
// to 8.
|
||||
#define ARN_CG 8
|
||||
#endif
|
||||
// groups per chunk
|
||||
#define ARN_CE (ARN_CG * ARN_GROUP) // 1024 elements per chunk
|
||||
#define ARN_ITERS (ARN_CE / (ARN_WV * ARN_EPL)) // 4 iterations to cover a chunk
|
||||
#define ARN_NWORD (ARN_ITERS * ARN_EPL * ARN_BITS / 32) // 6 dwords a lane holds for a chunk
|
||||
#define ARN_CBYTES (ARN_CE * ARN_BITS / 8) // 768 wire bytes a chunk
|
||||
#define ARN_CE (ARN_CG * ARN_GROUP) // elements per chunk (512 at ARN_CG 8)
|
||||
#define ARN_ITERS (ARN_CE / (ARN_WV * ARN_EPL)) // wave-iterations per chunk
|
||||
#define ARN_NWORD (ARN_ITERS * ARN_EPL * ARN_BITS / 32) // dwords a lane holds per chunk
|
||||
#define ARN_CBYTES (ARN_CE * ARN_BITS / 8) // wire bytes per chunk
|
||||
#define ARN_QMAX ((1 << (ARN_BITS - 1)) - 1)
|
||||
#define ARN_QMIN (-(1 << (ARN_BITS - 1)))
|
||||
#define ARN_MASK ((1u << ARN_BITS) - 1u)
|
||||
|
||||
// RTNE to bf16 and back: the scale ships as its top 16 bits, so the sender's own copy has to be
|
||||
// exactly what the receiver reconstructs.
|
||||
// RTNE to bf16 and back: the scale ships as its top 16 bits, and the sender's own copy must equal
|
||||
// what the receiver reconstructs.
|
||||
__device__ __forceinline__ float arn_bf16_round(float v) {
|
||||
unsigned u = __float_as_uint(v);
|
||||
const unsigned lsb = (u >> 16) & 1u;
|
||||
@@ -115,10 +86,9 @@ __device__ __forceinline__ float arn_bf16_round(float v) {
|
||||
}
|
||||
|
||||
|
||||
// `lo ? (v + o) : (o - v)` written as `o + (lo ? v : -v)`. The sign flip is one XOR against a
|
||||
// mask that is uniform over the whole stage, so the select disappears: two instructions an element
|
||||
// (xor, then the DPP-sourced add) instead of an add, a subtract and a v_cndmask. Bit-identical --
|
||||
// IEEE negation is exact and addition commutes.
|
||||
// `lo ? (v + o) : (o - v)` written as `o + (lo ? v : -v)`. The sign flip is one XOR with a mask
|
||||
// uniform over the stage: two instructions per element (xor, DPP-sourced add) instead of add,
|
||||
// subtract and v_cndmask. Bit-identical, since IEEE negation is exact and addition commutes.
|
||||
template <int M>
|
||||
__device__ __forceinline__ void arn_xstage(float* v, int lig) {
|
||||
const unsigned int sm = (lig & M) ? 0x80000000u : 0u;
|
||||
@@ -159,11 +129,9 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
|
||||
constexpr int VPL = HAD / 32, NW = THR / 32;
|
||||
constexpr int MAXB = R4D_ARN_MAXVALS / VPL;
|
||||
extern __shared__ float lds[];
|
||||
// One staging slice per row the block owns. The exact wire needs only one (the norm reads the
|
||||
// row straight from memory), but the compressed wire has to REDUCE first, and a per-row reduce
|
||||
// would put cpr chunks -- five at K = 5120 -- in front of NW waves behind a barrier, three times
|
||||
// over. With the whole block's rows staged, the reduce is one pass over every chunk the block
|
||||
// owns and there is one barrier, not one per row.
|
||||
// One staging slice per owned row on the compressed wire (the exact wire needs one, since the
|
||||
// norm reads rows from memory). The compressed wire must reduce first; staging all rows makes
|
||||
// the reduce one pass over the block's chunks behind one barrier instead of one per row.
|
||||
const int r0_ = (int)(((long)blockIdx.x * M) / gridDim.x);
|
||||
const int nrows = (int)(((long)(blockIdx.x + 1) * M) / gridDim.x) - r0_;
|
||||
float* red = lds + (size_t)(WIRE ? nrows : 1) * K;
|
||||
@@ -179,10 +147,9 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
|
||||
int4* ps = peer_base + (size_t)s_slot * slot_stride16;
|
||||
const int4* ms = my_base + (size_t)s_slot * slot_stride16;
|
||||
|
||||
// WIRE == 6 only. The slot is split exactly as the standalone compressed all-reduce splits it:
|
||||
// packed symbols from the base, bf16 group scales from half way up. Chunk indices are GLOBAL
|
||||
// over the whole [M, K] message, so both ranks address the same bytes without exchanging
|
||||
// anything; a block simply owns the chunks its rows cover.
|
||||
// WIRE == 6 only. The slot is split as in the standalone compressed all-reduce: packed symbols
|
||||
// from the base, bf16 group scales from halfway. Chunk indices are global over the [M, K]
|
||||
// message, so both ranks address the same bytes; a block owns the chunks its rows cover.
|
||||
const int cpr = K / ARN_CE; // chunks a row spans (K % ARN_CE == 0, checked)
|
||||
const int c00 = r0 * cpr, cpb = (r1 - r0) * cpr;
|
||||
char* p_pay = (char*)ps;
|
||||
@@ -190,16 +157,15 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
|
||||
unsigned short* p_sc = (unsigned short*)((char*)ps + (size_t)(slot_stride16 >> 1) * 16);
|
||||
const unsigned short* m_sc =
|
||||
(const unsigned short*)((const char*)ms + (size_t)(slot_stride16 >> 1) * 16);
|
||||
// This rank's own packed half, kept in LDS so the reduce folds exactly the bytes it sent
|
||||
// without a global round trip -- the standalone kernel needs a side buffer for this because it
|
||||
// has no LDS to spare; here the norm's staging array is already the reason there is a barrier.
|
||||
// This rank's own packed half, kept in LDS so the reduce folds exactly the bytes it sent without
|
||||
// a global round trip (the standalone kernel uses a side buffer instead).
|
||||
unsigned int* Lpk = (unsigned int*)(red + 2 * NW);
|
||||
float* Lsc = (float*)(Lpk + (size_t)cpb * ARN_WV * ARN_NWORD);
|
||||
const int lig = lane & (ARN_LPG - 1), gw = lane / ARN_LPG;
|
||||
|
||||
if constexpr (WIRE == 0) {
|
||||
// push my rows -> peer slot. K bf16 is K/8 16B words, and rows are contiguous, so a row range
|
||||
// is a word range.
|
||||
// Push my rows to the peer slot. A row is K/8 16B words and rows are contiguous, so a row
|
||||
// range is a word range.
|
||||
const int wpr = K >> 3;
|
||||
const int wstart = r0 * wpr, wend = r1 * wpr;
|
||||
const int4* in4 = (const int4*)X;
|
||||
@@ -210,9 +176,9 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
|
||||
}
|
||||
for (; k < wend; k += THR) ps[k] = in4[k];
|
||||
} else {
|
||||
// rotate, amax, quantise and pack straight into the peer's slot, keeping the same words in
|
||||
// LDS. A wave owns whole chunks, so every lane emits exactly ARN_NWORD dwords per chunk and
|
||||
// the flush is lane-uniform: one 512B uint4 store and one 256B uint2 store a wave a chunk.
|
||||
// Rotate, amax, quantise and pack straight into the peer's slot, keeping the same words in
|
||||
// LDS. A wave owns whole chunks, so every lane emits exactly ARN_NWORD dwords per chunk and the
|
||||
// flush is lane-uniform.
|
||||
for (int ci = wave; ci < cpb; ci += NW) {
|
||||
const int c = c00 + ci;
|
||||
unsigned int acc[ARN_NWORD];
|
||||
@@ -249,7 +215,7 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
|
||||
}
|
||||
}
|
||||
// Flush lane-contiguously region by region, widest first, so each region is one coalesced
|
||||
// store of ARN_WV x width bytes. ARN_NWORD is 6 at ARN_CG 16 and 3 at 8.
|
||||
// store of ARN_WV x width bytes (ARN_NWORD is 3).
|
||||
char* pb = p_pay + (size_t)c * ARN_CBYTES;
|
||||
#pragma unroll
|
||||
for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4)
|
||||
@@ -272,8 +238,7 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
|
||||
if (drain == 2) __threadfence_system();
|
||||
arn_store_rel(&peer_flags[b], sq);
|
||||
unsigned long long z = 0;
|
||||
// A handshake that cannot complete is a lockstep violation: norming a slot the peer never
|
||||
// filled would hand stale bytes on as a sum, so it traps instead.
|
||||
// A handshake that cannot complete is a lockstep violation; trap rather than use stale bytes.
|
||||
while (r4d_ar_seq_behind(arn_load_acq(&my_flags[b]), sq)) {
|
||||
if (++z > R4D_ARN_SPIN_MAX) __builtin_trap();
|
||||
}
|
||||
@@ -281,14 +246,14 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
|
||||
__syncthreads();
|
||||
if (acq) __threadfence_system();
|
||||
|
||||
// The peer's rows are now in MY scratch, in the same [M, K] layout as X.
|
||||
// The peer's rows are now in my scratch, in the same [M, K] layout as X.
|
||||
const __hip_bfloat16* P = (const __hip_bfloat16*)ms;
|
||||
|
||||
if constexpr (WIRE == 6) {
|
||||
// REDUCE: unpack both halves of every chunk this block owns, add in fp32, inverse-rotate and
|
||||
// leave the reduced value in the norm's own staging slice. The norm then reads it exactly
|
||||
// where it would have read `x + p`, and overwrites the same slot with its rotated result --
|
||||
// one lane owns a slot in both passes, so the aliasing needs no second array.
|
||||
// Reduce: unpack both halves of every owned chunk, add in fp32, inverse-rotate, and leave the
|
||||
// result in the norm's staging slice. The norm reads it where it would read `x + p` and
|
||||
// overwrites it with its rotated result; one lane owns a slot in both passes, so the aliasing
|
||||
// is safe.
|
||||
for (int ci = wave; ci < cpb; ci += NW) {
|
||||
const int c = c00 + ci;
|
||||
const char* pb = m_pay + (size_t)c * ARN_CBYTES;
|
||||
@@ -321,22 +286,20 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
|
||||
psy |= pac[wi + 1] << (32 - bo);
|
||||
lsy |= lac[wi + 1] << (32 - bo);
|
||||
}
|
||||
// The two ranks fold the identical pair in OPPOSITE order; fp32 add commutes exactly, so
|
||||
// they stay bit-identical as long as neither product is contracted into an FMA.
|
||||
// libr4d/CMakeLists.txt passes -ffp-contract=off for exactly this.
|
||||
// The ranks fold the same pair in opposite order; fp32 add commutes, so they stay
|
||||
// bit-identical as long as neither product becomes an FMA (libr4d/CMakeLists.txt passes
|
||||
// -ffp-contract=off).
|
||||
v[i] = (float)((int)(psy & ARN_MASK) + ARN_QMIN) * psc
|
||||
+ (float)((int)(lsy & ARN_MASK) + ARN_QMIN) * lsc;
|
||||
}
|
||||
arn_wht(v, lig);
|
||||
const int e0 = (int)((long)(c * ARN_CG + gl) * ARN_GROUP + (long)lig * ARN_EPL
|
||||
- (long)r0 * K);
|
||||
// Rounded to bf16, as the unfused compressed all-reduce stores its sum and the norm reads
|
||||
// it back, so this matches the pair exactly.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < ARN_EPL; ++i)
|
||||
#if ARN_W6_MATCH
|
||||
lds[e0 + i] = __bfloat162float(__float2bfloat16(v[i]));
|
||||
#else
|
||||
lds[e0 + i] = v[i];
|
||||
#endif
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
@@ -356,15 +319,11 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
|
||||
float v[VPL];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPL; j++) {
|
||||
// WIRE == 0: ROUNDED TO bf16 ON PURPOSE. The standalone all-reduce accumulates in fp32
|
||||
// and STORES bf16, and the norm then reads that back -- so folding the reduce into the
|
||||
// norm's load would otherwise drop a rounding step and change the token stream. It would
|
||||
// change it for the better, but keeping the fused form bit-identical to the pair it
|
||||
// replaces is worth more than the accuracy. The price is one software RTNE per element
|
||||
// (gfx1201 has no bf16 convert instruction) on a kernel that is launch-bound rather than
|
||||
// ALU-bound. WIRE == 6 has no such pair to match: the compressed all-reduce it
|
||||
// replaces stores the fp32 sum straight to bf16 and the norm reads that, so here the sum
|
||||
// is taken from LDS in fp32 and the bf16 round trip is simply gone.
|
||||
// WIRE == 0 rounds to bf16 on purpose: the standalone all-reduce stores its fp32 sum as
|
||||
// bf16 and the norm reads that, so skipping the rounding would change the token stream.
|
||||
// Bit-identity with the unfused pair is preferred over the extra accuracy; the software
|
||||
// RTNE (gfx1201 has no bf16 convert) is cheap on this launch-bound kernel. WIRE == 6 reads
|
||||
// the reduced value from LDS, already rounded.
|
||||
float t;
|
||||
if constexpr (WIRE == 0) {
|
||||
t = __bfloat162float(__float2bfloat16(
|
||||
@@ -416,31 +375,27 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
|
||||
const int t = __float2int_rn(rl[sr] * inv);
|
||||
q[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
|
||||
}
|
||||
// lds and red are re-used by the next row this block owns.
|
||||
// lds and red are reused by the block's next row.
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
|
||||
// What the compressed wire costs in LDS, so the caller can pick its block count instead of
|
||||
// guessing. A block owns whole rows and holds, per row, a staging slice at `stage_bits` bits an
|
||||
// element plus the packed half of its own chunks; getting this wrong is not a slow launch but a
|
||||
// refused one.
|
||||
// LDS cost of the compressed wire, so the caller can choose a block count. A block owns whole
|
||||
// rows and holds, per row, a staging slice at `stage_bits` bits per element plus the packed half
|
||||
// of its own chunks; a block count that does not fit is refused.
|
||||
void r4d_ar_ln_wire_dims(int* stage_bits, int* chunk_elems, int* chunk_bytes, int* scale_bytes) {
|
||||
// 32: the reduced values are staged as fp32 IN THE NORM'S OWN ARRAY -- the norm reads a slot
|
||||
// and overwrites it with its rotated result, so the staging is not extra LDS at all. Staging
|
||||
// at bf16 instead would fit half again as many rows per block, but all that buys is a LOWER
|
||||
// block count and this kernel wants a higher one; at the row counts it actually runs, the two
|
||||
// occupy the same LDS and bf16 only adds conversions.
|
||||
// 32: reduced values are staged as fp32 in the norm's own array, so staging costs no extra LDS.
|
||||
// bf16 staging would fit more rows per block, but only lowers the block count, which this
|
||||
// kernel does not want; at the row counts it runs, the LDS is the same.
|
||||
if (stage_bits) *stage_bits = 32;
|
||||
if (chunk_elems) *chunk_elems = ARN_CE;
|
||||
if (chunk_bytes) *chunk_bytes = ARN_WV * ARN_NWORD * (int)sizeof(unsigned int);
|
||||
if (scale_bytes) *scale_bytes = ARN_CG * (int)sizeof(float);
|
||||
}
|
||||
|
||||
// The LDS one launch asks for: the norm's fp32 staging -- one row on the exact wire, every row the
|
||||
// block owns on the compressed one -- the two reduction planes, and on the compressed wire this
|
||||
// rank's packed half of every chunk the block owns. One formula for the launcher and for
|
||||
// r4d_ar_ln_blocks_min, so the block count a caller is told fits is the one the launcher accepts.
|
||||
// LDS per launch: the norm's fp32 staging (one row on the exact wire, every owned row on the
|
||||
// compressed one), the two reduction planes, and on the compressed wire this rank's packed half of
|
||||
// every owned chunk. Shared by the launcher and r4d_ar_ln_blocks_min so they agree.
|
||||
static size_t ar_ln_lds_bytes(int rows_max, int K, int thr, int wire) {
|
||||
size_t b = (size_t)(wire ? rows_max : 1) * K * sizeof(float) + 2 * (thr / 32) * sizeof(float);
|
||||
if (wire) {
|
||||
@@ -449,14 +404,13 @@ static size_t ar_ln_lds_bytes(int rows_max, int K, int thr, int wire) {
|
||||
}
|
||||
return b;
|
||||
}
|
||||
// The ceiling on that dynamic allocation: a workgroup's 64 KiB less the kernel's own static words
|
||||
// (the sequence and the slot), which the runtime places in front of it.
|
||||
// Dynamic LDS ceiling: a workgroup's 64 KiB less the kernel's static words (seq and slot), which
|
||||
// the runtime places in front of it.
|
||||
static constexpr size_t kArnLdsCap = 65536 - 16;
|
||||
|
||||
// The fewest blocks at which this shape fits: every block owns ceil(M / nb) rows, and on the
|
||||
// compressed wire each of them costs a staging slice and its chunks' packed half. -1 when no
|
||||
// block count serves it -- a row too wide to stage even alone, or too wide for the register
|
||||
// staging at this width -- which is the case the launcher would otherwise throw on.
|
||||
// Fewest blocks at which this shape fits: each block owns ceil(M / nb) rows, and on the compressed
|
||||
// wire each row costs a staging slice and its chunks' packed half. -1 when no block count fits (a
|
||||
// row too wide to stage alone, or for the register staging), where the launcher would throw.
|
||||
int r4d_ar_ln_blocks_min(int M, int K, int had, int nthreads, int wire) {
|
||||
if (M < 1 || K < 1 || had < 32 || K % had) return -1;
|
||||
if (wire != 0 && wire != 6) return -1;
|
||||
@@ -478,7 +432,6 @@ void r4d_ar_ln_had_quant_i8(long peer_scratch, long my_scratch, long peer_flags,
|
||||
int M, int K, int had, float eps, float wadd,
|
||||
long stream, int nblocks, int nthreads, int drain, int acq, int wire) {
|
||||
if (K % 16) throw std::runtime_error("r4d ar_ln_had_quant_i8: K must be a multiple of 16");
|
||||
if (K % 8) throw std::runtime_error("r4d ar_ln_had_quant_i8: K*2 must be 16B-aligned");
|
||||
if (M < 1) throw std::runtime_error("r4d ar_ln_had_quant_i8: M must be positive");
|
||||
if (had < 2 || (had & (had - 1))) throw std::runtime_error(
|
||||
"r4d ar_ln_had_quant_i8: had must be a power of two");
|
||||
@@ -496,10 +449,10 @@ void r4d_ar_ln_had_quant_i8(long peer_scratch, long my_scratch, long peer_flags,
|
||||
const int rows_max = (M + nb - 1) / nb;
|
||||
if (wire) {
|
||||
if (wire != 6) throw std::runtime_error("r4d ar_ln_had_quant_i8: wire must be 0 or 6");
|
||||
// A chunk may not straddle a row, or a block's rows would not be a whole number of chunks
|
||||
// and the two ranks would disagree about who owns which bytes.
|
||||
// A chunk may not straddle a row, or the ranks would disagree on byte ownership.
|
||||
if (K % ARN_CE) throw std::runtime_error(
|
||||
"r4d ar_ln_had_quant_i8: the 6-bit wire needs K to be a multiple of 1024");
|
||||
"r4d ar_ln_had_quant_i8: the 6-bit wire needs K to be a multiple of " +
|
||||
std::to_string(ARN_CE));
|
||||
}
|
||||
const size_t shmem = ar_ln_lds_bytes(rows_max, K, thr, wire);
|
||||
if (shmem > kArnLdsCap) throw std::runtime_error(
|
||||
|
||||
@@ -1,28 +1,23 @@
|
||||
// r4d_ar_oneshot_2rank_exact.hip: r4d_ar_oneshot_2rank_exact -- multi-block one-shot P2P-BAR
|
||||
// all-reduce, exactly two ranks, for dual R9700 (gfx1201/RDNA4, PCIe). "One-shot" is the
|
||||
// algorithm class: each rank pushes its whole input, so the scratch is sized by the full message
|
||||
// and there is no ring or reduce-scatter stage. "2rank" is a hard constraint, not a tuning
|
||||
// choice -- the handshake is one peer flag per block, not a tree. Pure HIP behind the C ABI in
|
||||
// r4d.h (wheel-ROCm ships no rocThrust, which torch/extension.h needs); the caller passes raw
|
||||
// data_ptr / numel / dtype / stream.
|
||||
// all-reduce, exactly two ranks, for dual R9700 (gfx1201/RDNA4, PCIe). One-shot: each rank pushes
|
||||
// its whole input, so scratch is sized by the full message and there is no ring or reduce-scatter
|
||||
// stage. Two ranks is a hard constraint: the handshake is one peer flag per block. Pure HIP behind
|
||||
// the C ABI in r4d.h; the caller passes raw pointers, element count, dtype and stream.
|
||||
//
|
||||
// Design:
|
||||
// * PUSH model: each rank writes ITS input into the PEER's IPC scratch, then reduces
|
||||
// (local input + peer's data now in MY scratch) -> out. Only scratch+flags are
|
||||
// IPC-shared; input/output stay local -> no cudagraph buffer registration needed.
|
||||
// * MULTI-BLOCK, per-chunk independent flags (NO grid barrier): block b owns a
|
||||
// contiguous chunk of 16B words -> pushes it to peer, sets peer_flags[b], spins on
|
||||
// my_flags[b], reduces its chunk. Spreads the push across CUs (PCIe saturation) and
|
||||
// the reduce across CUs (HBM saturation): the single-block bandwidth fix.
|
||||
// * cudagraph-safe: seq is a DEVICE-resident PER-BLOCK counter the kernel increments.
|
||||
// Both ranks execute the identical graph sequence (SPMD) so seq_ctr[b] stays in
|
||||
// lockstep across ranks regardless of which batch-size graphs ran.
|
||||
// * race-free reuse: scratch DOUBLE-BUFFERED by a per-LAUNCH parity (r4d_ar_seq.h says why it
|
||||
// is not seq&1); same-stream serialization + the per-block flag handshake guarantee a slot
|
||||
// is drained before reuse.
|
||||
// * FINE-GRAINED memory (hipDeviceMallocFinegrained) => uncached => posted straight to
|
||||
// the fabric => SCOPE_SYS release/acquire skip the L2 writeback. drain/acq explicit
|
||||
// fences are tunable (all-thread system fences; default drain=1/acq=0 on fine-grained).
|
||||
// * Push: each rank writes its input into the peer's IPC scratch, then reduces local input +
|
||||
// peer data (now in its own scratch) into out. Only scratch and flags are IPC-shared; input and
|
||||
// output stay local, so graph capture needs no buffer registration.
|
||||
// * Multi-block with per-chunk flags and no grid barrier: block b owns a contiguous chunk of 16B
|
||||
// words, pushes it, sets peer_flags[b], spins on my_flags[b] and reduces its chunk. This
|
||||
// spreads the push (PCIe) and the reduce (memory) across CUs.
|
||||
// * Graph-safe: seq is a device-resident per-block counter the kernel increments. Both ranks run
|
||||
// the same launch sequence (SPMD), so seq_ctr[b] stays in lockstep across ranks.
|
||||
// * Reuse: scratch is double-buffered by a per-launch parity (r4d_ar_seq.h explains why not
|
||||
// seq&1); same-stream serialisation plus the handshake drain a slot before reuse.
|
||||
// * 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.h"
|
||||
#include "r4d_ar_seq.h"
|
||||
#include "r4d_ar_hc.h" // the gather word and the hc write word, shared with the rotated wire
|
||||
@@ -51,7 +46,7 @@ __device__ __forceinline__ void rd_from_f(float v, float& o) { o = v; }
|
||||
__device__ __forceinline__ void rd_from_f(float v, __half& o) { o = __float2half(v); }
|
||||
__device__ __forceinline__ void rd_from_f(float v, __hip_bfloat16& o) { o = (__hip_bfloat16)v; }
|
||||
|
||||
// vectorized 128-bit add: an int4 packs LANES elements of T; fp32-accumulate reduce.
|
||||
// Vectorised 128-bit add: an int4 packs LANES elements of T, summed in fp32.
|
||||
template <typename T, int LANES>
|
||||
__device__ __forceinline__ int4 vadd(const int4& a, const int4& b) {
|
||||
int4 r;
|
||||
@@ -63,8 +58,8 @@ __device__ __forceinline__ int4 vadd(const int4& a, const int4& b) {
|
||||
return r;
|
||||
}
|
||||
|
||||
// Multi-block one-shot all-reduce. Each block owns words [start,end) of the 16B-word
|
||||
// space and drives its own flag handshake; fully independent, no cross-block sync.
|
||||
// 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>
|
||||
__global__ void r4d_ar_oneshot_2rank_exact_kernel(
|
||||
const int4* __restrict__ in4, int4* peer_base, const int4* my_base, int4* __restrict__ out4,
|
||||
@@ -82,7 +77,7 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel(
|
||||
const int start = b * w;
|
||||
int end = start + w; if (end > n16) end = n16;
|
||||
|
||||
// push chunk -> peer slot, 4x-unrolled for memory-level parallelism (PCIe saturation)
|
||||
// Push the chunk to the peer slot, 4x unrolled for memory-level parallelism.
|
||||
{
|
||||
int k = start + tid;
|
||||
for (; k + 3 * nt < end; k += 4 * nt) {
|
||||
@@ -91,15 +86,14 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel(
|
||||
}
|
||||
for (; k < end; k += nt) ps[k] = in4[k];
|
||||
}
|
||||
// drain modes (ordering of the pushes vs the release flag, so the peer sees data first):
|
||||
// 0 = none (relies purely on PCIe posted-write ordering + the release flag)
|
||||
// 1 = all-thread __threadfence_system (safe but emits an L2 wb-invalidate per
|
||||
// wavefront (WASTED on fine-grained/uncached memory; floods at high nt*nb)
|
||||
// 2 = single-thread __threadfence_system (cheap but only drains wavefront 0's stores)
|
||||
// 3 = all-thread store-completion wait (s_wait_storecnt 0): every wavefront drains
|
||||
// its posted writes into the fabric with NO L2 wb-invalidate; PCIe keeps posted
|
||||
// writes to the same peer ordered, so the later release flag lands after the data.
|
||||
// Correct for FINE-GRAINED memory (uncached; coarse would leave data in L2).
|
||||
// Drain modes, ordering the pushes before the release flag so the peer sees data first:
|
||||
// 0 = none (relies on PCIe posted-write ordering and the release flag)
|
||||
// 1 = all-thread __threadfence_system: safe, but an L2 writeback-invalidate per wave, wasted
|
||||
// on fine-grained memory and costly at high nt*nb
|
||||
// 2 = single-thread __threadfence_system: cheap, but drains only wave 0's stores
|
||||
// 3 = all-thread s_wait_storecnt 0: every wave drains its posted writes with no L2
|
||||
// writeback-invalidate; PCIe keeps posted writes to one peer ordered, so the release flag
|
||||
// lands after the data. Correct only for fine-grained memory (coarse leaves data in L2).
|
||||
if (drain == 1) __threadfence_system();
|
||||
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
|
||||
__syncthreads();
|
||||
@@ -107,15 +101,14 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel(
|
||||
if (drain == 2) __threadfence_system();
|
||||
store_sys_rel(&peer_flags[b], s);
|
||||
unsigned long long z = 0;
|
||||
// A handshake that cannot complete is a lockstep violation: reducing a slot the peer never
|
||||
// filled would hand stale bytes on as a sum, so it traps instead.
|
||||
// A handshake that cannot complete is a lockstep violation; trap rather than sum stale bytes.
|
||||
while (r4d_ar_seq_behind(load_sys_acq(&my_flags[b]), s)) {
|
||||
if (++z > R4D_AR_SPIN_MAX) __builtin_trap();
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (acq) __threadfence_system();
|
||||
// reduce chunk (vectorized, 4x-unrolled): out = local input + peer input (staged in local scratch)
|
||||
// Reduce the chunk, 4x unrolled: out = local input + peer input (staged in local scratch).
|
||||
{
|
||||
int k = start + tid;
|
||||
for (; k + 3 * nt < end; k += 4 * nt) {
|
||||
@@ -128,16 +121,14 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// THE SAME ALL-REDUCE WITH THE GATED RESIDUAL'S WRITE AS ITS EPILOGUE. `y` is the message: every
|
||||
// word is reduced exactly as the kernel above reduces it and stored back, and then the hc streams
|
||||
// behind it take the write, h[r][c*n + i] += inj[r][c] * y[r][i], in hc_write's arithmetic
|
||||
// (r4d_hc_bf16.hip) -- its bf16 helpers, its expression, and the reduced value read as the bf16
|
||||
// the reduction stored, which is what hc_write reads back from memory. So the pair's output is
|
||||
// reproduced to the byte with no second launch: on this part a dependent launch is a gap of about
|
||||
// three microseconds, around a write that costs one or two.
|
||||
// The same all-reduce with the gated residual write as its epilogue. `y` is the message: each word
|
||||
// is reduced as above and stored back, then the hc streams take
|
||||
// h[r][c*n + i] += inj[r][c] * y[r][i] in hc_write's arithmetic (r4d_hc_bf16.hip) over the stored
|
||||
// bf16 value. The output matches the two-kernel pair byte for byte without the second launch (a
|
||||
// dependent launch gap is about 3 us on this part, against a 1-2 us write).
|
||||
//
|
||||
// A word is eight elements and a row is `n` of them with n a multiple of eight, so a word never
|
||||
// straddles a row and the block that reduces it owns every stream element behind it.
|
||||
// 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.
|
||||
__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,
|
||||
@@ -190,28 +181,24 @@ __global__ void r4d_ar_hc_write_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// THE SAME WRITE WITH THE MoE GATHER AS ITS PROLOGUE. The routed experts' rows go back to token
|
||||
// order -- y[t][i] = sum over t's slots, ascending, of w[t][j] * y_expert[slot][i], rounded to
|
||||
// bf16 -- with the shared arm folded as moe_gather folds it, and the word is pushed to the peer
|
||||
// and kept as this rank's message exactly as if moe_gather had written it and this kernel had read
|
||||
// it back. The arithmetic is moe_gather's, rounding helpers included: its narrows are
|
||||
// round-to-nearest-even (r4d_common.h), where the hc write below keeps hc_write's own. So the
|
||||
// three kernels' bytes are reproduced with two fewer dependent launches.
|
||||
// The same write with the MoE gather as its prologue. The routed experts' rows go back to token
|
||||
// order, y[t][i] = sum over t's slots, ascending, of w[t][j] * y_expert[slot][i] rounded to bf16,
|
||||
// with the shared arm folded in as moe_gather does; the word is pushed to the peer and kept as this
|
||||
// rank's message. The gather uses moe_gather's round-to-nearest-even narrows (r4d_common.h), the hc
|
||||
// write keeps hc_write's, so the bytes match the three separate kernels with two fewer launches.
|
||||
//
|
||||
// A block's words sit in at most R4D_ARG_ROWS rows (the launcher sizes the grid so), and the
|
||||
// slots of those rows are found once, in LDS, by one pass over the sorted list -- the scan
|
||||
// moe_gather makes a token at a time.
|
||||
// A block's words sit in at most R4D_ARG_ROWS rows (the launcher sizes the grid for it), and their
|
||||
// slots are found once, in LDS, in one pass over the sorted list.
|
||||
//
|
||||
// AT A PREFILL CHUNK THAT TABLE IS THE WRONG SHAPE. Eight rows a block is what makes it fit in
|
||||
// LDS, and at 2048 rows it takes hundreds of blocks -- each scanning the whole sorted list, and
|
||||
// each paying its own flag round trip over a fabric the all-reduce saturates with a few dozen. So
|
||||
// with INV the slots come from an inverse table instead -- inv[token * top_k + slot] = the sorted
|
||||
// row holding it, or -1 -- built by one launch in front (r4d_ar_gather_inv_kernel), and a block
|
||||
// owns as many rows as the all-reduce's own block count gives it. The gather's reads of the
|
||||
// routed rows then run beside the push of the words already summed, where the pair of kernels runs
|
||||
// them one after the other. The arithmetic is the table form's, value for value.
|
||||
/* inv[f] = i for every sorted row i holding slot f, and -1 for a slot no row holds: one block, so
|
||||
* the clear and the scatter are two phases with a barrier between them. */
|
||||
// That table does not suit a prefill chunk: eight rows per block means hundreds of blocks at 2048
|
||||
// rows, each scanning the whole sorted list and paying its own flag round trip, where a few dozen
|
||||
// already saturate the fabric. With INV the slots come from an inverse table instead
|
||||
// (inv[token * top_k + slot] = sorted row holding it, or -1), built by r4d_ar_gather_inv_kernel
|
||||
// beforehand, and the block count stays the all-reduce's. The gather's reads then overlap the push
|
||||
// of words already summed. The arithmetic is identical to the table form.
|
||||
|
||||
/* inv[f] = i for every sorted row i holding slot f, -1 for a slot no row holds. One block, so the
|
||||
* clear and the scatter are separated by a barrier. */
|
||||
__global__ void r4d_ar_gather_inv_kernel(int* __restrict__ inv, const int* __restrict__ sorted,
|
||||
int T) {
|
||||
for (int x = threadIdx.x; x < T; x += blockDim.x) inv[x] = -1;
|
||||
@@ -249,8 +236,8 @@ __global__ void r4d_ar_gather_hc_write_kernel(
|
||||
const int nrow = end > start ? (end - 1) / wpr - row_lo + 1 : 0;
|
||||
const int K = G.top_k;
|
||||
|
||||
/* The slot table. A slot no sorted row claims reads -1, so the clear and the scan are two
|
||||
* phases with a barrier between them, as in moe_gather. */
|
||||
/* Slot table. A slot no sorted row claims reads -1, so clear and scan are separated by a
|
||||
* barrier, as in moe_gather. */
|
||||
if (!INV) {
|
||||
for (int x = tid; x < nrow * K; x += nt) s_i[x] = -1;
|
||||
__syncthreads();
|
||||
@@ -271,7 +258,7 @@ __global__ void r4d_ar_gather_hc_write_kernel(
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
/* The gather, one word a thread a pass, pushed and kept. */
|
||||
/* Gather one word per thread per pass; push it and keep it. */
|
||||
for (int k = start + tid; k < end; k += nt) {
|
||||
const int row = k / wpr, i0 = (k - row * wpr) * 8;
|
||||
const int4 out = r4d_ar_gather_word<INV>(G, inv, s_i, s_w, s_g, row, row - row_lo, i0);
|
||||
@@ -302,8 +289,7 @@ __global__ void r4d_ar_gather_hc_write_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// The IPC handle is returned through a caller-owned buffer rather than a std::string so this
|
||||
// stays a C ABI; R4D_AR_HANDLE_BYTES is the fixed size the header promises.
|
||||
// The IPC handle goes into a caller-owned buffer of R4D_AR_HANDLE_BYTES so this stays a C ABI.
|
||||
static_assert(sizeof(hipIpcMemHandle_t) <= R4D_AR_HANDLE_BYTES, "ipc handle larger than the ABI buffer");
|
||||
|
||||
long r4d_ar_ipc_alloc(long size, int finegrained, char* out_handle, int* out_len) {
|
||||
@@ -311,8 +297,8 @@ long r4d_ar_ipc_alloc(long size, int finegrained, char* out_handle, int* out_len
|
||||
if (finegrained) HIPOK(hipExtMallocWithFlags(&p, size, hipDeviceMallocFinegrained));
|
||||
else HIPOK(hipMalloc(&p, size));
|
||||
HIPOK(hipMemset(p, 0, size));
|
||||
// The zeroes must be in memory before the pointer is handed to a peer, whose first push or flag
|
||||
// store would otherwise race a memset still queued behind it.
|
||||
// The zeroes must land before the pointer reaches a peer, or its first push or flag store could
|
||||
// race the queued memset.
|
||||
HIPOK(hipStreamSynchronize(nullptr));
|
||||
hipIpcMemHandle_t h;
|
||||
HIPOK(hipIpcGetMemHandle(&h, p));
|
||||
@@ -320,34 +306,18 @@ long r4d_ar_ipc_alloc(long size, int finegrained, char* out_handle, int* out_len
|
||||
*out_len = (int)sizeof(h);
|
||||
return (long)p;
|
||||
}
|
||||
long r4d_ar_ipc_open(const char* handle, int len) {
|
||||
hipIpcMemHandle_t h;
|
||||
if (len != (int)sizeof(h)) throw std::runtime_error("bad ipc handle size");
|
||||
std::memcpy(&h, handle, sizeof(h));
|
||||
void* p = nullptr;
|
||||
HIPOK(hipIpcOpenMemHandle(&p, h, hipIpcMemLazyEnablePeerAccess));
|
||||
return (long)p;
|
||||
}
|
||||
// A strided device-to-device copy, which is what an ALL-GATHER between two ranks is once the
|
||||
// peer's buffer is IPC-mapped: no reduction, no codec, nothing to schedule. The runtime's copy
|
||||
// path is the fast one for peer traffic on this part -- 13.52 GB/s per direction with both
|
||||
// directions running, against 9.30 for a kernel doing b128 peer loads and 10.1 for RCCL.
|
||||
// `dpitch`, `spitch` and `width` are BYTES; `height` is rows.
|
||||
// THE SAME COPY AS A KERNEL, WITH A BOUNDED WORKGROUP COUNT.
|
||||
// r4d_p2p_copy2d as a kernel with a bounded workgroup count.
|
||||
//
|
||||
// `hipMemcpy2DAsync` is not a DMA engine on this part -- it runs as
|
||||
// `__amd_rocclr_copyBufferRectAligned` -- and it launches ONE 16-thread workgroup per 16 bytes of
|
||||
// a row: a 64 x 248 KB rectangle is 62080 workgroups. Alone that is fine and reaches the link
|
||||
// rate. Sharing the part with a GEMM it is meant to hide under, it fills every scheduling slot,
|
||||
// costs that GEMM around 60% of its runtime again, and gains almost nothing itself.
|
||||
// hipMemcpy2DAsync is not a DMA engine on this part: it runs as
|
||||
// `__amd_rocclr_copyBufferRectAligned`, one 16-thread workgroup per 16 bytes of a row (62080
|
||||
// workgroups for 64 x 248 KB). Alone it reaches link rate, but beside the GEMM it should hide
|
||||
// under, it fills every scheduling slot and slows that GEMM by about 60%.
|
||||
//
|
||||
// A peer copy needs a very small grid: across access width x workgroup size x workgroup count x
|
||||
// loads-in-flight (swept by `dev/prrun.py`), 32 workgroups of 64 threads is within 0.1% of the
|
||||
// best point at every size. So this takes the grid as an argument and defaults to 64 workgroups,
|
||||
// which is a 0.1% footprint against the blit's 62080.
|
||||
// A peer copy needs only a small grid: 32 workgroups of 64 threads is within 0.1% of the best
|
||||
// configuration at every size. The grid is an argument and defaults to at most 64 workgroups.
|
||||
//
|
||||
// 16-byte accesses, so every pitch, the width and both base addresses must be 16-byte aligned; the
|
||||
// caller checks and falls back to `r4d_p2p_copy2d` when they are not.
|
||||
// 16-byte accesses: every pitch, the width and both base addresses must be 16-byte aligned; the
|
||||
// caller checks and falls back to r4d_p2p_copy2d otherwise.
|
||||
typedef unsigned r4d_u4v __attribute__((ext_vector_type(4)));
|
||||
|
||||
__global__ __launch_bounds__(256) void r4d_p2p_copy2d_k(const r4d_u4v* __restrict__ src,
|
||||
@@ -378,12 +348,10 @@ int r4d_p2p_copy2d_kernel(long dst, long src, long dpitch, long spitch, long wid
|
||||
return e == hipSuccess ? 0 : -100 - (int)e;
|
||||
}
|
||||
|
||||
// A SYSTEM-SCOPE RELEASE on `stream`, for the case where this device has written into the PEER's
|
||||
// memory and something other than this device is about to read it. A peer write issued by a copy
|
||||
// or a kernel is a posted write: it retires from the wave long before it lands, and the only thing
|
||||
// that orders it against a later handshake on a different path is a system-scope release. One
|
||||
// thread is enough -- the fence is a memory-system operation, not a per-lane one -- and it costs a
|
||||
// dispatch.
|
||||
// A system-scope release on `stream`, for when this device has written into peer memory that
|
||||
// another agent will read. A peer write from a copy or kernel is posted and retires long before it
|
||||
// lands; only a system-scope release orders it against a later handshake on a different path. One
|
||||
// thread suffices, since the fence is a memory-system operation.
|
||||
__global__ void r4d_p2p_fence_kernel() { __threadfence_system(); }
|
||||
|
||||
int r4d_p2p_fence(long stream) {
|
||||
@@ -392,6 +360,10 @@ int r4d_p2p_fence(long stream) {
|
||||
return e == hipSuccess ? 0 : -100 - (int)e;
|
||||
}
|
||||
|
||||
// A strided device-to-device copy: a two-rank all-gather once the peer's buffer is IPC-mapped.
|
||||
// The runtime's copy path is the fast one for peer traffic on this part (13.52 GB/s per direction
|
||||
// with both directions busy, against 9.30 for a b128-load kernel and 10.1 for RCCL).
|
||||
// `dpitch`, `spitch` and `width` are bytes; `height` is rows.
|
||||
int r4d_p2p_copy2d(long dst, long src, long dpitch, long spitch, long width, long height,
|
||||
long stream) {
|
||||
hipError_t e = hipMemcpy2DAsync((void*)dst, (size_t)dpitch, (const void*)src, (size_t)spitch,
|
||||
@@ -407,6 +379,7 @@ void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long m
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
if (n <= 0 || M <= 0 || n % 8) throw std::runtime_error("ar_hc_write: n must be a positive multiple of 8");
|
||||
if (hc < 1 || hrow % 8) throw std::runtime_error("ar_hc_write: the streams must be whole 16B words");
|
||||
if (M * n * 2 / 16 > slot_stride16) throw std::runtime_error("ar_hc_write: message larger than a slot");
|
||||
const int n16 = (int)(M * n * 2 / 16);
|
||||
int nb = (int)nblocks;
|
||||
if (nb < 1) nb = 1;
|
||||
@@ -434,20 +407,20 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags,
|
||||
if (n <= 0 || M <= 0 || n % 8 || hc < 1 || hrow % 8) return -1;
|
||||
if (top_k < 1 || top_k > R4D_ARG_SLOTS) return -2;
|
||||
if (ye_ld % 8 || (sh && sh_ld < n)) return -3;
|
||||
if (M * n * 2 / 16 > slot_stride16) return -5; /* larger than a slot */
|
||||
const int n16 = (int)(M * n * 2 / 16);
|
||||
const int wpr = (int)(n / 8);
|
||||
const unsigned nbw = (unsigned)r4d_ar_max_blocks();
|
||||
int nb = (int)nblocks;
|
||||
if (nb < 1) nb = 1;
|
||||
/* THE GRID IS AT LEAST WIDE ENOUGH THAT NO BLOCK SPANS MORE THAN R4D_ARG_ROWS ROWS: a block of
|
||||
* w words starting anywhere touches at most (w - 1) / wpr + 2 rows. Both ranks compute the same
|
||||
* count from the same M and n, which the per-block handshake requires. */
|
||||
/* Enough blocks that none spans more than R4D_ARG_ROWS rows: a block of w words touches at most
|
||||
* (w - 1) / wpr + 2 rows. Both ranks compute the same count from the same M and n, as the
|
||||
* per-block handshake requires. */
|
||||
const int wmax = (R4D_ARG_ROWS - 2) * wpr + 1;
|
||||
const int nb_min = (n16 + wmax - 1) / wmax;
|
||||
/* THE INVERSE TABLE WHEN THE LDS ONE WOULD NEED MORE BLOCKS THAN THE REDUCTION WANTS, which is
|
||||
* a prefill chunk and never a decode step. Both ranks decide it from the same M and n. The
|
||||
* block count stays the reduction's: at a 2048-row chunk 48 and 96 blocks measure within half
|
||||
* a percent of its 24, and 192 no better. */
|
||||
/* Use the inverse table when the LDS table would need more blocks than requested (a prefill
|
||||
* chunk, never a decode step); both ranks decide from the same M and n. The block count stays
|
||||
* the requested one: at a 2048-row chunk, 48, 96 and 192 blocks are no faster than 24. */
|
||||
const bool by_inv = inv != 0 && nb_min > nb;
|
||||
if (!by_inv && nb < nb_min) nb = nb_min;
|
||||
if (nb > n16) nb = n16;
|
||||
@@ -455,8 +428,8 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags,
|
||||
int nt = (int)nthreads;
|
||||
if (nt < 64) nt = 64;
|
||||
if (nt > 1024) nt = 1024;
|
||||
/* Zeroed whole, padding included: the struct is passed by value, so its tail padding is
|
||||
* kernel-argument bytes too, and a recorded pass's audit compares those bytes. */
|
||||
/* Zeroed including padding: the struct is passed by value, so its tail padding is part of the
|
||||
* kernel-argument bytes a recorded pass's audit compares. */
|
||||
R4dArGather G;
|
||||
std::memset(&G, 0, sizeof G);
|
||||
G.ye = (const unsigned short*)ye;
|
||||
@@ -483,8 +456,8 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags,
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
|
||||
/* The inverse slot table alone, on `stream`, for the wide fused gather (r4d_ar_oneshot_Nrank_exact.hip):
|
||||
* the same kernel and the same launch as above, so both widths read one table. */
|
||||
/* The inverse slot table alone, for the wide fused gather (r4d_ar_oneshot_Nrank_exact.hip); same
|
||||
* kernel and launch as above. */
|
||||
int r4d_ar_gather_inv(long inv, long sorted, long T, long stream_i) {
|
||||
if (!inv || !sorted || T < 1) return -1;
|
||||
r4d_ar_gather_inv_kernel<<<1, 1024, 0, (hipStream_t)stream_i>>>((int*)inv, (const int*)sorted,
|
||||
@@ -493,14 +466,11 @@ int r4d_ar_gather_inv(long inv, long sorted, long T, long stream_i) {
|
||||
}
|
||||
|
||||
void r4d_ar_ipc_free(long p) { if (p) (void)hipFree((void*)p); }
|
||||
void r4d_ar_ipc_memzero(long p, long size) { if (p) HIPOK(hipMemset((void*)p, 0, size)); }
|
||||
|
||||
// THE HOST MAILBOX. Coherent so a peer's stores are not held in a CPU cache line this card reads
|
||||
// around, mapped so the cards address it, portable so every card does and not only the one
|
||||
// current at allocation. A card reaches it through the same fine-grained path a peer's VRAM
|
||||
// scratch is reached by, so the kernels' fences mean what they mean there. The address a card
|
||||
// uses must be the CPU's own, because one pointer is published to every rank: a mapping that put
|
||||
// the pages elsewhere on some card would have each rank write where no other rank reads.
|
||||
// Host mailbox. Coherent so a peer's stores are not held in a CPU cache line, mapped so cards can
|
||||
// address it, portable so every card can (not only the current one). Cards reach it over the same
|
||||
// fine-grained path as a peer's VRAM scratch, so the kernels' fences apply unchanged. The card
|
||||
// address must equal the CPU address, because one pointer is published to every rank.
|
||||
long r4d_ar_host_alloc(long size) {
|
||||
void* p = nullptr;
|
||||
HIPOK(hipHostMalloc(&p, size, hipHostMallocCoherent | hipHostMallocMapped |
|
||||
@@ -518,9 +488,8 @@ long r4d_ar_host_alloc(long size) {
|
||||
}
|
||||
void r4d_ar_host_free(long p) { if (p) (void)hipHostFree((void*)p); }
|
||||
|
||||
// Enable direct peer access. radiance runs one process with a thread per rank sharing an address
|
||||
// space, so a peer pointer is valid here once this has run and no IPC handle exchange is needed;
|
||||
// see the header of r4d_ar_entry.hip.
|
||||
// Enable direct peer access. Ranks are threads of one process sharing an address space, so a peer
|
||||
// pointer is valid once this has run and no IPC handle exchange is needed (see r4d_ar_entry.hip).
|
||||
void r4d_ar_ipc_enable_peer(long peer) {
|
||||
hipError_t e = hipDeviceEnablePeerAccess((int)peer, 0);
|
||||
if (e == hipErrorPeerAccessAlreadyEnabled) { (void)hipGetLastError(); return; }
|
||||
@@ -537,13 +506,14 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl
|
||||
const int esize = (dtype == 2) ? 4 : 2;
|
||||
const long nbytes = (long)n_elem * esize;
|
||||
if (nbytes % 16 != 0) throw std::runtime_error("all_reduce: n_elem*esize not 16B-aligned");
|
||||
if (nbytes / 16 > slot_stride16) throw std::runtime_error("all_reduce: message larger than a slot");
|
||||
const int n16 = (int)(nbytes / 16);
|
||||
int nb = (int)nblocks;
|
||||
if (nb < 1) nb = 1;
|
||||
if (nb > n16) nb = n16;
|
||||
if (nb > R4D_AR_MAX_BLOCKS) nb = R4D_AR_MAX_BLOCKS;
|
||||
// The counter allocation's block capacity, which every 2-rank kernel on an instance must agree
|
||||
// on because the parity counters sit that many words in (r4d_ar_seq.h).
|
||||
// Block capacity of the counter allocation. Every 2-rank kernel on an instance must agree on it,
|
||||
// because the parity counters start that many words in (r4d_ar_seq.h).
|
||||
const unsigned nbw = (unsigned)r4d_ar_max_blocks();
|
||||
if ((unsigned)nb > nbw) nb = (int)nbw;
|
||||
int nt = (int)nthreads;
|
||||
|
||||
@@ -1,37 +1,34 @@
|
||||
#pragma once
|
||||
// r4d_ar_oneshot_2rank_wht6.h: device code for r4d_ar_oneshot_2rank_wht6, the rotated 6-bit payload of the
|
||||
// one-shot 2-rank P2P all-reduce on dual R9700 (gfx1201/RDNA4, PCIe). Companion to
|
||||
// r4d_ar_oneshot_2rank_exact.hip: reuses the IPC scratch, per-block flags and device-resident seq
|
||||
// counters that module allocates. Dispatched for large messages, where the wire time dominates
|
||||
// and 6.25 bits per element buys more than the rotation and packing cost.
|
||||
// one-shot 2-rank P2P all-reduce on dual R9700 (gfx1201/RDNA4, PCIe). Reuses the IPC scratch,
|
||||
// per-block flags and device-resident seq counters of r4d_ar_oneshot_2rank_exact.hip. Used for
|
||||
// large messages, where wire time dominates and 6.25 bits per element saves more than the rotation
|
||||
// and packing cost.
|
||||
//
|
||||
// Design:
|
||||
// * Each group of GROUP=64 is rotated by an orthonormal Walsh-Hadamard, scaled by its own
|
||||
// amax and stored as BITS=6 uniform bits plus a bf16 scale -> 6.25 bits/element. The
|
||||
// rotation removes the outlier channel, which is what makes 6 uniform bits enough.
|
||||
// * PUSH rotates, quantizes and packs straight into the peer's scratch, keeping a copy of
|
||||
// the same words locally. REDUCE unpacks both halves, adds in fp32, inverse-rotates (the
|
||||
// transform is its own inverse) and stores bf16/fp16.
|
||||
// * The local half is kept packed rather than recomputed: re-deriving it would repeat the
|
||||
// rotation and the amax reduction.
|
||||
// * Both ranks fold the identical pair and fp32 add commutes, so the ranks stay
|
||||
// bit-identical. MUST be built with -ffp-contract=off: the two ranks see the two products
|
||||
// in opposite order, and contracting either into an FMA makes them disagree by ~1 ULP.
|
||||
// * cudagraph-safe and double-buffered as in r4d_ar_oneshot_2rank_exact.hip: per-block device-resident
|
||||
// seq counter, slot from the per-launch parity counters (r4d_ar_seq.h).
|
||||
// * Each group of GROUP=64 is rotated by an orthonormal Walsh-Hadamard, scaled by its own amax
|
||||
// and stored as BITS=6 uniform bits plus a bf16 scale (6.25 bits/element). The rotation
|
||||
// spreads the outlier channel, which is what makes 6 uniform bits enough.
|
||||
// * Push rotates, quantizes and packs straight into the peer's scratch and keeps a local copy
|
||||
// of the same words (cheaper than repeating the rotation and amax). Reduce unpacks both
|
||||
// halves, adds in fp32, inverse-rotates (the transform is its own inverse) and stores
|
||||
// bf16/fp16.
|
||||
// * Both ranks fold the same pair and fp32 add commutes, so the ranks stay bit-identical. Must
|
||||
// be built with -ffp-contract=off: the ranks see the two products in opposite order, and an
|
||||
// FMA on either makes them differ by ~1 ULP.
|
||||
// * Graph-safe and double-buffered as in r4d_ar_oneshot_2rank_exact.hip: per-block
|
||||
// device-resident seq counter, slot from the per-launch parity counters (r4d_ar_seq.h).
|
||||
//
|
||||
// Layout, per slot, inside the shared 2*max_bytes scratch:
|
||||
// [ packed symbols, chunk-interleaved ] ... [ scale_off_bytes ] ... [ bf16 scales: n_groups ]
|
||||
// A CHUNK is 32 groups = 2048 elements here. One wave owns a chunk and every lane emits exactly 64
|
||||
// symbols = 384 bits = three uint4, so flush points are lane-uniform and lane L's u-th uint4
|
||||
// lands at c*96 + u*WAVE + L: one coalesced 512B store per wave. A chunk of fewer groups
|
||||
// (Wht6Chunk, below) packs its lane's NW words the same way, as dwords when NW is not a multiple of
|
||||
// four.
|
||||
// A chunk is 32 groups = 2048 elements by default. One wave owns a chunk and every lane emits 64
|
||||
// symbols = 384 bits = three uint4, so flush points are lane-uniform and lane L's u-th uint4 lands
|
||||
// at c*96 + u*WAVE + L: one coalesced 512B store per wave. Smaller chunks (Wht6Chunk) pack a
|
||||
// lane's NW words the same way, as dwords when NW is not a multiple of four.
|
||||
//
|
||||
// n_groups need not tile a chunk. Groups past the end quantize zeros and are skipped on the way
|
||||
// out. That is only safe because a group spans LPG lane-contiguous lanes and every cross-lane
|
||||
// exchange in wht() is intra-group (m < LPG), so a group is wholly active or wholly inactive and
|
||||
// no shuffle is ever split across the guard.
|
||||
// n_groups need not tile a chunk: groups past the end quantize zeros and are skipped on output.
|
||||
// This is safe only because a group spans LPG contiguous lanes and every cross-lane exchange in
|
||||
// wht() stays inside the group (m < LPG), so no shuffle is split across the guard.
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <hip/hip_bf16.h>
|
||||
@@ -67,8 +64,8 @@ __device__ __forceinline__ float rd_to_f(const __hip_bfloat16& x) { return (floa
|
||||
__device__ __forceinline__ void rd_from_f(float v, __half& o) { o = __float2half(v); }
|
||||
__device__ __forceinline__ void rd_from_f(float v, __hip_bfloat16& o) { o = (__hip_bfloat16)v; }
|
||||
|
||||
// RTNE to bf16 and back: the scale ships as its top 16 bits, so the sender's local copy has to be
|
||||
// exactly what the receiver reconstructs.
|
||||
// RTNE to bf16 and back: the scale ships as its top 16 bits, and the sender's local copy must
|
||||
// equal what the receiver reconstructs.
|
||||
__device__ __forceinline__ float bf16_round(float v) {
|
||||
unsigned u = __float_as_uint(v);
|
||||
const unsigned lsb = (u >> 16) & 1u;
|
||||
@@ -77,9 +74,9 @@ __device__ __forceinline__ float bf16_round(float v) {
|
||||
}
|
||||
|
||||
|
||||
// `lo ? (v + o) : (o - v)` written as `o + (lo ? v : -v)`: the sign flip is one XOR against a mask
|
||||
// that is uniform over the whole stage, so the per-element select disappears. Bit-identical --
|
||||
// IEEE negation is exact and addition commutes.
|
||||
// `lo ? (v + o) : (o - v)` written as `o + (lo ? v : -v)`: the sign flip is one XOR with a mask
|
||||
// uniform over the stage, so the per-element select disappears. Bit-identical, since IEEE negation
|
||||
// is exact and addition commutes.
|
||||
template <int M>
|
||||
__device__ __forceinline__ void ar6_xstage(float* v, int lig) {
|
||||
const unsigned int sm = (lig & M) ? 0x80000000u : 0u;
|
||||
@@ -108,17 +105,16 @@ __device__ __forceinline__ void wht(float* v, int lig) {
|
||||
for (int i = 0; i < EPL; ++i) v[i] *= nrm;
|
||||
}
|
||||
|
||||
// THE WIRE'S TWO HALVES OVER ONE WAVE-CHUNK, so every kernel carrying the rotated payload -- the
|
||||
// all-reduce below and the fused gated-residual writes in r4d_ar_oneshot_2rank_wht6.hip -- packs and
|
||||
// unpacks the same bytes by the same arithmetic. `ld(off, v)` fills the EPL elements of a LIVE group
|
||||
// that start at message element `off`; `st(off, v)` takes the reduced EPL elements there. Each is
|
||||
// called once per live group a lane, and a dead group quantizes zeros and is skipped on the way out.
|
||||
// Push and reduce over one wave-chunk, shared by every kernel carrying the rotated payload (the
|
||||
// all-reduce below and the fused gated-residual writes in r4d_ar_oneshot_2rank_wht6.hip), so all
|
||||
// pack and unpack the same bytes. `ld(off, v)` fills the EPL elements of a live group starting at
|
||||
// message element `off`; `st(off, v)` takes the reduced EPL elements there. Each runs once per
|
||||
// live group per lane; a dead group quantizes zeros and is skipped on output.
|
||||
//
|
||||
// CG IS THE CHUNK, in groups: 32 here (2048 elements, three uint4 a lane), fewer where a kernel
|
||||
// wants more waves at work. It decides who owns which bytes and where they sit in the slot, never
|
||||
// their values -- the rotation and the amax close over a group at any chunking -- so two kernels
|
||||
// agree on the wire exactly when they agree on CG, which the kernel pair on the two ranks always
|
||||
// does. A chunk of NW words a lane that is not a whole number of uint4 goes out as dwords.
|
||||
// CG is the chunk in groups: 32 by default (2048 elements, three uint4 per lane), fewer where a
|
||||
// kernel wants more waves. It sets byte ownership and placement in the slot, never values (the
|
||||
// rotation and amax are per group), so two kernels agree on the wire iff they agree on CG. A
|
||||
// lane's NW words go out as dwords when NW is not a multiple of four.
|
||||
template <int CG>
|
||||
struct Wht6Chunk {
|
||||
static constexpr int ITERS = CG * GROUP / (WAVE * EPL); // group-iterations a chunk
|
||||
@@ -129,7 +125,7 @@ struct Wht6Chunk {
|
||||
static_assert(ITERS * EPL * BITS % 32 == 0, "a lane's symbols fill whole words");
|
||||
};
|
||||
|
||||
// PUSH: rotate, amax, quantize, pack -> peer scratch, plus a local copy for the reduce.
|
||||
// Push: rotate, amax, quantize, pack into peer scratch, plus a local copy for the reduce.
|
||||
template <int CG = CHUNK_GROUPS, typename Ld>
|
||||
__device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_groups, int lane,
|
||||
int lig, int gw, uint4* p_pay,
|
||||
@@ -194,9 +190,8 @@ __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_group
|
||||
}
|
||||
}
|
||||
|
||||
// The handshake: drain the pushes into the fabric, then a per-block release flag and a spin on the
|
||||
// peer's. A handshake that cannot complete is a lockstep violation -- reducing a slot the peer never
|
||||
// filled would hand stale bytes on as a sum -- so it traps instead.
|
||||
// Handshake: drain the pushes into the fabric, set a per-block release flag and spin on the peer's.
|
||||
// A handshake that cannot complete is a lockstep violation; trap rather than sum stale bytes.
|
||||
__device__ __forceinline__ void wht6_handshake(unsigned int* peer_flags, unsigned int* my_flags,
|
||||
int b, unsigned int s, int tid, int drain,
|
||||
int acq) {
|
||||
@@ -214,7 +209,7 @@ __device__ __forceinline__ void wht6_handshake(unsigned int* peer_flags, unsigne
|
||||
if (acq) __threadfence_system();
|
||||
}
|
||||
|
||||
// REDUCE: unpack both halves, add in fp32, inverse-rotate, hand each live group's EPL elements on.
|
||||
// Reduce: unpack both halves, add in fp32, inverse-rotate, pass each live group's EPL elements to st.
|
||||
template <int CG = CHUNK_GROUPS, typename St>
|
||||
__device__ __forceinline__ void wht6_reduce_chunk(const St& st, int c, int n_groups, int lane,
|
||||
int lig, int gw, const uint4* m_pay,
|
||||
@@ -293,7 +288,7 @@ __global__ void r4d_ar_oneshot_2rank_wht6_kernel(
|
||||
const int lane = tid & (WAVE - 1), wid = tid / WAVE, nwarp = nt / WAVE;
|
||||
const int lig = lane & (LPG - 1), gw = lane / LPG;
|
||||
__shared__ unsigned int s_seq, s_slot;
|
||||
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe (cudagraph)
|
||||
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot,
|
||||
slot_stride_bytes, scale_off_bytes);
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
// r4d_ar_oneshot_2rank_wht6.hip: translation unit for r4d_ar_oneshot_2rank_wht6, the all-reduce whose wire
|
||||
// payload is Walsh-Hadamard rotated and quantised to 6 bits. The device code and the launcher live
|
||||
// in r4d_ar_oneshot_2rank_wht6.h so the same source also compiles standalone (no Python, no r4d); this file gives
|
||||
// them the library's C ABI and reports the packing constants the caller needs to size its scratch.
|
||||
// It also holds the rotated wire's fused forms of ar_hc_write and ar_gather_hc_write, which need
|
||||
// the library's gather and hc-write arithmetic (r4d_ar_hc.h) and so live here, not in the header.
|
||||
// payload is Walsh-Hadamard rotated and quantised to 6 bits. Device code and launcher live in
|
||||
// r4d_ar_oneshot_2rank_wht6.h so they also compile standalone without r4d; this file exports them
|
||||
// through the library's C ABI with the packing constants for sizing scratch. It also holds the
|
||||
// rotated wire's fused ar_hc_write and ar_gather_hc_write, which need r4d_ar_hc.h.
|
||||
#include "r4d.h"
|
||||
#include "r4d_ar_hc.h" // the gather word and the hc write word, shared with the exact wire
|
||||
#include "r4d_ar_oneshot_2rank_wht6.h"
|
||||
#include <cstring>
|
||||
|
||||
void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
|
||||
long seq_ctrs, long loc_pack, long slot_stride_bytes,
|
||||
@@ -20,7 +20,7 @@ void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_fla
|
||||
// Block cap of both all-reduce kernels (the flag array is sized from it).
|
||||
int r4d_ar_max_blocks(void) { return R4D_AR_MAX_BLOCKS; }
|
||||
|
||||
// The rotated-6-bit wire format, which the caller needs to size its packed scratch.
|
||||
// Rotated 6-bit wire format dimensions, for sizing the caller's packed scratch.
|
||||
void r4d_ar_wht6_dims(int* group, int* bits, int* chunk_elems) {
|
||||
if (group) *group = GROUP;
|
||||
if (bits) *bits = BITS;
|
||||
@@ -28,37 +28,33 @@ void r4d_ar_wht6_dims(int* group, int* bits, int* chunk_elems) {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// THE ROTATED WIRE WITH THE GATED RESIDUAL'S WRITE AS ITS EPILOGUE, and with GATHER the MoE gather
|
||||
// as its prologue: the 6-bit twins of r4d_ar_hc_write_kernel and r4d_ar_gather_hc_write_kernel
|
||||
// (r4d_ar_oneshot_2rank_exact.hip). Each reproduces the unfused chain it replaces to the byte --
|
||||
// moe_gather, r4d_ar_oneshot_2rank_wht6, hc_write -- because every stage is the same code: the
|
||||
// gather word and the write word are r4d_ar_hc.h's, and the wire is wht6_push_chunk and
|
||||
// wht6_reduce_chunk (r4d_ar_oneshot_2rank_wht6.h) at a smaller chunk, which moves bytes between
|
||||
// owners and never changes them. The message's words are the chain's words: the gather's are rounded to
|
||||
// bf16 as moe_gather stores them, and the reduced sum is rounded to bf16 as the standalone
|
||||
// all-reduce stores it, stored into `y`, and read back as that bf16 by the write.
|
||||
// The rotated wire with the gated residual write as epilogue and, with GATHER, the MoE gather as
|
||||
// prologue: 6-bit counterparts of r4d_ar_hc_write_kernel and r4d_ar_gather_hc_write_kernel
|
||||
// (r4d_ar_oneshot_2rank_exact.hip). Each matches the unfused chain (moe_gather,
|
||||
// r4d_ar_oneshot_2rank_wht6, hc_write) byte for byte because every stage is the same code: the
|
||||
// gather and write words from r4d_ar_hc.h, and wht6_push_chunk / wht6_reduce_chunk at a smaller
|
||||
// chunk, which changes byte ownership but not values. Gathered words are rounded to bf16 as
|
||||
// moe_gather stores them; the reduced sum is rounded to bf16, stored into `y` and read back as
|
||||
// such by the write.
|
||||
//
|
||||
// A lane's EPL elements are one word, so a word -- and the write behind it -- never straddles a row
|
||||
// even where a group or a chunk does: the rotation closes over the flattened message, the write
|
||||
// over the row the word sits in.
|
||||
// A lane's EPL elements are one word, so a word and its write never straddle a row even where a
|
||||
// group or chunk does: the rotation spans the flattened message, the write the word's row.
|
||||
//
|
||||
// THE GATHER READS ITS SLOTS FROM A TABLE IN LDS, built by the block from the sorted list: the
|
||||
// rows a block owns (whole wave-chunks, so tens of rows at a prefill chunk) and every slot of them,
|
||||
// found by one pass over the list -- the exact form's decode-sized table, sized here by the launch
|
||||
// rather than fixed at R4D_ARG_ROWS. A word's reads of the routed rows then wait on nothing but
|
||||
// their own addresses, where the inverse table puts a dependent load of the slot in front of each.
|
||||
// The launcher widens the grid until a block's table fits.
|
||||
// The gather reads its slots from an LDS table the block builds in one pass over the sorted list,
|
||||
// covering every row it owns (whole wave-chunks, so tens of rows at a prefill chunk); unlike the
|
||||
// exact form it is sized by the launch, not fixed at R4D_ARG_ROWS. Reads of the routed rows then
|
||||
// depend only on their own addresses, where an inverse table adds a dependent slot load before
|
||||
// each. The launcher widens the grid until a block's table fits.
|
||||
static_assert(EPL == 8, "a lane's share of a group is one 16B word of the message");
|
||||
|
||||
// The LDS a block's slot table may take; the handshake's two words sit beside it.
|
||||
static constexpr size_t kWht6TableBytes = 60 * 1024;
|
||||
|
||||
// THE FUSED FORMS' CHUNK IS 8 GROUPS -- 512 elements, two group-iterations a wave -- where the
|
||||
// standalone all-reduce's is 32. A wave walks its chunk's groups one after another and each one
|
||||
// waits on its own reads -- the routed rows of the gather, the streams of the write -- so a
|
||||
// quarter of the chunk is four times the waves at work on the same message: at a 2048-row chunk
|
||||
// the gather form takes 403 us a call, against 500 at the standalone chunk and 416 at 16 groups.
|
||||
// The two ranks run the same kernel, so the chunking both push and reduce under is the same.
|
||||
// The fused forms use 8-group chunks (512 elements, two group-iterations per wave) instead of the
|
||||
// standalone 32. A wave walks its groups serially, each waiting on its own reads (routed rows,
|
||||
// streams), so a quarter-size chunk puts four times as many waves on the message: at a 2048-row
|
||||
// chunk the gather form takes 403 us against 500 at 32 groups and 416 at 16. Both ranks run the
|
||||
// same kernel, so they push and reduce under the same chunking.
|
||||
static constexpr int kWht6FusedCG = 8;
|
||||
|
||||
// The rows block b's chunks of `ce` elements touch: [row_lo, row_lo + nrow).
|
||||
@@ -85,7 +81,7 @@ __global__ void r4d_ar_hc_write_wht6_kernel(
|
||||
__shared__ unsigned int s_seq, s_slot;
|
||||
extern __shared__ int s_tab[]; // slots, weights: [rows_max * top_k]; gates: [rows_max]
|
||||
const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid);
|
||||
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe (cudagraph)
|
||||
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot,
|
||||
slot_stride_bytes, scale_off_bytes);
|
||||
@@ -93,8 +89,8 @@ __global__ void r4d_ar_hc_write_wht6_kernel(
|
||||
const int cpb = (n_chunks + nb - 1) / nb; // block b owns chunks [c0,c1)
|
||||
const int c0 = b * cpb; int c1 = c0 + cpb; if (c1 > n_chunks) c1 = n_chunks;
|
||||
|
||||
/* The slot table, as the exact form's: a slot no sorted row claims reads -1, so the clear and
|
||||
* the scan are two phases with a barrier between them. */
|
||||
/* Slot table, as in the exact form: a slot no sorted row claims reads -1, so clear and scan are
|
||||
* separated by a barrier. */
|
||||
int* s_i = s_tab;
|
||||
float* s_w = reinterpret_cast<float*>(s_tab + rows_max * G.top_k);
|
||||
float* s_g = s_w + rows_max * G.top_k;
|
||||
@@ -172,8 +168,8 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, lo
|
||||
const int n_chunks = (n_groups + kWht6FusedCG - 1) / kWht6FusedCG;
|
||||
int nb = clamp_blocks((int)nblocks, n_chunks);
|
||||
const int nt = clamp_threads((int)nthreads);
|
||||
/* THE TABLE HAS TO FIT, so the grid widens until it does: a block of cpb chunks touches at most
|
||||
* (cpb * ce - 1) / n + 2 rows. Both ranks compute the same grid from the same M and n, which the
|
||||
/* Widen the grid until the table fits: a block of cpb chunks touches at most
|
||||
* (cpb * ce - 1) / n + 2 rows. Both ranks compute the same grid from the same M and n, as the
|
||||
* per-block handshake requires. */
|
||||
int rows_max = 0;
|
||||
size_t lds = 0;
|
||||
@@ -187,7 +183,10 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, lo
|
||||
}
|
||||
if (lds > kWht6TableBytes || nb > R4D_AR_MAX_BLOCKS) return -3;
|
||||
}
|
||||
R4dArGather G{};
|
||||
/* Zeroed including padding, as in r4d_ar_gather_hc_write: the tail padding is part of the
|
||||
* kernel-argument bytes a recorded pass's audit compares. */
|
||||
R4dArGather G;
|
||||
std::memset(&G, 0, sizeof G);
|
||||
if (gather) {
|
||||
G.ye = (const unsigned short*)ye;
|
||||
G.ew = (const unsigned short*)ew;
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
// r4d_ar_oneshot_Nrank_exact.hip: r4d_ar_oneshot_3rank_exact, r4d_ar_oneshot_4rank_exact,
|
||||
// r4d_ar_oneshot_8rank_exact -- one-shot P2P push all-reduce, 3, 4 or 8
|
||||
// ranks, gfx1201. WS is compile-time; the 2-rank kernel keeps its own file.
|
||||
// r4d_ar_oneshot_8rank_exact -- one-shot P2P push all-reduce, 3, 4 or 8 ranks, gfx1201. WS is
|
||||
// compile-time; the 2-rank kernel has its own file.
|
||||
//
|
||||
// Per-block handshake: block b waits only on the peers' block b, so push
|
||||
// and reduce overlap. Scratch slot per (parity, source), flag per (block,
|
||||
// source). Reduce is fp32 in ascending rank order, one round at the store
|
||||
// -- required, or ranks diverge. Stuck handshake traps.
|
||||
// Sends (ws-1)*N bytes per rank: for small messages only, where latency dominates.
|
||||
// The two-shot covers larger sizes.
|
||||
// Per-block handshake: block b waits only on the peers' block b, so push and reduce overlap.
|
||||
// Scratch slot per (parity, source), flag per (block, source). The reduce is fp32 in ascending
|
||||
// rank order with one rounding at the store; any other order makes ranks diverge. A stuck
|
||||
// handshake traps. Sends (ws-1)*N bytes per rank, so it serves small, latency-bound messages; the
|
||||
// two-shot covers larger sizes.
|
||||
//
|
||||
// Also r4d_ar_hc_write_4rank: the same one-shot with hc_write as its epilogue (ar_hc_write at
|
||||
// width, exact wire only), and r4d_ar_gather_hc_write_4rank: that with moe_gather as its prologue
|
||||
// (ar_gather_hc_write at width, exact wire only).
|
||||
// Also r4d_ar_hc_write_4rank (the same one-shot with hc_write as epilogue) and
|
||||
// r4d_ar_gather_hc_write_4rank (that plus moe_gather as prologue), exact wire only.
|
||||
//
|
||||
// The IPC helpers live in r4d_ar_oneshot_2rank_exact.hip; this unit links beside it.
|
||||
#include "r4d.h"
|
||||
@@ -48,13 +46,14 @@ __global__ void r4d_ar_oneshot_wide_exact_kernel(
|
||||
const int4* __restrict__ my_base,
|
||||
unsigned int* __restrict__ my_flags, int4* __restrict__ out4,
|
||||
unsigned int* __restrict__ seq_ctrs, int n16, int slot_stride16, int rank,
|
||||
int drain, int acq, int pub) {
|
||||
int drain, int acq, int pub, long long* gate, unsigned int* gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
// The reduce holds WS source words live per output word, so the 2-rank unroll spills at ws=8.
|
||||
// The reduce holds WS source words live per output word, so the 2x unroll spills at ws=8.
|
||||
constexpr int RU = (WS <= 4) ? 2 : 1;
|
||||
|
||||
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);
|
||||
r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int parity = (int)s_slot;
|
||||
@@ -69,7 +68,7 @@ __global__ void r4d_ar_oneshot_wide_exact_kernel(
|
||||
for (int p = 0; p < NPEERS; ++p)
|
||||
ps[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16;
|
||||
|
||||
// push: 4x-unrolled, and the loaded words are reused across peers so the input is read once
|
||||
// Push, 4x unrolled; loaded words are reused across peers so the input is read once.
|
||||
{
|
||||
int k = start + tid;
|
||||
for (; k + 3 * nt < end; k += 4 * nt) {
|
||||
@@ -86,15 +85,14 @@ __global__ void r4d_ar_oneshot_wide_exact_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// Flag values live in the 2*seq space shared by the whole wide family (the two-shot's
|
||||
// half-step is 2s-1, its full step 2s), so one flag/seq/scratch set serves a mixed
|
||||
// kernel stream: every kernel advances seq_ctrs[b] once per AR, parity alternates
|
||||
// across the stream, and the monotonic wait stays coherent at a band crossover. The
|
||||
// slot guard is the same shared discipline: each AR's writes land in its (parity,
|
||||
// source) slot, the handshake keeps any rank at most one AR ahead, and the caller
|
||||
// sizes the stride for the largest family in the mix -- so a crossover neighbour can
|
||||
// never overlap this AR's bytes.
|
||||
// Flags use the 2*seq space shared by the wide family (the two-shot's half-step is 2s-1, its
|
||||
// full step 2s), so one flag/seq/scratch set serves a mixed kernel stream. Each AR writes only
|
||||
// its (parity, source) slot, the handshake keeps any rank at most one AR ahead, and the caller
|
||||
// sizes the stride for the largest family in the mix, so neighbouring ARs never overlap.
|
||||
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s, drain, acq, pub);
|
||||
// Every peer's push for this launch has landed and my own retired behind its flag store, so
|
||||
// the link is free for the reduce: the last block here ends the engine's hold (r4d_ar_seq.h).
|
||||
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
// Our own contribution comes from the input; slot[my rank] in my scratch is never written.
|
||||
const int4* src[WS];
|
||||
@@ -114,28 +112,28 @@ __global__ void r4d_ar_oneshot_wide_exact_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// THE SAME ONE-SHOT WITH THE GATED RESIDUAL'S WRITE AS ITS EPILOGUE, bf16 only. `y` is the
|
||||
// message and is reduced IN PLACE; everything up to the reduce is the kernel above, step for step,
|
||||
// because the two may run on one instance's buffers in one stream: the same seq take, the same
|
||||
// handshake value 2*s, the same (parity, source) slots and the same block partition of the word
|
||||
// space. The reduce is the same ar_vsum, so the stored word is the plain all-reduce's to the bit;
|
||||
// then h[r][c*n + i] += inj[r][c] * y[r][i] in hc_write's arithmetic over that bf16 word
|
||||
// (r4d_ar_hc_write_word, as the two-rank r4d_ar_hc_write_kernel).
|
||||
// The same one-shot with the gated residual write as its epilogue, bf16 only. `y` is the message
|
||||
// and is reduced in place. Up to the reduce it must match the kernel above step for step (seq take,
|
||||
// handshake value 2*s, (parity, source) slots, block partition), because both may run on one
|
||||
// instance's buffers in one stream. The reduce is the same ar_vsum, so the stored word matches the
|
||||
// plain all-reduce bit for bit; then h[r][c*n + i] += inj[r][c] * y[r][i] in hc_write's arithmetic
|
||||
// (r4d_ar_hc_write_word, as in the two-rank r4d_ar_hc_write_kernel).
|
||||
//
|
||||
// In place is safe: a thread reads every source of word k before it stores word k, its own block
|
||||
// pushed that word to the peers before the handshake, and no peer reads this rank's `y`. A word is
|
||||
// eight elements and n is a multiple of eight, so a word never straddles a row and the thread that
|
||||
// reduces it owns every stream element behind it.
|
||||
// In place is safe: a thread reads every source of word k before storing it, its block pushed the
|
||||
// word before the handshake, and no peer reads this rank's `y`. A word never straddles a row
|
||||
// (n is a multiple of eight), so the thread that reduces it owns every stream element behind it.
|
||||
template <int WS>
|
||||
__global__ void r4d_ar_hc_write_wide_kernel(
|
||||
int4* __restrict__ y4, R4DArWidePeers<int4, WS - 1> peers, const int4* __restrict__ my_base,
|
||||
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ 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 rank, int drain, int acq, int pub) {
|
||||
int hc, long irow, long hrow, int slot_stride16, int rank, int drain, int acq, int pub,
|
||||
long long* gate, unsigned int* gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
|
||||
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);
|
||||
r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int parity = (int)s_slot;
|
||||
@@ -166,6 +164,9 @@ __global__ void r4d_ar_hc_write_wide_kernel(
|
||||
}
|
||||
|
||||
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s, drain, acq, pub);
|
||||
// The two-rank fused write's release, at width: the reduce and the hc write behind it are
|
||||
// local VRAM traffic, so the last block here ends the engine's hold (r4d_ar_seq.h).
|
||||
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
const int4* src[WS];
|
||||
#pragma unroll
|
||||
@@ -183,26 +184,23 @@ __global__ void r4d_ar_hc_write_wide_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// THE SAME WRITE WITH THE MoE GATHER AS ITS PROLOGUE, bf16 only: the four-rank form of the
|
||||
// two-rank r4d_ar_gather_hc_write_kernel. `y` is not read but produced -- a block's words are
|
||||
// summed back to token order from the routed experts' rows by r4d_ar_gather_word, kept as this
|
||||
// rank's message and pushed to every peer, exactly as if moe_gather had written y and the kernel
|
||||
// above had read it back. From the handshake on it IS the kernel above: the same seq take, the
|
||||
// same value 2*s, the same (parity, source) slots, the same ar_vsum in ascending rank order over
|
||||
// the same sources -- this rank's own word from y, which the same thread stored before the
|
||||
// handshake -- and the same r4d_ar_hc_write_word over the stored bf16 word. So the bytes are those
|
||||
// of moe_gather, the four-rank exact all-reduce and hc_write.
|
||||
// The same write with the MoE gather as its prologue, bf16 only; the four-rank form of the two-rank
|
||||
// r4d_ar_gather_hc_write_kernel. `y` is produced, not read: r4d_ar_gather_word sums each word back
|
||||
// to token order from the routed experts' rows, stores it as this rank's message and pushes it to
|
||||
// every peer. From the handshake on it is the kernel above (own word read from y, stored by the
|
||||
// same thread before the handshake), so the bytes equal moe_gather, the four-rank exact all-reduce
|
||||
// and hc_write run separately.
|
||||
//
|
||||
// The slot table is the two-rank kernel's: without INV a block's rows (at most R4D_ARG_ROWS, which
|
||||
// the launcher sizes the grid for) find their slots once, in LDS, by one pass over the sorted
|
||||
// list; with INV they read the inverse table r4d_ar_gather_inv built in front.
|
||||
// Slot table as in the two-rank kernel: without INV a block's rows (at most R4D_ARG_ROWS; the
|
||||
// launcher sizes the grid for it) find their slots once, in LDS, in one pass over the sorted list;
|
||||
// with INV they read the inverse table r4d_ar_gather_inv built beforehand.
|
||||
template <int WS, bool INV>
|
||||
__global__ void r4d_ar_gather_hc_write_wide_kernel(
|
||||
int4* __restrict__ y4, R4DArWidePeers<int4, WS - 1> peers, const int4* __restrict__ my_base,
|
||||
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ 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 rank, int drain, int acq, int pub,
|
||||
R4dArGather G, const int* __restrict__ inv) {
|
||||
R4dArGather G, const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
|
||||
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
|
||||
@@ -210,6 +208,7 @@ __global__ void r4d_ar_gather_hc_write_wide_kernel(
|
||||
__shared__ int s_i[R4D_ARG_ROWS * R4D_ARG_SLOTS];
|
||||
__shared__ float s_w[R4D_ARG_ROWS * R4D_ARG_SLOTS];
|
||||
__shared__ float s_g[R4D_ARG_ROWS];
|
||||
const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid);
|
||||
r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int parity = (int)s_slot;
|
||||
@@ -227,8 +226,8 @@ __global__ void r4d_ar_gather_hc_write_wide_kernel(
|
||||
for (int p = 0; p < NPEERS; ++p)
|
||||
ps[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16;
|
||||
|
||||
/* The slot table. A slot no sorted row claims reads -1, so the clear and the scan are two
|
||||
* phases with a barrier between them, as in moe_gather. */
|
||||
/* Slot table. A slot no sorted row claims reads -1, so clear and scan are separated by a
|
||||
* barrier, as in moe_gather. */
|
||||
if (!INV) {
|
||||
for (int x = tid; x < nrow * K; x += nt) s_i[x] = -1;
|
||||
__syncthreads();
|
||||
@@ -249,7 +248,7 @@ __global__ void r4d_ar_gather_hc_write_wide_kernel(
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
/* The gather, one word a thread a pass, kept and pushed to every peer. */
|
||||
/* Gather one word per thread per pass; keep it and push it to every peer. */
|
||||
for (int k = start + tid; k < end; k += nt) {
|
||||
const int row = k / wpr, i0 = (k - row * wpr) * 8;
|
||||
const int4 out = r4d_ar_gather_word<INV>(G, inv, s_i, s_w, s_g, row, row - row_lo, i0);
|
||||
@@ -259,6 +258,9 @@ __global__ void r4d_ar_gather_hc_write_wide_kernel(
|
||||
}
|
||||
|
||||
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s, drain, acq, pub);
|
||||
// As in the kernel this is the gather form of: from the handshake on, the reduce and the
|
||||
// write are local, so the last block here ends the engine's hold (r4d_ar_seq.h).
|
||||
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
const int4* src[WS];
|
||||
#pragma unroll
|
||||
@@ -280,7 +282,8 @@ template <int WS>
|
||||
static void ar_wide_launch(const long* peer_scratch, const long* peer_flags, long my_scratch,
|
||||
long my_flags, long seq_ctrs, long slot_stride16, long inp, long out,
|
||||
long n_elem, long dtype, long rank, long stream_i, long nblocks,
|
||||
long nthreads, long drain, long acq, long pub) {
|
||||
long nthreads, long drain, long acq, long pub, long gate,
|
||||
long gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
static_assert(NPEERS <= R4D_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound");
|
||||
|
||||
@@ -317,9 +320,8 @@ static void ar_wide_launch(const long* peer_scratch, const long* peer_flags, lon
|
||||
peers.rank[i] = (i < (int)rank) ? i : i + 1;
|
||||
}
|
||||
|
||||
// scratch must back 2*WS slots of the declared stride, flags one word per (block, source
|
||||
// rank), seq a handshake and a parity word per block of capacity (r4d_ar_seq.h) -- checked
|
||||
// against the allocations, not the arguments.
|
||||
// Checked against the allocations: scratch backs 2*WS slots of the stride, flags one word per
|
||||
// (block, source rank), seq a handshake and a parity word per block of capacity (r4d_ar_seq.h).
|
||||
const long slot_bytes = 2L * WS * (long)slot_stride16 * 16;
|
||||
const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int);
|
||||
r4d_ar_check_extent(my_scratch, slot_bytes, "all_reduce", "my_scratch");
|
||||
@@ -336,7 +338,7 @@ static void ar_wide_launch(const long* peer_scratch, const long* peer_flags, lon
|
||||
r4d_ar_oneshot_wide_exact_kernel<T, LN, WS><<<nb, nt, 0, st>>>( \
|
||||
(const int4*)inp, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \
|
||||
(int4*)out, (unsigned int*)seq_ctrs, n16, (int)slot_stride16, (int)rank, \
|
||||
(int)drain, (int)acq, (int)pub)
|
||||
(int)drain, (int)acq, (int)pub, (long long*)gate, (unsigned int*)gate_ctr)
|
||||
if (dtype == 0) R4D_AR_WIDE_LAUNCH(__hip_bfloat16, 8);
|
||||
else if (dtype == 1) R4D_AR_WIDE_LAUNCH(__half, 8);
|
||||
else if (dtype == 2) R4D_AR_WIDE_LAUNCH(float, 4);
|
||||
@@ -344,11 +346,8 @@ static void ar_wide_launch(const long* peer_scratch, const long* peer_flags, lon
|
||||
#undef R4D_AR_WIDE_LAUNCH
|
||||
}
|
||||
|
||||
// Three ranks: the same kernel at WS=3. Nothing in the push, the handshake or the ascending-rank
|
||||
// reduce assumes a power of two -- the peer bundle is WS-1 wide and the slot/flag layout is
|
||||
// parity x source rank -- so this is an instantiation, not a variant. It exists because a 3-card
|
||||
// box is a real configuration (three R9700s) and the two-shot cannot serve it: that one shards the
|
||||
// message `world` ways and a residual width of 2560 does not divide by 3.
|
||||
// Three ranks: the same kernel at WS=3; nothing in it assumes a power of two. Needed for 3-card
|
||||
// systems because a residual width of 2560 does not split evenly three ways for the two-shot.
|
||||
void r4d_ar_oneshot_3rank_exact(long peer_scratch0, long peer_scratch1,
|
||||
long peer_flags0, long peer_flags1,
|
||||
long my_scratch, long my_flags, long seq_ctrs, long slot_stride16,
|
||||
@@ -357,8 +356,9 @@ void r4d_ar_oneshot_3rank_exact(long peer_scratch0, long peer_scratch1,
|
||||
long pub) {
|
||||
const long ps[2] = {peer_scratch0, peer_scratch1};
|
||||
const long pf[2] = {peer_flags0, peer_flags1};
|
||||
/* No link gate at three ranks: the row answers 1, the engine releases by barrier. */
|
||||
ar_wide_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem,
|
||||
dtype, rank, stream, nblocks, nthreads, drain, acq, pub);
|
||||
dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L);
|
||||
}
|
||||
|
||||
void r4d_ar_oneshot_4rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
@@ -366,11 +366,11 @@ void r4d_ar_oneshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee
|
||||
long my_scratch, long my_flags, long seq_ctrs, long slot_stride16,
|
||||
long inp, long out, long n_elem, long dtype, long rank,
|
||||
long stream, long nblocks, long nthreads, long drain, long acq,
|
||||
long pub) {
|
||||
long pub, long gate, long gate_ctr) {
|
||||
const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2};
|
||||
const long pf[3] = {peer_flags0, peer_flags1, peer_flags2};
|
||||
ar_wide_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem,
|
||||
dtype, rank, stream, nblocks, nthreads, drain, acq, pub);
|
||||
dtype, rank, stream, nblocks, nthreads, drain, acq, pub, gate, gate_ctr);
|
||||
}
|
||||
|
||||
void r4d_ar_oneshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
@@ -385,18 +385,19 @@ void r4d_ar_oneshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee
|
||||
peer_scratch4, peer_scratch5, peer_scratch6};
|
||||
const long pf[7] = {peer_flags0, peer_flags1, peer_flags2, peer_flags3,
|
||||
peer_flags4, peer_flags5, peer_flags6};
|
||||
/* No link gate at eight ranks: the row answers 1, the engine releases by barrier. */
|
||||
ar_wide_launch<8>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem,
|
||||
dtype, rank, stream, nblocks, nthreads, drain, acq, pub);
|
||||
dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L);
|
||||
}
|
||||
|
||||
// ar_wide_launch's checks, for the fused write: the same rank range, slot stride, grid clamps and
|
||||
// allocation extents, plus the write's own two shape rules.
|
||||
// ar_wide_launch's checks plus the fused write's two shape rules.
|
||||
template <int WS>
|
||||
static void ar_hc_write_wide_launch(const long* peer_scratch, const long* peer_flags,
|
||||
long my_scratch, 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 rank, long stream_i,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub) {
|
||||
long nblocks, long nthreads, long drain, long acq, long pub,
|
||||
long gate, long gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
static_assert(NPEERS <= R4D_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound");
|
||||
|
||||
@@ -449,7 +450,8 @@ static void ar_hc_write_wide_launch(const long* peer_scratch, const long* peer_f
|
||||
r4d_ar_hc_write_wide_kernel<WS><<<nb, nt, 0, st>>>(
|
||||
(int4*)y, peers, (const int4*)my_scratch, (unsigned int*)my_flags, (unsigned int*)seq_ctrs,
|
||||
(const unsigned short*)inj, (unsigned short*)h, n16, (int)n, (int)hc, irow, hrow,
|
||||
(int)slot_stride16, (int)rank, (int)drain, (int)acq, (int)pub);
|
||||
(int)slot_stride16, (int)rank, (int)drain, (int)acq, (int)pub, (long long*)gate,
|
||||
(unsigned int*)gate_ctr);
|
||||
}
|
||||
|
||||
void r4d_ar_hc_write_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
@@ -457,25 +459,26 @@ void r4d_ar_hc_write_4rank(long peer_scratch0, long peer_scratch1, long peer_scr
|
||||
long my_scratch, 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 rank, long stream, long nblocks, long nthreads,
|
||||
long drain, long acq, long pub) {
|
||||
long drain, long acq, long pub, long gate, long gate_ctr) {
|
||||
const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2};
|
||||
const long pf[3] = {peer_flags0, peer_flags1, peer_flags2};
|
||||
ar_hc_write_wide_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, y, inj, h,
|
||||
M, n, hc, irow, hrow, rank, stream, nblocks, nthreads, drain, acq,
|
||||
pub);
|
||||
pub, gate, gate_ctr);
|
||||
}
|
||||
|
||||
// ar_hc_write_wide_launch's checks plus the gather's, and the two-rank gather's grid rule: at least
|
||||
// wide enough that no block spans more than R4D_ARG_ROWS rows, or -- where that would take more
|
||||
// blocks than the reduction asked for and `inv` is given -- the reduction's count over the inverse
|
||||
// table. Every rank computes the same count and the same choice from the same M, n and scratch.
|
||||
// ar_hc_write_wide_launch's checks plus the gather's, and the two-rank gather's grid rule: enough
|
||||
// blocks that none spans more than R4D_ARG_ROWS rows, or, when that exceeds the requested count and
|
||||
// `inv` is given, the requested count over the inverse table. Every rank makes the same choice from
|
||||
// the same M, n and scratch.
|
||||
template <int WS>
|
||||
static void ar_gather_hc_write_wide_launch(
|
||||
const long* peer_scratch, const long* peer_flags, long my_scratch, 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 ye, long ew, long sorted, long sh, long sg, long ye_ld,
|
||||
long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, long rank, long stream_i,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub, long inv) {
|
||||
long nblocks, long nthreads, long drain, long acq, long pub, long inv, long gate,
|
||||
long gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
static_assert(NPEERS <= R4D_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound");
|
||||
|
||||
@@ -539,8 +542,8 @@ static void ar_gather_hc_write_wide_launch(
|
||||
r4d_ar_check_extent(peer_flags[i], flag_bytes, "ar_gather_hc_write", "peer flags");
|
||||
}
|
||||
|
||||
/* Zeroed whole, padding included: the struct is passed by value, so its tail padding is
|
||||
* kernel-argument bytes too, and a recorded pass's audit compares those bytes. */
|
||||
/* Zeroed including padding: the struct is passed by value, so its tail padding is part of the
|
||||
* kernel-argument bytes a recorded pass's audit compares. */
|
||||
R4dArGather G;
|
||||
std::memset(&G, 0, sizeof G);
|
||||
G.ye = (const unsigned short*)ye;
|
||||
@@ -561,13 +564,13 @@ static void ar_gather_hc_write_wide_launch(
|
||||
(int4*)y, peers, (const int4*)my_scratch, (unsigned int*)my_flags,
|
||||
(unsigned int*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, n16, (int)n,
|
||||
(int)hc, irow, hrow, (int)slot_stride16, (int)rank, (int)drain, (int)acq, (int)pub, G,
|
||||
(const int*)inv);
|
||||
(const int*)inv, (long long*)gate, (unsigned int*)gate_ctr);
|
||||
} else {
|
||||
r4d_ar_gather_hc_write_wide_kernel<WS, false><<<nb, nt, 0, st>>>(
|
||||
(int4*)y, peers, (const int4*)my_scratch, (unsigned int*)my_flags,
|
||||
(unsigned int*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, n16, (int)n,
|
||||
(int)hc, irow, hrow, (int)slot_stride16, (int)rank, (int)drain, (int)acq, (int)pub, G,
|
||||
nullptr);
|
||||
nullptr, (long long*)gate, (unsigned int*)gate_ctr);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -579,13 +582,13 @@ void r4d_ar_gather_hc_write_4rank(long peer_scratch0, long peer_scratch1, long p
|
||||
long sh, long sg, long ye_ld, long ew_ld, long sh_ld,
|
||||
long sg_ld, long top_k, long sig, long rank, long stream,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub,
|
||||
long inv) {
|
||||
long inv, long gate, long gate_ctr) {
|
||||
const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2};
|
||||
const long pf[3] = {peer_flags0, peer_flags1, peer_flags2};
|
||||
ar_gather_hc_write_wide_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, y,
|
||||
inj, h, M, n, hc, irow, hrow, ye, ew, sorted, sh, sg, ye_ld,
|
||||
ew_ld, sh_ld, sg_ld, top_k, sig, rank, stream, nblocks,
|
||||
nthreads, drain, acq, pub, inv);
|
||||
nthreads, drain, acq, pub, inv, gate, gate_ctr);
|
||||
}
|
||||
|
||||
void r4d_ar_wide_dims(int* max_blocks, int* nb_design, int* max_peers) {
|
||||
|
||||
+39
-51
@@ -1,51 +1,43 @@
|
||||
#pragma once
|
||||
// r4d_ar_seq.h: the step every all-reduce and all-gather kernel takes first -- its handshake
|
||||
// sequence number and the scratch slot it pushes into -- and the wrap-safe wait that follows the
|
||||
// push. One definition for the 2-rank and the wide families, because every kernel that shares an
|
||||
// instance's buffers has to take the step identically or the two ranks stop agreeing.
|
||||
// r4d_ar_seq.h: the first step of every all-reduce and all-gather kernel (its handshake sequence
|
||||
// number and scratch slot) and the wrap-safe wait after the push. Shared by the 2-rank and wide
|
||||
// families: kernels sharing an instance's buffers must take the step identically or the ranks
|
||||
// disagree.
|
||||
//
|
||||
// THE COUNTER ALLOCATION IS 2 * nbw WORDS, zeroed once, where nbw is the block capacity the flag
|
||||
// array was sized for, and the landed counter after them (r4d_ar_link_landed):
|
||||
// Counter allocation: 2 * nbw words, zeroed once (nbw = block capacity the flag array was sized
|
||||
// for), then the landed counter (r4d_ar_link_landed):
|
||||
//
|
||||
// [0, nbw) HANDSHAKE counters, one a block. Block b advances word b once per launch it
|
||||
// runs in, publishes the new value to the peer and waits for the peer's. Kept per
|
||||
// block so that a block which sat out a run of narrow launches resumes exactly
|
||||
// one step past the flag its peer last published: the wrap-safe compare below is
|
||||
// only sound while that gap stays far under 2^31, and a counter every block
|
||||
// shared would let an idle block's flag fall arbitrarily far behind.
|
||||
// [0, nbw) Handshake counters, one per block. Block b advances word b once per launch it
|
||||
// runs in, publishes it to the peer and waits for the peer's. Per block so a
|
||||
// block idle through narrow launches resumes one step past its peer's last flag;
|
||||
// the wrap-safe compare needs that gap far under 2^31.
|
||||
//
|
||||
// [nbw, 2*nbw) PARITY counters. Every launch advances ALL nbw of them exactly once, whatever
|
||||
// its own block count -- block b takes words b, b + nb, b + 2*nb, ... -- so all
|
||||
// of them always equal the number of launches, and each block reads the slot
|
||||
// parity off its own word without talking to any other block.
|
||||
// [nbw, 2*nbw) Parity counters. Every launch advances all nbw of them once, whatever its block
|
||||
// count (block b takes words b, b + nb, b + 2*nb, ...), so each equals the launch
|
||||
// count and a block reads the slot parity off its own word.
|
||||
//
|
||||
// [2*nbw] the LANDED counter: the blocks of the running launch that have seen their
|
||||
// peer's push land, back at zero when the launch ends.
|
||||
// [2*nbw] Landed counter: blocks of the running launch that have seen their peer's push
|
||||
// land; back at zero when the launch ends.
|
||||
//
|
||||
// WHY THE SLOT CANNOT COME OFF THE HANDSHAKE COUNTER. The double-buffered scratch is safe only if
|
||||
// consecutive launches on one instance use opposite slots: launch k+1 may push while the peer is
|
||||
// still reducing launch k, and it must not land in the bytes being read. Block counts differ from
|
||||
// launch to launch -- the standalone all-reduce scales with the message, the fused norm takes one
|
||||
// block a row -- and so does the byte range a block owns. The handshake counters therefore drift
|
||||
// apart block by block, and a slot taken from them lets a block of launch k+1 push into the slot a
|
||||
// DIFFERENT block of launch k is still reading on the peer, whenever their byte ranges overlap
|
||||
// and their counters happen to share a parity. The parity counters move in lockstep, so the slot
|
||||
// alternates per launch for every block, as the double buffer requires.
|
||||
// The slot cannot come from the handshake counter. Consecutive launches on one instance must use
|
||||
// opposite scratch slots, since launch k+1 may push while the peer still reduces launch k. Block
|
||||
// counts and per-block byte ranges vary by launch, so handshake counters drift apart per block,
|
||||
// and a block of launch k+1 could push into the slot a different block of launch k is still
|
||||
// reading. The parity counters move in lockstep, so the slot alternates per launch for every block.
|
||||
//
|
||||
// THE COST is one more returning atomic, issued from a second wave so its round trip overlaps the
|
||||
// handshake one rather than following it, and nbw / nb fire-and-forget atomics spread over the
|
||||
// other threads. Nothing waits on those: the barrier below orders LDS only, so they land in the
|
||||
// background, and all they need is to land before the next launch on the stream, which the kernel
|
||||
// boundary guarantees. Everything stays device-resident, so a captured graph still replays.
|
||||
// Cost: one more returning atomic, issued from a second wave so its round trip overlaps the
|
||||
// handshake's, plus nbw / nb fire-and-forget atomics over the other threads. Those only need to
|
||||
// land before the next launch, which the kernel boundary guarantees. All state is device-resident,
|
||||
// so a captured graph replays.
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
// Sets `s_seq` to this block's handshake value and `s_slot` to the launch's scratch slot (0 or 1),
|
||||
// then barriers so every thread can read both. `nbw` is the capacity the counters were allocated
|
||||
// for, and gridDim.x must not exceed it.
|
||||
//
|
||||
// The barrier is fenced on LDS alone. The only thing it publishes is the two words in LDS; a full
|
||||
// __syncthreads would also wait for every thread's outstanding parity atomics and invalidate the
|
||||
// vector caches, which puts the fire-and-forget traffic on the path to the first push.
|
||||
// The barrier fences LDS only, since it publishes just the two LDS words. A full __syncthreads
|
||||
// would wait for the outstanding parity atomics and invalidate the vector caches, putting that
|
||||
// traffic on the path to the first push.
|
||||
__device__ __forceinline__ void r4d_ar_seq_take(unsigned int* __restrict__ ctrs, unsigned int nbw,
|
||||
unsigned int& s_seq, unsigned int& s_slot) {
|
||||
const unsigned int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
|
||||
@@ -59,19 +51,16 @@ __device__ __forceinline__ void r4d_ar_seq_take(unsigned int* __restrict__ ctrs,
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local");
|
||||
}
|
||||
|
||||
// THE ENGINE'S HOLD ON THE LINK, ENDED BY THE LAUNCH (rad_abi.h, rad_kernel_collective answering
|
||||
// 2). The word is odd exactly while the engine holds the link for this launch, and nothing else
|
||||
// writes it while the launch runs, so its value is read once, at the start, by each block's first
|
||||
// thread (r4d_ar_link_word): the read crosses to host memory, and at the start it overlaps the push
|
||||
// where at the end it would hold up the reduce.
|
||||
// The engine's hold on the link, released by the launch (rad_abi.h, rad_kernel_collective
|
||||
// returning 2). The word is odd exactly while the engine holds the link for this launch and
|
||||
// nothing else writes it meanwhile, so each block's first thread reads it once at the start
|
||||
// (r4d_ar_link_word), where the host-memory read overlaps the push instead of delaying the reduce.
|
||||
//
|
||||
// r4d_ar_link_landed is called by every block once its handshake has seen the peer's push to it
|
||||
// land. The last block to get there knows every byte the peer sends this card has arrived, so the
|
||||
// link is free for the rest of the kernel's run -- the reduce and whatever it writes -- and takes
|
||||
// one off the word if it was odd, with an atomic so it commutes with any barrier counting the same
|
||||
// word down. `ctr` counts the blocks and is back at zero when the launch ends, ready for the next
|
||||
// one on the stream. The word is in memory the DMA engine polls past every cache, so it is read and
|
||||
// written at system scope.
|
||||
// Every block calls r4d_ar_link_landed once its handshake has seen the peer's push land. The last
|
||||
// block knows all of the peer's bytes have arrived, so the link is free for the rest of the
|
||||
// kernel; it decrements the word if odd, atomically so it commutes with any barrier counting the
|
||||
// same word down. `ctr` counts blocks and returns to zero at the end of the launch. The DMA engine
|
||||
// polls the word past every cache, so it is accessed at system scope.
|
||||
__device__ __forceinline__ long long r4d_ar_link_word(const long long* gate, unsigned int tid) {
|
||||
return gate && tid == 0 ? __hip_atomic_load(gate, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM)
|
||||
: 0;
|
||||
@@ -88,10 +77,9 @@ __device__ __forceinline__ void r4d_ar_link_landed(long long* gate, long long wo
|
||||
if (word & 1) __hip_atomic_fetch_add(gate, -1LL, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
|
||||
// True while `flag` has not yet reached `want`. The counters are u32 and wrap, so the comparison is
|
||||
// on the signed difference: a peer at or past `want` -- it may already be a launch ahead -- reads
|
||||
// as arrived on either side of the wrap, where a plain `flag < want` stops waiting altogether once
|
||||
// `want` wraps to a small number.
|
||||
// True while `flag` has not reached `want`. The u32 counters wrap, so compare the signed
|
||||
// difference: a peer at or past `want` (possibly a launch ahead) reads as arrived across the wrap,
|
||||
// where a plain `flag < want` would stop waiting once `want` wraps to a small number.
|
||||
__device__ __forceinline__ bool r4d_ar_seq_behind(unsigned int flag, unsigned int want) {
|
||||
return (int)(flag - want) < 0;
|
||||
}
|
||||
+19
-21
@@ -1,31 +1,30 @@
|
||||
#pragma once
|
||||
// r4d_ar_ti8.h: the three-tiered INT8 all-reduce wire codec, shared machinery for the wide
|
||||
// quantized kernels. A group's record tags which tier encoded it: Tier 1 is a plain amax-scaled
|
||||
// int8, Tier 2 lifts one dominant element out of the scale and ships it exactly in the record, and
|
||||
// Tier 3 rotates by an orthonormal WHT-32 first. The tiering keeps a massive outlier exact while
|
||||
// leaving ordinary groups on the cheapest path.
|
||||
// WIRE LAYOUT per slot, ng = numel/32 groups (fixed size, no escapes, no atomics):
|
||||
// r4d_ar_ti8.h: the three-tier INT8 all-reduce wire codec shared by the wide quantized kernels.
|
||||
// A group's record tags its tier: Tier 1 is plain amax-scaled int8, Tier 2 lifts one dominant
|
||||
// element out of the scale and ships it exactly in the record, Tier 3 applies an orthonormal
|
||||
// WHT-32 first. A massive outlier stays exact while ordinary groups take the cheapest path.
|
||||
// Wire layout per slot, ng = numel/32 groups (fixed size, no escapes, no atomics):
|
||||
// codes u8 [32*ng] at 0 (uint2 per 8-element lane vector)
|
||||
// rec u32[ng] at 32*ng
|
||||
// scale fp16[ng] at 36*ng -> 38 bytes/group = 9.5 bits/element
|
||||
// Slot base must be 16B-aligned; 32*ng keeps the u32 records 4B-aligned for any ng.
|
||||
//
|
||||
// A group of 32 = TI8_LPG=4 adjacent lanes x TI8_EPL=8 consecutive elements. All
|
||||
// cross-lane exchanges use masks < 4, so a group never leaves its 4-lane cluster and
|
||||
// never straddles a wave; kernels partition work in whole groups so the cluster always
|
||||
// branches together (the shuffles sit inside tier branches).
|
||||
// A group of 32 = TI8_LPG=4 adjacent lanes x TI8_EPL=8 consecutive elements. Cross-lane
|
||||
// exchanges use masks < 4, so a group stays in its 4-lane cluster and never straddles a wave.
|
||||
// Kernels partition work in whole groups so a cluster branches together (the shuffles sit inside
|
||||
// tier branches).
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cfloat>
|
||||
|
||||
// TI8_-prefixed (unlike the 2-rank header's bare GROUP/EPL): these must be includable
|
||||
// beside other codec headers in one TU without a macro collision.
|
||||
// TI8_-prefixed (unlike the 2-rank header's bare GROUP/EPL) so this header can share a TU with
|
||||
// other codec headers without macro collisions.
|
||||
#define TI8_GROUP 32
|
||||
#define TI8_EPL 8
|
||||
#define TI8_LPG 4
|
||||
// Per-group wire layout, derived from the spec above so a codec rev lands everywhere at once:
|
||||
// codes u8[GROUP] at 0, the u32 record at TI8_REC_OFF, the fp16 scale at TI8_SC_OFF.
|
||||
// Per-group wire layout: codes u8[GROUP] at 0, the u32 record at TI8_REC_OFF, the fp16 scale at
|
||||
// TI8_SC_OFF.
|
||||
#define TI8_REC_OFF TI8_GROUP
|
||||
#define TI8_SC_OFF (TI8_GROUP + 4)
|
||||
#define TI8_GROUP_BYTES (TI8_SC_OFF + 2)
|
||||
@@ -116,13 +115,12 @@ __device__ __forceinline__ void ti8_wht32(float* v, int lig) {
|
||||
for (int i = 0; i < TI8_EPL; ++i) v[i] *= nrm;
|
||||
}
|
||||
|
||||
// Encode one lane's 8 elements of a group into the wire words: this lane's 8 int8 codes,
|
||||
// plus the group record and scale (identical on all 4 lanes; the lig==0 lane stores them).
|
||||
// All 4 lanes of the group must call together (cross-lane classifier + Tier 3 rotation);
|
||||
// the caller fans the words to every destination slot. The _v form takes the values
|
||||
// already in registers (the phase-2 reduced vector, never stored exact) and consumes
|
||||
// them -- Tier 3 rotates v in place, so a caller wanting the reconstruction must decode
|
||||
// the wire words, exactly as every peer will.
|
||||
// Encode one lane's 8 elements of a group: this lane's 8 int8 codes, plus the group record and
|
||||
// scale (identical on all 4 lanes; the lig==0 lane stores them). All 4 lanes of the group must
|
||||
// call together (cross-lane classifier and Tier 3 rotation); the caller fans the words out to every
|
||||
// destination slot. The _v form consumes values already in registers (the phase-2 reduced vector):
|
||||
// Tier 3 rotates v in place, so a caller wanting the reconstruction must decode the wire words as
|
||||
// every peer does.
|
||||
template <typename T>
|
||||
__device__ __forceinline__ void ti8_encode_group_v(float* v, int lig, uint2* codes,
|
||||
unsigned int* rec, __half* scale) {
|
||||
|
||||
@@ -6,20 +6,18 @@
|
||||
// Shard s = a contiguous run of the message's 16-byte words, owned by rank s. Phase 1: push my
|
||||
// contribution to each peer-owned shard into the owner's slot[me] region A, flag 2s-1; reduce my
|
||||
// shard fp32 in ascending rank order (own contribution from the input). Phase 2: reduced words go
|
||||
// to my out AND every peer's slot[me] region B, flag 2s; assemble out from region B. Region A at
|
||||
// to my out and every peer's slot[me] region B, flag 2s; assemble out from region B. Region A at
|
||||
// 0, B at sh_max; the slot stride must hold 2*sh_max.
|
||||
//
|
||||
// UNEVEN SHARDS. A message of n16 words splits into base = n16/ws words a shard, and the first
|
||||
// n16 % ws shards take one more: shard s starts at s*base + min(s, rem). At 4 and 8 ranks every
|
||||
// residual the engine issues divides evenly and this is the plain 1/ws split. At 3 it almost never
|
||||
// does -- a 2048-wide bf16 row is 256 words, and 256 * rows is a multiple of 3 only when rows is --
|
||||
// so the split has to tolerate it rather than refuse it. The sum per word is the same fp32 fold in
|
||||
// ascending rank order whichever rank owns it, so the bits match the one-shot's.
|
||||
// Uneven shards: n16 words split into base = n16/ws words per shard, and the first n16 % ws shards
|
||||
// take one more, so shard s starts at s*base + min(s, rem). At 4 and 8 ranks engine residuals
|
||||
// divide evenly; at 3 they rarely do (a 2048-wide bf16 row is 256 words). Each word is the same
|
||||
// fp32 fold in ascending rank order whoever owns it, so the bits match the one-shot's.
|
||||
//
|
||||
// SHARES the wide family's flag/seq/scratch set: every wide kernel publishes in the 2*seq flag
|
||||
// space (this one adds the 2s-1 half-step) and advances the per-block counter once per AR, so
|
||||
// parity and the monotonic spin survive any mixed one-shot/two-shot stream on one buffer set.
|
||||
// The slot stride must hold the largest requirement of every family in the mix.
|
||||
// Shares the wide family's flag/seq/scratch set (r4d_ar_wide.h): it publishes in the 2*seq flag
|
||||
// space plus the 2s-1 half-step and advances the per-block counter once per AR, so one buffer set
|
||||
// can carry any mix of one-shot and two-shot launches. The slot stride must hold the largest
|
||||
// requirement in the mix.
|
||||
#include "r4d.h"
|
||||
#include "r4d_ar_wide.h"
|
||||
#include <stdexcept>
|
||||
@@ -30,10 +28,12 @@ __global__ void r4d_ar_twoshot_wide_exact_kernel(
|
||||
const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers,
|
||||
const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags,
|
||||
int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, int n16,
|
||||
int slot_stride16, int rank, int drain, int acq, int pub) {
|
||||
int slot_stride16, int rank, int drain, int acq, int pub,
|
||||
long long* gate, unsigned int* gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
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);
|
||||
r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int parity = (int)s_slot;
|
||||
@@ -93,6 +93,12 @@ __global__ void r4d_ar_twoshot_wide_exact_kernel(
|
||||
for (int p = 0; p < NPEERS; ++p) pa[p][sh_max + k] = o; // region B
|
||||
}
|
||||
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s, drain, acq, pub);
|
||||
/* The hold ends after the second handshake, not the first: the reduce above is fused with the
|
||||
* phase-2 push (every reduced word goes to each peer's region B), so at the first handshake the
|
||||
* link still carries this launch's phase-2 bytes. Here every phase-1 and phase-2 remote store
|
||||
* has retired behind its flag store and every peer's pushes to this rank have been waited on;
|
||||
* only the local assemble is left (r4d_ar_seq.h). */
|
||||
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
// ---- assemble: every peer-owned shard from my region B copies
|
||||
for (int p = 0; p < NPEERS; ++p) {
|
||||
@@ -111,7 +117,8 @@ template <int WS>
|
||||
static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, long my_scratch,
|
||||
long my_flags, long seq_ctrs, long slot_stride16, long inp,
|
||||
long out, long n_elem, long dtype, long rank, long stream_i,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub) {
|
||||
long nblocks, long nthreads, long drain, long acq, long pub,
|
||||
long gate, long gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
if (rank < 0 || rank >= WS)
|
||||
throw std::runtime_error("all_reduce: rank " + std::to_string(rank) +
|
||||
@@ -154,9 +161,8 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags,
|
||||
peers.rank[i] = (i < (int)rank) ? i : i + 1;
|
||||
}
|
||||
|
||||
// scratch must back 2*WS slots of the declared stride, flags one word per (block, source
|
||||
// rank), seq a handshake and a parity word per block of capacity (r4d_ar_seq.h) -- checked
|
||||
// against the allocations, not the arguments.
|
||||
// Checked against the allocations: scratch backs 2*WS slots of the stride, flags one word per
|
||||
// (block, source rank), seq a handshake and a parity word per block of capacity (r4d_ar_seq.h).
|
||||
const long slot_bytes = 2L * WS * (long)slot_stride16 * 16;
|
||||
const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int);
|
||||
r4d_ar_check_extent(my_scratch, slot_bytes, "all_reduce", "my_scratch");
|
||||
@@ -173,7 +179,8 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags,
|
||||
r4d_ar_twoshot_wide_exact_kernel<T, LN, WS><<<nb, nt, 0, st>>>( \
|
||||
(const int4*)inp, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \
|
||||
(int4*)out, (unsigned int*)seq_ctrs, (int)n16, (int)slot_stride16, \
|
||||
(int)rank, (int)drain, (int)acq, (int)pub)
|
||||
(int)rank, (int)drain, (int)acq, (int)pub, (long long*)gate, \
|
||||
(unsigned int*)gate_ctr)
|
||||
if (dtype == 0) R4D_AR_TS_LAUNCH(__hip_bfloat16, 8);
|
||||
else if (dtype == 1) R4D_AR_TS_LAUNCH(__half, 8);
|
||||
else if (dtype == 2) R4D_AR_TS_LAUNCH(float, 4);
|
||||
@@ -188,8 +195,9 @@ void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long pee
|
||||
long acq, long pub) {
|
||||
const long ps[2] = {peer_scratch0, peer_scratch1};
|
||||
const long pf[2] = {peer_flags0, peer_flags1};
|
||||
/* No link gate at three ranks: the row answers 1, the engine releases by barrier. */
|
||||
ar_twoshot_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem,
|
||||
dtype, rank, stream, nblocks, nthreads, drain, acq, pub);
|
||||
dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L);
|
||||
}
|
||||
|
||||
void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
@@ -197,11 +205,11 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee
|
||||
long my_scratch, long my_flags, long seq_ctrs,
|
||||
long slot_stride16, long inp, long out, long n_elem, long dtype,
|
||||
long rank, long stream, long nblocks, long nthreads, long drain,
|
||||
long acq, long pub) {
|
||||
long acq, long pub, long gate, long gate_ctr) {
|
||||
const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2};
|
||||
const long pf[3] = {peer_flags0, peer_flags1, peer_flags2};
|
||||
ar_twoshot_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem,
|
||||
dtype, rank, stream, nblocks, nthreads, drain, acq, pub);
|
||||
dtype, rank, stream, nblocks, nthreads, drain, acq, pub, gate, gate_ctr);
|
||||
}
|
||||
|
||||
void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
@@ -216,6 +224,7 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee
|
||||
peer_scratch4, peer_scratch5, peer_scratch6};
|
||||
const long pf[7] = {peer_flags0, peer_flags1, peer_flags2, peer_flags3,
|
||||
peer_flags4, peer_flags5, peer_flags6};
|
||||
/* No link gate at eight ranks: the row answers 1, the engine releases by barrier. */
|
||||
ar_twoshot_launch<8>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem,
|
||||
dtype, rank, stream, nblocks, nthreads, drain, acq, pub);
|
||||
dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L);
|
||||
}
|
||||
@@ -1,22 +1,20 @@
|
||||
// r4d_ar_twoshot_Nrank_ti8.hip: r4d_ar_twoshot_{3,4}rank_ti8 -- reduce-scatter + all-gather with
|
||||
// the tiered-int8 wire on both hops, at 3 or 4 ranks. Codec (tiers 1/2/3) from r4d_ar_ti8.h,
|
||||
// transport from r4d_ar_twoshot_Nrank_exact.hip. The second hop costs 38/64 of its exact
|
||||
// bytes. Own contribution reads exact from the input at fold time.
|
||||
// transport from r4d_ar_twoshot_Nrank_exact.hip. The second hop costs 38/64 of its exact bytes.
|
||||
// The own contribution is read exact from the input at fold time.
|
||||
//
|
||||
// Cross-rank identity: the phase-2 encode input is the deterministic fp32 fold, so the wire
|
||||
// words are identical on every rank by construction, and the owner stores the decode of the
|
||||
// words it published -- never the exact fold -- so every rank holds the same bytes for
|
||||
// every shard.
|
||||
// Cross-rank identity: the phase-2 encode input is the deterministic fp32 fold, and the owner
|
||||
// stores the decode of the words it published, never the exact fold, so every rank holds the same
|
||||
// bytes for every shard.
|
||||
//
|
||||
// Slot: region A = ti8 wire (38*sg bytes, codes | rec | scales), region B at align16(A end)
|
||||
// a second wire image of the same layout; the stride must hold both.
|
||||
//
|
||||
// UNEVEN SHARDS, in whole groups (the exact two-shot's rule one level up): ng = numel/32 groups
|
||||
// split ng/ws a shard and the first ng % ws take one more, so shard s starts at group
|
||||
// s*base + min(s, rem). Every slot is laid out for the LONGEST shard (sg_max), whichever shard it
|
||||
// carries, so a writer and a reader never have to agree on anything but sg_max. At 4 ranks the
|
||||
// entry still requires numel to tile 32 x 4 and this is the even split it always was; at 3 a
|
||||
// 2048-wide row is 64 groups and 64 * rows divides by 3 one step in three.
|
||||
// Uneven shards, in whole groups (the exact two-shot's rule applied to groups): ng = numel/32
|
||||
// groups split ng/ws per shard and the first ng % ws take one more, so shard s starts at group
|
||||
// s*base + min(s, rem). Every slot is laid out for the longest shard (sg_max), so writer and reader
|
||||
// agree on sg_max alone. At 4 ranks the entry requires numel to tile 32 x 4, so the split is even;
|
||||
// at 3, a 2048-wide row is 64 groups.
|
||||
#include "r4d.h"
|
||||
#include "r4d_ar_ti8.h"
|
||||
#include "r4d_ar_wide.h"
|
||||
@@ -28,10 +26,12 @@ __global__ void r4d_ar_twoshot_wide_ti8_kernel(
|
||||
const T* __restrict__ in, R4DArWidePeers<char, WS - 1> peers, char* __restrict__ my_base,
|
||||
unsigned int* __restrict__ my_flags, T* __restrict__ out,
|
||||
unsigned int* __restrict__ seq_ctrs, int n_groups, long slot_stride_bytes,
|
||||
long b_off_bytes, int rank, int drain, int acq, int pub) {
|
||||
long b_off_bytes, int rank, int drain, int acq, int pub,
|
||||
long long* gate, unsigned int* gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
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);
|
||||
r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int parity = (int)s_slot;
|
||||
@@ -51,8 +51,8 @@ __global__ void r4d_ar_twoshot_wide_ti8_kernel(
|
||||
for (int p = 0; p < NPEERS; ++p)
|
||||
pslot[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride_bytes;
|
||||
|
||||
// ---- phase 1: encode my contribution to each peer-owned shard into its owner's
|
||||
// region A. My own shard's contribution stays exact, read from the input at fold time.
|
||||
// ---- phase 1: encode my contribution to each peer-owned shard into its owner's region A. My
|
||||
// own shard's contribution stays exact, read from the input at fold time.
|
||||
for (int p = 0; p < NPEERS; ++p) {
|
||||
const T* src = in + R4D_TI8_OFF(peers.rank[p]);
|
||||
const int gE = gB < R4D_TI8_LEN(peers.rank[p]) ? gB : R4D_TI8_LEN(peers.rank[p]);
|
||||
@@ -72,9 +72,9 @@ __global__ void r4d_ar_twoshot_wide_ti8_kernel(
|
||||
}
|
||||
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s - 1u, drain, acq, pub);
|
||||
|
||||
// ---- reduce my shard: own contribution exact from the input, peers decoded from
|
||||
// region A, fp32 fold in ascending rank order; the reduced group is re-encoded and its
|
||||
// wire words go to every peer's region B, the owner keeping their decode.
|
||||
// ---- reduce my shard: own contribution exact, peers decoded from region A, fp32 fold in
|
||||
// ascending rank order. The reduced group is re-encoded to every peer's region B and the owner
|
||||
// keeps its decode.
|
||||
const T* my_in = in + R4D_TI8_OFF(rank);
|
||||
T* my_out = out + R4D_TI8_OFF(rank);
|
||||
const int gM = gB < R4D_TI8_LEN(rank) ? gB : R4D_TI8_LEN(rank);
|
||||
@@ -117,9 +117,12 @@ __global__ void r4d_ar_twoshot_wide_ti8_kernel(
|
||||
ti8_store8(my_out + k * TI8_EPL, v2);
|
||||
}
|
||||
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s, drain, acq, pub);
|
||||
/* As in the exact two-shot, the hold ends after the second handshake: the reduce above is fused
|
||||
* with the phase-2 wire push. Only the local decode-assemble is left (r4d_ar_seq.h). */
|
||||
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
// ---- assemble: decode each peer-owned shard from region B, the mirror of the owner's
|
||||
// roundtrip store.
|
||||
// ---- assemble: decode each peer-owned shard from region B, matching the owner's roundtrip
|
||||
// store.
|
||||
for (int p = 0; p < NPEERS; ++p) {
|
||||
const int owner = peers.rank[p];
|
||||
const char* baseB = my_base +
|
||||
@@ -147,7 +150,8 @@ static void ar_twoshot_ti8_launch(const long* peer_scratch, const long* peer_fla
|
||||
long my_scratch, long my_flags, long seq_ctrs,
|
||||
long slot_stride_bytes, long inp, long out, long n_elem,
|
||||
long dtype, long rank, long stream_i, long nblocks,
|
||||
long nthreads, long drain, long acq, long pub) {
|
||||
long nthreads, long drain, long acq, long pub, long gate,
|
||||
long gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
if (rank < 0 || rank >= WS)
|
||||
throw std::runtime_error("ti8 ar: rank " + std::to_string(rank) +
|
||||
@@ -174,11 +178,10 @@ static void ar_twoshot_ti8_launch(const long* peer_scratch, const long* peer_fla
|
||||
int nt = (int)nthreads;
|
||||
if (nt < 64) nt = 64;
|
||||
if (nt > 1024) nt = 1024;
|
||||
// A wire group is TI8_LPG adjacent lanes and every cross-lane exchange in the codec is a
|
||||
// __shfl_xor masked below TI8_LPG, so the group has to land on lanes 4j..4j+3. The kernel
|
||||
// walks work as k = 4*gA + tid stepping by nt, which keeps k%TI8_LPG == lane%TI8_LPG only
|
||||
// while nt divides by TI8_LPG. A nt that does not would rotate the mapping and give
|
||||
// silently wrong answers with divergent shuffles, so refuse it instead of clamping.
|
||||
// A wire group is TI8_LPG adjacent lanes (codec shuffles use masks below TI8_LPG), so it must
|
||||
// land on lanes 4j..4j+3. The kernel walks k = 4*gA + tid in steps of nt, which keeps
|
||||
// k%TI8_LPG == lane%TI8_LPG only while TI8_LPG divides nt; otherwise the results are silently
|
||||
// wrong, so refuse rather than clamp.
|
||||
if (nt % TI8_LPG)
|
||||
throw std::runtime_error("ti8 ar: nthreads must be a multiple of " +
|
||||
std::to_string(TI8_LPG) + " (a wire group is that many "
|
||||
@@ -194,9 +197,8 @@ static void ar_twoshot_ti8_launch(const long* peer_scratch, const long* peer_fla
|
||||
peers.rank[i] = (i < (int)rank) ? i : i + 1;
|
||||
}
|
||||
|
||||
// scratch must back 2*WS slots of the declared stride, flags one word per (block, source
|
||||
// rank), seq a handshake and a parity word per block of capacity (r4d_ar_seq.h) -- checked
|
||||
// against the allocations, not the arguments.
|
||||
// Checked against the allocations: scratch backs 2*WS slots of the stride, flags one word per
|
||||
// (block, source rank), seq a handshake and a parity word per block of capacity (r4d_ar_seq.h).
|
||||
const long slot_bytes = 2L * WS * slot_stride_bytes;
|
||||
const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int);
|
||||
r4d_ar_check_extent(my_scratch, slot_bytes, "ti8 ar", "my_scratch");
|
||||
@@ -213,7 +215,7 @@ static void ar_twoshot_ti8_launch(const long* peer_scratch, const long* peer_fla
|
||||
r4d_ar_twoshot_wide_ti8_kernel<T, WS><<<nb, nt, 0, st>>>( \
|
||||
(const T*)inp, peers, (char*)my_scratch, (unsigned int*)my_flags, (T*)out, \
|
||||
(unsigned int*)seq_ctrs, (int)n_groups, (long)slot_stride_bytes, b_off, (int)rank, \
|
||||
(int)drain, (int)acq, (int)pub)
|
||||
(int)drain, (int)acq, (int)pub, (long long*)gate, (unsigned int*)gate_ctr)
|
||||
if (dtype == 0) R4D_AR_TS8_LAUNCH(__hip_bfloat16);
|
||||
else R4D_AR_TS8_LAUNCH(__half);
|
||||
#undef R4D_AR_TS8_LAUNCH
|
||||
@@ -226,9 +228,10 @@ void r4d_ar_twoshot_3rank_ti8(long peer_scratch0, long peer_scratch1, long peer_
|
||||
long nthreads, long drain, long acq, long pub) {
|
||||
const long ps[2] = {peer_scratch0, peer_scratch1};
|
||||
const long pf[2] = {peer_flags0, peer_flags1};
|
||||
/* No link gate at three ranks: the row answers 1, the engine releases by barrier. */
|
||||
ar_twoshot_ti8_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride_bytes, inp,
|
||||
out, n_elem, dtype, rank, stream, nblocks, nthreads, drain,
|
||||
acq, pub);
|
||||
acq, pub, 0L, 0L);
|
||||
}
|
||||
|
||||
void r4d_ar_twoshot_4rank_ti8(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
@@ -236,15 +239,16 @@ void r4d_ar_twoshot_4rank_ti8(long peer_scratch0, long peer_scratch1, long peer_
|
||||
long my_scratch, long my_flags, long seq_ctrs,
|
||||
long slot_stride_bytes, long inp, long out, long n_elem,
|
||||
long dtype, long rank, long stream, long nblocks,
|
||||
long nthreads, long drain, long acq, long pub) {
|
||||
long nthreads, long drain, long acq, long pub, long gate,
|
||||
long gate_ctr) {
|
||||
const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2};
|
||||
const long pf[3] = {peer_flags0, peer_flags1, peer_flags2};
|
||||
ar_twoshot_ti8_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride_bytes, inp,
|
||||
out, n_elem, dtype, rank, stream, nblocks, nthreads, drain,
|
||||
acq, pub);
|
||||
acq, pub, gate, gate_ctr);
|
||||
}
|
||||
|
||||
// The tiered-int8 wire format, which the caller needs to size its packed scratch.
|
||||
// Tiered-int8 wire format dimensions, for sizing the caller's packed scratch.
|
||||
void r4d_ar_ti8_dims(int* group, int* group_bytes) {
|
||||
if (group) *group = TI8_GROUP;
|
||||
if (group_bytes) *group_bytes = TI8_GROUP_BYTES;
|
||||
|
||||
+17
-19
@@ -1,14 +1,13 @@
|
||||
#pragma once
|
||||
// r4d_ar_wide.h: the wide (ws>2) all-reduce family's shared transport. Every wide kernel --
|
||||
// one-shot exact, two-shot exact, two-shot ti8 -- publishes in the 2*seq flag space (the
|
||||
// two-shots add the 2s-1 half-step), advances seq_ctrs[b] once per AR, and lays scratch out
|
||||
// as 2*ws slots of one stride (parity x source rank). The parity is the launch's, from the
|
||||
// counters r4d_ar_seq.h keeps beside the handshake ones, so seq_ctrs is 2 * R4D_AR_WIDE_MAX_BLOCKS
|
||||
// words. The constants that size that shared flag/seq/scratch set live here exactly once, a
|
||||
// safety against drift over time across them.
|
||||
// r4d_ar_wide.h: shared transport of the wide (ws>2) all-reduce family. Every wide kernel
|
||||
// (one-shot exact, two-shot exact, two-shot ti8) publishes in the 2*seq flag space (the two-shots
|
||||
// add the 2s-1 half-step), advances seq_ctrs[b] once per AR, and lays scratch out as 2*ws slots of
|
||||
// one stride (parity x source rank). The parity is the launch's, from the parity counters in
|
||||
// r4d_ar_seq.h, so seq_ctrs is 2 * R4D_AR_WIDE_MAX_BLOCKS words. The constants sizing the shared
|
||||
// flag/seq/scratch set are defined only here so they cannot drift apart.
|
||||
//
|
||||
// The 2-rank pair is deliberately NOT here: it has its own flag layout (one word per block,
|
||||
// no ws stride), an acquire-on-load spin, and its own block ceiling.
|
||||
// The 2-rank pair is not here: it has its own flag layout (one word per block, no ws stride), an
|
||||
// acquire-on-load spin and its own block ceiling.
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <hip/hip_bf16.h>
|
||||
@@ -60,10 +59,10 @@ __device__ __forceinline__ void r4d_ar_acquire(int acq) {
|
||||
else if (acq != 2) __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "");
|
||||
}
|
||||
|
||||
// publish `val` to every peer's flag word [b][rank], then wait until every one of this block's
|
||||
// own words has reached or passed it (peers may already be a step ahead; the counter only
|
||||
// grows). One spin lane per source, wrap-safe monotonic compare, never equality. Every rank
|
||||
// publishes before it waits, so there is no cycle; a handshake that cannot complete traps.
|
||||
// Publish `val` to every peer's flag word [b][rank], then wait until each of this block's own
|
||||
// words has reached or passed it (peers may be a step ahead; counters only grow). One spin lane
|
||||
// per source, wrap-safe monotonic compare, never equality. Every rank publishes before it waits,
|
||||
// so there is no cycle; a handshake that cannot complete traps.
|
||||
template <int WS, typename S, int NPEERS>
|
||||
__device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers<S, NPEERS>& peers,
|
||||
unsigned int* __restrict__ my_flags, int b,
|
||||
@@ -75,8 +74,8 @@ __device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers<S, NPEERS>
|
||||
if (tid == 0) {
|
||||
if (drain == 2) __threadfence_system();
|
||||
if (pub) {
|
||||
// One system writeback for the whole publish, then relaxed stores: the extra writebacks
|
||||
// a per-peer release store inserts add no ordering, since the flags go to different peers.
|
||||
// One system writeback for the whole publish, then relaxed stores. Per-peer release stores
|
||||
// would add writebacks that order nothing, since the flags go to different peers.
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "");
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p)
|
||||
@@ -99,10 +98,9 @@ __device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers<S, NPEERS>
|
||||
r4d_ar_acquire(acq);
|
||||
}
|
||||
|
||||
// Host side. The stride and grid are enforced against the real allocations, not trusted:
|
||||
// every scratch, flag, and seq pointer came from hipMalloc / hipIpcOpenMemHandle, so the
|
||||
// runtime can report the extent behind it. A pointer the runtime cannot size is refused
|
||||
// rather than assumed.
|
||||
// Host side: checks stride and grid against the real allocations. Every scratch, flag and seq
|
||||
// pointer comes from hipMalloc / hipIpcOpenMemHandle, so the runtime can report its extent; a
|
||||
// pointer it cannot size is refused.
|
||||
inline void r4d_ar_check_extent(long p, long need, const char* prefix, const char* what) {
|
||||
hipDeviceptr_t base = nullptr;
|
||||
size_t sz = 0;
|
||||
|
||||
+119
-151
@@ -1,18 +1,14 @@
|
||||
/* r4d_args.h -- how a libr4d entry point reads its arguments.
|
||||
*
|
||||
* THERE IS NO ADAPTER LAYER. An entry point takes `(const RadArgs*, RadStream)` and returns a
|
||||
* status, which is the SAME contract RadLaunchFn publishes to every other plugin. An adapter
|
||||
* between the core and a first-party library would be a statement that the interface is wrong: an
|
||||
* out-of-tree author could not write the same kernel without also writing the same adapter, and
|
||||
* that adapter would live in this repository where they cannot reach it.
|
||||
* There is no adapter layer. An entry point takes `(const RadArgs*, RadStream)` and returns a
|
||||
* status, the same RadLaunchFn contract every other plugin implements; an out-of-tree author can
|
||||
* write the same kernel without an adapter they could not reach.
|
||||
*
|
||||
* What this header holds is the part that is not translation: reading a parameter, finding an
|
||||
* operand, asking whether a tensor is contiguous. Every plugin needs it, none of it is libr4d's,
|
||||
* and most of it is one line over rad_abi.h -- which is the shape a shared helper should have.
|
||||
* This header holds the shared helpers: reading a parameter, finding an operand, testing
|
||||
* contiguity. Most are one line over rad_abi.h.
|
||||
*
|
||||
* Nothing here includes r4d.h or HIP: a host translation unit (the row table, the layouts, the
|
||||
* shape hooks) includes this too, and that split is what lets the tables a transcription error
|
||||
* hides in be compiled and read on a machine with no ROCm.
|
||||
* Nothing here includes r4d.h or HIP: host translation units (the row table, the layouts, the
|
||||
* shape hooks) include it too, so those tables compile and can be checked without ROCm.
|
||||
*/
|
||||
#ifndef R4D_ARGS_H
|
||||
#define R4D_ARGS_H
|
||||
@@ -27,9 +23,8 @@
|
||||
|
||||
/* ================================================================== parameter access
|
||||
*
|
||||
* ONE-LINE FORWARDS. rad_args_geti and rad_args_gets are static inline in rad_abi.h -- the header
|
||||
* a third-party plugin gets -- so every plugin shares ONE definition rather than writing its own.
|
||||
* These keep libr4d's spelling for its own call sites and forward. */
|
||||
* Forwards to rad_abi.h's static inline helpers, the ones a third-party plugin gets, keeping
|
||||
* libr4d's spelling at its call sites. */
|
||||
static inline int r4d_geti(const RadArgs* a, const char* k, long long* out) {
|
||||
return rad_args_geti(a, k, out);
|
||||
}
|
||||
@@ -42,11 +37,10 @@ static inline const char* r4d_gets(const RadArgs* a, const char* k) {
|
||||
return rad_args_gets(a, k);
|
||||
}
|
||||
|
||||
/* A float parameter is RAD_P_F64 (rad_types.h, docs/OPS.md "The four rules"), so `dval` is what
|
||||
* arrives and the step path runs no strtod. This one does NOT forward, because it
|
||||
* is deliberately laxer than rad_args_getf_or: the string and integer spellings are still read,
|
||||
* since a tool or a selftest may call a launch directly with no declare in front of it to enforce
|
||||
* the type, and failing such a caller over a spelling tells it nothing useful. */
|
||||
/* A float parameter is RAD_P_F64 (rad_types.h, docs/OPS.md "The four rules"), so `dval` arrives
|
||||
* and the step path runs no strtod. Deliberately laxer than rad_args_getf_or: string and integer
|
||||
* spellings are still read, because a tool or selftest may call a launch directly with no declare
|
||||
* to enforce the type. */
|
||||
static inline double r4d_getf(const RadArgs* a, const char* k, double dflt) {
|
||||
if (!a || !k) return dflt;
|
||||
for (int i = 0; i < a->n_p; ++i) {
|
||||
@@ -63,12 +57,10 @@ static inline double r4d_getf(const RadArgs* a, const char* k, double dflt) {
|
||||
return dflt;
|
||||
}
|
||||
|
||||
/* An enumerated parameter. `act` is "silu" or "sigmoid" and NOT 0 or 1: a --debug-graph dump
|
||||
* reading `act=1` is exactly the "unclear what actually runs" complaint this engine exists to
|
||||
* answer. The mapping to libr4d's integer belongs here, in the shim, and not in the caller.
|
||||
* Returns -1 for a name that is not in the list, which every caller turns into RAD_E_INVAL rather
|
||||
* than running the other activation. `alt` is libr4d's own integer spelling of the same key --
|
||||
* `mode` on gated_had_quant_i8 -- consulted only when the name is absent. */
|
||||
/* An enumerated parameter: `act` is "silu" or "sigmoid", not 0 or 1, so a --debug-graph dump says
|
||||
* what runs; the mapping to libr4d's integer lives in the shim. Returns -1 for an unknown name,
|
||||
* which every caller turns into RAD_E_INVAL. `alt` is libr4d's own integer spelling of the same
|
||||
* key (`mode` on gated_had_quant_i8), consulted only when the name is absent. */
|
||||
static inline int r4d_act_code(const RadArgs* a, const char* key, const char* alt, int dflt) {
|
||||
if (const char* s = r4d_gets(a, key)) {
|
||||
if (!std::strcmp(s, "silu") || !std::strcmp(s, "swish")) return 0;
|
||||
@@ -80,15 +72,8 @@ static inline int r4d_act_code(const RadArgs* a, const char* key, const char* al
|
||||
return dflt;
|
||||
}
|
||||
|
||||
/* Same, off a RadParam list rather than RadArgs -- init() and the layout hooks get the bare list.
|
||||
* rad_plugin.h calls these rad_param_*; these keep libr4d's spelling for its call sites. */
|
||||
static inline int r4d_pgeti(const RadParam* p, int n_p, const char* k, long long* out) {
|
||||
const RadParam* f = rad_param_find(p, n_p, k);
|
||||
if (!f || f->kind != RAD_P_INT) return 0;
|
||||
if (out) *out = f->ival;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Same, off a bare RadParam list (init() and the layout hooks); forwards to rad_plugin.h's
|
||||
* rad_param_*. */
|
||||
static inline long long r4d_pgeti_or(const RadParam* p, int n_p, const char* k, long long dflt) {
|
||||
return rad_param_geti(p, n_p, k, dflt);
|
||||
}
|
||||
@@ -99,18 +84,17 @@ static inline const char* r4d_pgets(const RadParam* p, int n_p, const char* k) {
|
||||
|
||||
/* ================================================================== operand access
|
||||
*
|
||||
* An absent optional operand is a null RadTensor.data (rad_abi.h). r4d_opt() returns null for
|
||||
* both "index past the end" and "present but null", so a shim's optional-operand test is one
|
||||
* pointer test. r4d_req() is the same lookup for a required operand and the caller turns a null
|
||||
* into RAD_E_INVAL -- a missing required operand is a bug in the issue, not a shape this kernel
|
||||
* declines.
|
||||
* An absent optional operand is a null RadTensor.data (rad_abi.h). r4d_opt() returns null both
|
||||
* past the end and for a present-but-null operand, so an optional test is one pointer test. For a
|
||||
* required operand the caller turns null into RAD_E_INVAL: it is a bug in the issue, not a shape
|
||||
* the kernel declines.
|
||||
*/
|
||||
static inline const RadTensor* r4d_opt(const RadArgs* a, int i) { return rad_arg_in(a, i); }
|
||||
|
||||
static inline const void* r4d_p(const RadTensor* t) { return t ? t->data : nullptr; }
|
||||
|
||||
/* ...and the same for an operand a kernel WRITES. RadTensor::data is `void*` already; this exists
|
||||
* so an output cast reads as an output cast rather than as a pointer laundered through `long`. */
|
||||
/* The same for an operand a kernel writes, so an output cast reads as one rather than as a
|
||||
* pointer laundered through `long`. */
|
||||
static inline void* r4d_wp(const RadTensor* t) { return t ? t->data : nullptr; }
|
||||
static inline long r4d_addr(const RadTensor* t) { return t ? (long)(uintptr_t)t->data : 0L; }
|
||||
|
||||
@@ -126,10 +110,9 @@ static inline long long r4d_stride(const RadTensor* t, int i) {
|
||||
|
||||
static inline long long r4d_numel(const RadTensor* t) { return rad_tensor_numel(t); }
|
||||
|
||||
/* [rows..., K] flattened to (M, K). Every per-row kernel in libr4d owns whole ROWS -- one
|
||||
* workgroup per row -- so the leading axes are only a row count and just the last axis is
|
||||
* structural. A rank-3 activation is a rank-2 one here by construction, which is the same fold
|
||||
* the GEMM has to make explicitly (see gemm_ops). */
|
||||
/* [rows..., K] flattened to (M, K). Every per-row kernel in libr4d owns whole rows (one
|
||||
* workgroup per row), so the leading axes are only a row count. The GEMM makes the same fold
|
||||
* explicitly (see gemm_ops). */
|
||||
|
||||
static inline int r4d_rows_of(const RadTensor* t, long long* M, long long* K) {
|
||||
if (!t || t->rank < 1) return RAD_E_SHAPE;
|
||||
@@ -139,14 +122,14 @@ static inline int r4d_rows_of(const RadTensor* t, long long* M, long long* K) {
|
||||
return (*M >= 1 && *K >= 1) ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
/* Dense row-major over the whole tensor. libr4d's entry points take raw pointers and, where they
|
||||
* take a pitch at all, take exactly ONE -- so anything they do not pitch has to be tight, and the
|
||||
* shim is where that is checked. This is the "necessary condition only" boundary from spec §2.1:
|
||||
* the constraint table settles the geometry, contiguity is a property of the call. */
|
||||
/* Dense row-major over the whole tensor. libr4d's entry points take at most one pitch, so
|
||||
* everything else must be tight, and the shim checks it. This is the "necessary condition only"
|
||||
* boundary of spec §2.1: the constraint table settles geometry, contiguity is a property of the
|
||||
* call. */
|
||||
static inline int r4d_contig(const RadTensor* t) { return rad_tensor_is_contiguous(t); }
|
||||
|
||||
/* Contiguous in every axis but the leading one, whose stride is the row pitch libr4d takes as an
|
||||
* explicit argument (`xpitch`, `a_stride`, `xrow`, ...). Returns the pitch in ELEMENTS, or -1. */
|
||||
* explicit argument (`xpitch`, `a_stride`, `xrow`, ...). Returns the pitch in elements, or -1. */
|
||||
static inline long long r4d_row_pitch(const RadTensor* t) {
|
||||
if (!t || t->rank == 0) return -1;
|
||||
if (t->rank == 1) return 1;
|
||||
@@ -159,15 +142,12 @@ static inline long long r4d_row_pitch(const RadTensor* t) {
|
||||
}
|
||||
|
||||
/* [rows..., n] read as (rows, n): the leading axes are a row count and only the last is
|
||||
* structural. Returns the pitch in ELEMENTS, or -1.
|
||||
* structural. Returns the pitch in elements, or -1.
|
||||
*
|
||||
* THE COLUMN-SLICE CASE MUST REFUSE. A slice of a wider buffer -- k out of a fused
|
||||
* [tok, 2*kv_dim] projection, read as [tok*n_head_kv, head_dim] for the per-head norm -- is rows
|
||||
* of `n` that are `n` apart INSIDE a token and a whole buffer row apart BETWEEN tokens. No single
|
||||
* pitch describes that, and answering with the leading stride gives the between-tokens one: the
|
||||
* consumer then reads every n_head_kv-th head against the right numbers and the rest against
|
||||
* garbage, silently, from an op whose own arithmetic is correct. So the trailing axes must be the
|
||||
* WHOLE of the row before their pitch means anything. */
|
||||
* A column slice must refuse. k out of a fused [tok, 2*kv_dim] projection, read as
|
||||
* [tok*n_head_kv, head_dim] for a per-head norm, has rows `n` apart within a token and a buffer
|
||||
* row apart between tokens; no single pitch describes that, and the leading stride would make the
|
||||
* consumer read most heads from garbage. So the trailing axes must cover the whole row. */
|
||||
static inline long long r4d_rows_pitch(const RadTensor* t, long long n, long long* rows) {
|
||||
if (!t || t->rank < 1 || n <= 0) return -1;
|
||||
const long long nel = rad_tensor_numel(t);
|
||||
@@ -184,23 +164,31 @@ static inline long long r4d_rows_pitch(const RadTensor* t, long long n, long lon
|
||||
return trail == n ? r4d_row_pitch(t) : -1;
|
||||
}
|
||||
|
||||
/* 16-byte alignment. Every libr4d kernel that pushes over P2P or issues a global_load_b128 needs
|
||||
* it, and the kernels themselves do not check, so the shim is where it is checked. */
|
||||
/* An attention operand, [tokens, heads * head_dim] over its trailing axes: the token count, head
|
||||
* count and row pitch in elements. False when the trailing axes are not whole heads or no single
|
||||
* pitch describes the rows. */
|
||||
static inline bool r4d_head_rows(const RadTensor* t, long long head_dim, long long* n_tok,
|
||||
long long* n_head, long long* ld) {
|
||||
long long width = 1;
|
||||
for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i];
|
||||
if (t->rank < 2 || width % head_dim) return false;
|
||||
*n_head = width / head_dim;
|
||||
*ld = r4d_rows_pitch(t, width, n_tok);
|
||||
return *ld >= 0;
|
||||
}
|
||||
|
||||
/* 16-byte alignment, needed by every kernel that pushes over P2P or issues a global_load_b128.
|
||||
* The kernels do not check it, so the shim does. */
|
||||
static inline int r4d_aligned(const void* p, unsigned bytes) {
|
||||
return p ? (((uintptr_t)p & (uintptr_t)(bytes - 1)) == 0) : 1;
|
||||
}
|
||||
|
||||
/* ================================================================== which check refused
|
||||
*
|
||||
* A shim rejects a call in a dozen places and returns the same three or four codes from all of
|
||||
* them, so the engine's report -- "kernel X refused op Y at M=5: shape this kernel does not serve"
|
||||
* -- names the kernel and the geometry and says nothing about WHICH condition failed. Distinct
|
||||
* causes are then indistinguishable in the report: an activation declared [tokens, heads, width]
|
||||
* where a shim expected [tokens, width] prints identically to any other refusal at that geometry.
|
||||
*
|
||||
* So: wrap a refusal in R4D_NO() and it names its own line when RAD_R4D_TRACE is set in the
|
||||
* environment. Off, it is the bare return it replaces -- one load of a cached flag, on a path that
|
||||
* is about to fail the step anyway. */
|
||||
* A shim refuses in many places with the same few codes, so the engine's report names the kernel
|
||||
* and geometry but not the failing condition. R4D_NO() wraps a refusal and prints its own line
|
||||
* when RAD_R4D_TRACE is set; otherwise it is the bare return plus one cached-flag load on a path
|
||||
* that is failing anyway. */
|
||||
static inline int r4d_trace_on(void) {
|
||||
static int on = -1;
|
||||
if (on < 0) { const char* e = std::getenv("RAD_R4D_TRACE"); on = (e && *e && *e != '0'); }
|
||||
@@ -213,8 +201,8 @@ static inline int r4d_refused(int code, const char* file, int line) {
|
||||
#define R4D_NO(code) r4d_refused((code), __FILE__, __LINE__)
|
||||
|
||||
/* ================================================================== dtype helpers */
|
||||
/* Widest world any libr4d all-reduce serves. Fixed by the 8-rank entry points' argument lists,
|
||||
* which name seven peers explicitly. */
|
||||
/* Widest world any libr4d all-reduce serves, fixed by the 8-rank entry points' argument lists
|
||||
* (seven explicit peers). */
|
||||
enum { R4D_MAX_RANKS = 8, R4D_MAX_PEERS = 7 };
|
||||
|
||||
/* libr4d's all-reduce dtype code: 0 bf16, 1 fp16, 2 fp32. Returns -1 for anything else. */
|
||||
@@ -231,12 +219,9 @@ static inline int r4d_ar_esize(int code) { return code == 2 ? 4 : 2; }
|
||||
|
||||
/* ================================================================== weight layout constants
|
||||
*
|
||||
* These are libr4d's compile-time constants, restated here because r4d_layout.cpp must not include
|
||||
* r4d.h (it is host code compiled without ROCm) and because the .rad container records them in the
|
||||
* layout tag. THE BUILD CHECKS THEM: libr4d/CMakeLists.txt passes the same
|
||||
* -DR4D_GEMM_*_GROUP=128 to libr4d's translation units, and r4d_gemm_args.h static_asserts the
|
||||
* group constants against libr4d's own macros, so a divergence is a compile error rather than a
|
||||
* silently wrong weight file.
|
||||
* libr4d's compile-time constants, restated because r4d_layout.cpp is host code built without
|
||||
* ROCm and cannot include r4d.h, and because the .rad container records them in the layout tag.
|
||||
* r4d_gemm_args.h static_asserts the group constants against libr4d's macros.
|
||||
*/
|
||||
enum {
|
||||
R4D_W4_GROUP = 128, /* K per (scale, zero) dword; libr4d R4D_GEMM_W4_GROUP */
|
||||
@@ -245,19 +230,17 @@ enum {
|
||||
R4D_W8_KPB = 32, /* K per packed block: 2 k steps, 16 bytes per lane */
|
||||
R4D_W2_GROUP = 128, /* libr4d R4D_GEMM_W2A8_GROUP */
|
||||
R4D_MXFP4_GROUP = 32, /* K per E8M0 exponent, fixed by the OCP MX format */
|
||||
/* The block-scaled fp8 family's block, on BOTH axes. Unlike every other constant here it is not
|
||||
* a choice this project's quantiser made: it is `quantization_config.weight_block_size` in the
|
||||
* checkpoint's own config.json, and the weight bytes on disk are laid out to it. It cannot be
|
||||
* static_asserted against libr4d's `r4d_gemm_fp8a8_block()` because that is a function and not
|
||||
* a macro, so r4d_gemm_fp8a8.hip checks it at launch -- a scalar compare against a constant,
|
||||
* which is nothing, and the alternative is a silently wrong scale grid. */
|
||||
/* The block-scaled fp8 family's block, on both axes. Not a quantiser choice: it is the
|
||||
* checkpoint's `quantization_config.weight_block_size`, and the bytes on disk follow it. It
|
||||
* 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,
|
||||
R4D_WAVE = 32,
|
||||
R4D_NTILE = 16 /* output rows per WMMA n-tile */
|
||||
};
|
||||
|
||||
/* Plugin-private dtypes. The core never interprets these: rad_types.h reserves everything at or
|
||||
* above RAD_DT_PLUGIN_BASE for exactly this, and the layout hook is what sizes them. */
|
||||
* above RAD_DT_PLUGIN_BASE for this, and the layout hook sizes them. */
|
||||
enum {
|
||||
R4D_DT_W4_FRAG = RAD_DT_PLUGIN_BASE + 0, /* 4-bit codes in WMMA fragment order */
|
||||
R4D_DT_W4_SZ = RAD_DT_PLUGIN_BASE + 1, /* (f16 scale, f16 -(1024+zero)) dwords */
|
||||
@@ -266,35 +249,33 @@ enum {
|
||||
R4D_DT_W2_FRAG = RAD_DT_PLUGIN_BASE + 4,
|
||||
R4D_DT_MXFP4_FRAG = RAD_DT_PLUGIN_BASE + 5,
|
||||
R4D_DT_E8M0 = RAD_DT_PLUGIN_BASE + 6, /* [K/32][N] shared exponents, and Wref[N] */
|
||||
/* The grouped MoE GEMM's 4-bit expert weight: ROW-MAJOR packed nibbles, each a code into a
|
||||
* sixteen-entry table, expanded to E4M3 on the way into LDS. Not R4D_DT_W4_FRAG -- that plane
|
||||
* is a WMMA fragment permutation for a kernel that loads its weight straight from global, and
|
||||
* this one stages through LDS because its rows are gathered. See r4d_layout.cpp. */
|
||||
/* The grouped MoE GEMM's 4-bit expert weight: row-major packed nibbles, each a code into a
|
||||
* sixteen-entry table, expanded to E4M3 on the way into LDS. Not R4D_DT_W4_FRAG, which is a
|
||||
* WMMA fragment permutation for a kernel loading its weight from global; this one stages
|
||||
* through LDS because its rows are gathered. See r4d_layout.cpp. */
|
||||
R4D_DT_MOEW4 = RAD_DT_PLUGIN_BASE + 7,
|
||||
/* The same GEMM's 5-bit expert weight: each row is R4D_DT_MOEW4's nibble plane of the codes'
|
||||
* low four bits -- a magnitude -- followed by one bit a code, the sign, a dword a 32
|
||||
* elements in the order the kernel merges them (r4d_layout.cpp, moew5_row). Five bits an
|
||||
* element, so a row is 5K/8 bytes. */
|
||||
/* The same GEMM's 5-bit expert weight: per row, R4D_DT_MOEW4's nibble plane of the codes' low
|
||||
* four bits (the magnitude), then the sign bits, one dword per 32 elements in the order the
|
||||
* kernel merges them (r4d_layout.cpp, moew5_row). A row is 5K/8 bytes. */
|
||||
R4D_DT_MOEW5 = RAD_DT_PLUGIN_BASE + 8
|
||||
};
|
||||
|
||||
/* THE GROUPED MoE GEMM'S CODE TABLES, as the four dwords w4_e4m3's byte permutes read
|
||||
* (r4d_moe.hip): entries 0..3, 4..7, 8..11 and 12..15, one E4M3 byte an entry, the lowest entry in
|
||||
* the low byte. `w4a8` and `w4a8h` decode a two's complement nibble, -8..7. `w4nla8h` decodes
|
||||
* libquant's `table=w4nl` -- magnitudes ascending, then their negatives -- and kW4nlTable is that
|
||||
* table as the floats a container stores, which the layout hook compares the container's own table
|
||||
* plane with before it serves a byte of it. */
|
||||
/* The grouped MoE GEMM's code tables, as the four dwords w4_e4m3's byte permutes read
|
||||
* (r4d_moe.hip): entries 0..3, 4..7, 8..11 and 12..15, one E4M3 byte an entry, lowest entry in the
|
||||
* low byte. `w4a8` and `w4a8h` decode a two's complement nibble, -8..7. `w4nla8h` decodes
|
||||
* libquant's `table=w4nl` (magnitudes ascending, then their negatives); kW4nlTable is that table
|
||||
* as a container stores it, which the layout hook compares with the container's table plane
|
||||
* before serving it. */
|
||||
static constexpr uint32_t kW4IntPerm[4] = { 0x44403800u, 0x4E4C4A48u, 0xCACCCED0u, 0xB8C0C4C8u };
|
||||
static constexpr uint32_t kW4nlPerm[4] = { 0x504B4539u, 0x5B595653u, 0xD0CBC5B9u, 0xDBD9D6D3u };
|
||||
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 };
|
||||
|
||||
/* `w5nl64a8h` DECODES libquant's `table=w5nl`: thirty-two levels, the sixteen magnitudes
|
||||
* ascending and then their negatives, so a code's high bit is its sign and its low four bits index
|
||||
* the magnitudes. The kernel expands the magnitude as it does a w4nl code, out of kW5nlMagPerm --
|
||||
* those sixteen magnitudes' E4M3 bytes in w4_e4m3's dword order -- and sets the byte's sign bit
|
||||
* from the sign plane. Every level is exact in E4M3. */
|
||||
/* `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
|
||||
* magnitudes. The kernel expands the magnitude from kW5nlMagPerm (their E4M3 bytes in w4_e4m3's
|
||||
* dword order) and sets the sign bit from the sign plane. Every level is exact in E4M3. */
|
||||
static constexpr uint32_t kW5nlMagPerm[4] = { 0x4B484235u, 0x5453514Fu, 0x5A595856u, 0x5F5D5C5Bu };
|
||||
static constexpr float kW5nlTable[32] = {
|
||||
0.8125f, 2.5f, 4.0f, 5.5f, 7.5f, 9.0f, 11.0f, 12.0f,
|
||||
@@ -302,41 +283,34 @@ static constexpr float kW5nlTable[32] = {
|
||||
-0.8125f, -2.5f, -4.0f, -5.5f, -7.5f, -9.0f, -11.0f, -12.0f,
|
||||
-14.0f, -16.0f, -18.0f, -20.0f, -22.0f, -24.0f, -26.0f, -30.0f };
|
||||
|
||||
/* `w4nl64a8h`'S, `w4nl32a8h`'S AND `w5nl64a8h`'S FIXED SECOND LEVEL: a weight's E4M3 scale a (row,
|
||||
* 64 or 32 of K) multiplies it, and a container states it (libquant's scale2_value=, one f32 for
|
||||
* each weight), which the layout hook compares with this before serving a byte. It is fixed rather
|
||||
* than per row because the experts' scales -- with the rotation's 1/128 folded in -- sit between
|
||||
* 2^-15 and 2^-10.6 on Qwen3.8-Flash-Next at a 64 (a 32's sit a little lower, and w5nl's, over a
|
||||
* top level of 30 rather than 22, half a binade lower), so under 2^-13 every one is a normal E4M3
|
||||
* value with binades to spare either side, and E4M3's three mantissa bits are the same in every
|
||||
* binade a row level would have put it in. */
|
||||
/* The fixed second-level scale of `w4nl64a8h`, `w4nl32a8h` and `w5nl64a8h`: it multiplies a
|
||||
* weight's per-(row, 64 or 32 of K) E4M3 scale. A container states it (libquant's scale2_value=),
|
||||
* and the layout hook compares it with this before serving. Fixed rather than per row because the
|
||||
* experts' scales (with the rotation's 1/128 folded in) lie between 2^-15 and 2^-10.6 on
|
||||
* Qwen3.8-Flash-Next at group 64 (slightly lower at 32, half a binade lower for w5nl). Under
|
||||
* 2^-13 each is a normal E4M3 value, and E4M3 has three mantissa bits in every binade. */
|
||||
static constexpr float kW4G64Scale = 0x1p-13f;
|
||||
|
||||
|
||||
/* ================================================================== skinny-GEMM variants
|
||||
*
|
||||
* libr4d's five skinny-GEMM knobs. Exposed as RadVariant.config so `rad-tune` can walk them and
|
||||
* `--debug-graph` can name the pick (spec §15). The axis earns its keep because the best setting
|
||||
* is per (N, K) AND per M band, and the spread between the best and a single fixed default is
|
||||
* large enough to matter on every shape in a step.
|
||||
* libr4d's five skinny-GEMM knobs, exposed as RadVariant.config so `rad-tune` can walk them and
|
||||
* `--debug-graph` can name the pick (spec §15). The best setting depends on (N, K) and the M band.
|
||||
*
|
||||
* sk == 0 means "choose the largest legal split count at issue". The split-K constraint is
|
||||
* K % (SK * group) == 0, which depends on K, so no fixed default is legal at every shape -- and a
|
||||
* default that is illegal at a shape would make an UNTUNED install fail rather than be slow, which
|
||||
* spec §15 says is the wrong way round. The sentinel is the plugin's own rule, declared here and
|
||||
* resolved in one place (r4d_gemm_args.h:pick_sk), not a hidden fallback.
|
||||
* sk == 0 means "choose the largest legal split count at issue". Split-K requires
|
||||
* K % (SK * group) == 0, so no fixed default is legal at every shape, and an illegal default would
|
||||
* make an untuned install fail rather than run slowly (spec §15). The sentinel is resolved in one
|
||||
* place, r4d_gemm_args.h:pick_sk.
|
||||
*/
|
||||
struct R4dGemmCfg { int wv, sk, mb, npw, nt; };
|
||||
|
||||
/* The tiled and prefill GEMMs take a single opaque variant index into libr4d's own switch. Only
|
||||
* arms that compute a CORRECT result are listed. Most arms of that switch are cost ablations that
|
||||
* compute wrong answers by construction, and a tuner handed one would benchmark a kernel that does
|
||||
* not compute the GEMM and then pick it. */
|
||||
/* The tiled and prefill GEMMs take one opaque variant index into libr4d's own switch of compiled
|
||||
* tile arms; the row's tunable lists the arms a tuner may pick (r4d_rows.cpp, kTileArms). */
|
||||
struct R4dTileCfg { int variant; int bm; int bn; };
|
||||
|
||||
/* The MXFP4 tiled GEMM's column width in 32-column units per wave: TN=2 gives a 256 x 64 block,
|
||||
* TN=4 a 256 x 128 one. Its crossover is a function of M (r4d_gemm_mxfp4a8_tiled.hip carries the
|
||||
* measurement), so 0 -- the default -- decides at issue and a fixed value is for a tuner. */
|
||||
* TN=4 a 256 x 128 one. The crossover depends on M (see r4d_gemm_mxfp4a8_tiled.hip), so 0, the
|
||||
* default, decides at issue; a fixed value is for a tuner. */
|
||||
struct R4dMxTileCfg { int tn; };
|
||||
|
||||
/* The MXFP4 decode GEMM's split-K width, K slab and weight-load hint. 0 on each is the rule in
|
||||
@@ -344,30 +318,27 @@ struct R4dMxTileCfg { int tn; };
|
||||
* the weight past L2/MALL, 2 loads it plainly. */
|
||||
struct R4dMxDecCfg { int ks; int bk; int nt; };
|
||||
|
||||
/* Split-KV segment count for the paged decode kernels. 0 is libr4d's own split law, which is
|
||||
* measured (r4d_attn_paged_h256_gqa6.hip carries the table) and reads num_seqs and max_ctx that
|
||||
* only exist at issue -- so it stays the default and the fixed counts are there for a tuner that
|
||||
* has a concrete shape. RadScratchFn is handed the same variant index, so the arena is sized for
|
||||
* whatever this picks rather than for the law's answer at some other shape. */
|
||||
/* Split-KV segment count for the paged decode kernels. 0 is libr4d's split law (table in
|
||||
* r4d_attn_paged_h256_gqa6.hip), which needs num_seqs and max_ctx from the issue, so it stays the
|
||||
* default; fixed counts are for a tuner. RadScratchFn gets the same variant index, so the arena
|
||||
* is sized for what this picks. */
|
||||
struct R4dSplitCfg { int splits; };
|
||||
|
||||
/* The all-reduce launch geometry. libr4d takes nblocks/nthreads/drain/acq (and `pub` at width) as
|
||||
* arguments rather than compiling them in. The defaults are nthreads=1024, drain=3
|
||||
* (s_wait_storecnt, which is what fine-grained uncached scratch requires), acq=0 and pub=1, with
|
||||
* nblocks scaled by message size and clamped. nblocks == 0 selects that scaling rule. */
|
||||
/* The all-reduce launch geometry, passed to libr4d as nblocks/nthreads/drain/acq (and `pub` at
|
||||
* width). Defaults: nthreads=1024, drain=3 (s_wait_storecnt, which fine-grained uncached scratch
|
||||
* requires), acq=0, pub=1, and nblocks scaled by message size and clamped; nblocks == 0 selects
|
||||
* that rule. */
|
||||
struct R4dArCfg { int nblocks; int nthreads; int drain; int acq; int pub; };
|
||||
|
||||
/* rowtopk: RC is how many candidates a chunk keeps (>= R), NCH the requested chunk width (a
|
||||
* REQUEST -- libr4d rounds it up to a multiple of eight columns, so the scratch hook asks
|
||||
* r4d_rowtopk_bf16_chunks() what the launch will actually use), PT1 the stage-1 thread count. */
|
||||
/* rowtopk: RC is how many candidates a chunk keeps (>= R), NCH the requested chunk width (libr4d
|
||||
* rounds it up to a multiple of eight columns, so the scratch hook asks r4d_rowtopk_bf16_chunks()
|
||||
* for the real one), PT1 the stage-1 thread count. */
|
||||
struct R4dTopkCfg { int rc; int nch; int pt1; };
|
||||
|
||||
/* The block-scaled fp8 matvec's rows a wave. Blocking trades waves for memory-level parallelism, so
|
||||
* where it lands depends on whether the kernel is waiting on loads or on the ALU -- a property of
|
||||
* the shape AND of the inner loop. THE RULE IS FITTED, so it holds only for the loop it was fitted
|
||||
* against: any change to the matvec's inner loop (the width of the scale load, the activation
|
||||
* dtype) invalidates it and it has to be re-fitted. 0 selects libr4d's default rule, so an untuned
|
||||
* install is fast rather than broken; the rest pin it for rad-tune. */
|
||||
/* The block-scaled fp8 matvec's rows a wave. Blocking trades waves for memory-level parallelism,
|
||||
* so the best value depends on whether the kernel waits on loads or the ALU. The default rule is
|
||||
* fitted to the current inner loop: any change to it (scale load width, activation dtype)
|
||||
* requires re-fitting. 0 selects that rule; other values pin it for rad-tune. */
|
||||
struct R4dMvCfg { int rb; };
|
||||
|
||||
|
||||
@@ -375,13 +346,10 @@ struct R4dMvCfg { int rb; };
|
||||
extern "C" {
|
||||
/* -- the tuned configuration (r4d_rows.cpp) --
|
||||
*
|
||||
* The core resolved one instantiation, picked a point in the space the row declared, and appended
|
||||
* the choices to RadArgs::p. These read that point back, falling to the axis's own default when a
|
||||
* cold caller supplied none -- so the default is defined once, in the RadTunable table, and a
|
||||
* checker calling the kernel with no tuned key gets exactly what an untuned install runs.
|
||||
*
|
||||
* They cannot fail: every axis has a default and the loader refuses a plugin whose default is not
|
||||
* one of that axis's own values, so there is no "out of range" to report. */
|
||||
* The core picked a point in the space the row declared and appended it to RadArgs::p. These read
|
||||
* it back, falling to the axis's default (defined once, in the RadTunable table) when a caller
|
||||
* supplied none, so a checker with no tuned key runs what an untuned install runs. They cannot
|
||||
* fail: the loader refuses a plugin whose default is not one of the axis's values. */
|
||||
void r4d_cfg_gemm (const RadArgs*, struct R4dGemmCfg*);
|
||||
void r4d_cfg_tiled (const RadArgs*, struct R4dTileCfg*);
|
||||
void r4d_cfg_prefill(const RadArgs*, struct R4dTileCfg*);
|
||||
|
||||
+34
-62
@@ -1,20 +1,15 @@
|
||||
/* r4d_attn_args.h -- the paged-attention operand list, read once for four kernel geometries.
|
||||
/* r4d_attn_args.h -- the paged-attention operand reader shared by every paged kernel geometry.
|
||||
*
|
||||
* The paged kernels -- h256/gqa6, h128/gqa4 and the gqa8/gqa12 instantiations, prefill and decode
|
||||
* -- take the SAME operands in the same order, because they implement the same op. The reader for
|
||||
* that list therefore belongs to the family rather than to any one of them, and this is where it
|
||||
* lives: a header beside the kernels, included by each unit's entry point.
|
||||
* The paged kernels (h256/gqa6, h128/gqa4, the gqa8/gqa12 instantiations; prefill and decode) take
|
||||
* the same operands in the same order, so one reader serves them all.
|
||||
*
|
||||
* It is NOT a translation layer. libr4d's R4DArgs carries the same convention RadTensor does --
|
||||
* strides in ELEMENTS (spec 2.1) -- so this is field extraction plus the validation a constraint
|
||||
* cannot do: a constraint settles whether a kernel EXISTS for a geometry and says nothing about a
|
||||
* particular call, so contiguity, alignment and buffer sizes are checked here and refused with the
|
||||
* code that names the class.
|
||||
* R4DArgs uses RadTensor's convention (strides in elements, spec 2.1), so this is field extraction
|
||||
* plus the per-call validation a constraint cannot express: contiguity, alignment and buffer
|
||||
* sizes, each refused with the code that names the class.
|
||||
*
|
||||
* The kernels already return a negative code for a shape they do not serve (-1 head_dim or
|
||||
* block_size, -2 gqa, -4 too many decode rows, -100-hipError for a launch failure) and those are
|
||||
* passed through unchanged: a caller that gets one has hit a selection bug, and the exact value is
|
||||
* what says which.
|
||||
* Kernel return codes for an unserved shape (-1 head_dim or block_size, -2 gqa, -4 too many decode
|
||||
* rows, -100-hipError for a launch failure) pass through unchanged. Getting one means a selection
|
||||
* bug, and the value says which.
|
||||
*/
|
||||
#ifndef R4D_ATTN_ARGS_H
|
||||
#define R4D_ATTN_ARGS_H
|
||||
@@ -23,10 +18,10 @@
|
||||
#include "r4d_args.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
/* libr4d's compiled-in geometry, checked against the row table at build time rather than trusted.
|
||||
* A libr4d rebuilt for a different head size would otherwise change what the rows mean without
|
||||
* changing the rows. */
|
||||
/* Checks libr4d's compiled-in geometry against the row table, so a libr4d rebuilt for a
|
||||
* different head size cannot silently change what the rows mean. */
|
||||
static inline int check_dims_once() {
|
||||
int hd = 0, gqa = 0, bs = 0, rows = 0;
|
||||
r4d_attn_dims(&hd, &gqa, &bs, &rows);
|
||||
@@ -38,20 +33,12 @@ enum { AP_Q = 0, AP_KV, AP_BT, AP_SEQ, AP_KDS, AP_VDS, AP_CU, AP_OUT };
|
||||
|
||||
/* Fill R4DArgs from a RadArgs. Returns RAD_OK, or the negative code naming what is wrong.
|
||||
*
|
||||
* RAGGED BATCHES. libr4d's paged kernels take a scalar q_len AND an optional cu_seqlens, and which
|
||||
* one this call uses is decided here. Without cu_seqlens every sequence in the batch has to present
|
||||
* the same query length, which is a restriction the scheduler does not honour and cannot be asked
|
||||
* to: core/sched/scheduler.cpp builds RAD_PHASE_MIXED steps deliberately, because a decode row
|
||||
* costs nothing once another sequence's prefill chunk is already reading the weights. A step that
|
||||
* mixes them has total_q that need not divide n_seq, and refusing that with RAD_E_SHAPE would be
|
||||
* reported by the run phase as a kernel that does not serve the shape, which aborts the engine. So
|
||||
* the operand is passed whenever it is there and the uniform arithmetic is kept only for the case
|
||||
* where it is not.
|
||||
*
|
||||
* q_len then means the batch MAXIMUM, and it comes from the PARAMETER, which is exactly what the
|
||||
* arch block issued the op with (RAD_ISSUE_N(..., batch->max_q_len, ...)). Deriving it from the
|
||||
* tensors is only possible in the uniform case, and that is what the code below does there --
|
||||
* total_q / num_seqs -- because the parameter is a band bound there, not a count.
|
||||
* Ragged batches: the kernels take a scalar q_len and an optional cu_seqlens. Without cu_seqlens
|
||||
* every sequence must have the same query length, which RAD_PHASE_MIXED steps (decode rows riding
|
||||
* on another sequence's prefill chunk, core/sched/scheduler.cpp) do not satisfy; refusing them
|
||||
* would abort the engine. So cu_seqlens is used whenever present, and the uniform arithmetic
|
||||
* (q_len = total_q / num_seqs) only when it is not. In the ragged case q_len is the batch maximum,
|
||||
* taken from the parameter the arch block issued the op with (batch->max_q_len).
|
||||
*/
|
||||
static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) {
|
||||
const RadTensor* q = r4d_opt(a, AP_Q);
|
||||
@@ -65,13 +52,9 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim)
|
||||
if (q->rank < 2 || o->rank < 2 || bt->rank != 2 || su->rank < 1) return R4D_NO(RAD_E_SHAPE);
|
||||
if (kv->rank != 4) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* THE HEAD AXIS MAY BE SPELLED OR FLATTENED, and both are the same dense block. An architecture
|
||||
* plugin declares the query buffer [tokens, n_head, head_dim] when something downstream needs
|
||||
* the head axis and [tokens, n_head*head_dim] when nothing does -- a gated attention block does
|
||||
* the latter, because its query comes out of a de-interleave and goes straight here. The kernel
|
||||
* indexes one dense [total_q, q_heads, head_dim] block either way, so the shim reads the rank
|
||||
* it was given rather than demanding three. `head_dim` is the op's parameter, which is what
|
||||
* makes the flattened form readable at all. */
|
||||
/* The query may be [tokens, n_head, head_dim] or flattened to [tokens, n_head*head_dim]
|
||||
* (a gated attention block's de-interleaved query). Both are the same dense block, so any rank
|
||||
* is accepted; head_dim comes from the op parameter, which makes the flattened form readable. */
|
||||
const long long head_dim = expect_head_dim;
|
||||
const long long total_q = q->shape[0];
|
||||
const long long num_seqs = bt->shape[0];
|
||||
@@ -79,7 +62,7 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim)
|
||||
if (r4d_numel(q) % (total_q * head_dim)) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long q_heads = r4d_numel(q) / (total_q * head_dim);
|
||||
if (q_heads <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
/* Ragged unless cu_seqlens says otherwise; see the note above fill_paged. */
|
||||
/* Ragged exactly when cu_seqlens is present; see the note above fill_paged. */
|
||||
const bool ragged = (cu != nullptr) && cu->data;
|
||||
if (ragged) {
|
||||
if (cu->rank != 1 || cu->shape[0] != num_seqs + 1) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -96,15 +79,14 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim)
|
||||
if (su->shape[0] != num_seqs) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!r4d_contig(bt) || !r4d_contig(su)) return R4D_NO(RAD_E_STRIDE);
|
||||
|
||||
/* The KV cache is the one operand that IS pitched: kv_block_stride and kv_head_stride are
|
||||
* taken as arguments, so a padded cache is legal. Everything inside a (block, head) slot is
|
||||
* not, because the kernel walks it with a vector load. */
|
||||
/* The KV cache is pitched (kv_block_stride, kv_head_stride), so a padded cache is legal.
|
||||
* Each (block, head) slot must be dense, because the kernel walks it with vector loads. */
|
||||
const long long block_size = kv->shape[2];
|
||||
if (kv->stride[3] != 1) return R4D_NO(RAD_E_STRIDE);
|
||||
if (kv->stride[2] != 2 * head_dim) return R4D_NO(RAD_E_STRIDE);
|
||||
if (kv->shape[3] != 2 * head_dim) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* 16-byte alignment: every one of these is read through a 128-bit load. */
|
||||
/* 16-byte alignment for 128-bit loads. */
|
||||
if (!r4d_aligned(q->data, 16) || !r4d_aligned(o->data, 16) || !r4d_aligned(kv->data, 16))
|
||||
return R4D_NO(RAD_E_ALIGN);
|
||||
|
||||
@@ -124,20 +106,12 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim)
|
||||
r->num_seqs = (int)num_seqs;
|
||||
r->cu_q = ragged ? (const int*)cu->data : nullptr;
|
||||
r->total_q = (int)total_q;
|
||||
/* q_len is the exact count when the batch is uniform, and an UPPER BOUND on the per-sequence
|
||||
* lengths when it is ragged -- it sizes the prefill grid and the decode wave count, and the
|
||||
* kernels take the exact lengths from cu_seqlens.
|
||||
*
|
||||
* The bound is the smaller of two things that are both >= the true maximum and neither of
|
||||
* which is it. The `q_len` parameter is the resolved BAND (RadArgs carries the geometry with
|
||||
* ranges collapsed, not the value the op was issued with), and the band was selected by
|
||||
* max_q_len, so it is at least that. total_q is a sum of lengths, so it is at least the
|
||||
* largest of them. Taking the smaller keeps the decode band legal: its bound is 10 and
|
||||
* 10 * gqa is 60 rows, under the 64 a decode workgroup holds, while total_q alone would be
|
||||
* the whole batch and would be refused with -4.
|
||||
*
|
||||
* The cost of the bound not being tight is empty workgroups that exit on their first
|
||||
* comparison -- the prefill kernel's `qb * BLOCK_Q >= qlen` and the decode kernel's `live`. */
|
||||
/* q_len is exact for a uniform batch and an upper bound for a ragged one; it sizes the
|
||||
* prefill grid and the decode wave count, and the kernels read exact lengths from cu_seqlens.
|
||||
* The bound is min(band, total_q): the `q_len` parameter is the resolved band selected by
|
||||
* max_q_len, and total_q is a sum of lengths, so both are >= the true maximum. The min keeps
|
||||
* decode legal (band bound 10 * gqa 6 = 60 rows fits a 64-row workgroup; total_q alone would
|
||||
* be refused with -4). A loose bound only costs workgroups that exit on their first compare. */
|
||||
r->q_len = (int)(total_q / num_seqs);
|
||||
if (ragged) {
|
||||
const long long band = r4d_geti_or(a, "q_len", total_q);
|
||||
@@ -154,13 +128,11 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim)
|
||||
r->causal = (int)r4d_geti_or(a, "causal", 1);
|
||||
r->causal_seq = nullptr;
|
||||
|
||||
/* The softmax scale. Absent, 1/sqrt(head_dim) -- right for every model in scope, and a
|
||||
* parameter rather than a hardcode for the ones that are not. */
|
||||
/* Softmax scale; defaults to 1/sqrt(head_dim). */
|
||||
r->scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)head_dim));
|
||||
|
||||
/* max_ctx is the HOST-visible context bound; seqused_k is device-side and the split law
|
||||
* cannot read it. The block table's width times the block size is an exact upper bound on
|
||||
* what any sequence in this batch can have, so it is a safe default. */
|
||||
/* max_ctx is the host-visible context bound for the split law (seqused_k is device-side).
|
||||
* Block-table width times block size is a safe upper bound. */
|
||||
long long mc = r4d_geti_or(a, "max_ctx", 0);
|
||||
if (mc <= 0) mc = (long long)r->max_blocks * block_size;
|
||||
r->max_ctx = (int)mc;
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
// R4D decode. The prefill core (lazy reference-max softmax, f16 operands, folded query scale,
|
||||
// contiguous-k fragments, prefetch + scheduling barrier, dot2 row sum) on the split-KV MTP-verify
|
||||
// shape, plus two decode-only changes:
|
||||
// R4D split-KV decode (also the MTP-verify shape). Same core as the prefill kernel (lazy
|
||||
// reference-max softmax, f16 operands, folded query scale, contiguous-k fragments, prefetch +
|
||||
// scheduling barrier, dot2 row sum), plus two decode-only options:
|
||||
//
|
||||
// KLDS0 reads K straight from the paged cache, including when that cache is fp8. The
|
||||
// widening moves from once-per-workgroup to once-per-warp; it costs VALU on a leg that is
|
||||
// bandwidth-bound and buys back the whole sK allocation, which at TILE 16 is 8.3 KB of
|
||||
// the 14.5 KB that sets resident-CTA count. This is the argmin at every depth.
|
||||
// PF16 split-KV partials as f16 instead of f32. The partial buffer is written once and read
|
||||
// back once, and at 16K context that round trip is ~14 MB against ~17 MB of KV -- i.e.
|
||||
// nearly half the leg's DRAM traffic. Storing O/l rather than O bounds the value by
|
||||
// max|v|, so f16 cannot overflow and its 11-bit mantissa costs ~5e-4 relative.
|
||||
// KLDS0 reads K straight from the paged cache (bf16 or fp8), widening once per warp instead of
|
||||
// once per workgroup. Costs VALU on a bandwidth-bound leg and frees sK, which at TILE 16
|
||||
// is 8.3 KB of the 14.5 KB that limits resident workgroups. Best at every depth.
|
||||
// PF16 split-KV partials stored as f16. At 16K context the partial round trip is ~14 MB
|
||||
// against ~17 MB of KV. Storing O/l instead of O bounds values by max|v|, so f16 cannot
|
||||
// overflow; the 11-bit mantissa costs ~5e-4 relative.
|
||||
//
|
||||
// This file compiles neither an fp8-P leg nor an alternative to the CONTIG fragment layout; see
|
||||
// r4d_attn_prefill_h256_gqa6.hip for the full option set and the reasoning behind each bit.
|
||||
// No fp8-P leg and no non-CONTIG alternative here; r4d_attn_prefill_h256_gqa6.hip documents the
|
||||
// full option set.
|
||||
#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 <algorithm>
|
||||
#include <type_traits>
|
||||
|
||||
#define O_F16 1
|
||||
@@ -30,60 +29,29 @@
|
||||
#define O_PF8 3072
|
||||
#define O_SGB 4096
|
||||
#define O_DOT2 16384
|
||||
// The tile-staging set, shared with r4d_attn_prefill_h256_gqa6.hip -- see the comments there.
|
||||
// BTS block table entries for the tile in SGPRs, loaded a tile ahead. On this leg it also
|
||||
// removes a dependent global load from INSIDE the m-tile loop: with KLDS0 the K address
|
||||
// comes from bt[kk/BS] on every m-tile.
|
||||
// Tile-staging options, shared with r4d_attn_prefill_h256_gqa6.hip:
|
||||
// BTS the tile's block-table entries in SGPRs, loaded a tile ahead. With KLDS0 this also takes
|
||||
// the dependent bt[kk/BS] load out of the m-tile loop.
|
||||
// GPREV tile ti+1's V fetched into registers before the m-tile loop.
|
||||
// LDSB an LDS-scoped barrier, so __syncthreads() stops invalidating the vector cache.
|
||||
// LDSB an LDS-scoped barrier, so the barrier does not invalidate the vector cache.
|
||||
#define O_BTS 262144
|
||||
#define O_GPREV 1048576
|
||||
#define O_LDSB 2097152
|
||||
// O_KNT: a non-temporal hint on the K global load. The KV a decode step reads is 134 MB a layer
|
||||
// streamed once and never re-read, and it walks the whole last level on the way past -- so what the
|
||||
// hint would protect is not this kernel but the GEMMs either side of it, whose activation is small
|
||||
// enough to live in cache if something stops evicting it. V cannot take the hint at all: it is
|
||||
// loaded through `global_load_tr_b128` and that intrinsic has no non-temporal form.
|
||||
//
|
||||
// OFF BY DEFAULT. The hint changes no bytes and costs nothing, and it also gains nothing: on this
|
||||
// part the KV stream is not what evicts the neighbouring GEMMs' activation, so neither this kernel
|
||||
// nor they move when it is set. The bit costs one template parameter and is kept so the option
|
||||
// stays available for a deployment where the cache pressure is different.
|
||||
#define O_KNT 4194304
|
||||
// O_V8: an fp8 cache's V tile staged in LDS as its codes, converted when a fragment is read.
|
||||
//
|
||||
// The f16 tile is 12 KiB a workgroup and a one-wave workgroup has nothing else in LDS, so it is
|
||||
// what caps residency: ten workgroups a WGP, two and a half waves a SIMD, for a leg whose tile
|
||||
// loop is a chain of global latencies. The codes are 6 KiB. At one wave a workgroup the number of
|
||||
// conversions is the same either way -- each V element is read once by the one wave -- and the
|
||||
// conversion is exact, so the fragments, and every byte after them, match the f16 tile's. With more
|
||||
// waves a workgroup each would convert the whole tile, so the launcher sets it at one.
|
||||
// Bit 4194304 is free: a non-temporal hint on the K load gained nothing on the target GPU (the KV
|
||||
// stream does not evict the neighbouring GEMMs' activations).
|
||||
// O_V8: an fp8 cache's V tile staged in LDS as codes (6 KiB instead of 12 KiB of f16), converted
|
||||
// when a fragment is read. For a one-wave workgroup the f16 tile is what caps residency (ten
|
||||
// workgroups per WGP). At one wave the conversion count is unchanged and the conversion is exact,
|
||||
// so results are identical; with more waves each would convert the whole tile, so the launcher
|
||||
// uses it only at one wave.
|
||||
#define O_V8 8388608
|
||||
// O_KRAW: with K read straight from the paged cache (KLDS0, CONTIG), an m-tile's K is loaded in ONE
|
||||
// round -- all HEAD_DIM/16 fragment loads, issued as soon as the row address is known -- and each
|
||||
// fragment is converted from its registers just before its WMMA.
|
||||
//
|
||||
// The prefetch depth (PF) and the scheduling barrier between a group's loads and its WMMAs say
|
||||
// what may overlap, and a compiler is free to honour them literally: LLVM 24 does, and with PF 2 a
|
||||
// tile's K then arrives in HEAD_DIM/32 round trips, one after another, which cost the head_dim-128
|
||||
// drafter leg 16-19% on a bf16 cache. LLVM 22 lifted the loads over the barriers and issued them in
|
||||
// one round. This bit asks for that round explicitly. What is held is the cache's own bytes -- 8 a
|
||||
// fragment from fp8, 16 from bf16 -- not the converted fragment, so a full round costs 2 or 4 x
|
||||
// HEAD_DIM/16 VGPRs; PF = HEAD_DIM/16 would hold every converted fragment at once and cost the
|
||||
// waves a SIMD. The fragments, and every byte after them, are unchanged.
|
||||
// O_KRAW: with K read from the paged cache (KLDS0, CONTIG), issue all HEAD_DIM/16 fragment loads
|
||||
// of an m-tile in one round and convert each fragment just before its WMMA. LLVM 24 honours the PF
|
||||
// groups and scheduling barriers literally, so with PF 2 K arrives in HEAD_DIM/32 serial round
|
||||
// trips (16-19% on the head_dim-128 drafter leg, bf16 cache). Raw cache bytes are held (8 per
|
||||
// fragment for fp8, 16 for bf16), costing 2 or 4 x HEAD_DIM/16 VGPRs; PF = HEAD_DIM/16 would hold
|
||||
// converted fragments and cost occupancy. Results are unchanged.
|
||||
#define O_KRAW 16777216
|
||||
// `__builtin_nontemporal_load` will not take `uint4`/`uint2` -- they are HIP_vector_type class
|
||||
// templates, not native vectors -- so the hinted loads go through these and bit-cast the WHOLE
|
||||
// value back (never a subscript of it, which miscompiles).
|
||||
typedef unsigned r4d_ntu4 __attribute__((ext_vector_type(4)));
|
||||
typedef unsigned r4d_ntu2 __attribute__((ext_vector_type(2)));
|
||||
|
||||
template <int NT, typename T, typename V>
|
||||
__device__ __forceinline__ T r4d_kload(const T* p) {
|
||||
if (!NT) return *p;
|
||||
return __builtin_bit_cast(T, __builtin_nontemporal_load((const V*)p));
|
||||
}
|
||||
|
||||
__host__ __device__ __forceinline__ int r4d_attn_tiles(int ctx, int tile) { return (ctx + tile - 1) / tile; }
|
||||
__host__ __device__ __forceinline__ int r4d_attn_tps(int ctx, int tile, int splits) {
|
||||
int t = r4d_attn_tiles(ctx, tile); return (t + splits - 1) / splits;
|
||||
@@ -99,9 +67,8 @@ __host__ __device__ __forceinline__ int r4d_attn_used(int ctx, int tile, int spl
|
||||
int t = r4d_attn_tiles(ctx, tile), tps = r4d_attn_tps(ctx, tile, splits); return (t + tps - 1) / tps;
|
||||
}
|
||||
|
||||
// WIN turns on a sliding window (a.window positions, ending at each row's causal
|
||||
// limit). It is a TEMPLATE parameter and defaults to 0, so a full-attention geometry
|
||||
// compiles with no bound, no clamp and no extra mask term.
|
||||
// WIN enables a sliding window (a.window positions ending at each row's causal limit). As a
|
||||
// template parameter defaulting to 0, full attention compiles with no window code.
|
||||
template<int NWARPS, int TILE, int HEAD_DIM, int GQA, int BS, int KVP, int OPT,
|
||||
int WIN = 0>
|
||||
__global__ __launch_bounds__(NWARPS * 32)
|
||||
@@ -118,7 +85,6 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
|
||||
constexpr int DOT2 = ((OPT & O_DOT2) && (OPT & O_F16)) ? 1 : 0;
|
||||
constexpr int BTS = (OPT & O_BTS) ? 1 : 0;
|
||||
constexpr int LDSB = (OPT & O_LDSB) ? 1 : 0;
|
||||
constexpr int KNT = (OPT & O_KNT) ? 1 : 0;
|
||||
constexpr int V8 = ((OPT & O_V8) && !KVP) ? 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;
|
||||
@@ -134,27 +100,18 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
|
||||
constexpr int NB = TILE / BS;
|
||||
constexpr int NTR = (TILE / 8) * (HEAD_DIM / (KVP ? 32 : 64));
|
||||
constexpr int VREGS = (NTR + NWARPS - 1) / NWARPS;
|
||||
// A V prefetch costs VREGS x 4 VGPRs and this leg already carries a 128-VGPR accumulator and a
|
||||
// 64-VGPR query. At two uint4 (fp8 KV, TILE 16) it is worth 6-8% at depth; at four (fp8
|
||||
// TILE 32, or bf16 TILE 16, whose V is twice the bytes) it spills and LOSES 10%. So the
|
||||
// geometry decides, not the flag.
|
||||
// THREE is reachable only because the K prefetch needs just two: the three-uint4 form is what
|
||||
// the 48-row shape (q_len 8, gqa 6, so NWARPS 3 over NTR 8) needs, it stays inside 255 VGPRs
|
||||
// with no spill, and it is worth a further 2-15% on top -- most at the depths where the K
|
||||
// stream has the least other work to hide behind. At NWARPS 1 or 2, and for a bf16 cache whose
|
||||
// V is twice the bytes, VREGS is 4 or more and the prefetch stays off.
|
||||
#ifndef R4D_GPREV_VREGS
|
||||
#define R4D_GPREV_VREGS 3
|
||||
#endif
|
||||
constexpr int GPREV = ((OPT & O_GPREV) && VREGS <= R4D_GPREV_VREGS) ? 1 : 0;
|
||||
// A V prefetch costs VREGS x 4 VGPRs on top of a 128-VGPR accumulator and a 64-VGPR query.
|
||||
// Up to three uint4 it fits in 255 VGPRs without spilling (two: +6-8% at depth; three, the
|
||||
// 48-row shape q_len 8 x gqa 6 at NWARPS 3: a further 2-15%). At four or more (NWARPS 1-2, or a
|
||||
// bf16 cache) it spills and loses ~10%, so the geometry gates it, not just the flag.
|
||||
constexpr int GPREV = ((OPT & O_GPREV) && VREGS <= 3) ? 1 : 0;
|
||||
constexpr float PSHIFT = D::SHIFT;
|
||||
constexpr float PGROW = D::GROW;
|
||||
|
||||
__shared__ uint16_t sK[KLDS ? TILE * KSTR : 1];
|
||||
__shared__ uint16_t sV16[V8 ? 1 : HEAD_DIM * VSTR];
|
||||
/* A row of the code tile is 16 keys and 8 of padding: 24 bytes is six dwords, so the sixteen
|
||||
* lanes of a fragment read land on distinct banks, and a lane's eight codes are one aligned
|
||||
* 8-byte load. */
|
||||
/* A code-tile row is 16 keys + 8 padding = 24 bytes (six dwords): the sixteen lanes of a
|
||||
* fragment read hit distinct banks, and a lane's eight codes are one aligned 8-byte load. */
|
||||
constexpr int VSTR8 = TILE + 8;
|
||||
__shared__ uint8_t sV8[V8 ? HEAD_DIM * VSTR8 : 1];
|
||||
|
||||
@@ -165,19 +122,16 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
|
||||
const int ctx = a.seqused_k[seq];
|
||||
if (ctx <= 0) return;
|
||||
|
||||
// Ragged batches (r4d.h, R4DArgs::cu_q): the rows of q and out this sequence owns, and its
|
||||
// own query length. `a.q_len` is the batch maximum when cu_q is set, and it is what the
|
||||
// launcher sized the wave count from, so rows past `qlen` are simply not live.
|
||||
// Ragged batches (r4d.h, R4DArgs::cu_q): this sequence's q/out rows and query length. With
|
||||
// cu_q, a.q_len is the batch maximum that sized the wave count; rows past qlen are not live.
|
||||
const int qoff = r4d_q_off(a.cu_q, seq, a.q_len);
|
||||
const int qlen = r4d_q_len(a.cu_q, seq, a.q_len);
|
||||
if (qlen <= 0) return; // a slot carrying no query rows this step
|
||||
|
||||
const int ntl = r4d_attn_tiles(ctx, TILE);
|
||||
// A sliding-window layer reads only the last `window` positions. The blocks below
|
||||
// that are not merely useless: the engine has freed them and may already have handed
|
||||
// them to another sequence, so reading one is wrong rather than wasteful. The walk
|
||||
// starts at the tile holding the window's first token -- taken at query row 0,
|
||||
// whose window reaches furthest back -- and the splits divide THAT range.
|
||||
// A sliding-window layer must not read below the window: those blocks may already be freed
|
||||
// and reassigned to another sequence. The walk starts at the tile holding row 0's first
|
||||
// window token (row 0 reaches furthest back), and the splits divide that range.
|
||||
const int wlo0 = WIN ? r4d_attn_wlo(ctx, qlen, 0, a.window) : 0;
|
||||
const int tb = WIN ? wlo0 / TILE : 0;
|
||||
const int neff = ntl - tb;
|
||||
@@ -211,9 +165,9 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
|
||||
}
|
||||
}
|
||||
|
||||
// The row's absolute position. Causal masking bounds the key by it; non-causal
|
||||
// masking bounds the key by the sequence and lets the window bound it on BOTH
|
||||
// sides, which is what a block-diffusion drafter's own block needs.
|
||||
// The row's absolute position. Causal masking bounds the key by it; non-causal masking
|
||||
// bounds it by the sequence, with the window applied on both sides (a block-diffusion
|
||||
// drafter's own block).
|
||||
const int pos = ctx - qlen + qrow;
|
||||
const int cz = a.causal_seq ? (int)((const unsigned char*)a.causal_seq)[seq] : a.causal;
|
||||
const int klimit = cz ? pos
|
||||
@@ -287,12 +241,10 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
|
||||
}
|
||||
};
|
||||
|
||||
// A tile's NB entries are read whole, and when a tile spans several blocks the last one can run
|
||||
// past the sequence's last block -- past the end of its row, and on the last row past the end
|
||||
// of the table. Every key is clamped to ctx - 1 before it picks an entry, so no entry past
|
||||
// `lastb` is ever used and clamping the index there changes no value that is. Only a window
|
||||
// that reaches past `lastb` takes the clamped form, so every other tile keeps its one wide
|
||||
// scalar load; at one block a tile no window can reach past it and the test folds away.
|
||||
// A tile's NB entries are read whole, and a multi-block tile can run past the sequence's last
|
||||
// block (on the last row, past the end of the table). Keys are clamped to ctx - 1, so entries
|
||||
// past lastb are never used; only tiles reaching past lastb take the clamped load, and the
|
||||
// rest keep one wide scalar load. With NB == 1 the test folds away.
|
||||
const int lastb = (ctx - 1) / BS;
|
||||
auto load_bt = [&](int t0, int* out) {
|
||||
if (NB > 1 && t0 + NB - 1 > lastb) {
|
||||
@@ -327,13 +279,11 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
|
||||
uint16_t* kd = &sK[key * KSTR];
|
||||
uint32_t w4[4];
|
||||
if (KVP) {
|
||||
const uint4 r = r4d_kload<KNT, uint4, r4d_ntu4>(
|
||||
(const uint4*)((const uint16_t*)a.kv + o + ch * 8));
|
||||
const uint4 r = *(const uint4*)((const uint16_t*)a.kv + o + ch * 8);
|
||||
w4[0] = D::from_bf16w(r.x); w4[1] = D::from_bf16w(r.y);
|
||||
w4[2] = D::from_bf16w(r.z); w4[3] = D::from_bf16w(r.w);
|
||||
} else {
|
||||
fp8x8_to_16x4w<D>(r4d_kload<KNT, uint2, r4d_ntu2>(
|
||||
(const uint2*)((const uint8_t*)a.kv + o + ch * 8)), w4);
|
||||
fp8x8_to_16x4w<D>(*(const uint2*)((const uint8_t*)a.kv + o + ch * 8), w4);
|
||||
}
|
||||
*(uint2*)(kd + ch * 8) = make_uint2(w4[0], w4[1]);
|
||||
*(uint2*)(kd + ch * 8 + 4) = make_uint2(w4[2], w4[3]);
|
||||
@@ -355,7 +305,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
|
||||
+ (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * (2 * HEAD_DIM))
|
||||
* (KVP ? 2 : 1);
|
||||
}
|
||||
// A fragment's K bytes: 8 elements at 1 byte (fp8) or 2 (bf16), as the branches below read.
|
||||
// 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];
|
||||
if constexpr (KRAW) {
|
||||
@@ -373,8 +323,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
|
||||
if (KLDS) {
|
||||
const uint16_t* kp = &sK[(mt * 16 + c) * KSTR + 16 * t];
|
||||
if (CTG) {
|
||||
const uint4 u = r4d_kload<KNT, uint4, r4d_ntu4>(
|
||||
(const uint4*)(kp + 8 * h));
|
||||
const uint4 u = *(const uint4*)(kp + 8 * h);
|
||||
kb[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w));
|
||||
} else {
|
||||
kb[j] = D::mk(*(const uint2*)(kp + 4 * h), *(const uint2*)(kp + 8 + 4 * h));
|
||||
@@ -395,7 +344,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
|
||||
} else {
|
||||
const uint8_t* kp = grow + 16 * t;
|
||||
uint32_t w4[4];
|
||||
// CONTIG makes this ONE 8-byte load where the split map needs two 4-byte.
|
||||
// CONTIG: one 8-byte load; the split map needs two 4-byte loads.
|
||||
uint2 raw;
|
||||
if constexpr (KRAW && KVP == 0) raw = kraw[t];
|
||||
else raw = CTG ? *(const uint2*)(kp + 8 * h)
|
||||
@@ -528,29 +477,17 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
|
||||
}
|
||||
}
|
||||
|
||||
// Vectorised merge, and the one the h256 launcher takes whenever the split count fits a wave.
|
||||
// The arithmetic is identical to r4d_attn_splitkv_combine_kernel below, bit for bit; what changes
|
||||
// is the thread map. One WAVE owns one output row and each lane owns EIGHT of that row's 256
|
||||
// dims, so a segment is one 16-byte load per lane instead of eight 2-byte loads -- the same 512
|
||||
// bytes per instruction across the wave, at an eighth of the instructions -- and one block
|
||||
// carries JPB rows. There is no barrier and no LDS anywhere in it, which is also what lets the
|
||||
// rows sharing a block have different contexts, and so different segment counts.
|
||||
// ---- THE OUTPUT GATE AND THE fp8 QUANTISER AS THE MERGE'S EPILOGUE (attn_paged_gate_quant) ----
|
||||
// ---- Output gate and fp8 quantiser as the merge's epilogue (attn_paged_gate_quant) ----
|
||||
//
|
||||
// A gated attention's output goes from here straight into `gate_quant_fp8`: bf16(sigmoid(gate)),
|
||||
// times the merged row, rounded to bf16, and E4M3 codes with one scale per 128 columns taken over
|
||||
// that product. A merge row is one (token, head) pair and 128 columns are one scale group, so the
|
||||
// row that is merged here is exactly the rows the quantiser would read back -- and it is still in
|
||||
// registers. The `_gq` forms below finish it in place, with no dispatch between the two.
|
||||
// A gated attention's merged row feeds gate_quant_fp8: bf16(sigmoid(gate)) times the row, rounded
|
||||
// to bf16, then E4M3 codes with one scale per 128 columns. A merge row is one (token, head) pair
|
||||
// and a scale group is 128 columns, so the `_gq` forms finish the row in registers instead of in a
|
||||
// second dispatch.
|
||||
//
|
||||
// BYTE-FOR-BYTE `gate_quant_fp8`'s arithmetic, which r4d_fused_quant_fp8.hip states: the gate
|
||||
// rounded to bf16 before the multiply, the product rounded, the group's absmax (a max, so the
|
||||
// order it is taken in cannot matter), scale = amax / 448 or 1 at zero, codes over product / scale
|
||||
// clamped to +-448 -- and the bf16 product is what lands in `out`, as the in-place pair leaves it.
|
||||
// A padded slot merges to zeros and then takes the same epilogue, as the pair would give it.
|
||||
//
|
||||
// GQ == 2 IS THE SAME EPILOGUE AT INT8 CODES, for an int8 out projection: scale amax / 127 and the
|
||||
// value over it rounded to nearest-even (r4d_q8.h) -- gate_quant_fp8's int8 form, byte for byte.
|
||||
// Byte-identical to gate_quant_fp8 (r4d_fused_quant_fp8.hip): gate rounded to bf16 before the
|
||||
// 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).
|
||||
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
|
||||
@@ -567,6 +504,10 @@ __device__ __forceinline__ uint16_t r4d_gq_gate(uint16_t gb, uint16_t xb) {
|
||||
}
|
||||
__device__ __forceinline__ float r4d_gq_clamp(float v) { return fminf(fmaxf(v, -448.0f), 448.0f); }
|
||||
|
||||
// Vectorised merge, used by the h256 launcher whenever the split count fits a wave. Bit-identical
|
||||
// to splitkv_combine_body below; only the thread map differs. One wave owns one output row and
|
||||
// each lane HEAD_DIM/32 dims, so a segment is one 16-byte load per lane; a block carries JPB rows.
|
||||
// No barrier and no LDS, so rows in one block may have different contexts and segment counts.
|
||||
template<int HEAD_DIM, int CHAINS, int PF16, int JPB, int WIN, int GQ>
|
||||
__device__ __forceinline__
|
||||
void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DGateQuant& gq)
|
||||
@@ -580,9 +521,8 @@ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DG
|
||||
const int ctx = a.seqused_k[seq];
|
||||
uint16_t* outp = (uint16_t*)a.out + (size_t)job * HEAD_DIM + lane * DPL;
|
||||
|
||||
/* The row's bf16 values, then either the plain store or the gated, quantised one. A lane's
|
||||
* DPL columns sit inside one 128-column group, and the group is the 128 / DPL lanes around it,
|
||||
* so its absmax is a butterfly over those lanes and nothing wider. */
|
||||
/* Plain store, or gated + quantised. A lane's DPL columns lie in one 128-column group of
|
||||
* 128 / DPL lanes, so the group absmax is a butterfly over those lanes only. */
|
||||
auto finish = [&](const uint16_t (&ob)[DPL]) {
|
||||
if constexpr (!GQ) {
|
||||
union { uint4 u4; uint2 u2; uint16_t w[DPL]; } o_;
|
||||
@@ -643,9 +583,9 @@ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DG
|
||||
else { const float* so = (const float*)a.scratch;
|
||||
sm = so + nrow * HEAD_DIM; sl = sm + nrow; }
|
||||
|
||||
// max is exact in any order, and taken sequentially it is wave-uniform, so this is a scalar
|
||||
// walk. The sum keeps the LDS tree association: the stride-32 pre-accumulation is that tree
|
||||
// off=32 round, and the xor butterfly 16..1 is the rest of it, leaving the value in every lane.
|
||||
// max is order-independent and wave-uniform, so it is a scalar walk. The sum reproduces the
|
||||
// LDS tree's association (stride-32 pre-accumulation, then xor butterfly 16..1) so results
|
||||
// match the non-vector merge bit for bit.
|
||||
float gmax = -INFINITY;
|
||||
for (int s = 0; s < u; ++s) gmax = fmaxf(gmax, sm[base + s]);
|
||||
float tot = 0.0f;
|
||||
@@ -671,7 +611,7 @@ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DG
|
||||
int s = 0;
|
||||
if (PF16) {
|
||||
const uint16_t* op = (const uint16_t*)a.scratch + base * HEAD_DIM + lane * DPL;
|
||||
// One aligned access a lane a segment: 16 bytes at head_dim 256, 8 at 128.
|
||||
// One aligned access per lane per segment: 16 bytes at head_dim 256, 8 at 128.
|
||||
union { uint4 u4; uint2 u2; __fp16 h[DPL]; } r;
|
||||
auto rd = [&](int sx) {
|
||||
if (DPL == 8) r.u4 = *(const uint4*)(op + (size_t)sx * HEAD_DIM);
|
||||
@@ -719,8 +659,7 @@ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DG
|
||||
float av = 0.0f;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < CHAINS; ++i) av += ch[i][j];
|
||||
// (av * vd) / tot, in that order: folding vd/tot into one reciprocal first is a different
|
||||
// rounding and shows up as a whole bf16 ULP on the merged output.
|
||||
// (av * vd) / tot in this order; folding vd/tot first rounds differently (one bf16 ULP).
|
||||
ob[j] = f32_to_bf16(tot > 0.0f ? av * vd / tot : 0.0f);
|
||||
}
|
||||
finish(ob);
|
||||
@@ -741,9 +680,9 @@ void r4d_attn_splitkv_combine_vec_gq_kernel(const R4DArgs a, int splits, int til
|
||||
splitkv_combine_vec_body<HEAD_DIM, CHAINS, PF16, JPB, WIN, GQ>(a, splits, tile, gq);
|
||||
}
|
||||
|
||||
// Merge. PF16=1 reads normalised f16 partials and folds l into the weight; PF16=0 is the plain
|
||||
// path (unnormalised f32 partials, l summed separately). Both walk the segments in FIXED INDEX
|
||||
// ORDER so a request's rounding never depends on CTA scheduling.
|
||||
// Merge. PF16=1 reads normalised f16 partials and folds l into the weight; PF16=0 reads
|
||||
// unnormalised f32 partials with l summed separately. Both walk segments in fixed index order so
|
||||
// rounding never depends on workgroup scheduling.
|
||||
template<int HEAD_DIM, int CHAINS, int PF16, int WIN, int GQ>
|
||||
__device__ __forceinline__
|
||||
void splitkv_combine_body(const R4DArgs& a, int splits, int tile, const R4DGateQuant& gq)
|
||||
@@ -755,9 +694,9 @@ void splitkv_combine_body(const R4DArgs& a, int splits, int tile, const R4DGateQ
|
||||
const int seq = r4d_q_seq(a.cu_q, a.num_seqs, a.q_len, tok);
|
||||
const int ctx = a.seqused_k[seq];
|
||||
|
||||
/* One thread a column, so a 128-column scale group is four waves: each takes its own absmax
|
||||
* and the group's is the max over its four, through `red` -- whose last read, the total's,
|
||||
* is behind a barrier before the merge loop, and which a padded slot never used. */
|
||||
/* One thread per column, so a 128-column scale group is four waves, combined through `red`.
|
||||
* Reusing `red` is safe: its last read (the total) is behind a barrier before the merge loop,
|
||||
* and a padded slot never used it. */
|
||||
auto finish = [&](uint16_t ob) {
|
||||
uint16_t* op = (uint16_t*)a.out + (size_t)job * HEAD_DIM + d;
|
||||
if constexpr (!GQ) {
|
||||
@@ -787,12 +726,11 @@ void splitkv_combine_body(const R4DArgs& a, int splits, int tile, const R4DGateQ
|
||||
}
|
||||
};
|
||||
|
||||
// A padded batch slot has no context at all. Its output is discarded by the caller, but the
|
||||
// segment count below would divide by zero, so leave zeros and stop. `ctx` is block-uniform,
|
||||
// so every thread takes this branch together and the barriers further down stay matched.
|
||||
// A padded slot (ctx 0) would divide by zero below; write zeros and stop. ctx is
|
||||
// block-uniform, so the barriers below stay matched.
|
||||
if (ctx <= 0) { finish(0); return; }
|
||||
// Segment count, derived the same way the decode kernel derived it -- including the
|
||||
// window's tile floor, or the merge would read partials no segment ever wrote.
|
||||
// Segment count, derived exactly as in the decode kernel, including the window's tile floor;
|
||||
// otherwise the merge would read partials no segment wrote.
|
||||
const int nef = r4d_attn_tiles(ctx, tile)
|
||||
- (WIN ? r4d_attn_wlo(ctx, r4d_q_len(a.cu_q, seq, a.q_len), 0, a.window) / tile : 0);
|
||||
const int tp_ = (nef + splits - 1) / splits;
|
||||
@@ -874,3 +812,94 @@ void r4d_attn_splitkv_combine_gq_kernel(const R4DArgs a, int splits, int tile,
|
||||
{
|
||||
splitkv_combine_body<HEAD_DIM, CHAINS, PF16, WIN, GQ>(a, splits, tile, gq);
|
||||
}
|
||||
|
||||
// ---- host helpers shared by the paged decode dispatches -----------------------------------------
|
||||
|
||||
// Split law of the full-attention legs (h256/gqa6 and the gqa8 family): as many workgroups as fit
|
||||
// under 128 (grid = splits * kv_heads * num_seqs), at least two tiles per segment. It does not
|
||||
// depend on gqa or head_dim.
|
||||
//
|
||||
// floor(128 / units), not a power of two: a power of two leaves 96-112 workgroups at 3, 5, 6 and
|
||||
// 7 requests, and floor is 2-20% faster there. Staying under a multiple of 64 matters (at five
|
||||
// requests, 13 splits = 130 workgroups is three rounds of 64 and slower than 12).
|
||||
//
|
||||
// Fewer splits mainly save partial-buffer traffic (seqs x q_len x q_heads x splits rows of
|
||||
// head_dim f16, written once and read once): at eight requests 12.8 MB at splits 32 vs 3.2 MB at
|
||||
// 8, 19% of a 16K step's KV but 1.2% at 128K. The effect fades with depth, never enough to need a
|
||||
// context term.
|
||||
static inline int r4d_decode_splits(const R4DArgs* a, int tile) {
|
||||
if (a->splits > 0) return a->splits;
|
||||
const int tiles = (a->max_ctx + tile - 1) / tile;
|
||||
const int units = std::max(1, a->kv_heads * a->num_seqs);
|
||||
int s = 128 / units;
|
||||
const int cap = tiles / 2;
|
||||
if (s > cap) s = cap;
|
||||
if (s > tiles) s = tiles;
|
||||
if (s < 1) s = 1;
|
||||
return s;
|
||||
}
|
||||
|
||||
// Split law of the windowed legs (the DFlash2 drafter at h128/gqa4, Gemma 4 at h256/gqa2): target
|
||||
// 192 workgroups, round down to a power of two (min 16), keep at least two tiles per segment, then
|
||||
// step up off splits * units == 256, a slow spot for these geometries. The tile count comes from
|
||||
// the window when one is set, since that is the span the kernel walks.
|
||||
static inline int r4d_decode_splits_win(const R4DArgs* a, int tile) {
|
||||
if (a->splits > 0) return a->splits;
|
||||
const int span = (a->window > 0 && a->window + a->q_len < a->max_ctx)
|
||||
? a->window + a->q_len : a->max_ctx;
|
||||
const int tiles = (span + tile - 1) / tile;
|
||||
const int units = std::max(1, a->kv_heads * a->num_seqs);
|
||||
const int raw = 192 / units;
|
||||
int s = 128;
|
||||
while (s > 16 && s > raw) s >>= 1;
|
||||
const int cap = tiles / 2;
|
||||
while (s > 16 && s > cap) s >>= 1;
|
||||
if (s > tiles) s = tiles;
|
||||
if (s < 1) s = 1;
|
||||
if (s * units == 256 && s * 2 <= tiles) s <<= 1;
|
||||
return s;
|
||||
}
|
||||
|
||||
// Bytes of split-KV partials one decode launch needs, the same for both cache dtypes: f16 O/l plus
|
||||
// m and l under O_PF16, else f32 O plus m and l.
|
||||
static inline long r4d_decode_scratch(const R4DArgs* a, int splits, int opt) {
|
||||
const long rows = (long)r4d_q_total(*a) * a->q_heads;
|
||||
return (opt & O_PF16) ? rows * splits * (long)(a->head_dim * 2 + 8)
|
||||
: rows * splits * (long)(a->head_dim + 2) * 4L;
|
||||
}
|
||||
|
||||
// The windowed legs' decode (WIN = 1): the attention kernel at the gqa-aligned height, then the
|
||||
// merge, one wave per row when there are enough rows and the segment count fits a wave, else the
|
||||
// LDS-tree form; both give identical bytes. Tile 16, paged block 16, at most 64 query rows, and
|
||||
// the full-attention legs' merge constants (two rows a block, the wave form from 256 rows).
|
||||
// Returns 0, a negative code for a shape it does not serve, or -100 - hipError_t.
|
||||
template <int HEAD_DIM, int GQA, int OPT, int KVP>
|
||||
static int r4d_decode_launch_win(const R4DArgs* a, hipStream_t s) {
|
||||
constexpr int TILE = 16, BS = 16, JPB = 2, VECMIN = 256, PF16 = (OPT & O_PF16) ? 1 : 0;
|
||||
if (a->head_dim != HEAD_DIM || a->block_size != BS) return -1;
|
||||
if (a->q_heads / a->kv_heads != GQA) return -2;
|
||||
const int rows = a->q_len * GQA;
|
||||
if (rows > 64) return -4;
|
||||
const int nw = (rows + 15) / 16;
|
||||
const int splits = r4d_decode_splits_win(a, TILE);
|
||||
#define R4D_WIN_LAUNCH(NW) \
|
||||
hipLaunchKernelGGL((r4d_attn_decode_kernel<NW, TILE, HEAD_DIM, GQA, BS, KVP, OPT, 1>), \
|
||||
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits)
|
||||
if (nw == 1) R4D_WIN_LAUNCH(1);
|
||||
else if (nw == 2) R4D_WIN_LAUNCH(2);
|
||||
else if (nw == 3) R4D_WIN_LAUNCH(3);
|
||||
else R4D_WIN_LAUNCH(4);
|
||||
#undef R4D_WIN_LAUNCH
|
||||
hipError_t e = hipGetLastError();
|
||||
if (e != hipSuccess) return -100 - (int)e;
|
||||
|
||||
const int jobs3 = r4d_q_total(*a) * a->q_heads;
|
||||
if (splits <= 64 && jobs3 >= VECMIN)
|
||||
hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel<HEAD_DIM, 4, PF16, JPB, 1>),
|
||||
dim3((jobs3 + JPB - 1) / JPB), dim3(32 * JPB), 0, s, *a, splits, TILE);
|
||||
else
|
||||
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<HEAD_DIM, 4, PF16, 1>), dim3(jobs3),
|
||||
dim3(HEAD_DIM), splits * sizeof(float), s, *a, splits, TILE);
|
||||
e = hipGetLastError();
|
||||
return e == hipSuccess ? 0 : -100 - (int)e;
|
||||
}
|
||||
@@ -2,25 +2,26 @@
|
||||
// with an optional two-sided window |i - j| < window. bf16 in and out, f16 operands, f32
|
||||
// accumulate. Head widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair is a row.
|
||||
//
|
||||
// The core is the vision kernel's (r4d_attn_vit_h72_bf16.hip): S^T = K.Q^T, so the wave32
|
||||
// column-distributed accumulator gives each lane one query row, the softmax state is lane-private,
|
||||
// and the C fragment of S^T is already the B fragment the PV matmul wants -- P never goes through
|
||||
// LDS. What this file adds:
|
||||
// Core from the vision kernel (r4d_attn_vit_h72_bf16.hip): S^T = K.Q^T, so the wave32
|
||||
// column-distributed accumulator gives each lane one query row, softmax state is lane-private, and
|
||||
// the C fragment of S^T is already the B fragment of P.V, so P never goes through LDS. Additions:
|
||||
//
|
||||
// GQA IN THE WORKGROUP. A workgroup owns one KV head and every query head that reads it, so a
|
||||
// staged K/V tile is consumed by GQA times as many WMMAs as one head would give it. The grid is
|
||||
// (query blocks, kv heads, segments).
|
||||
// GQA in the workgroup: a workgroup owns one KV head and all query heads reading it, so each
|
||||
// staged K/V tile feeds GQA times as many WMMAs. Grid is (query blocks, kv heads, segments).
|
||||
//
|
||||
// A WINDOW. A workgroup's key range is cut to the keys any of its queries can see, and the
|
||||
// per-element test runs only on tiles that straddle a window edge or the segment's end; an
|
||||
// interior tile pays nothing. Sliding layers at |i - j| <= 512 then cost O(T * window), not
|
||||
// O(T^2).
|
||||
// Window: the key range is cut to keys any of the workgroup's queries can see, and the
|
||||
// per-element mask runs only on tiles straddling a window edge or the segment end. Sliding
|
||||
// layers cost O(T * window), not O(T^2).
|
||||
//
|
||||
// A HEAD SPLIT ACROSS WAVES (DSPLIT). One lane's output is head_dim / 2 floats, so head_dim 512
|
||||
// would need 256 accumulator VGPRs before the query fragments -- more than a lane has. At
|
||||
// DSPLIT 2 two waves own the same 16 queries and half the head each: each contracts its half
|
||||
// of q.k, the two partial scores are summed through LDS, both run the same softmax (a + b ==
|
||||
// b + a, so the two copies agree to the bit), and each accumulates its half of P.V.
|
||||
// Blocks: `block` cuts a segment into blocks of that many rows from its start, each attending
|
||||
// only within itself (a chunked audio encoder's windows). The key range is cut to the blocks
|
||||
// the workgroup's queries are in, and the per-element test runs only where a workgroup or a
|
||||
// tile straddles a block edge. `cu_div` reads cu_seqlens in units that many rows apart.
|
||||
//
|
||||
// Head split across waves (DSPLIT): a lane's output is head_dim / 2 floats, so head_dim 512
|
||||
// would need 256 accumulator VGPRs. At DSPLIT 2 two waves share 16 queries and each owns half
|
||||
// the head: partial q.k scores are summed through LDS, both run the same softmax (a + b == b + a,
|
||||
// so both copies agree bit for bit), and each accumulates its half of P.V.
|
||||
//
|
||||
// Every operand is read at its own token pitch, so q, k and v may be column slices of one fused
|
||||
// projection; pitches and head offsets must be multiples of 8 elements for the 16-byte fetches.
|
||||
@@ -35,8 +36,8 @@ template<int HD, int GQA, int NQB, int DSPLIT, int TILE>
|
||||
__global__ __launch_bounds__(NQB * GQA * DSPLIT * 32)
|
||||
void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
|
||||
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
|
||||
const int* __restrict__ cu, float scale, int window,
|
||||
int q_ld, int k_ld, int v_ld, int o_ld)
|
||||
const int* __restrict__ cu, float scale, int window, int block,
|
||||
int cdiv, int q_ld, int k_ld, int v_ld, int o_ld)
|
||||
{
|
||||
typedef DT16<1> D;
|
||||
typedef D::frag frag16;
|
||||
@@ -73,7 +74,7 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
|
||||
const int kvh = blockIdx.y, seq = blockIdx.z;
|
||||
const int hq = kvh * GQA + g;
|
||||
|
||||
const int s0 = cu[seq], slen = cu[seq + 1] - s0;
|
||||
const int s0 = cu[seq] / cdiv, slen = cu[seq + 1] / cdiv - s0;
|
||||
const int q0 = blockIdx.x * BQ;
|
||||
if (slen <= 0 || q0 >= slen) return;
|
||||
const int qlast = min(q0 + BQ, slen) - 1;
|
||||
@@ -84,6 +85,13 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
|
||||
kb = max(0, q0 - (window - 1));
|
||||
ke = min(slen, qlast + window);
|
||||
}
|
||||
const bool blocks = block > 0;
|
||||
if (blocks) {
|
||||
kb = max(kb, q0 / block * block);
|
||||
ke = min(ke, (qlast / block + 1) * block);
|
||||
}
|
||||
// A workgroup whose queries are all in one block masks only the tiles crossing its edges.
|
||||
const bool q_straddle = blocks && q0 / block != qlast / block;
|
||||
|
||||
const float mul = scale * 1.44269504089f;
|
||||
const int qpos = q0 + qbi * 16 + c;
|
||||
@@ -117,11 +125,13 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
|
||||
const int ntiles = (ke - kb + TILE - 1) / TILE;
|
||||
for (int ti = 0; ti < ntiles; ++ti) {
|
||||
const int k0 = kb + ti * TILE;
|
||||
// Whether any (query, key) pair of this tile is outside the window or past the keys:
|
||||
// uniform over the workgroup, so the interior tiles skip the test entirely.
|
||||
// Whether any (query, key) pair of this tile is outside the window or past the keys.
|
||||
// Workgroup-uniform, so interior tiles skip the test.
|
||||
const bool mask = (k0 + TILE > ke) ||
|
||||
(window > 0 && (k0 < qlast - (window - 1) ||
|
||||
k0 + TILE - 1 > q0 + (window - 1)));
|
||||
k0 + TILE - 1 > q0 + (window - 1))) ||
|
||||
(blocks && (q_straddle || k0 / block != (k0 + TILE - 1) / block ||
|
||||
k0 / block != q0 / block));
|
||||
|
||||
uint4 kr[KP], vr[VP];
|
||||
#pragma unroll
|
||||
@@ -133,8 +143,8 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
|
||||
kr[p] = *(const uint4*)(kbase + (long)(s0 + kk) * k_ld + gg * 8);
|
||||
}
|
||||
}
|
||||
// V transposed on the way in: the eight lanes of a group name eight key rows at the same
|
||||
// eight dims, and global_load_tr_b128 hands lane j dim d0+j across all eight.
|
||||
// V transposed on load: a group's eight lanes name eight key rows at the same eight dims,
|
||||
// and global_load_tr_b128 gives lane j dim d0+j across all eight.
|
||||
#pragma unroll
|
||||
for (int r = 0; r < VP; ++r) {
|
||||
const int u = lgi + r * LGRP;
|
||||
@@ -213,13 +223,14 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int key = kq + e;
|
||||
const int d = qpos - key;
|
||||
const bool ok = key < ke && (window <= 0 || (d < window && -d < window));
|
||||
const bool ok = key < ke && (window <= 0 || (d < window && -d < window)) &&
|
||||
(!blocks || key / block == qpos / block);
|
||||
sc[e] = ok ? sc[e] : -INFINITY;
|
||||
}
|
||||
}
|
||||
|
||||
// The softmax against a reference max, rescaled only when the row max outgrows what
|
||||
// the f16 P can hold (r4d_dt16.h).
|
||||
// Softmax against a reference max, rescaled only when the row max outgrows the f16
|
||||
// P range (r4d_dt16.h).
|
||||
float smax = sc[0];
|
||||
#pragma unroll
|
||||
for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]);
|
||||
@@ -240,7 +251,7 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e += 2)
|
||||
pw[e >> 1] = D::pk(ex2(sc[e] + soff), ex2(sc[e + 1] + soff));
|
||||
// The row sum off the packed P, so the denominator is the values P.V used.
|
||||
// Row sum from the packed P, so the denominator matches the values P.V used.
|
||||
const v2hf one = {(__fp16)1.0f, (__fp16)1.0f};
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 4; ++e)
|
||||
@@ -290,46 +301,47 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
|
||||
template<int HD, int GQA, int NQB, int DSPLIT, int TILE>
|
||||
static int r4d_attn_dense_launch(const void* q, const void* k, const void* v, void* o,
|
||||
const void* cu, int num_seqs, int max_seqlen, int n_head_kv,
|
||||
float scale, int window, int q_ld, int k_ld, int v_ld, int o_ld,
|
||||
hipStream_t s)
|
||||
float scale, int window, int block, int cdiv, int q_ld, int k_ld,
|
||||
int v_ld, int o_ld, hipStream_t s)
|
||||
{
|
||||
constexpr int BQ = NQB * 16;
|
||||
dim3 grid((max_seqlen + BQ - 1) / BQ, n_head_kv, num_seqs);
|
||||
hipLaunchKernelGGL((r4d_attn_dense_kernel<HD, GQA, NQB, DSPLIT, TILE>), grid,
|
||||
dim3(NQB * GQA * DSPLIT * 32), 0, s, (const uint16_t*)q, (const uint16_t*)k,
|
||||
(const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, q_ld,
|
||||
k_ld, v_ld, o_ld);
|
||||
(const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, block,
|
||||
cdiv, q_ld, k_ld, v_ld, o_ld);
|
||||
const hipError_t e = hipGetLastError();
|
||||
return e == hipSuccess ? 0 : -100 - (int)e;
|
||||
}
|
||||
|
||||
// q, o: [tokens, n_head * head_dim]; k, v: [tokens, n_head_kv * head_dim], each at its own token
|
||||
// pitch in elements. cu_seqlens is [num_seqs + 1] int32 on the device; max_seqlen is a host-side
|
||||
// bound on the segment lengths and sizes the grid. window 0 is the whole segment.
|
||||
// bound on the segment lengths, in rows, and sizes the grid. window 0 is the whole segment, block
|
||||
// 0 no blocks; cu_seqlens counts in units cdiv rows apart.
|
||||
extern "C" int r4d_attn_dense_bf16(const void* q, const void* k, const void* v, void* o,
|
||||
const void* cu_seqlens, int num_seqs, int max_seqlen,
|
||||
int n_head, int n_head_kv, int head_dim, float scale,
|
||||
int window, int q_ld, int k_ld, int v_ld, int o_ld,
|
||||
void* stream)
|
||||
int window, int block, int cdiv, int q_ld, int k_ld, int v_ld,
|
||||
int o_ld, void* stream)
|
||||
{
|
||||
if (n_head <= 0 || n_head_kv <= 0 || n_head % n_head_kv) return -2;
|
||||
if ((q_ld | k_ld | v_ld | o_ld) & 7) return -3;
|
||||
if (window < 0) return -4;
|
||||
if (window < 0 || block < 0 || cdiv <= 0) return -4;
|
||||
if (num_seqs <= 0 || max_seqlen <= 0) return 0;
|
||||
const int gqa = n_head / n_head_kv;
|
||||
hipStream_t s = (hipStream_t)stream;
|
||||
if (head_dim == 64 && gqa == 1)
|
||||
return r4d_attn_dense_launch<64, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen,
|
||||
n_head_kv, scale, window, q_ld, k_ld, v_ld,
|
||||
o_ld, s);
|
||||
n_head_kv, scale, window, block, cdiv, q_ld,
|
||||
k_ld, v_ld, o_ld, s);
|
||||
if (head_dim == 256 && gqa == 2)
|
||||
return r4d_attn_dense_launch<256, 2, 8, 1, 32>(q, k, v, o, cu_seqlens, num_seqs,
|
||||
max_seqlen, n_head_kv, scale, window, q_ld,
|
||||
k_ld, v_ld, o_ld, s);
|
||||
max_seqlen, n_head_kv, scale, window, block,
|
||||
cdiv, q_ld, k_ld, v_ld, o_ld, s);
|
||||
if (head_dim == 512 && gqa == 4)
|
||||
return r4d_attn_dense_launch<512, 4, 2, 2, 16>(q, k, v, o, cu_seqlens, num_seqs,
|
||||
max_seqlen, n_head_kv, scale, window, q_ld,
|
||||
k_ld, v_ld, o_ld, s);
|
||||
max_seqlen, n_head_kv, scale, window, block,
|
||||
cdiv, q_ld, k_ld, v_ld, o_ld, s);
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -351,34 +363,31 @@ extern "C" int r4d_rad_attn_dense(const RadArgs* a, RadStream s) {
|
||||
const long long gqa = r4d_geti_or(a, "gqa", 1);
|
||||
if (head_dim <= 0 || gqa <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
/* [tokens, heads * head_dim] (or [tokens, heads, head_dim]) at the operand's own row pitch. */
|
||||
auto rows = [&](const RadTensor* t, long long* n_tok, long long* n_head, long long* ld) {
|
||||
long long width = 1;
|
||||
for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i];
|
||||
if (t->rank < 2 || width % head_dim) return false;
|
||||
*n_head = width / head_dim;
|
||||
*ld = r4d_rows_pitch(t, width, n_tok);
|
||||
return *ld >= 0;
|
||||
};
|
||||
long long total = 0, nh = 0, q_ld = 0;
|
||||
long long tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0, to = 0, ho = 0, o_ld = 0;
|
||||
if (!rows(q, &total, &nh, &q_ld) || !rows(k, &tk, &hk, &k_ld) ||
|
||||
!rows(v, &tv, &hv, &v_ld) || !rows(o, &to, &ho, &o_ld))
|
||||
if (!r4d_head_rows(q, head_dim, &total, &nh, &q_ld) ||
|
||||
!r4d_head_rows(k, head_dim, &tk, &hk, &k_ld) ||
|
||||
!r4d_head_rows(v, head_dim, &tv, &hv, &v_ld) ||
|
||||
!r4d_head_rows(o, head_dim, &to, &ho, &o_ld))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
if (hk != hv || ho != nh || hk * gqa != nh) return R4D_NO(RAD_E_SHAPE);
|
||||
if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE);
|
||||
if (cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
const int num_seqs = (int)(cu->shape[0] - 1);
|
||||
|
||||
/* max_seqlen sizes the grid and is a bound, not a length: the kernel reads the device-side
|
||||
* cu_seqlens. Absent, the total token count is a valid bound. */
|
||||
/* max_seqlen is a grid-sizing bound (the kernel reads device-side cu_seqlens); defaults to
|
||||
* the total token count. */
|
||||
long long msl = r4d_geti_or(a, "max_seqlen", 0);
|
||||
if (msl <= 0 || msl > total) msl = total;
|
||||
const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)head_dim));
|
||||
const long long window = r4d_geti_or(a, "window", 0);
|
||||
const long long block = r4d_geti_or(a, "block", 0);
|
||||
const long long cdiv = r4d_geti_or(a, "cu_div", 1);
|
||||
|
||||
const int e = r4d_attn_dense_bf16(q->data, k->data, v->data, o->data, cu->data, num_seqs,
|
||||
(int)msl, (int)nh, (int)hk, (int)head_dim, scale,
|
||||
(int)window, (int)q_ld, (int)k_ld, (int)v_ld, (int)o_ld, s);
|
||||
if (e == -1) return R4D_NO(RAD_E_SHAPE);
|
||||
return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
|
||||
(int)window, (int)block, (int)cdiv, (int)q_ld, (int)k_ld,
|
||||
(int)v_ld, (int)o_ld, s);
|
||||
if (e == 0) return RAD_OK;
|
||||
return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
|
||||
}
|
||||
+85
-92
@@ -1,33 +1,27 @@
|
||||
// R4D attention over a paged prefix and the pass's own rows (attn_prefix_self), and the causal
|
||||
// dense attention a text encoder's prompt pass needs (attn_dense, causal 1, head_dim 128).
|
||||
//
|
||||
// THE KERNEL IS THE DENSE ONE (r4d_attn_dense_bf16.hip) WITH A SECOND KEY SOURCE. S^T = K.Q^T, so a
|
||||
// lane owns one query row and its softmax state, the C fragment of S^T is the B fragment the P.V
|
||||
// matmul wants, and P never goes through LDS. A workgroup owns one KV head and every query head
|
||||
// that reads it. What is new:
|
||||
// The dense kernel (r4d_attn_dense_bf16.hip) with a second key source. S^T = K.Q^T, so a lane
|
||||
// owns one query row and its softmax state, the C fragment of S^T is the B fragment of P.V, and P
|
||||
// never goes through LDS. A workgroup owns one KV head and every query head reading it.
|
||||
//
|
||||
// THE PREFIX. A sequence's first `used[s]` keys are in the paged cache -- [blocks, kv_heads, 16,
|
||||
// 2 * HD], K then V in a slot -- and its own rows' keys are dense, beside the queries. The key
|
||||
// loop walks the prefix tiles first and then the own tiles; a tile is one source or the other,
|
||||
// and its rows are fetched through that source's address rule. Every prefix key is visible.
|
||||
// Prefix: a sequence's first `used[s]` keys are in the paged cache ([blocks, kv_heads, 16,
|
||||
// 2 * HD], K then V per slot); its own rows' keys are dense beside the queries. Prefix tiles are
|
||||
// walked first, then own tiles; each tile has one source. Every prefix key is visible.
|
||||
//
|
||||
// CAUSAL OWN KEYS. With `causal` a query sees its own rows up to itself: a text segment of a
|
||||
// conditioning sequence, and the text encoder's prompt. A tile wholly below every query of the
|
||||
// workgroup pays no test.
|
||||
// Causal own keys: with `causal` a query sees its own rows up to itself (a conditioning
|
||||
// sequence's text segment, a text encoder's prompt). Tiles wholly below every query skip the mask.
|
||||
//
|
||||
// bf16 operands (DT16<0>): a diffusion transformer's values carry outliers an f16 operand could
|
||||
// overflow, and the reference takes P to bf16 for its P.V product too (rounded there, truncated
|
||||
// here -- see the softmax).
|
||||
// bf16 operands (DT16<0>): diffusion transformer values carry outliers that could overflow f16,
|
||||
// and the reference also takes P to bf16 for P.V (rounded there, truncated here; see the softmax).
|
||||
//
|
||||
// THE INT8 Q.K FORM (`I8`, the op's `k_i8` operand present). The score product runs on
|
||||
// v_wmma_i32_16x16x16_iu8, which issues in half the cycles of the bf16 one; P.V stays bf16. Every
|
||||
// code is quant_act_i8g's: a scale per (row, head) of amax / 127 (1 for an all-zero row) and a code
|
||||
// rint(x * (1 / scale)) clamped to +-127. The own rows' keys arrive quantised that way (k_i8 and
|
||||
// k_scale, one op ahead of this one), the query is quantised here once a workgroup, and a prefix
|
||||
// tile is quantised as it is staged -- the prefix is a picture's conditioning, a few hundred rows
|
||||
// against the thousands of own rows. A score is (q . k) * qs * ks, the integer dot product exact.
|
||||
// At a DiT's 16384 rows this takes the kernel from 38 to about 32 ms; against the bf16 form the
|
||||
// picture moves by less than swapping between exact attention implementations moves it.
|
||||
// Int8 Q.K form (`I8`, op operand `k_i8` present): scores run on v_wmma_i32_16x16x16_iu8 (half the
|
||||
// cycles of bf16); P.V stays bf16. Codes follow quant_act_i8g: per (row, head) scale amax / 127
|
||||
// (1 for an all-zero row), code rint(x / scale) clamped to +-127. Own keys arrive quantised
|
||||
// (k_i8, k_scale, from the preceding op); the query is quantised here once per workgroup, and
|
||||
// prefix tiles (a few hundred conditioning rows) as they are staged. A score is (q . k) * qs * ks
|
||||
// with an exact integer dot product. At a DiT's 16384 rows this is ~38 -> ~32 ms, with image
|
||||
// error below the spread between exact attention implementations.
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -39,7 +33,7 @@
|
||||
typedef int v2i_ps __attribute__((ext_vector_type(2)));
|
||||
typedef int v8i_ps __attribute__((ext_vector_type(8)));
|
||||
|
||||
/* quant_act_i8g's scale and codes for eight values against `inv` = 1 / scale. */
|
||||
/* quant_act_i8g codes for four values against `inv` = 1 / scale, packed into one dword. */
|
||||
__device__ __forceinline__ uint32_t ps_q8x4(float a, float b, float c, float d, float inv) {
|
||||
auto q = [inv](float x) {
|
||||
return (uint32_t)((int)rintf(fminf(fmaxf(x * inv, -127.0f), 127.0f)) & 0xff);
|
||||
@@ -91,10 +85,9 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
constexpr float GROW = D::GROW;
|
||||
constexpr int BS = 16; // the paged block, libr4d's (block_size == 16)
|
||||
static_assert(HD % 16 == 0 && TILE % 16 == 0, "geometry");
|
||||
// THE INT8 KEY TILE: a key's row is HD bytes, padded by 8 so the sixteen rows a fragment read
|
||||
// touches land on distinct bank pairs (34 dwords a row), and written as 8-byte halves because
|
||||
// the padding leaves odd rows 8-byte aligned. A prefix tile's key is DG lanes of 8 dims each,
|
||||
// which is why those lanes must sit in one half-wave for the row's absolute maximum.
|
||||
// Int8 key tile: HD bytes per row padded by 8 (34 dwords), so a fragment read's sixteen rows
|
||||
// hit distinct bank pairs; written as 8-byte halves since odd rows are only 8-byte aligned.
|
||||
// A prefix key spans DG lanes of 8 dims, which must sit in one half-wave for the row absmax.
|
||||
constexpr int KSTR8 = HD + 8;
|
||||
constexpr int K8G = HD / 16; // 16-byte pieces of an own key's row
|
||||
constexpr int K8P = (TILE * K8G + NTHR - 1) / NTHR;
|
||||
@@ -112,9 +105,9 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
const int kvh = blockIdx.y;
|
||||
const int hq = kvh * GQA + g;
|
||||
|
||||
// THE GRID IS FLAT OVER THE SEQUENCES' QUERY BLOCKS: block b is the b-th BQ-row block counting
|
||||
// through every sequence in order, so a pass of many equal sequences launches what it needs
|
||||
// rather than (longest sequence) x (sequences). A handful of sequences, so a walk.
|
||||
// Flat grid over all sequences' query blocks: block b is the b-th BQ-row block counting through
|
||||
// the sequences in order, instead of (longest sequence) x (sequences). Few sequences, so a
|
||||
// linear walk.
|
||||
int seq = -1, q0 = 0;
|
||||
for (int s = 0, b = blockIdx.x; s < num_seqs; ++s) {
|
||||
const int nb = (cu[s + 1] - cu[s] + BQ - 1) / BQ;
|
||||
@@ -132,9 +125,9 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
const int qpos = q0 + qbi * 16 + c;
|
||||
const bool live = qpos < slen;
|
||||
|
||||
// The query: bf16 fragments pre-multiplied by the softmax scale, or int8 codes against its
|
||||
// row's absolute maximum -- a lane holds half the head's dims, the lane 16 away the other half
|
||||
// -- with the scale carried in `qs` and applied to the integer score.
|
||||
// The query: bf16 fragments pre-multiplied by the softmax scale, or int8 codes against the
|
||||
// row absmax (a lane holds half the head's dims, lane + 16 the other half) with the scale in
|
||||
// `qs`, applied to the integer score.
|
||||
qfrag qf[NKS];
|
||||
float qs = mul;
|
||||
{
|
||||
@@ -199,8 +192,8 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
const int klim = pre ? P : ke;
|
||||
const bool mask = (k0 + TILE > klim) || (!pre && causal && k0 + TILE - 1 > q0);
|
||||
|
||||
// An own tile in the int8 form is K8P 16-byte pieces a thread and a scale for the first
|
||||
// TILE threads; anything else is the bf16 rows (a prefix tile quantised below).
|
||||
// An int8 own tile is K8P 16-byte pieces per thread plus a scale from each of the first
|
||||
// TILE threads; otherwise bf16 rows (an int8 prefix tile is quantised below).
|
||||
const bool own8 = I8 && !pre;
|
||||
uint4 kr[KP], vr[VP];
|
||||
float ksr = 0.0f;
|
||||
@@ -239,8 +232,8 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
vr[r] = __builtin_bit_cast(uint4, load_tr_b128(vrow(pre, kk) + dg * 8));
|
||||
}
|
||||
}
|
||||
// A prefix key in the int8 form: its row's maximum across the DG lanes that hold it (one
|
||||
// half-wave, so a DPP butterfly), then its eight codes a lane.
|
||||
// Int8 prefix key: row absmax over its DG lanes (one half-wave, DPP butterfly), then eight
|
||||
// codes per lane.
|
||||
uint2 kq[KP];
|
||||
float kqs[KP];
|
||||
if (I8 && pre) {
|
||||
@@ -299,8 +292,8 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
|
||||
#pragma unroll 1
|
||||
for (int mt = 0; mt < MT; ++mt) {
|
||||
// The scores of 16 keys, in log2 units once times `qs` (a no-op 1 for bf16, whose
|
||||
// query carries the scale already).
|
||||
// Scores of 16 keys, in log2 units once multiplied by `qs` (int8 only; the bf16 query
|
||||
// already carries the scale).
|
||||
float sc[8];
|
||||
if constexpr (I8) {
|
||||
v8i_ps si = (v8i_ps){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
@@ -356,7 +349,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
}
|
||||
}
|
||||
|
||||
// `qs` is positive, so the maximum of the scaled scores is the scaled maximum.
|
||||
// qs > 0, so the max of the scaled scores is the scaled max.
|
||||
float smax = sc[0];
|
||||
#pragma unroll
|
||||
for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]);
|
||||
@@ -374,10 +367,10 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
soff = -mnew;
|
||||
}
|
||||
|
||||
// P TO BF16 BY TRUNCATION: one v_perm a pair where gfx1201's software round-to-nearest
|
||||
// is about six VALU a value, on a path where the WMMA and the VALU share the SIMD
|
||||
// (4-7% of the kernel at a DiT's 16384 rows). Its error is the rounding's in size, and
|
||||
// its downward bias cancels: the row sum below is taken off the same truncated values.
|
||||
// P to bf16 by truncation: one v_perm per pair, where gfx1201's software
|
||||
// round-to-nearest costs ~6 VALU per value on a SIMD shared with the WMMA (4-7% of the
|
||||
// kernel at 16384 rows). The downward bias cancels because the row sum below uses the
|
||||
// same truncated values.
|
||||
uint32_t pw[4];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e += 2) {
|
||||
@@ -387,7 +380,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
const uint32_t hi = __builtin_bit_cast(uint32_t, ex2(a1));
|
||||
pw[e >> 1] = __builtin_amdgcn_perm(hi, lo, 0x07060302u);
|
||||
}
|
||||
// The row sum off the packed P, so the denominator is the values P.V used.
|
||||
// Row sum from the packed P, so the denominator matches the values P.V used.
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 4; ++e)
|
||||
l_i += __builtin_bit_cast(float, pw[e] << 16) +
|
||||
@@ -438,7 +431,7 @@ static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, cons
|
||||
hipStream_t s)
|
||||
{
|
||||
constexpr int BQ = NQB * 16;
|
||||
// Every sequence's blocks: at most total / BQ, plus one partial block a sequence.
|
||||
// At most total / BQ full blocks plus one partial block per sequence.
|
||||
dim3 grid((max_q + BQ - 1) / BQ + num_seqs, n_head_kv, 1);
|
||||
hipLaunchKernelGGL((r4d_attn_ps_kernel<HD, GQA, NQB, TILE, I8>), grid, dim3(NQB * GQA * 32), 0, s,
|
||||
(const uint16_t*)q, (const uint16_t*)k, (const int8_t*)k8, ks,
|
||||
@@ -449,10 +442,10 @@ static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, cons
|
||||
return e == hipSuccess ? 0 : -100 - (int)e;
|
||||
}
|
||||
|
||||
/* head_dim 128 at gqa 1, 2, 4 and 8. `used`/`bt`/`kvc` null is no prefix: the dense form. `max_q`
|
||||
* is the query rows of every sequence together, which bounds the flat grid. `k8` non-null is the
|
||||
* int8 Q.K form -- the own keys as int8 codes (`k8_ld` bytes a row) with a scale per (row, head)
|
||||
* in `ks` (`ks_ld` floats a row) -- at gqa 1, the only ratio a DiT has. */
|
||||
/* head_dim 128 at gqa 1, 2, 4 and 8. Null `used`/`bt`/`kvc` means no prefix (the dense form).
|
||||
* `max_q` is the total query rows over all sequences and bounds the flat grid. Non-null `k8`
|
||||
* selects the int8 Q.K form (own-key codes, `k8_ld` bytes per row; a scale per (row, head) in
|
||||
* `ks`, `ks_ld` floats per row), gqa 1 only. */
|
||||
static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float* ks,
|
||||
const void* v, void* o, const int* cu,
|
||||
const int* used, const int* bt, int bt_pitch, const void* kvc,
|
||||
@@ -470,9 +463,9 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float
|
||||
return r4d_attn_ps_launch<128, G, NQB, T, I8>(q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, \
|
||||
num_seqs, max_q, n_head_kv, scale, causal, \
|
||||
q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, s)
|
||||
/* SIXTEEN QUERY TILES A WORKGROUP at gqa 1: a workgroup streams its head's whole K and V once,
|
||||
* so the rows it serves divide that traffic. At a DiT's 16384 rows a head's K and V are 8 MB
|
||||
* and fall out of L2; 128 rows a workgroup ran at 66 TFLOP/s, 256 at 111, 512 at 102. */
|
||||
/* Sixteen query tiles per workgroup at gqa 1: a workgroup streams its head's whole K and V
|
||||
* once, so more rows per workgroup divide that traffic. At 16384 rows a head's K/V (8 MB) do
|
||||
* not fit L2; 128 rows per workgroup gave 66 TFLOP/s, 256 gave 111, 512 gave 102. */
|
||||
if (k8) {
|
||||
if (gqa != 1) return -1;
|
||||
R4D_PS(1, 16, 64, true);
|
||||
@@ -488,17 +481,6 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
/* [tokens, heads * head_dim] (or rank 3) at the operand's own row pitch. */
|
||||
static bool ps_rows(const RadTensor* t, long long head_dim, long long* n_tok, long long* n_head,
|
||||
long long* ld) {
|
||||
long long width = 1;
|
||||
for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i];
|
||||
if (t->rank < 2 || width % head_dim) return false;
|
||||
*n_head = width / head_dim;
|
||||
*ld = r4d_rows_pitch(t, width, n_tok);
|
||||
return *ld >= 0;
|
||||
}
|
||||
|
||||
enum { PS_Q = 0, PS_K, PS_V, PS_KV, PS_BT, PS_USED, PS_CU, PS_KDES, PS_VDES, PS_K8, PS_KS,
|
||||
PS_OUT };
|
||||
|
||||
@@ -523,16 +505,18 @@ extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) {
|
||||
if (r4d_numel(su) < num_seqs) return R4D_NO(RAD_E_SHAPE);
|
||||
long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0;
|
||||
long long to = 0, ho = 0, o_ld = 0;
|
||||
if (!ps_rows(q, hd, &total, &nh, &q_ld) || !ps_rows(k, hd, &tk, &hk, &k_ld) ||
|
||||
!ps_rows(v, hd, &tv, &hv, &v_ld) || !ps_rows(o, hd, &to, &ho, &o_ld))
|
||||
if (!r4d_head_rows(q, hd, &total, &nh, &q_ld) ||
|
||||
!r4d_head_rows(k, hd, &tk, &hk, &k_ld) ||
|
||||
!r4d_head_rows(v, hd, &tv, &hv, &v_ld) ||
|
||||
!r4d_head_rows(o, hd, &to, &ho, &o_ld))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
if (hk != hv || ho != nh || hk * gqa != nh || hk != kv->shape[1]) return R4D_NO(RAD_E_SHAPE);
|
||||
if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long bt_pitch = bt->rank >= 2 ? bt->shape[1] : r4d_numel(bt) / num_seqs;
|
||||
if (bt->rank >= 2 && bt->stride[1] != 1) return R4D_NO(RAD_E_STRIDE);
|
||||
const long long mq = total;
|
||||
/* THE INT8 Q.K FORM (`qk` "i8"): the own keys' codes [tokens, kv_heads * head_dim] and their
|
||||
* scales [tokens, kv_heads], as quant_act_i8g writes them at group head_dim. */
|
||||
/* Int8 Q.K form (`qk` "i8"): own-key codes [tokens, kv_heads * head_dim] and scales
|
||||
* [tokens, kv_heads], as quant_act_i8g writes them at group head_dim. */
|
||||
const RadTensor* k8 = r4d_opt(a, PS_K8);
|
||||
const RadTensor* ks = r4d_opt(a, PS_KS);
|
||||
const char* qk = r4d_gets(a, "qk");
|
||||
@@ -543,7 +527,7 @@ extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) {
|
||||
if (k8) {
|
||||
if (k8->dtype != RAD_I8 || ks->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
|
||||
long long t8 = 0, h8 = 0, ts = 0;
|
||||
if (!ps_rows(k8, hd, &t8, &h8, &k8_ld)) return R4D_NO(RAD_E_STRIDE);
|
||||
if (!r4d_head_rows(k8, hd, &t8, &h8, &k8_ld)) return R4D_NO(RAD_E_STRIDE);
|
||||
ks_ld = r4d_rows_pitch(ks, hk, &ts);
|
||||
if (ks_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (h8 != hk || t8 < total || ts < total) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -556,7 +540,8 @@ extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) {
|
||||
scale, (int)r4d_geti_or(a, "causal", 0), (int)q_ld, (int)k_ld,
|
||||
(int)k8_ld, (int)ks_ld, (int)v_ld, (int)o_ld, (hipStream_t)s);
|
||||
if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE);
|
||||
return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
|
||||
if (e == 0) return RAD_OK;
|
||||
return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* attn_dense at head_dim 128, causal or not: the same kernel with no prefix. */
|
||||
@@ -570,11 +555,16 @@ extern "C" int r4d_rad_attn_dense_h128(const RadArgs* a, RadStream s) {
|
||||
if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long hd = r4d_geti_or(a, "head_dim", 0), gqa = r4d_geti_or(a, "gqa", 1);
|
||||
if (hd != 128 || gqa <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
if (r4d_geti_or(a, "window", 0) != 0) return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
/* Every key of a segment, its bounds read as they stand: no window, blocks or cu_div. */
|
||||
if (r4d_geti_or(a, "window", 0) != 0 || r4d_geti_or(a, "block", 0) != 0 ||
|
||||
r4d_geti_or(a, "cu_div", 1) != 1)
|
||||
return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0;
|
||||
long long to = 0, ho = 0, o_ld = 0;
|
||||
if (!ps_rows(q, hd, &total, &nh, &q_ld) || !ps_rows(k, hd, &tk, &hk, &k_ld) ||
|
||||
!ps_rows(v, hd, &tv, &hv, &v_ld) || !ps_rows(o, hd, &to, &ho, &o_ld))
|
||||
if (!r4d_head_rows(q, hd, &total, &nh, &q_ld) ||
|
||||
!r4d_head_rows(k, hd, &tk, &hk, &k_ld) ||
|
||||
!r4d_head_rows(v, hd, &tv, &hv, &v_ld) ||
|
||||
!r4d_head_rows(o, hd, &to, &ho, &o_ld))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
if (hk != hv || ho != nh || hk * gqa != nh) return R4D_NO(RAD_E_SHAPE);
|
||||
if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -586,24 +576,24 @@ extern "C" int r4d_rad_attn_dense_h128(const RadArgs* a, RadStream s) {
|
||||
(int)r4d_geti_or(a, "causal", 0), (int)q_ld, (int)k_ld, 0, 0,
|
||||
(int)v_ld, (int)o_ld, (hipStream_t)s);
|
||||
if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE);
|
||||
return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
|
||||
if (e == 0) return RAD_OK;
|
||||
return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
// ============================================================== wide heads (attn_dense, h768 / h1152)
|
||||
// AN IMAGE DECODER'S MID-BLOCK ATTENTION: one head 1152 wide over every latent pixel -- 16384 rows
|
||||
// at 2048 x 2048. A lane cannot hold a 1152-wide output row (576 accumulator registers), so the
|
||||
// head is split across the workgroup's eight waves instead of its rows: a wave owns HD/8 of the
|
||||
// dims for the whole 16-query block.
|
||||
// Image decoder mid-block attention: one head up to 1152 wide over every latent pixel (16384 rows
|
||||
// at 2048 x 2048). A lane cannot hold a 1152-wide output row (576 accumulator VGPRs), so the head
|
||||
// is split across the workgroup's eight waves: a wave owns HD/8 dims of the 16-query block.
|
||||
//
|
||||
// S = Q.K^T is contracted in eight pieces, a wave's dims each, and the partial score tiles are
|
||||
// summed through LDS in wave order -- a fixed order, so the sum is the same every run.
|
||||
// P is formed once, by sixteen threads (a query row each), rounded to bf16, and its row sum is
|
||||
// taken off the rounded values, the denominator P.V uses.
|
||||
// O += P.V is a wave's own dims: V^T fragments straight from global with the transposing load
|
||||
// (no LDS), P^T from LDS.
|
||||
// S = Q.K^T in eight partial tiles (one per wave), summed through LDS in fixed wave order so
|
||||
// the result is run-to-run deterministic.
|
||||
// P formed by sixteen threads (one per query row), rounded to bf16; the row sum uses the
|
||||
// rounded values.
|
||||
// O += P.V over the wave's own dims: V^T straight from global via the transposing load, P^T
|
||||
// from LDS.
|
||||
//
|
||||
// S^T = K.Q^T as in the dense kernel above, so a partial tile's C layout is (query = lane % 16,
|
||||
// key = 8 (lane / 16) + e) and both the reduction and the P^T fragment index it the same way.
|
||||
// S^T = K.Q^T as above, so a partial tile's C layout is (query = lane % 16, key = 8 (lane / 16) + e)
|
||||
// for both the reduction and the P^T fragment.
|
||||
template<int HD>
|
||||
__global__ __launch_bounds__(256)
|
||||
void r4d_attn_wide_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
|
||||
@@ -733,8 +723,8 @@ void r4d_attn_wide_kernel(const uint16_t* __restrict__ gq, const uint16_t* __res
|
||||
}
|
||||
}
|
||||
|
||||
/* attn_dense at head_dim 768 or 1152 (an image encoder's and decoder's mid block), one query head a
|
||||
* KV head, bidirectional. */
|
||||
/* attn_dense at head_dim 768 or 1152 (image encoder/decoder mid block): one query head per KV
|
||||
* head, bidirectional. */
|
||||
extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* q = r4d_opt(a, 0);
|
||||
const RadTensor* k = r4d_opt(a, 1);
|
||||
@@ -745,12 +735,15 @@ extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream s) {
|
||||
if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long hd = r4d_geti_or(a, "head_dim", 0);
|
||||
if ((hd != 768 && hd != 1152) || r4d_geti_or(a, "gqa", 1) != 1 || r4d_geti_or(a, "causal", 0) != 0 ||
|
||||
r4d_geti_or(a, "window", 0) != 0)
|
||||
r4d_geti_or(a, "window", 0) != 0 || r4d_geti_or(a, "block", 0) != 0 ||
|
||||
r4d_geti_or(a, "cu_div", 1) != 1)
|
||||
return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0;
|
||||
long long to = 0, ho = 0, o_ld = 0;
|
||||
if (!ps_rows(q, hd, &total, &nh, &q_ld) || !ps_rows(k, hd, &tk, &hk, &k_ld) ||
|
||||
!ps_rows(v, hd, &tv, &hv, &v_ld) || !ps_rows(o, hd, &to, &ho, &o_ld))
|
||||
if (!r4d_head_rows(q, hd, &total, &nh, &q_ld) ||
|
||||
!r4d_head_rows(k, hd, &tk, &hk, &k_ld) ||
|
||||
!r4d_head_rows(v, hd, &tv, &hv, &v_ld) ||
|
||||
!r4d_head_rows(o, hd, &to, &ho, &o_ld))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
if (hk != nh || hv != nh || ho != nh) return R4D_NO(RAD_E_SHAPE);
|
||||
if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
+92
-174
@@ -1,30 +1,23 @@
|
||||
// R4D attention dispatch at EIGHT queries per KV head, for head_dim 256 and head_dim 128.
|
||||
// R4D paged attention dispatch at eight queries per KV head, head_dim 256 and 128.
|
||||
//
|
||||
// It is the same device code as the 27B target's h256/gqa6 dispatch -- the kernels are templates
|
||||
// on head_dim and gqa, so this file is a set of instantiations and not a set of kernels -- and it
|
||||
// exists because two models in scope are gqa 8 and the constraint tables gate on the exact value:
|
||||
// Instantiations of the h256/gqa6 kernel templates (templated on head_dim and gqa), for the gqa-8
|
||||
// models; the constraint tables gate on the exact ratio:
|
||||
//
|
||||
// Qwen3.6-35B-A3B 16 query heads over 2 KV heads, head_dim 256 (the routed sibling of the
|
||||
// 27B, which is 24 over 4 at the same head_dim)
|
||||
// Qwen3.6-35B-A3B 16 query heads over 2 KV heads, head_dim 256
|
||||
// MiniCPM5-2B 16 query heads over 2 KV heads, head_dim 128
|
||||
//
|
||||
// WHAT CHANGES WITH GQA, AND IT IS ONLY THE TWO BOUNDS. A decode workgroup carries `q_len * gqa`
|
||||
// rows and holds 64 of them, so the verify width falls from 10 at gqa 6 to 8 at gqa 8 -- and that
|
||||
// bound is the constraint value the selector bands on, so it is stated in the row and nowhere
|
||||
// else. A prefill block carries `NWARPS * 16 / gqa` query positions, 48 here against 64 there.
|
||||
// Gqa changes only two bounds. A decode workgroup holds 64 rows of q_len * gqa, so the verify
|
||||
// width is 8 here (10 at gqa 6); the selector bands on that value, stated in the row. A prefill
|
||||
// block carries NWARPS * 16 / gqa query positions (48 here, 64 at gqa 6).
|
||||
//
|
||||
// WHAT CHANGES WITH HEAD_DIM IS HOW K IS FETCHED. `O_KWIDE` fetches 16 K elements a thread and its
|
||||
// thread-to-(key, channel) map is written for 16 channels of 16 -- which is head_dim 256 exactly.
|
||||
// At 128 it would stage past the tile, so the h128 prefill runs without it and pays one more pass
|
||||
// over a tile that is half the size; and its fragments are half as many registers, so it keeps a
|
||||
// K prefetch of 4 where head_dim 256 takes 2 (3430923 against 3954187). Everything else -- the
|
||||
// lazy reference-max softmax, f16 operands, the folded query scale, contiguous-k fragments, the
|
||||
// SGPR block table, the V prefetch, the LDS-scoped barrier -- is unchanged, and each bit is
|
||||
// defined and justified in r4d_attn_prefill_h256_gqa6.hip.
|
||||
// Head_dim changes how K is fetched. O_KWIDE's thread-to-(key, channel) map covers exactly 16 x 16
|
||||
// channels (head_dim 256); at 128 it would stage past the tile, so the h128 prefill runs without it.
|
||||
// Its fragments take half the registers, so it keeps K prefetch 4 where h256 uses 2. All other
|
||||
// option bits are as defined in r4d_attn_prefill_h256_gqa6.hip.
|
||||
//
|
||||
// NO `r4d_attn_dims` HERE. That entry point and the `check_dims_once` assertion built on it are
|
||||
// the h256/gqa6 unit's statement about ITSELF, and a second definition would not link. A geometry
|
||||
// gate is what the row table's constraints are for; this file states its own in the launchers.
|
||||
// No r4d_attn_dims here: that entry point (and check_dims_once) belongs to the h256/gqa6 unit,
|
||||
// and a second definition would not link. Geometry is gated by the row constraints and the
|
||||
// launchers below.
|
||||
#include "r4d.h"
|
||||
#include "r4d_attn_args.h"
|
||||
#include "r4d_emit.h"
|
||||
@@ -32,49 +25,43 @@
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
using std::max;
|
||||
// The decode kernel shares its query conversion and fragment helpers with the prefill one, so the
|
||||
// prefill header comes first here for the same reason it does in the other two dispatches.
|
||||
// The decode kernel uses helpers defined in the prefill unit, so prefill is included first.
|
||||
#include "r4d_attn_prefill_h256_gqa6.hip"
|
||||
#include "r4d_attn_decode_h256_gqa6.hip"
|
||||
|
||||
#define CHK8() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0)
|
||||
|
||||
/* THE QUERIES PER KV HEAD, AND THE SYMBOL NAMES BUILT FROM IT.
|
||||
/* Queries per KV head, and the symbol names built from it.
|
||||
*
|
||||
* This unit is a set of INSTANTIATIONS of templates that already take `gqa`, so a second ratio is
|
||||
* a second set of macro values and not a second kernel -- and a second COPY of this file would be
|
||||
* the drift the header warns about, in a dispatch two shipped models run. So the geometry comes
|
||||
* from macros with this unit's own values as the defaults, the entry points paste the ratio into
|
||||
* their names, and another ratio is a four-line file that defines the macros and includes this
|
||||
* one (r4d_attn_paged_h256_gqa12.hip).
|
||||
*
|
||||
* WHAT CHANGES WITH THE RATIO IS THE TWO BOUNDS AND NOTHING ELSE, exactly as the header says: the
|
||||
* decode verify width is 64/gqa (8 here, 5 at gqa 12) and a prefill block carries 384/gqa query
|
||||
* positions (48 here, 32 at gqa 12). Both must divide, and both are stated in the ROW so the
|
||||
* selector bands on them. */
|
||||
* Another ratio reuses this file: it defines these macros and includes this one (e.g.
|
||||
* r4d_attn_paged_h256_gqa12.hip), and the entry points paste the ratio into their names. Only
|
||||
* the two bounds change: decode verify width 64/gqa (8 here, 5 at gqa 12) and prefill block
|
||||
* 384/gqa query positions (48 here, 32 at gqa 12). Both must divide, and both are stated in the
|
||||
* row so the selector bands on them. */
|
||||
#ifndef R4D_ATTN_GQA
|
||||
#define R4D_ATTN_GQA 8
|
||||
#define R4D_ATTN_H128 1 /* this ratio also serves head_dim 128 -- MiniCPM5-2B is 16 over 2 */
|
||||
#endif
|
||||
/* A head_dim 64 PREFILL leg, off unless the including unit asks for it: LFM2 is 32 query heads
|
||||
* over 8 at head_dim 64 (r4d_attn_paged_h256_gqa4.hip). It runs the h128 prefill option set --
|
||||
* O_KWIDE's 16-channel staging is written for 256. There is no decode leg: the split-KV kernel
|
||||
* holds a lane's columns as one or two dwords of codes, which is head_dim 128 or 256, so the
|
||||
* query-tiled kernel serves every query length at this width. */
|
||||
/* Head_dim 64 prefill leg, off unless the including unit enables it (LFM2: 32 query heads over 8,
|
||||
* r4d_attn_paged_h256_gqa4.hip). Uses the h128 option set (no O_KWIDE). No decode leg: the
|
||||
* split-KV merge holds a lane's columns as one or two dwords of codes (head_dim 128 or 256), so
|
||||
* the query-tiled kernel serves every query length at this width. */
|
||||
#ifndef R4D_ATTN_H64
|
||||
#define R4D_ATTN_H64 0
|
||||
#endif
|
||||
/* Head_dim 256 leg, on unless the including unit serves only head_dim 128 (as R4D_ATTN_H128 0
|
||||
* leaves the 128 leg out). */
|
||||
#ifndef R4D_ATTN_H256
|
||||
#define R4D_ATTN_H256 1
|
||||
#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)
|
||||
|
||||
#define G8_GQA R4D_ATTN_GQA
|
||||
/* The KV page, in tokens. Overridable by the including translation unit because the BODY IS
|
||||
* GENERIC IN IT -- `bt[kk / BS]` picks the page, `kk % BS` the offset inside it, and
|
||||
* `NB = TILE / BS` is how many block-table entries the O_BTS prefetch stages a tile. 16 is what
|
||||
* every geometry here has wanted so far; Qwen4-Exp's QSA wants 4, because its indexer selects
|
||||
* 4-token blocks and a page of 4 makes the selection a block table rather than a new kernel
|
||||
* (docs/QSA.md). */
|
||||
/* KV page size in tokens; the kernel body is generic in it, so an including unit may override.
|
||||
* Qwen4-Exp's QSA uses 4: its indexer selects 4-token blocks, so the selection is just a block
|
||||
* table (docs/QSA.md). */
|
||||
#ifndef G8_BLOCK_SIZE
|
||||
#define G8_BLOCK_SIZE 16
|
||||
#endif
|
||||
@@ -82,10 +69,10 @@ using std::max;
|
||||
|
||||
#define G8_P_NWARPS 24
|
||||
#define G8_P_TILE 48
|
||||
// K prefetch 2, as the h256/gqa6 prefill and for the same reason (see P_OPT there): 4 spills the
|
||||
// m-tile loop. The head_dim-128 set keeps its prefetch of 4, which fits.
|
||||
// K prefetch 2 at head_dim 256, as in the h256/gqa6 prefill (P_OPT there): 4 spills the m-tile
|
||||
// loop. The head_dim-128 set keeps prefetch 4, which fits.
|
||||
#define G8_P_OPT_256 3954187
|
||||
#define G8_P_OPT_128 3430923 // without O_KWIDE, at prefetch 4; see the header
|
||||
#define G8_P_OPT_128 3430923 // without O_KWIDE, prefetch 4
|
||||
#define G8_P_OPT_64 G8_P_OPT_128
|
||||
#define G8_D_TILE 16
|
||||
#define G8_D_OPT 3429947
|
||||
@@ -107,38 +94,16 @@ static int g8_prefill_launch(const R4DArgs* a, hipStream_t s) {
|
||||
}
|
||||
|
||||
// ---- decode ------------------------------------------------------------------------------------
|
||||
// The h256/gqa6 split law verbatim -- as many workgroups as fit under 128, at least two tiles a
|
||||
// segment. It reads kv_heads, num_seqs and max_ctx and nothing about gqa or head_dim, so there is
|
||||
// nothing in it to re-derive for this geometry; copying it rather than sharing it is the cost of
|
||||
// the three dispatches being three translation units, and the target count is the h256 leg's.
|
||||
static int g8_decode_splits(const R4DArgs* a) {
|
||||
if (a->splits > 0) return a->splits;
|
||||
const int tiles = (a->max_ctx + G8_D_TILE - 1) / G8_D_TILE;
|
||||
const int units = max(1, a->kv_heads * a->num_seqs);
|
||||
int s = 128 / units;
|
||||
const int cap = tiles / 2;
|
||||
if (s > cap) s = cap;
|
||||
if (s > tiles) s = tiles;
|
||||
if (s < 1) s = 1;
|
||||
return s;
|
||||
}
|
||||
|
||||
// The h256/gqa6 split law (r4d_decode_splits).
|
||||
extern "C" long GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(const R4DArgs* a) {
|
||||
const int splits = g8_decode_splits(a);
|
||||
const long rows = (long)r4d_q_total(*a) * a->q_heads;
|
||||
return (G8_D_OPT & 32) ? rows * splits * (long)(a->head_dim * 2 + 8)
|
||||
: rows * splits * (long)(a->head_dim + 2) * 4L;
|
||||
return r4d_decode_scratch(a, r4d_decode_splits(a, G8_D_TILE), G8_D_OPT);
|
||||
}
|
||||
|
||||
template <int HEAD_DIM, int KVP>
|
||||
/* THE DECODE PATH TAKES A SINK, so the same geometry serves the launch and the description.
|
||||
* Two dispatches: the attention kernel and the split-KV combine that follows it. The kernel takes
|
||||
* `R4DArgs` BY VALUE -- 168 bytes -- which the descriptor's blob carries like any other argument,
|
||||
* because a kernel parameter is a kernel parameter whatever its size.
|
||||
*
|
||||
* `gq` is attn_paged_gate_quant's epilogue: the same two dispatches, with the combine taking the
|
||||
* output gate and the fp8 quantiser on (r4d_attn_decode_h256_gqa6.hip, R4DGateQuant). */
|
||||
static int g8_decode_launch(const R4DArgs* a, const R4dSink& sk,
|
||||
/* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (168
|
||||
* 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). */
|
||||
static int g8_decode_launch(const R4DArgs* a, RadStream stream,
|
||||
const R4DGateQuant* gq = nullptr) {
|
||||
int emit_rc = RAD_OK;
|
||||
if (a->head_dim != HEAD_DIM || a->block_size != G8_BLOCK_SIZE) return -1;
|
||||
@@ -146,16 +111,15 @@ static int g8_decode_launch(const R4DArgs* a, const R4dSink& sk,
|
||||
const int rows = a->q_len * G8_GQA;
|
||||
if (rows > G8_MAX_DECODE_ROWS) return -4;
|
||||
const int nw = (rows + 15) / 16;
|
||||
const int splits = g8_decode_splits(a);
|
||||
const int splits = r4d_decode_splits(a, G8_D_TILE);
|
||||
|
||||
#define G8_LAUNCH(NW) \
|
||||
emit_rc = R4D_EMIT(sk, (r4d_attn_decode_kernel<NW, G8_D_TILE, HEAD_DIM, G8_GQA, \
|
||||
emit_rc = R4D_EMIT(stream, (r4d_attn_decode_kernel<NW, G8_D_TILE, HEAD_DIM, G8_GQA, \
|
||||
G8_BLOCK_SIZE, KVP, G8_D_OPT>), \
|
||||
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, *a, splits)
|
||||
/* One wave a workgroup stages V as its codes (O_V8): the one wave converts each element once
|
||||
* either way, and the tile is half the LDS. */
|
||||
/* One-wave workgroups stage V as codes (O_V8): same conversion count, half the LDS. */
|
||||
if (nw == 1)
|
||||
emit_rc = R4D_EMIT(sk, (r4d_attn_decode_kernel<1, G8_D_TILE, HEAD_DIM, G8_GQA,
|
||||
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>),
|
||||
dim3(splits, a->kv_heads, a->num_seqs), dim3(32), 0, *a, splits);
|
||||
else if (nw == 2) G8_LAUNCH(2);
|
||||
@@ -163,21 +127,22 @@ static int g8_decode_launch(const R4DArgs* a, const R4dSink& sk,
|
||||
else G8_LAUNCH(4);
|
||||
#undef G8_LAUNCH
|
||||
if (emit_rc != RAD_OK) return -5;
|
||||
if (!sk.desc) CHK8();
|
||||
CHK8();
|
||||
|
||||
// The same two merge forms and the same rule for choosing between them as the other two
|
||||
// dispatches: a wave a row while there are enough rows to fill the part and the segment count
|
||||
// fits a wave, the general LDS-tree form otherwise. Both produce the same bytes.
|
||||
// Merge form, as in the other dispatches: one wave per row when there are enough rows and the
|
||||
// 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 is the int8 codes' epilogue, 1 the E4M3 one; see R4DGateQuant. */
|
||||
/* GQ 2: int8 codes, GQ 1: E4M3; see R4DGateQuant. */
|
||||
#define G8_GQ_VEC(PF, GQV) \
|
||||
R4D_EMIT(sk, (r4d_attn_splitkv_combine_vec_gq_kernel<HEAD_DIM, 4, PF, G8_D_JPB, 0, GQV>), \
|
||||
R4D_EMIT(stream, \
|
||||
(r4d_attn_splitkv_combine_vec_gq_kernel<HEAD_DIM, 4, PF, G8_D_JPB, 0, GQV>), \
|
||||
dim3((jobs3 + G8_D_JPB - 1) / G8_D_JPB), dim3(32 * G8_D_JPB), 0, *a, splits, \
|
||||
G8_D_TILE, *gq)
|
||||
#define G8_GQ_GEN(PF, GQV) \
|
||||
R4D_EMIT(sk, (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)
|
||||
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;
|
||||
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);
|
||||
@@ -192,34 +157,34 @@ static int g8_decode_launch(const R4DArgs* a, const R4dSink& sk,
|
||||
} 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(sk, (r4d_attn_splitkv_combine_vec_kernel<HEAD_DIM, 4, 1, G8_D_JPB>),
|
||||
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(sk, (r4d_attn_splitkv_combine_vec_kernel<HEAD_DIM, 4, 0, G8_D_JPB>),
|
||||
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)
|
||||
/* THE BLOCK IS HEAD_DIM THREADS AND NOT 256: the general combine is
|
||||
* __launch_bounds__(HEAD_DIM), one thread a channel, so a 128-wide head launched at 256
|
||||
* is refused by the runtime. A dispatch that serves only head_dim 256 can write 256 here;
|
||||
* this one serves both widths and cannot. */
|
||||
emit_rc = R4D_EMIT(sk, (r4d_attn_splitkv_combine_kernel<HEAD_DIM, 4, 1>), dim3(jobs3),
|
||||
/* 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(sk, (r4d_attn_splitkv_combine_kernel<HEAD_DIM, 4, 0>), dim3(jobs3),
|
||||
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);
|
||||
if (emit_rc != RAD_OK) return -5;
|
||||
if (!sk.desc) CHK8();
|
||||
CHK8();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
|
||||
#if R4D_ATTN_H256
|
||||
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;
|
||||
/* Absent descales mean 1.0, exactly as on the gqa6 leg: the kernels spell it that way and a
|
||||
* cache written at the default scale needs no plane to allocate or keep in step. */
|
||||
/* 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) {
|
||||
@@ -228,6 +193,7 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h256_gqa, _bf16)(const RadArgs* a, Ra
|
||||
if (rc != RAD_OK) return rc;
|
||||
return g8_prefill_launch<256, G8_P_OPT_256, 1>(&r, (hipStream_t)s);
|
||||
}
|
||||
#endif
|
||||
#if R4D_ATTN_H128
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h128_gqa, _fp8)(const RadArgs* a, RadStream s) {
|
||||
R4DArgs r;
|
||||
@@ -257,13 +223,10 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _bf16)(const RadArgs* a, Rad
|
||||
}
|
||||
#endif
|
||||
|
||||
/* The split-KV partial buffer, sized at declare from the band's upper bound. IT IS CALLED WITH
|
||||
* PARAMETERS AND NO TENSORS -- that is what declare is -- so the parameters are the primary source
|
||||
* and the tensors the fallback, which is the trap the h256/gqa6 dispatch documents at length.
|
||||
*
|
||||
* The size is the largest over EVERY sequence count up to max_seqs, not the size at max_seqs:
|
||||
* S * floor(128 / (kv_heads * S)) is not monotone in S, which the h256/gqa6 dispatch also
|
||||
* spells out. */
|
||||
/* Split-KV partial buffer size at declare time, from the band's upper bound. Declare passes
|
||||
* parameters and no tensors, so parameters come first and tensors are the fallback (see the
|
||||
* h256/gqa6 dispatch). The size is the maximum over every sequence count up to max_seqs, because
|
||||
* S * floor(128 / (kv_heads * S)) is not monotone in S. */
|
||||
static int64_t g8_decode_scratch(const RadArgs* a, int head_dim) {
|
||||
const int sp = split_of(a);
|
||||
if (sp < 0) return R4D_NO(RAD_E_INVAL);
|
||||
@@ -297,9 +260,11 @@ static int64_t g8_decode_scratch(const RadArgs* a, int head_dim) {
|
||||
return GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(&r);
|
||||
}
|
||||
|
||||
#if R4D_ATTN_H256
|
||||
extern "C" int64_t GQ_SYM(r4d_rad_attn_decode_h256_gqa, _scratch)(const RadArgs* a) {
|
||||
return g8_decode_scratch(a, 256);
|
||||
}
|
||||
#endif
|
||||
#if R4D_ATTN_H128
|
||||
extern "C" int64_t GQ_SYM(r4d_rad_attn_decode_h128_gqa, _scratch)(const RadArgs* a) {
|
||||
return g8_decode_scratch(a, 128);
|
||||
@@ -317,31 +282,17 @@ static int g8_decode_common(const RadArgs* a, R4DArgs* r, int head_dim) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int GQ_SYM(rad_attn_decode_h256_gqa, _fp8_body)(const RadArgs* a, const R4dSink& sk) {
|
||||
#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, sk);
|
||||
return g8_decode_launch<256, 0>(&r, stream);
|
||||
}
|
||||
/* R4D_ENTRY CANNOT BE USED HERE. It pastes `_describe` onto its first argument, and this
|
||||
* name is itself a macro -- the paste would land on the GQ_SYM invocation text rather than on
|
||||
* the symbol it expands to. Both entries are spelled instead, through the same join. */
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _fp8)(const RadArgs* a, RadStream s) {
|
||||
R4dSink sk; sk.stream = s;
|
||||
return GQ_SYM(rad_attn_decode_h256_gqa, _fp8_body)(a, sk);
|
||||
}
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _fp8_describe)(
|
||||
const RadArgs* a, RadStream s, RadLaunchDesc* d, int cap, int* n) {
|
||||
if (!n) return RAD_E_INVAL;
|
||||
*n = 0;
|
||||
R4dSink sk; sk.stream = s; sk.desc = d; sk.cap = cap; sk.n = n;
|
||||
return GQ_SYM(rad_attn_decode_h256_gqa, _fp8_body)(a, sk);
|
||||
}
|
||||
/* ---- attn_paged_gate_quant: attn_paged's eight operands, then the gate, the codes and the
|
||||
* scales. The gate is gate_quant_fp8's: a [T, n_head, head_dim] column view of the [q|gate]
|
||||
* projection, whose (token, head) rows are one pitch apart only because the view narrowed the last
|
||||
* axis and nothing above it -- the same test gate_quant_fp8's shim applies (tq_pitch), repeated
|
||||
* here because this unit cannot link that one. */
|
||||
/* ---- 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. */
|
||||
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) {
|
||||
@@ -374,8 +325,8 @@ static int g8_gate_quant_args(const RadArgs* a, const R4DArgs& r, R4DGateQuant*
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const long long gp = gq_row_pitch(g, n), qp = gq_row_pitch(q, n), sp = gq_row_pitch(s, nkb);
|
||||
if (gp < 0 || qp < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
/* The vector merge reads a lane's gate as one 16-byte access and stores its codes as one
|
||||
* 8-byte one. */
|
||||
/* The vector merge reads a lane's gate in one 16-byte access and stores its codes in one
|
||||
* 8-byte access. */
|
||||
if ((r4d_addr(g) & 15) || (gp % 8) || (r4d_addr(q) & 7) || (qp % 8))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
gq->g = (const uint16_t*)r4d_addr(g);
|
||||
@@ -388,77 +339,44 @@ static int g8_gate_quant_args(const RadArgs* a, const R4DArgs& r, R4DGateQuant*
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int GQ_SYM(rad_attn_decode_gq_h256_gqa, _fp8_body)(const RadArgs* a, const R4dSink& sk) {
|
||||
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, sk, &gq);
|
||||
}
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _fp8)(const RadArgs* a, RadStream s) {
|
||||
R4dSink sk; sk.stream = s;
|
||||
return GQ_SYM(rad_attn_decode_gq_h256_gqa, _fp8_body)(a, sk);
|
||||
}
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _fp8_describe)(
|
||||
const RadArgs* a, RadStream s, RadLaunchDesc* d, int cap, int* n) {
|
||||
if (!n) return RAD_E_INVAL;
|
||||
*n = 0;
|
||||
R4dSink sk; sk.stream = s; sk.desc = d; sk.cap = cap; sk.n = n;
|
||||
return GQ_SYM(rad_attn_decode_gq_h256_gqa, _fp8_body)(a, sk);
|
||||
return g8_decode_launch<256, 0>(&r, stream, &gq);
|
||||
}
|
||||
|
||||
/* The bf16 cache's decode, plain and with the gate and the quantiser in the merge: the fp8 pair's
|
||||
* dispatches at KVP 1, described the same way so either cache replays as a graph. */
|
||||
static int GQ_SYM(rad_attn_decode_h256_gqa, _bf16_body)(const RadArgs* a, const R4dSink& sk) {
|
||||
/* bf16-cache decode, plain and gated: the fp8 pair at KVP 1. */
|
||||
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);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return g8_decode_launch<256, 1>(&r, sk);
|
||||
return g8_decode_launch<256, 1>(&r, stream);
|
||||
}
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _bf16)(const RadArgs* a, RadStream s) {
|
||||
R4dSink sk; sk.stream = s;
|
||||
return GQ_SYM(rad_attn_decode_h256_gqa, _bf16_body)(a, sk);
|
||||
}
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _bf16_describe)(
|
||||
const RadArgs* a, RadStream s, RadLaunchDesc* d, int cap, int* n) {
|
||||
if (!n) return RAD_E_INVAL;
|
||||
*n = 0;
|
||||
R4dSink sk; sk.stream = s; sk.desc = d; sk.cap = cap; sk.n = n;
|
||||
return GQ_SYM(rad_attn_decode_h256_gqa, _bf16_body)(a, sk);
|
||||
}
|
||||
static int GQ_SYM(rad_attn_decode_gq_h256_gqa, _bf16_body)(const RadArgs* a, const R4dSink& sk) {
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_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);
|
||||
if (gc != RAD_OK) return gc;
|
||||
return g8_decode_launch<256, 1>(&r, sk, &gq);
|
||||
}
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _bf16)(const RadArgs* a, RadStream s) {
|
||||
R4dSink sk; sk.stream = s;
|
||||
return GQ_SYM(rad_attn_decode_gq_h256_gqa, _bf16_body)(a, sk);
|
||||
}
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _bf16_describe)(
|
||||
const RadArgs* a, RadStream s, RadLaunchDesc* d, int cap, int* n) {
|
||||
if (!n) return RAD_E_INVAL;
|
||||
*n = 0;
|
||||
R4dSink sk; sk.stream = s; sk.desc = d; sk.cap = cap; sk.n = n;
|
||||
return GQ_SYM(rad_attn_decode_gq_h256_gqa, _bf16_body)(a, sk);
|
||||
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, r4d_stream_sink(s));
|
||||
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);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return g8_decode_launch<128, 1>(&r, r4d_stream_sink(s));
|
||||
return g8_decode_launch<128, 1>(&r, s);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,14 @@
|
||||
// R4D attention at two queries per KV head, head_dim 128: Qwen3-1.7B's 16 query heads over 8 KV
|
||||
// heads, Qwen3-ASR's decoder (arch/qwen3asr_bf16). Geometry only; r4d_attn_paged_gqa8.hip is the
|
||||
// body. The ratio changes two bounds, both stated in the row table:
|
||||
//
|
||||
// decode verify width 64 / gqa = 32 (a workgroup holds 64 (query, head) rows).
|
||||
// prefill block width 384 / gqa = 192 query positions.
|
||||
//
|
||||
// No head_dim 256 leg (R4D_ATTN_H256 0): gqa 2 at 256 is r4d_attn_paged_h256_gqa2.hip's, a
|
||||
// windowed kernel of its own. Page size 16.
|
||||
#define R4D_ATTN_GQA 2
|
||||
#define R4D_ATTN_H128 1
|
||||
#define R4D_ATTN_H256 0
|
||||
|
||||
#include "r4d_attn_paged_gqa8.hip"
|
||||
@@ -1,132 +1,39 @@
|
||||
// R4D attention dispatch for the DFlash2 drafter's geometry: head_dim 128, 4 queries per KV head,
|
||||
// paged block 16, and a SLIDING WINDOW. It is the same device code as the 27B target's h256/gqa6
|
||||
// dispatch -- the kernels are templates on head_dim and gqa, so this file is a second set of
|
||||
// instantiations and not a second kernel -- with the window bit turned on.
|
||||
// R4D attention dispatch for the DFlash2 drafter: head_dim 128, 4 queries per KV head, paged
|
||||
// block 16, sliding window. Instantiations of the h256/gqa6 kernel templates with WIN = 1.
|
||||
//
|
||||
// Decode only, deliberately. A query long enough to want the query-tiled prefill kernel is rare on
|
||||
// a drafter (it happens on a prefill step and nowhere else), and the caller has a working fallback
|
||||
// for it; instantiating a second prefill kernel to serve that case would cost build time and a
|
||||
// second masking path to keep correct for no measurable return. The caller asks
|
||||
// r4d_attn_h128_gqa4_have_prefill() and routes the whole batch elsewhere when it is 0.
|
||||
// Decode only. Queries long enough for the query-tiled prefill kernel occur on a drafter only in
|
||||
// prefill steps; the rows declare the decode band (q_len * gqa <= 64), so those resolve elsewhere.
|
||||
//
|
||||
// WHY THIS EXISTS. A general unified-attention kernel (vLLM's) spends 30.9 us a layer on this
|
||||
// shape at one request and 203.7 at eight -- against a KV stream that the window caps at 2048
|
||||
// positions, i.e. 2.1 MB and 16.8 MB, which is 3.3 us and 26.3 us of DRAM. The gap is grid shape,
|
||||
// not bandwidth: it launches (q_blocks, kv_heads,
|
||||
// segments) with the query in the GRID and pads q_blocks for capture, so the great majority of its
|
||||
// workgroups start and immediately return. R4D carries the query INSIDE the workgroup (up to 64
|
||||
// rows of q_len * gqa), so its grid is (splits, kv_heads, num_seqs) and has nothing dead in it.
|
||||
// Rationale: a general unified-attention kernel (vLLM's) launches (q_blocks, kv_heads, segments)
|
||||
// with q_blocks padded for capture, so most workgroups return immediately; on this shape it is
|
||||
// 8-9x slower than the window-capped DRAM bound. R4D keeps the query inside the workgroup (up to 64 rows of
|
||||
// q_len * gqa), so its grid is (splits, kv_heads, num_seqs) with no dead workgroups.
|
||||
#include "r4d.h"
|
||||
#include "r4d_common.h"
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
using std::max;
|
||||
// The decode kernel shares its query conversion and fragment helpers with the prefill one,
|
||||
// so the prefill header comes first here for the same reason it does in the h256 dispatch.
|
||||
// Nothing in this translation unit instantiates r4d_attn_prefill_kernel.
|
||||
// The decode kernel uses helpers from the prefill unit, so prefill is included first.
|
||||
// Nothing here instantiates r4d_attn_prefill_kernel.
|
||||
#include "r4d_attn_prefill_h256_gqa6.hip"
|
||||
#include "r4d_attn_decode_h256_gqa6.hip"
|
||||
|
||||
#define CHK4() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0)
|
||||
|
||||
// Tile, block size, row cap and merge: r4d_decode_launch_win (r4d_attn_decode_h256_gqa6.hip).
|
||||
#define B_HEAD_DIM 128
|
||||
#define B_GQA 4
|
||||
#define B_BLOCK_SIZE 16
|
||||
#define B_MAX_DECODE_ROWS 64 // q_len * gqa a single decode workgroup can hold
|
||||
#define B_TILE 16
|
||||
// The same option set the h256 decode kernel ships, K prefetch of 2 included. This geometry does
|
||||
// not need it -- head_dim 128 halves both the accumulator and the query, so it sits at 162-179
|
||||
// VGPRs and does not spill at 4 -- but 2 is still 0.3-1.3% faster at every concurrency and window,
|
||||
// for bit-identical output, so the two legs stay on one number -- plus O_KRAW, which loads an
|
||||
// m-tile's K codes in one round (see r4d_attn_decode_h256_gqa6.hip): at head_dim 128 that round is
|
||||
// 16 VGPRs and leaves the residency where it was.
|
||||
// The h256 decode option set, including K prefetch 2 (head_dim 128 would not spill at 4, but 2 is
|
||||
// 0.3-1.3% faster here with identical output), plus O_KRAW: one-round K loads
|
||||
// (r4d_attn_decode_h256_gqa6.hip), 16 VGPRs at head_dim 128 with no occupancy loss.
|
||||
#define B_OPT 20207163
|
||||
#ifndef B_JPB
|
||||
#define B_JPB 2
|
||||
#endif
|
||||
#ifndef B_VECMIN
|
||||
#define B_VECMIN 256
|
||||
#endif
|
||||
|
||||
extern "C" int r4d_attn_h128_gqa4_have_prefill(void) { return 0; }
|
||||
|
||||
// Split law. It aims at 192 workgroups, snaps DOWN to a power of two but never below 16, clamps to
|
||||
// at least two tiles a segment, and then steps UP off the exact grid size `splits * units == 256`,
|
||||
// which is a pothole in this geometry's timing.
|
||||
//
|
||||
// The one thing it does that the h256 law does not: under a sliding window the context the kernel
|
||||
// actually walks is the window, not the sequence, so the tile count that feeds the machine-fill
|
||||
// target and the thin-segment clamp comes from the window. Without that the law reads a 16K
|
||||
// sequence and asks for segments that are two tiles of a 129-tile walk.
|
||||
static int decode_splits_h128(const R4DArgs* a) {
|
||||
if (a->splits > 0) return a->splits;
|
||||
const int span = (a->window > 0 && a->window + a->q_len < a->max_ctx)
|
||||
? a->window + a->q_len : a->max_ctx;
|
||||
const int tiles = (span + B_TILE - 1) / B_TILE;
|
||||
const int units = std::max(1, a->kv_heads * a->num_seqs);
|
||||
const int raw = 192 / units;
|
||||
int s = 128;
|
||||
while (s > 16 && s > raw) s >>= 1;
|
||||
const int cap = tiles / 2;
|
||||
while (s > 16 && s > cap) s >>= 1;
|
||||
if (s > tiles) s = tiles;
|
||||
if (s < 1) s = 1;
|
||||
if (s * units == 256 && s * 2 <= tiles) s <<= 1; // step off the pothole, see above
|
||||
return s;
|
||||
}
|
||||
|
||||
extern "C" long r4d_attn_decode_h128_gqa4_scratch_bytes(const R4DArgs* a) {
|
||||
const int splits = decode_splits_h128(a);
|
||||
const long rows = (long)r4d_q_total(*a) * a->q_heads;
|
||||
return (B_OPT & 32) ? rows * splits * (long)(a->head_dim * 2 + 8)
|
||||
: rows * splits * (long)(a->head_dim + 2) * 4L;
|
||||
}
|
||||
|
||||
template <int KVP>
|
||||
static int decode_launch_h128(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;
|
||||
const int rows = a->q_len * B_GQA;
|
||||
if (rows > B_MAX_DECODE_ROWS) return -4;
|
||||
const int nw = (rows + 15) / 16;
|
||||
const int splits = decode_splits_h128(a);
|
||||
|
||||
#define B_LAUNCH(NW) \
|
||||
hipLaunchKernelGGL((r4d_attn_decode_kernel<NW, B_TILE, B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, \
|
||||
KVP, B_OPT, 1>), \
|
||||
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits)
|
||||
if (nw == 1) B_LAUNCH(1);
|
||||
else if (nw == 2) B_LAUNCH(2);
|
||||
else if (nw == 3) B_LAUNCH(3);
|
||||
else B_LAUNCH(4);
|
||||
#undef B_LAUNCH
|
||||
CHK4();
|
||||
|
||||
// Same two merge forms, and the same rule for choosing between them, as the h256 dispatch:
|
||||
// a wave a row while there are enough rows to fill the part and the segment count fits a
|
||||
// wave, the general LDS-tree form otherwise. Both produce the same bytes.
|
||||
const int jobs3 = r4d_q_total(*a) * a->q_heads;
|
||||
if (splits <= 64 && jobs3 >= B_VECMIN) {
|
||||
const int blocks = (jobs3 + B_JPB - 1) / B_JPB;
|
||||
if (B_OPT & 32)
|
||||
hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel<B_HEAD_DIM, 4, 1, B_JPB, 1>),
|
||||
dim3(blocks), dim3(32 * B_JPB), 0, s, *a, splits, B_TILE);
|
||||
else
|
||||
hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel<B_HEAD_DIM, 4, 0, B_JPB, 1>),
|
||||
dim3(blocks), dim3(32 * B_JPB), 0, s, *a, splits, B_TILE);
|
||||
} else if (B_OPT & 32)
|
||||
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<B_HEAD_DIM, 4, 1, 1>), dim3(jobs3),
|
||||
dim3(B_HEAD_DIM), splits * sizeof(float), s, *a, splits, B_TILE);
|
||||
else
|
||||
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<B_HEAD_DIM, 4, 0, 1>), dim3(jobs3),
|
||||
dim3(B_HEAD_DIM), splits * sizeof(float), s, *a, splits, B_TILE);
|
||||
CHK4();
|
||||
return 0;
|
||||
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 decode_launch_h128<0>(a, 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 decode_launch_h128<1>(a, s);
|
||||
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 1>(a, s);
|
||||
}
|
||||
@@ -1,37 +1,21 @@
|
||||
// R4D attention at TWELVE queries per KV head, head_dim 256 -- Qwen3.8-Flash-Next's QSA layers,
|
||||
// which are 24 query heads over 2 KV heads.
|
||||
// R4D attention at twelve queries per KV head, head_dim 256: Qwen3.8-Flash-Next's QSA layers
|
||||
// (24 query heads over 2 KV heads). Geometry only; r4d_attn_paged_gqa8.hip is the body. The ratio
|
||||
// changes two bounds, both stated in the row table:
|
||||
//
|
||||
// Four lines of geometry and the dispatch itself, because r4d_attn_paged_gqa8.hip's kernels are
|
||||
// templates on `gqa` and that unit is the parameterised body. What the ratio changes is
|
||||
// exactly two bounds, and both are in the ROW table rather than here:
|
||||
// decode verify width 64 / gqa = 5. A wider speculative verify takes the prefill kernel.
|
||||
// prefill block width 384 / gqa = 32 query positions.
|
||||
//
|
||||
// the decode verify width 64 / gqa = 5, against 8 at gqa 8 and 10 at gqa 6. A workgroup holds
|
||||
// 64 (query, head) rows and carries q_len * gqa of them, so a
|
||||
// speculative verify wider than five positions takes the prefill
|
||||
// kernel instead -- which serves any q_len and is what the row says.
|
||||
// a prefill block's width 384 / gqa = 32 query positions, against 48 at gqa 8.
|
||||
//
|
||||
// NO head_dim 128 LEG. Nothing in scope is gqa 12 at 128, and an instantiation nothing resolves is
|
||||
// a kernel nobody has run: R4D_ATTN_H128 leaves those four entry points out of this translation
|
||||
// unit entirely rather than shipping them untested.
|
||||
// No head_dim 128 leg: nothing in scope is gqa 12 at 128, so those entry points are not built.
|
||||
#define R4D_ATTN_GQA 12
|
||||
#define R4D_ATTN_H128 0
|
||||
// THE KV PAGE IS FOUR TOKENS HERE, as in the gqa 6 unit that serves the same layers at four
|
||||
// ranks; every other geometry in this library pages at 16.
|
||||
// KV page of 4 tokens (as in the gqa6-bs4 unit for the same layers at four ranks; 16 elsewhere).
|
||||
// The QSA indexer selects 4-token blocks, so a selected block is a page and sparse attention is
|
||||
// this kernel with a different block table (docs/QSA.md). The only cost is reading NB = TILE / BS
|
||||
// table entries per tile (4 at TILE 16), within step noise; output is identical.
|
||||
//
|
||||
// Qwen3.8-Flash-Next's QSA indexer selects 4-TOKEN BLOCKS of the key history. With a page of 4 a
|
||||
// selected block IS a page, so the selection is a paged block table and the sparse attention is
|
||||
// this kernel with a different table -- instead of a new attention kernel, which is the most
|
||||
// expensive kind of kernel in this tree to get right. docs/QSA.md is the decomposition.
|
||||
//
|
||||
// IT COSTS NOTHING. A page size is pure storage, so the only thing it can move is the block-table
|
||||
// walk -- `NB = TILE / BS` entries a tile instead of one, four instead of one at TILE 16 -- and at
|
||||
// a realistic context that is inside the noise of the step, with identical output either way.
|
||||
//
|
||||
// THE ROWS HAVE TO AGREE. `C_EQ("block_size", 4)` on all four gqa12 rows is what makes the core
|
||||
// size the pages at 4 (RadKVGroupDecl carries no block size on purpose -- it is taken off the
|
||||
// resolved kernel). A row that says 16 against this define is a kernel that refuses at issue
|
||||
// rather than at declare.
|
||||
// Note: the rows must agree. C_EQ("block_size", 4) on all four gqa12 rows makes the core size 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
|
||||
|
||||
#include "r4d_attn_paged_gqa8.hip"
|
||||
@@ -1,26 +1,18 @@
|
||||
// R4D attention dispatch for the Gemma 4 dense model's sliding-window geometry: head_dim 256,
|
||||
// 2 queries per KV head, paged block 16, and a SLIDING WINDOW (window 1024 in the model, 50 of its
|
||||
// 60 layers). It is the same device code as the 27B target's h256/gqa6 dispatch -- the kernels are
|
||||
// templates on head_dim and gqa, so this file is another set of instantiations, not a second
|
||||
// kernel -- with the window bit (template arg WIN) turned on, the way the DFlash2 drafter leg does
|
||||
// it at head_dim 128.
|
||||
// R4D attention dispatch for Gemma 4 dense's sliding-window layers: head_dim 256, 2 queries per KV
|
||||
// head, paged block 16, window 1024 (50 of 60 layers). Instantiations of the h256/gqa6 kernel
|
||||
// templates with WIN = 1, as the DFlash2 drafter leg does at head_dim 128.
|
||||
//
|
||||
// Both bands, now. The decode band (q_len * gqa <= 64, i.e. q_len <= 32 at gqa 2) is the
|
||||
// windowed decode kernel above. The prefill band (a query long enough to want the query-tiled
|
||||
// prefill kernel) is the windowed prefill kernel below -- the same r4d_attn_prefill_kernel the
|
||||
// h256/gqa6 dispatch instantiates, with the window bit (template arg WIN) turned on, the way the
|
||||
// decode leg does. A trunk layer prefills, so it needs the prefill band on the device:
|
||||
// libref is an opt-in fallback the engine refuses by default (spec §17). The drafter leg is
|
||||
// decode-only because a drafter never prefills.
|
||||
// Both bands: decode (q_len * gqa <= 64, so q_len <= 32) and the query-tiled prefill kernel. Unlike
|
||||
// the drafter leg, a trunk layer prefills, and the libref fallback is opt-in and refused by
|
||||
// default (spec §17).
|
||||
#include "r4d.h"
|
||||
#include "r4d_attn_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
using std::max;
|
||||
// The decode and prefill kernels share their query conversion and fragment helpers, so the prefill
|
||||
// header comes first here for the same reason it does in the h256 dispatch. This translation unit
|
||||
// instantiates BOTH r4d_attn_prefill_kernel (below, WIN=1) and the windowed decode kernel.
|
||||
// The decode kernel uses helpers from the prefill unit, so prefill is included first. Both kernels
|
||||
// are instantiated here with WIN = 1.
|
||||
#include "r4d_attn_prefill_h256_gqa6.hip"
|
||||
#include "r4d_attn_decode_h256_gqa6.hip"
|
||||
|
||||
@@ -29,110 +21,26 @@ using std::max;
|
||||
#define B_HEAD_DIM 256
|
||||
#define B_GQA 2
|
||||
#define B_BLOCK_SIZE 16
|
||||
#define B_MAX_DECODE_ROWS 64 // q_len * gqa a single decode workgroup can hold
|
||||
#define B_TILE 16
|
||||
// The same option set the h256 decode kernel ships, K prefetch of 2 included. At head_dim 256 it
|
||||
// is the same register picture gqa6 has (256 VGPRs with a small spill), so this is a correctness
|
||||
// instantiation here -- the register count is a 3b tuning question, not a 3a one. The window bit
|
||||
// is already in the template; this file only turns it on.
|
||||
#define B_TILE 16 // decode: r4d_decode_launch_win (r4d_attn_decode_h256_gqa6.hip)
|
||||
// The h256 decode option set, K prefetch 2 included. Same register use as gqa6 (256 VGPRs, small
|
||||
// spill); not separately tuned for this geometry.
|
||||
#define B_OPT 3429947
|
||||
#ifndef B_JPB
|
||||
#define B_JPB 2
|
||||
#endif
|
||||
#ifndef B_VECMIN
|
||||
#define B_VECMIN 256
|
||||
#endif
|
||||
|
||||
// Split law, the drafter leg's with the same window-aware term. It aims at 192 workgroups, snaps
|
||||
// DOWN to a power of two but never below 16, clamps to at least two tiles a segment, and then steps
|
||||
// UP off the exact grid size `splits * units == 256`, a pothole in this geometry's timing.
|
||||
//
|
||||
// THE WINDOW-AWARE TERM is the one thing it does that the h256 full-attention law does not: under a
|
||||
// sliding window the context the kernel actually walks is the window, not the sequence, so the tile
|
||||
// count that feeds the machine-fill target and the thin-segment clamp comes from the window.
|
||||
// Without that the law reads a 16K sequence and asks for segments two tiles deep off a 1024-token
|
||||
// walk.
|
||||
static int decode_splits_h256_gqa2(const R4DArgs* a) {
|
||||
if (a->splits > 0) return a->splits;
|
||||
const int span = (a->window > 0 && a->window + a->q_len < a->max_ctx)
|
||||
? a->window + a->q_len : a->max_ctx;
|
||||
const int tiles = (span + B_TILE - 1) / B_TILE;
|
||||
const int units = std::max(1, a->kv_heads * a->num_seqs);
|
||||
const int raw = 192 / units;
|
||||
int s = 128;
|
||||
while (s > 16 && s > raw) s >>= 1;
|
||||
const int cap = tiles / 2;
|
||||
while (s > 16 && s > cap) s >>= 1;
|
||||
if (s > tiles) s = tiles;
|
||||
if (s < 1) s = 1;
|
||||
if (s * units == 256 && s * 2 <= tiles) s <<= 1; // step off the pothole, see above
|
||||
return s;
|
||||
}
|
||||
|
||||
extern "C" long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a) {
|
||||
const int splits = decode_splits_h256_gqa2(a);
|
||||
const long rows = (long)r4d_q_total(*a) * a->q_heads;
|
||||
return (B_OPT & 32) ? rows * splits * (long)(a->head_dim * 2 + 8)
|
||||
: rows * splits * (long)(a->head_dim + 2) * 4L;
|
||||
}
|
||||
|
||||
template <int KVP>
|
||||
static int decode_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;
|
||||
const int rows = a->q_len * B_GQA;
|
||||
if (rows > B_MAX_DECODE_ROWS) return -4;
|
||||
const int nw = (rows + 15) / 16;
|
||||
const int splits = decode_splits_h256_gqa2(a);
|
||||
|
||||
#define B_LAUNCH(NW) \
|
||||
hipLaunchKernelGGL((r4d_attn_decode_kernel<NW, B_TILE, B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, \
|
||||
KVP, B_OPT, 1>), \
|
||||
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits)
|
||||
if (nw == 1) B_LAUNCH(1);
|
||||
else if (nw == 2) B_LAUNCH(2);
|
||||
else if (nw == 3) B_LAUNCH(3);
|
||||
else B_LAUNCH(4);
|
||||
#undef B_LAUNCH
|
||||
CHK4();
|
||||
|
||||
// Same two merge forms, and the same rule for choosing between them, as the h256 dispatch:
|
||||
// a wave a row while there are enough rows to fill the part and the segment count fits a
|
||||
// wave, the general LDS-tree form otherwise. Both produce the same bytes, and both carry the
|
||||
// window bit here (the final template argument) for the same reason the decode kernel does.
|
||||
const int jobs3 = r4d_q_total(*a) * a->q_heads;
|
||||
if (splits <= 64 && jobs3 >= B_VECMIN) {
|
||||
const int blocks = (jobs3 + B_JPB - 1) / B_JPB;
|
||||
if (B_OPT & 32)
|
||||
hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel<B_HEAD_DIM, 4, 1, B_JPB, 1>),
|
||||
dim3(blocks), dim3(32 * B_JPB), 0, s, *a, splits, B_TILE);
|
||||
else
|
||||
hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel<B_HEAD_DIM, 4, 0, B_JPB, 1>),
|
||||
dim3(blocks), dim3(32 * B_JPB), 0, s, *a, splits, B_TILE);
|
||||
} else if (B_OPT & 32)
|
||||
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<B_HEAD_DIM, 4, 1, 1>), dim3(jobs3),
|
||||
dim3(B_HEAD_DIM), splits * sizeof(float), s, *a, splits, B_TILE);
|
||||
else
|
||||
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<B_HEAD_DIM, 4, 0, 1>), dim3(jobs3),
|
||||
dim3(B_HEAD_DIM), splits * sizeof(float), s, *a, splits, B_TILE);
|
||||
CHK4();
|
||||
return 0;
|
||||
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 decode_launch_h256_gqa2<0>(a, s);
|
||||
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 0>(a, s);
|
||||
}
|
||||
extern "C" int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s) {
|
||||
return decode_launch_h256_gqa2<1>(a, s);
|
||||
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 1>(a, s);
|
||||
}
|
||||
|
||||
// ---- prefill ---------------------------------------------------------------------------------
|
||||
// The h256/gqa6 prefill option set (P_OPT 3955211) is reused unchanged: at head_dim 256 the wide K
|
||||
// fetch (O_KWIDE) is valid -- it is written for 16 channels = head_dim 256 exactly, and a wider head
|
||||
// would read past the tile -- so this leg keeps it. gqa 2 makes
|
||||
// BLOCK_Q (NWARPS*16/2 = 192) larger than gqa 6's 64, so a workgroup covers more query positions:
|
||||
// fewer grid.x blocks, the same KV tile. WIN is on (the last template arg); window <= 0 folds it
|
||||
// away to the full-attention form, so a windowless launch is safe.
|
||||
// The h256/gqa6 prefill option set but at K prefetch 4 (P_OPT there is 3954187); O_KWIDE is valid
|
||||
// at head_dim 256. At gqa 2 a block covers NWARPS * 16 / 2 = 192 query positions. WIN is on;
|
||||
// window <= 0 gives full attention.
|
||||
#define P_NWARPS 24
|
||||
#define P_TILE 48
|
||||
#define P_OPT 3955211
|
||||
@@ -157,9 +65,8 @@ extern "C" int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s
|
||||
return prefill_launch_h256_gqa2<1>(a, s);
|
||||
}
|
||||
|
||||
/* The prefill RadArgs wrappers, defined here (not in the h256 dispatch): an entry point appended to
|
||||
* a textual inclusion compiles into nothing.
|
||||
* Absent descales mean 1.0 (fill_paged leaves them null and the kernel reads 1.0). */
|
||||
/* 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) {
|
||||
R4DArgs r;
|
||||
int rc = fill_paged(a, &r, B_HEAD_DIM);
|
||||
|
||||
@@ -1,19 +1,13 @@
|
||||
// R4D attention at FOUR queries per KV head, head_dim 256 -- Qwen3.5-0.8B and its siblings that
|
||||
// keep the 27B's head width with fewer heads (8 query heads over 2 KV heads).
|
||||
// R4D attention at four queries per KV head, head_dim 256: Qwen3.5-0.8B and siblings (8 query heads
|
||||
// over 2 KV heads). Geometry only; r4d_attn_paged_gqa8.hip is the body. The ratio changes two
|
||||
// bounds, both stated in the row table:
|
||||
//
|
||||
// The geometry and the dispatch only, as r4d_attn_paged_h256_gqa12.hip is: r4d_attn_paged_gqa8.hip
|
||||
// is the parameterised body and its kernels are templates on `gqa`. What the ratio changes is the
|
||||
// two bounds, and both are in the ROW table rather than here:
|
||||
// decode verify width 64 / gqa = 16.
|
||||
// prefill block width 384 / gqa = 96 query positions.
|
||||
//
|
||||
// the decode verify width 64 / gqa = 16, against 8 at gqa 8 and 10 at gqa 6. A workgroup holds
|
||||
// 64 (query, head) rows and carries q_len * gqa of them.
|
||||
// a prefill block's width 384 / gqa = 96 query positions, against 48 at gqa 8.
|
||||
//
|
||||
// NO head_dim 128 LEG. gqa 4 at 128 is the DFlash2 drafter's windowed geometry, which
|
||||
// r4d_attn_paged_h128_gqa4.hip serves; R4D_ATTN_H128 leaves those entry points out of this unit.
|
||||
// A head_dim 64 PREFILL leg, for LFM2 (32 query heads over 8, d1-3B among them), which serves
|
||||
// every query length: the split-KV decode kernel has no 64-wide form.
|
||||
// The page is the body's default 16.
|
||||
// No head_dim 128 leg: gqa 4 at 128 is the DFlash2 drafter's windowed geometry, served by
|
||||
// r4d_attn_paged_h128_gqa4.hip. A head_dim 64 prefill leg serves LFM2 (32 query heads over 8) at
|
||||
// every query length, since the split-KV decode kernel has no 64-wide form. Page size 16.
|
||||
#define R4D_ATTN_GQA 4
|
||||
#define R4D_ATTN_H128 0
|
||||
#define R4D_ATTN_H64 1
|
||||
|
||||
@@ -1,24 +1,20 @@
|
||||
// R4D attention dispatch. One translation unit so the KV-dtype variants share the device code:
|
||||
// each is a template instantiation, not a copy. The entry points are named for the geometry they
|
||||
// are compiled for (head_dim 256, 6 queries per KV head, paged block 16) because that geometry is
|
||||
// a hard gate -- everything else is rejected below rather than run.
|
||||
// R4D paged attention dispatch for head_dim 256, 6 queries per KV head, paged block 16. The
|
||||
// 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 variant. A single-term 8-bit query is an order of magnitude worse
|
||||
// against an fp32 reference (2.58e-02 relative against ~2.3e-03), and the two-term e4m3 form that
|
||||
// DOES reach f16 accuracy is 4-10% slower end to end, so no 8-bit query variant is compiled. Two
|
||||
// families ship, differing only in KV cache dtype: bf16 KV (all 16-bit) and fp8 KV (16/8 mixed,
|
||||
// the production configuration).
|
||||
// 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), 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 fp8
|
||||
// (the production configuration).
|
||||
//
|
||||
// `opt` is a bitmask of the optimisation steps, all of them on:
|
||||
// `opt` is a bitmask of optimisation steps:
|
||||
// prefill 3954187 = f16 operands | mask skip | folded query scale | contiguous-k fragments
|
||||
// | prefetch 2 + scheduling barrier | dot2 row sum | block table in SGPRs
|
||||
// | wide K fetch | V prefetch across the m-tile loop | LDS-scoped barrier
|
||||
// decode 3429947 = the same, minus the wide K fetch (its K never reaches LDS), with the K
|
||||
// prefetch at 2 rather than 4, plus reading K straight from the paged cache
|
||||
// (bit 16) and f16 split-KV partials (32).
|
||||
// Each bit is defined and justified where it is used, in r4d_attn_prefill_h256_gqa6.hip and
|
||||
// r4d_attn_decode_h256_gqa6.hip.
|
||||
// They are kept separable so any one of them can be turned off on its own after a geometry change.
|
||||
// decode 3429947 = the same minus the wide K fetch (its K never reaches LDS), plus K read
|
||||
// straight from the paged cache (bit 16) and f16 split-KV partials (32).
|
||||
// Each bit is defined where it is used (r4d_attn_prefill_h256_gqa6.hip,
|
||||
// r4d_attn_decode_h256_gqa6.hip) and can be turned off on its own after a geometry change.
|
||||
#include "r4d.h"
|
||||
#include "r4d_attn_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -30,9 +26,8 @@ using std::max;
|
||||
|
||||
#define CHK() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0)
|
||||
|
||||
// The geometry every kernel in this translation unit is compiled for. HEAD_DIM and GQA appear in
|
||||
// the entry-point names; BLOCK_SIZE does not, because it is 16 for the whole library and so
|
||||
// discriminates nothing between them.
|
||||
// The geometry of every kernel in this unit. BLOCK_SIZE is not in the entry-point names because
|
||||
// it is 16 for all of them.
|
||||
#define A_HEAD_DIM 256
|
||||
#define A_GQA 6
|
||||
#define A_BLOCK_SIZE 16
|
||||
@@ -46,13 +41,12 @@ extern "C" void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max
|
||||
}
|
||||
|
||||
// ---- prefill ---------------------------------------------------------------------------------
|
||||
// LDS, head_dim 256, 16-bit K and V: sK = TILE*264*2, sV = 256*(TILE+8)*2. bf16 KV at TILE 64
|
||||
// would need 68096 B > 65536, so the geometry stops at 48.
|
||||
// LDS at head_dim 256, 16-bit K and V: sK = TILE*264*2, sV = 256*(TILE+8)*2. TILE 64 would need
|
||||
// 68096 B > 65536, so TILE is 48.
|
||||
#define P_NWARPS 24
|
||||
#define P_TILE 48
|
||||
// K PREFETCH 2, NOT 4. Four fragments in flight hold more than the m-tile loop has to give at six
|
||||
// waves a SIMD, and the loop then spills: LLVM 22 to 36 bytes a lane and LLVM 24 to 48, which cost
|
||||
// LLVM 24 4% of the prefill. At 2 both compilers spill the same 20 bytes, outside the WMMA groups.
|
||||
// K prefetch 2, not 4: four fragments in flight make the m-tile loop spill at six waves per SIMD
|
||||
// (36-48 bytes per lane, ~4% of the prefill). At 2 the spill is 20 bytes, outside the WMMA groups.
|
||||
#define P_OPT 3954187
|
||||
|
||||
// KVP: 0 = fp8 e4m3 cache, 1 = bf16 cache. Reached only through the two named wrappers below.
|
||||
@@ -77,72 +71,23 @@ extern "C" int r4d_attn_prefill_h256_gqa6_bf16kv(const R4DArgs* a, hipStream_t s
|
||||
}
|
||||
|
||||
// ---- decode ----------------------------------------------------------------------------------
|
||||
#ifndef D_TILE
|
||||
#define D_TILE 16
|
||||
#endif
|
||||
// The decode leg prefetches TWO K fragments per WMMA group, not four. Four costs 8 more VGPRs at
|
||||
// the peak of the QK loop and that is exactly the amount this kernel is over: it allocates 256
|
||||
// VGPRs, spills 18 of them, and reloads three 16-byte groups of the query FROM SCRATCH ON EVERY
|
||||
// TILE. Two fits in 255 with no spill and is 1.7-7.5% faster across concurrency and depth, for
|
||||
// bit-identical output.
|
||||
#ifndef D_OPT
|
||||
// Decode prefetches two K fragments per WMMA group, not four. Four costs 8 more VGPRs at the peak
|
||||
// of the QK loop and spills 18, reloading part of the query from scratch on every tile. Two fits in
|
||||
// 255 VGPRs and is 1.7-7.5% faster, with identical output.
|
||||
#define D_OPT 3429947
|
||||
#endif
|
||||
// Output rows per block in the vectorised merge: 32 threads own a row, so this is the block width
|
||||
// in waves. 1, 2 and 4 are within 1% of each other everywhere the vectorised form is taken; 2 is
|
||||
// the best of them on average across concurrency and depth.
|
||||
#ifndef D_JPB
|
||||
// Output rows (waves) per block in the vectorised merge. 1, 2 and 4 are within 1%; 2 is best on
|
||||
// average.
|
||||
#define D_JPB 2
|
||||
#endif
|
||||
// Output rows below which the vectorised merge is NOT taken. It gives a row 32 lanes where the
|
||||
// general form gives it 256, so it trades parallelism for eight-times-fewer load instructions --
|
||||
// and that trade is only good while there are enough rows to fill the part. At one request there
|
||||
// are 96 rows and the segment count is at its largest (the split law scales splits with 1/num_seqs),
|
||||
// so each of 96 waves walks 64 segments on an idle machine and the vectorised form LOSES up to
|
||||
// 23%. The crossover is around 192 rows, and above 288 the vectorised form wins by 1.2-20%; the
|
||||
// cut is set at four rows per CU.
|
||||
#ifndef D_VECMIN
|
||||
// Minimum output rows for the vectorised merge. It gives a row 32 lanes instead of 256, trading
|
||||
// parallelism for 8x fewer loads, which pays only when there are enough rows to fill the GPU. At
|
||||
// one request (96 rows, most segments) it loses up to 23%; the crossover is ~192 rows and above
|
||||
// 288 it wins by 1.2-20%. The cut is four rows per CU.
|
||||
#define D_VECMIN 256
|
||||
#endif
|
||||
|
||||
// Split law: AS MANY WORKGROUPS AS FIT UNDER 128. `splits * kv_heads * num_seqs` is the whole
|
||||
// grid, and 128 of them is the argmin at every concurrency this serve reaches on this geometry.
|
||||
//
|
||||
// THE COUNT IS `128 / units`, NOT THE LARGEST POWER OF TWO UNDER IT. A power of two lands exactly
|
||||
// on 128 only when units is one too -- one, two, four and eight requests -- and at three, five,
|
||||
// six and seven it lands on 96, 80, 96 and 112 workgroups instead, which is a third of the part
|
||||
// idle in the last round. `floor(128 / units)` is the argmin at all eight, worth 2-20% over a
|
||||
// power-of-two law at the four counts where they differ.
|
||||
//
|
||||
// Nearby counts are not interchangeable: at five requests 13 splits is 130 workgroups, three
|
||||
// rounds of 64 for two rounds of work, and is slower than 12. UNDER a multiple of 64 is what
|
||||
// matters, not near it.
|
||||
//
|
||||
// What the count buys is partial-buffer traffic, not parallelism. The split-KV scratch is
|
||||
// `seqs x q_len x q_heads x splits` rows of head_dim f16, written once by the decode kernel and
|
||||
// read back once by the combine: at eight requests that is 12.8 MB at splits 32 against 3.2 at 8,
|
||||
// which is 19% of a 16K step's KV and 1.2% of a 128K one. So the win shrinks with depth -- a few
|
||||
// percent up to 16K, under 2% at 64K and a wash at 128K -- and never reverses enough to be worth a
|
||||
// context term.
|
||||
static int decode_splits(const R4DArgs* a) {
|
||||
if (a->splits > 0) return a->splits;
|
||||
const int tiles = (a->max_ctx + D_TILE - 1) / D_TILE;
|
||||
const int units = max(1, a->kv_heads * a->num_seqs);
|
||||
int s = 128 / units; // as many workgroups as fit under 128
|
||||
const int cap = tiles / 2; // >= 2 tiles per segment
|
||||
if (s > cap) s = cap;
|
||||
if (s > tiles) s = tiles;
|
||||
if (s < 1) s = 1;
|
||||
return s;
|
||||
}
|
||||
|
||||
// Same for both cache dtypes: the split law does not read the dtype, and the partials are f16
|
||||
// either way (opt bit 32).
|
||||
// Split law: r4d_decode_splits (r4d_attn_decode_h256_gqa6.hip).
|
||||
extern "C" long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a) {
|
||||
const int splits = decode_splits(a);
|
||||
const long rows = (long)r4d_q_total(*a) * a->q_heads;
|
||||
return (D_OPT & 32) ? rows * splits * (long)(a->head_dim * 2 + 8) // f16 O/l + m + l
|
||||
: rows * splits * (long)(a->head_dim + 2) * 4L; // f32 O partials + m + l
|
||||
return r4d_decode_scratch(a, r4d_decode_splits(a, D_TILE), D_OPT);
|
||||
}
|
||||
|
||||
template <int KVP>
|
||||
@@ -152,7 +97,7 @@ static int decode_launch(const R4DArgs* a, hipStream_t s) {
|
||||
const int rows = a->q_len * A_GQA;
|
||||
if (rows > A_MAX_DECODE_ROWS) return -4; // verify width <= 10 at gqa 6
|
||||
const int nw = (rows + 15) / 16; // gqa-aligned height; no dead m-tiles issued
|
||||
const int splits = decode_splits(a);
|
||||
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, \
|
||||
@@ -165,11 +110,9 @@ static int decode_launch(const R4DArgs* a, hipStream_t s) {
|
||||
#undef D_LAUNCH
|
||||
CHK();
|
||||
|
||||
// The vectorised merge owns a row per WAVE, so its wave-wide sum only reproduces the general
|
||||
// path's LDS tree while the segment count fits 64 lanes-worth. Past that -- reachable only
|
||||
// when kv_heads * num_seqs is 1, where the law asks for 128 splits -- fall back rather than
|
||||
// change the merge order. Both forms produce the same bytes; which one runs is a speed choice
|
||||
// only.
|
||||
// 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;
|
||||
if (splits <= 64 && jobs3 >= D_VECMIN) {
|
||||
const int blocks = (jobs3 + D_JPB - 1) / D_JPB;
|
||||
@@ -198,14 +141,11 @@ extern "C" int r4d_attn_decode_h256_gqa6_bf16kv(const R4DArgs* a, hipStream_t s)
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader is r4d_attn_args.h, a header this kernel family shares because the paged
|
||||
// geometries implement one op and take one operand list. See libr4d/r4d_args.h for why there is no
|
||||
// adapter directory between the core and these launches.
|
||||
// The operand reader is r4d_attn_args.h, shared by every paged geometry.
|
||||
//
|
||||
// THEY GO IN THE TRANSLATION UNIT AND NOT IN THE FILES IT #includes. r4d_attn_prefill_*.hip and
|
||||
// r4d_attn_decode_*.hip are textual inclusions of this one -- appending an entry point to either
|
||||
// compiles it into nothing, and the .so then carries an UNDEFINED symbol that no build step
|
||||
// reports. The plugin still links; only r4d_selftest catches the missing symbol.
|
||||
// Note: entry points belong in this translation unit, not in the r4d_attn_prefill_*.hip or
|
||||
// r4d_attn_decode_*.hip files it includes. An entry point added there does not get compiled, and
|
||||
// the .so carries an undefined symbol that only r4d_selftest catches.
|
||||
/* ------------------------------------------------------------------ paged prefill */
|
||||
|
||||
extern "C" int r4d_rad_attn_prefill_h256_fp8(const RadArgs* a, RadStream s) {
|
||||
@@ -213,13 +153,10 @@ extern "C" int r4d_rad_attn_prefill_h256_fp8(const RadArgs* a, RadStream s) {
|
||||
R4DArgs r;
|
||||
int rc = fill_paged(a, &r, 256);
|
||||
if (rc != RAD_OK) return rc;
|
||||
/* ABSENT DESCALES MEAN 1.0, they are not an error. The kernels already spell it that way --
|
||||
* `a.k_descale ? a.k_descale[seq * kv_heads + kvh] : 1.0f` -- and 1.0 is what vLLM defaults
|
||||
* both scales to, so a cache written by kv_store_fp8 at its default scale is read back by
|
||||
* exactly this path with no descale plane to allocate, fill or keep in step. Refusing here
|
||||
* would make the operands mandatory in the shim while they stay optional in the schema and
|
||||
* optional in the kernel, which is three answers to one question. A CALIBRATED pair still
|
||||
* works: pass the operands and they are used. */
|
||||
/* 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);
|
||||
}
|
||||
|
||||
@@ -233,30 +170,19 @@ extern "C" int r4d_rad_attn_prefill_h256_bf16(const RadArgs* a, RadStream s) {
|
||||
|
||||
/* ------------------------------------------------------------------ paged decode */
|
||||
|
||||
/* The split-KV partial buffer. The decode kernel writes it and the combine reads it back, and
|
||||
* nothing else touches it -- so it is arena scratch, sized at declare from the band's upper bound
|
||||
* exactly as RadScratchFn intends.
|
||||
/* Split-KV partial buffer: written by the decode kernel, read by the combine, nothing else. Arena
|
||||
* scratch sized at declare from the band's upper bound (RadScratchFn).
|
||||
*
|
||||
* IT IS CALLED WITH PARAMETERS AND NO TENSORS. That is what declare is: the op is known, the batch
|
||||
* is not, and there is nothing to point at yet. So the parameters are the primary source here and
|
||||
* the tensors are the fallback, not the other way round -- reading tensors first makes this hook
|
||||
* refuse every attn_paged row in the model with "invalid argument", which presents as a pile of
|
||||
* missing kernels rather than as one hook asking the wrong question.
|
||||
* Declare passes parameters and no tensors (the batch is not known yet), so parameters are the
|
||||
* primary source and tensors the fallback. Reading tensors first would refuse every attn_paged
|
||||
* row with "invalid argument". q_len is the band's upper bound, since the region is sized once
|
||||
* for the worst step.
|
||||
*
|
||||
* q_len is the band's upper bound, deliberately: this region is sized once for the worst step the
|
||||
* arena will ever hold, so the bound is the right number and a per-step count would be the wrong
|
||||
* one.
|
||||
*
|
||||
* THE SEQUENCE COUNT IS EVERY COUNT UP TO max_seqs, NOT max_seqs ALONE. Both split laws hand a
|
||||
* step of S sequences a split count that falls as S grows -- about 128 / (kv_heads * S) -- so the
|
||||
* partials are S * splits(S) rows a (query position, head), and that product is not monotone in
|
||||
* S: at kv_heads 2 the h256 law gives 60 at twelve sequences and 63 at nine, and the h128 law's
|
||||
* step off its pothole doubles the splits at one count and not at the next. A step may carry any
|
||||
* count up to the bound, so the region is the largest over all of them. The laws are closed forms
|
||||
* and this runs at declare, so the sweep costs nothing a step. */
|
||||
// One hook per geometry but one shared (seqs x heads x rows) partial layout, so the worst-over-
|
||||
// the-batch sweep below asks each geometry its own bytes in one place instead of triplicating the
|
||||
// sweep. which: 0 = h256/gqa6, 1 = h128/gqa4, 2 = h256/gqa2 (the Gemma 4 windowed leg).
|
||||
* The size is the maximum over every sequence count up to max_seqs: S * splits(S) is not monotone
|
||||
* in S (at kv_heads 2 the h256 law gives 60 at twelve sequences and 63 at nine, and the h128 law's
|
||||
* step-up doubles splits at one count only). The laws are closed forms, so the sweep is cheap. */
|
||||
// Per-geometry byte counts over the shared partial layout, so one sweep serves all.
|
||||
// which: 0 = h256/gqa6, 1 = h128/gqa4, 2 = h256/gqa2 (Gemma 4 windowed).
|
||||
static int64_t decode_scratch_bytes_of(const R4DArgs* r, int which) {
|
||||
if (which == 1) return (int64_t)r4d_attn_decode_h128_gqa4_scratch_bytes(r);
|
||||
if (which == 2) return (int64_t)r4d_attn_decode_h256_gqa2_scratch_bytes(r);
|
||||
@@ -281,8 +207,8 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which) {
|
||||
r.max_ctx = (int)r4d_geti_or(a, "max_ctx", 0);
|
||||
r.block_size = (int)r4d_geti_or(a, "block_size", 16);
|
||||
r.splits = sp;
|
||||
/* max_ctx feeds the split law only. Zero would make it choose one split, which UNDERSIZES
|
||||
* the buffer for the launch that later picks more, so refuse rather than guess low. */
|
||||
/* max_ctx feeds only the split law. Zero would pick one split and undersize the buffer
|
||||
* for a launch that later picks more, so refuse. */
|
||||
if (r.max_ctx <= 0) return R4D_NO(RAD_E_INVAL);
|
||||
int64_t worst = 0;
|
||||
for (long long n = 1; n <= max_seqs; ++n) {
|
||||
@@ -350,10 +276,9 @@ 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);
|
||||
}
|
||||
|
||||
/* Gemma 4 dense sliding window -- head_dim 256, 2 queries per KV head, window 1024. Decode only;
|
||||
* a prefill step does not match the row's q_len band and takes the caller's (windowed) fallback.
|
||||
* Same shape as the drafter leg above (h128): one `which` routing to the gqa2 scratch law and the
|
||||
* gqa2 decode launch, no check_dims_once because this is not the geometry that reports dims. */
|
||||
/* 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. */
|
||||
extern "C" int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs* a) {
|
||||
return decode_scratch(a, 256, 2);
|
||||
}
|
||||
|
||||
@@ -1,44 +1,23 @@
|
||||
// R4D attention at SIX queries per KV head, head_dim 256 -- the same QSA layers of
|
||||
// Qwen3.8-Flash-Next that r4d_attn_paged_h256_gqa12.hip serves at two ranks, served at FOUR: the
|
||||
// two KV heads are replicated across the rank pairs, so each rank answers 6 queries for the one KV
|
||||
// head it holds and the ratio the constraint table gates on is 6 rather than 12.
|
||||
// R4D attention at six queries per KV head, head_dim 256: Qwen3.8-Flash-Next's QSA layers at four
|
||||
// ranks (r4d_attn_paged_h256_gqa12.hip serves them at two). The two KV heads are replicated across
|
||||
// rank pairs, so each rank serves 6 queries for its one KV head. Geometry only;
|
||||
// r4d_attn_paged_gqa8.hip is the body. The ratio changes two bounds, both stated in the row table:
|
||||
//
|
||||
// Four lines of geometry and the dispatch itself, because r4d_attn_paged_gqa8.hip's kernels are
|
||||
// templates on `gqa` and that unit is the parameterised body. What the ratio changes is
|
||||
// exactly two bounds, and both are in the ROW table rather than here:
|
||||
// decode verify width 64 / gqa = 10. MTP's K=3 verify (q_len 4) fits either ratio; a draft
|
||||
// block of six or seven positions fits decode here but not at gqa 12.
|
||||
// prefill block width 384 / gqa = 64 query positions.
|
||||
//
|
||||
// the decode verify width 64 / gqa = 10, against 5 at gqa 12 and 8 at gqa 8. A workgroup holds
|
||||
// 64 (query, head) rows and carries q_len * gqa of them, so this is
|
||||
// the WIDEST of the three legs: MTP's K=3 verify is q_len 4 and fits
|
||||
// either ratio, and a draft block of six or seven positions -- which
|
||||
// the gqa12 leg has to send to the prefill kernel -- fits the decode
|
||||
// kernel here.
|
||||
// a prefill block's width 384 / gqa = 64 query positions, against 32 at gqa 12 and 48 at
|
||||
// gqa 8.
|
||||
//
|
||||
// NO head_dim 128 LEG, for the gqa12 file's reason: nothing in scope is gqa 6 at 128, and an
|
||||
// instantiation nothing resolves is a kernel nobody has run. R4D_ATTN_H128 leaves those four entry
|
||||
// points out of this translation unit entirely rather than shipping them untested.
|
||||
// No head_dim 128 leg: nothing in scope is gqa 6 at 128, so those entry points are not built.
|
||||
#define R4D_ATTN_GQA 6
|
||||
#define R4D_ATTN_H128 0
|
||||
// THE KV PAGE IS FOUR TOKENS HERE, as in the gqa 12 unit; every other geometry in this library
|
||||
// pages at 16.
|
||||
// KV page of 4 tokens, as in the gqa12 unit (the model's page; TP4 changes only queries per head).
|
||||
// The QSA indexer selects 4-token blocks, so a selected block is a page and sparse attention is
|
||||
// this kernel with a different block table (docs/QSA.md). The only cost is reading NB = TILE / BS
|
||||
// table entries per tile, within step noise; output is identical.
|
||||
//
|
||||
// Qwen3.8-Flash-Next's QSA indexer selects 4-TOKEN BLOCKS of the key history. With a page of 4 a
|
||||
// selected block IS a page, so the selection is a paged block table and the sparse attention is
|
||||
// this kernel with a different table -- instead of a new attention kernel, which is the most
|
||||
// expensive kind of kernel in this tree to get right. docs/QSA.md is the decomposition. The page
|
||||
// is 4 at this ratio for exactly the reason it is 4 at gqa 12 -- the model's page, not the
|
||||
// parallelism's; what TP4 changes is the queries a head, not the storage.
|
||||
//
|
||||
// IT COSTS NOTHING. A page size is pure storage, so the only thing it can move is the block-table
|
||||
// walk -- `NB = TILE / BS` entries a tile instead of one, four instead of one at TILE 16 -- and at
|
||||
// a realistic context that is inside the noise of the step, with identical output either way.
|
||||
//
|
||||
// THE ROWS HAVE TO AGREE. `C_EQ("block_size", 4)` on all four gqa6-bs4 rows is what makes the core
|
||||
// size the pages at 4 (RadKVGroupDecl carries no block size on purpose -- it is taken off the
|
||||
// resolved kernel). A row that says 16 against this define is a kernel that refuses at issue
|
||||
// rather than at declare.
|
||||
// Note: the rows must agree. C_EQ("block_size", 4) on all four gqa6-bs4 rows makes the core size
|
||||
// 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
|
||||
|
||||
#include "r4d_attn_paged_gqa8.hip"
|
||||
@@ -1,22 +1,20 @@
|
||||
/* r4d_attn_paged_window.hip -- paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV
|
||||
* head, ANY sliding window, causal or not, bf16 or fp8-e4m3 cache, q at any row pitch.
|
||||
* head, any sliding window, causal or not, bf16 or fp8-e4m3 cache, q at any row pitch.
|
||||
*
|
||||
* Gemma 4's text layers are two of these geometries: its sliding layers are 16 query heads over 8
|
||||
* KV heads at head_dim 256 with a 1024-token window (gqa 2 at every TP), and its full layers 16
|
||||
* over 2 at head_dim 512 (gqa 8 at TP1/TP2, 4 at TP4, 2 at TP8). The library's other h256 legs are
|
||||
* gqa 2 (windowed, q dense) and gqa 4/6/8/12 (`window == 0`); the row table says which serves
|
||||
* where two meet (r4d_rows.cpp).
|
||||
* Gemma 4's text layers: sliding layers are 16 query heads over 8 KV heads at head_dim 256 with a
|
||||
* 1024-token window (gqa 2 at every TP); full layers are 16 over 2 at head_dim 512 (gqa 8 at
|
||||
* TP1/TP2, 4 at TP4, 2 at TP8). Where this overlaps the library's other h256 legs, the row table
|
||||
* decides (r4d_rows.cpp).
|
||||
*
|
||||
* WHAT THIS IS. Two kernels behind one entry point. The scalar one, for decode and verify steps: one
|
||||
* workgroup owns one (sequence, KV head, slice of BQ query positions, split of the key range); each
|
||||
* wave owns RW of the tile's R = BQ*gqa query rows; K and V come through LDS one paged block (or
|
||||
* two) at a time, prefetched into registers while the previous tile is being consumed; the dot
|
||||
* products are scalar FMAs with a butterfly reduce-scatter that leaves key j's score in lane j; the
|
||||
* softmax is online, in the log2 domain. It is memory-bound at decode, where that is the only thing
|
||||
* that matters. A prefill-shaped launch takes the WMMA kernel further down instead (its own header
|
||||
* says how), which feeds RDNA4's matrix cores.
|
||||
* Two kernels behind one entry point:
|
||||
* - Scalar, for decode and verify: a workgroup owns one (sequence, KV head, slice of BQ query
|
||||
* positions, split of the key range); each wave owns RW of the tile's R = BQ*gqa query rows.
|
||||
* K/V go through LDS one or two paged blocks at a time, prefetched into registers while the
|
||||
* previous tile is consumed. Dot products are scalar FMAs with a butterfly reduce-scatter that
|
||||
* leaves key j's score in lane j; online softmax in the log2 domain. Memory-bound at decode.
|
||||
* - WMMA, for prefill-shaped launches (see its header below).
|
||||
*
|
||||
* WHAT IT COMPUTES is libref's ref_attn_paged, predicate for predicate:
|
||||
* Both compute libref's ref_attn_paged, predicate for predicate:
|
||||
* pos = seqused[s] - q_len(s) + i (seqused INCLUDES this step's queries)
|
||||
* causal key j visible when j <= pos; non-causal when j < seqused[s]
|
||||
* window causal: pos - j < window; non-causal: |pos - j| < window; 0 = none
|
||||
@@ -24,16 +22,15 @@
|
||||
* no visible key at all -> a zero row
|
||||
* k_descale / v_descale per (sequence, kv head), absent = 1
|
||||
*
|
||||
* THE PAGED LAYOUT is kv_cache[n_blocks, kv_heads, 16, 2*head_dim], K then V inside a slot, which
|
||||
* makes one block of one KV head ONE contiguous run of 16 * 2 * head_dim elements: a key tile is
|
||||
* one or two such runs, fetched as 16-byte loads.
|
||||
* 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.
|
||||
*
|
||||
* SPLIT-KV. A launch with few (tile, kv head) pairs -- a decode step, a short verify -- would leave
|
||||
* most of the card idle, so the key range of each tile is cut into `n_split` pieces, each written
|
||||
* as an unnormalised partial (acc, max, sum) into the op's scratch, and a second kernel merges
|
||||
* them. The split count is chosen at launch from host-side numbers only (rows, sequences, the
|
||||
* window or max_ctx); each workgroup divides ITS OWN key range by it, so a split that receives no
|
||||
* keys writes (0, -inf, 0) and the merge needs no host knowledge of the device-side context.
|
||||
* 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
|
||||
* second kernel. The split count comes from host-side numbers only (rows, sequences, window or
|
||||
* max_ctx); each workgroup divides its own key range, so a split with no keys writes (0, -inf, 0)
|
||||
* and the merge needs no device-side context.
|
||||
*
|
||||
* Nothing here allocates, synchronises, or uses anything but hipLaunchKernel (docs/PLUGIN.md §5).
|
||||
* Wave32 (RDNA): the shuffles and the reduce-scatter are written for 32 lanes.
|
||||
@@ -56,16 +53,15 @@ namespace r4d_win {
|
||||
constexpr int kThreads = 256;
|
||||
constexpr int kWaves = kThreads / 32;
|
||||
|
||||
/* split-KV bookkeeping: at most this many (tile, kv head, split) triples carry partials, and the
|
||||
* tile table behind them holds at most kTinfoMax tiles. The launch keeps under both by
|
||||
* construction; the scratch hook sizes for exactly these. */
|
||||
/* Split-KV bookkeeping: at most kPartBudget (tile, kv head, split) triples carry partials and the
|
||||
* tile table holds at most kTinfoMax tiles. The launch stays under both; scratch is sized for them. */
|
||||
constexpr int kPartBudget = 192;
|
||||
constexpr int kTinfoMax = 128;
|
||||
constexpr int kMaxSplit = 64;
|
||||
|
||||
template <int HD> struct Geo;
|
||||
/* R query rows a workgroup (R / 8 a wave), BK keys a tile. BK * 2 * HD bf16 = 32 KiB of LDS either
|
||||
* way: two paged blocks at 256, one at 512. */
|
||||
/* R query rows per workgroup (R / 8 per wave), BK keys per tile. BK * 2 * HD bf16 = 32 KiB of LDS
|
||||
* either way: two paged blocks at 256, one at 512. */
|
||||
template <> struct Geo<256> { static constexpr int R = 32, BK = 32; };
|
||||
template <> struct Geo<512> { static constexpr int R = 16, BK = 16; };
|
||||
|
||||
@@ -102,10 +98,9 @@ __device__ __forceinline__ float ex2(float x) {
|
||||
__device__ __forceinline__ int imin(int a, int b) { return a < b ? a : b; }
|
||||
__device__ __forceinline__ int imax(int a, int b) { return a > b ? a : b; }
|
||||
|
||||
/* f(Ic<0>{}), ..., f(Ic<N-1>{}): a loop whose index is a CONSTANT in every body, unconditionally.
|
||||
* `#pragma unroll` is a request the unroller drops past a size threshold -- the fp8 legs of the
|
||||
* row loop crossed it -- and a register array indexed by a loop variable that survives is demoted
|
||||
* to scratch memory. This cannot be dropped. */
|
||||
/* f(Ic<0>{}), ..., f(Ic<N-1>{}): a loop whose index is a compile-time constant in every body.
|
||||
* `#pragma unroll` is dropped past a size threshold (the fp8 row loop crosses it), and a register
|
||||
* array indexed by a surviving loop variable is demoted to scratch. This guarantees the unroll. */
|
||||
template <int I> struct Ic { static constexpr int value = I; };
|
||||
template <int I, int N> struct StaticFor {
|
||||
template <typename F> __device__ __forceinline__ static void run(F& f) {
|
||||
@@ -122,7 +117,7 @@ __device__ __forceinline__ void bf16x4(uint2 w, float (&f)[4]) {
|
||||
f[2] = __uint_as_float(w.y << 16);
|
||||
f[3] = __uint_as_float(w.y & 0xffff0000u);
|
||||
}
|
||||
/* OCP E4M3 (e4m3fn, bias 7, 0x7f/0xff NaN, no infinity) -- the KV cache's bytes at
|
||||
/* OCP E4M3 (e4m3fn, bias 7, 0x7f/0xff NaN, no infinity), the KV cache format at
|
||||
* --kv-cache-dtype fp8 (docs/PLUGIN.md §10). Exact; subnormals kept. */
|
||||
__device__ __forceinline__ float fp8e4m3(unsigned b) {
|
||||
const unsigned e = (b >> 3) & 15u, m = b & 7u;
|
||||
@@ -132,8 +127,7 @@ __device__ __forceinline__ float fp8e4m3(unsigned b) {
|
||||
}
|
||||
__device__ __forceinline__ void fp8x4(unsigned w, float (&f)[4]) {
|
||||
#if defined(__GFX12__)
|
||||
/* v_cvt_pk_f32_fp8: RDNA4 converts OCP E4M3 in hardware, two bytes an instruction -- the same
|
||||
* instruction the library's other attention kernels read their fp8 cache with. */
|
||||
/* v_cvt_pk_f32_fp8: RDNA4 hardware OCP E4M3 conversion, two bytes per instruction. */
|
||||
const auto a = __builtin_amdgcn_cvt_pk_f32_fp8((int)w, false);
|
||||
const auto b = __builtin_amdgcn_cvt_pk_f32_fp8((int)w, true);
|
||||
f[0] = a[0]; f[1] = a[1]; f[2] = b[0]; f[3] = b[1];
|
||||
@@ -160,18 +154,17 @@ __device__ __forceinline__ void lds4(const unsigned char* row, int e, float (&f)
|
||||
else bf16x4(*(const uint2*)(row + 2 * e), f);
|
||||
}
|
||||
|
||||
/* THE REDUCE-SCATTER. Each lane holds a partial dot for every key of the tile; after it, lane l
|
||||
* holds key l's full sum. Each step keeps the half of the vector its lane bit selects and adds the
|
||||
* partner's copy of that half: 16 + 8 + 4 + 2 + 1 = 31 shuffles for 32 keys, against 32 * 5 for 32
|
||||
* separate reductions. */
|
||||
/* Reduce-scatter: each lane holds a partial dot for every key of the tile; afterwards lane l holds
|
||||
* key l's full sum. Each step keeps the half its lane bit selects and adds the partner's copy:
|
||||
* 16 + 8 + 4 + 2 + 1 = 31 shuffles for 32 keys, instead of 32 * 5 for separate reductions. */
|
||||
template <int H, int N>
|
||||
__device__ __forceinline__ void reduce_scatter(float (&v)[N], int lane) {
|
||||
if constexpr (H >= 1) {
|
||||
const bool up = (lane & H) != 0;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < H; ++i) {
|
||||
/* VALUES, not lvalues: `up ? v[i + H] : v[i]` selects between two ADDRESSES, and an
|
||||
* array addressed by a lane-dependent pointer is demoted to scratch memory. */
|
||||
/* Select values, not lvalues: `up ? v[i + H] : v[i]` selects an address, and an array
|
||||
* addressed by a lane-dependent pointer is demoted to scratch. */
|
||||
const float lo = v[i], hi = v[i + H];
|
||||
const float keep = up ? hi : lo;
|
||||
const float send = up ? lo : hi;
|
||||
@@ -197,10 +190,9 @@ struct AttnArgs {
|
||||
int max_blocks, n_seq, q_len, tps, kv_heads, causal, window, n_split;
|
||||
};
|
||||
|
||||
/* Tile `tile` of a ragged batch: the sequence it belongs to and which BQ-position slice of that
|
||||
* sequence's query it is. Tiles are numbered sequence by sequence, ceil(q_len(s) / BQ) each, so the
|
||||
* answer is a prefix sum over cu_seqlens -- done by the whole block, 256 sequences a pass. Every
|
||||
* thread returns the same answer: it is read back out of LDS after a barrier. */
|
||||
/* Tile `tile` of a ragged batch: its sequence and which BQ-position slice of that sequence's query
|
||||
* it is. Tiles are numbered sequence by sequence, ceil(q_len(s) / BQ) each, so this is a block-wide
|
||||
* prefix sum over cu_seqlens, NT sequences per pass. All threads get the same answer from LDS. */
|
||||
template <int BQ, int NT = kThreads>
|
||||
__device__ void find_tile(const int* cu, int n_seq, int tile, int* s_scan, int* s_res, int& s_out,
|
||||
int& lt_out) {
|
||||
@@ -336,9 +328,9 @@ __global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) {
|
||||
int blk = -1;
|
||||
if (lb < A.max_blocks && (lb << 4) < hi) blk = A.bt[(long long)s * A.bt_rs + lb];
|
||||
pre_ok[b] = blk >= 0;
|
||||
/* never a null: a select against null makes the pointer FLAT rather than global, and
|
||||
* every tile load a flat_load. A missing block points at the cache's base and its
|
||||
* value is replaced by zeros below. */
|
||||
/* Never null: selecting against null makes the pointer flat instead of global, and every
|
||||
* tile load a flat_load. A missing block points at the cache base; its value is
|
||||
* replaced by zeros below. */
|
||||
src[b] = A.kv + ((long long)(blk >= 0 ? blk : 0) * A.kv_sb + (long long)kh * A.kv_sh) * ESZ;
|
||||
}
|
||||
#pragma unroll
|
||||
@@ -451,42 +443,33 @@ __global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) {
|
||||
|
||||
/* ================================================================== the WMMA prefill kernel
|
||||
*
|
||||
* WHY A SECOND KERNEL. The kernel above is scalar FMAs: right for decode, where a step is a few
|
||||
* rows and the cache read is the whole cost, and about 8 TFLOP/s a card on a long prefill, where
|
||||
* the global layers' attention is quadratic in the prompt and 46% of a 48k-token prefill. RDNA4's
|
||||
* matrix cores do a 16x16x16 bf16 product a WMMA instruction; this kernel feeds them. It is chosen
|
||||
* at launch for prefill-shaped steps only (a sequence with >= kWmmaMinQ query rows) and computes
|
||||
* the same function, predicate for predicate.
|
||||
* The scalar kernel reaches ~8 TFLOP/s on a long prefill, where global-layer attention is
|
||||
* quadratic and 46% of a 48k-token prefill. This kernel uses RDNA4's 16x16x16 WMMA instead. It is
|
||||
* chosen only for prefill-shaped steps (a sequence with >= kWmmaMinQ query rows) and computes the
|
||||
* same function.
|
||||
*
|
||||
* THE LAYOUTS (RDNA4, wave32, v_wmma_f32_16x16x16_bf16 -- confirmed against llama.cpp's mma.cuh,
|
||||
* which runs on the card): A[M][K] gives lane L row M = L % 16 and K = 8 * (L / 16) .. + 7; B[K][N]
|
||||
* gives lane L column N = L % 16 and the same K; the f32 result gives lane L column N = L % 16 and
|
||||
* rows M = 8 * (L / 16) .. + 7. So the kernel computes S TRANSPOSED: S^T = K * Q^T puts each
|
||||
* lane's eight values in ONE query row (row L % 16, keys 8h .. 8h + 7), the row's other eight keys
|
||||
* in lane L ^ 16 -- the softmax statistics are one shuffle -- and those eight values, as bf16, are
|
||||
* exactly the B operand of O^T = V^T * P^T. O^T's lane L likewise holds only row L % 16, so the
|
||||
* online-softmax rescale is a per-lane scalar.
|
||||
* Layouts (wave32 v_wmma_f32_16x16x16_bf16): A[M][K] gives lane L row M = L % 16 and
|
||||
* K = 8 * (L / 16) .. + 7; B[K][N] gives lane L column N = L % 16, same K; the f32 result gives lane
|
||||
* L column N = L % 16, rows M = 8 * (L / 16) .. + 7. So the kernel computes S^T = K * Q^T: each lane
|
||||
* holds eight keys of one query row (row L % 16, keys 8h .. 8h + 7), the other eight are in lane
|
||||
* L ^ 16 (softmax statistics are one shuffle), and those values as f16 are the B operand of
|
||||
* O^T = V^T * P^T. O^T's lane L also holds only row L % 16, so the rescale is a per-lane scalar.
|
||||
*
|
||||
* THE SPLIT. O^T for 16 rows of a 512-dim head is 256 f32 a lane -- the whole register file. So a
|
||||
* wave owns 16 rows by a 128-dim slice of the head (kDQ): its Q^T (32 VGPRs) and O^T (64). The
|
||||
* slices of one row group each compute S^T over their own dims; the partials meet in LDS and every
|
||||
* slice sums them in the same order, so all of them see bit-identical scores and take identical
|
||||
* softmax steps. 16 waves: h512 is 4 row groups of 4 slices (64 rows), h256 8 of 2 (128 rows).
|
||||
* Head split: O^T for 16 rows of a 512-dim head is 256 f32 per lane, the whole register file, so a
|
||||
* wave owns 16 rows by a 128-dim slice (kDQ): Q^T in 32 VGPRs, O^T in 64. Slices compute partial
|
||||
* S^T over their own dims; partials meet in LDS and every slice sums them in the same order, so all
|
||||
* see bit-identical scores. 16 waves: h512 is 4 row groups x 4 slices (64 rows), h256 8 x 2 (128).
|
||||
*
|
||||
* THE TILE is one paged block, 16 keys. K goes to LDS as it is ([key][dim] bf16, a 16-byte pad a row
|
||||
* so the A-fragment reads hit 32 different banks); V goes TRANSPOSED ([dim][key], rows of 48
|
||||
* bytes), since the PV product reduces over keys and an operand's eight K-values must be
|
||||
* contiguous. The transposed write is two keys' dims packed a dword, the dword index rotated per
|
||||
* lane group so a wave's 32 writes land in 32 banks. An fp8 cache is widened on the way in -- exact,
|
||||
* e4m3 has 3 mantissa bits. Keys outside the tile's range or in a missing block are written as
|
||||
* zeros: a probability of 0 times a NaN in a recycled slot is still NaN.
|
||||
* Tile = one paged block, 16 keys. K goes to LDS as [key][dim] bf16 with a 16-byte row pad so
|
||||
* A-fragment reads hit 32 banks. V goes transposed ([dim][key], 48-byte rows) because P.V reduces
|
||||
* over keys; two keys are packed per dword with the dword index rotated per lane group so a wave's
|
||||
* 32 writes hit 32 banks. An fp8 cache is widened on load (exact). Keys outside the range or in a
|
||||
* missing block are written as zeros, since 0 * NaN from a recycled slot is still NaN.
|
||||
*
|
||||
* P AND V IN f16, Q AND K IN bf16. The probabilities are rounded for the matrix product, and bf16's
|
||||
* 8 bits leave 2^-9 of |v| in every output -- measured in the emulator against f64 at up to 0.25%
|
||||
* of the V range, four times the scalar kernel's error. f16 runs at the same rate with 11 bits. V's
|
||||
* bf16 values are exact in f16 between 2^-14 and 65504 (clamped beyond, NaN kept); an fp8 cache's
|
||||
* are exact outright. The denominator sums the probabilities as rounded, so a row is a true
|
||||
* weighted mean of V: a dominant key keeps weight 1 exactly.
|
||||
* P and V in f16, Q and K in bf16: bf16 P leaves up to 2^-9 |v| error per output (up to 0.25% of the
|
||||
* V range against f64, 4x the scalar kernel), while f16 runs at the same rate with 11 bits. bf16 V
|
||||
* is exact in f16 within [2^-14, 65504] (clamped beyond, NaN kept); fp8 V is always exact. The
|
||||
* denominator sums P as rounded, so a row is a true weighted mean of V.
|
||||
*/
|
||||
typedef short win_v8s __attribute__((ext_vector_type(8))); /* 8 bf16, as the builtin takes them */
|
||||
typedef float win_v8f __attribute__((ext_vector_type(8)));
|
||||
@@ -733,9 +716,9 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) sacc[e] = 0.0f;
|
||||
{
|
||||
/* one accumulator: a second one hides the chain's latency but costs 12 VGPRs, and at
|
||||
* 187 two 16-wave workgroups share a WGP (8 waves a SIMD, 1536 VGPRs) where at 200
|
||||
* one does -- the other waves hide the latency better */
|
||||
/* One accumulator: a second hides the chain latency but costs 12 VGPRs; at 187 VGPRs
|
||||
* two 16-wave workgroups fit a WGP (8 waves per SIMD), at 200 only one, and the extra
|
||||
* waves hide latency better. */
|
||||
const unsigned char* ka = kb + n * KS + (sl * kDQ + 8 * h) * 2;
|
||||
#pragma unroll
|
||||
for (int kc = 0; kc < kDQ / 16; ++kc)
|
||||
@@ -813,12 +796,9 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
|
||||
|
||||
/* ------------------------------------------------------------------ the split-KV merge
|
||||
*
|
||||
* ONE WAVE A ROW, THE SPLITS ACROSS ITS LANES. Lane z reads split z's (max, sum) and lane z + 32
|
||||
* split z + 32's -- kMaxSplit is 64 -- so the row's max and denominator are one wave reduction
|
||||
* each; then one sweep over the splits that saw a key, four at a time, every lane accumulating
|
||||
* its 4 * NC dims. The first version walked the splits three times over,
|
||||
* serially, in one thread block per tile: at the 64 splits a decode step of a full-attention layer
|
||||
* gets, that was 750 us a call, a quarter of the step's device time. */
|
||||
* One wave per row, splits across lanes: lane z holds split z's (max, sum) and z + 32's
|
||||
* (kMaxSplit is 64), so the row max and denominator are one wave reduction each. Then one sweep
|
||||
* over the splits that saw a key, four at a time, each lane accumulating its 4 * NC dims. */
|
||||
template <int HD, int GQA>
|
||||
__global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) {
|
||||
constexpr int R = Geo<HD>::R, NC = HD / 128;
|
||||
@@ -855,10 +835,9 @@ __global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) {
|
||||
for (int c = 0; c < NC; ++c)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 4; ++e) acc[c][e] = 0.0f;
|
||||
/* The splits that carry weight, as a 64-bit set every lane holds the same copy of, taken
|
||||
* four at a time so 4 * NC loads are in flight before the first FMA waits on one. A short
|
||||
* group repeats its first split at weight 0: the index is a written one, so the product is
|
||||
* 0 * finite. An empty split's accumulator was never written and is never read. */
|
||||
/* Splits with weight, as a wave-uniform 64-bit set, taken four at a time so 4 * NC loads
|
||||
* are in flight before the first FMA. A short group repeats its first split at weight 0
|
||||
* (a written split, so 0 * finite). An empty split's accumulator is never read. */
|
||||
uint64_t live = (uint64_t)__builtin_amdgcn_ballot_w32(w0 != 0.0f) |
|
||||
((uint64_t)__builtin_amdgcn_ballot_w32(w1 != 0.0f) << 32);
|
||||
while (live) {
|
||||
@@ -898,9 +877,9 @@ __global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) {
|
||||
|
||||
/* ------------------------------------------------------------------ host: the launch adapter */
|
||||
|
||||
/* q and out as [rows, heads, head_dim] at whatever rank they arrived in: rank 3 (or more, leading
|
||||
* axes dense), or rank 2 [rows, heads * head_dim] with its own row pitch -- a column slice of a
|
||||
* fused projection. The last axis must be dense. */
|
||||
/* q and out as [rows, heads, head_dim]: rank >= 3 (leading axes dense), rank 2
|
||||
* [rows, heads * head_dim] with its own row pitch (a column slice of a fused projection), or flat.
|
||||
* The last axis must be dense. */
|
||||
static bool head_view(const RadTensor* t, int64_t heads, int64_t hd, int64_t* rows, int64_t* rs,
|
||||
int64_t* hs) {
|
||||
if (t->rank >= 3) {
|
||||
@@ -1015,11 +994,10 @@ static int launch_attn(const RadArgs* a, RadStream stream) {
|
||||
if (nt <= 0) return RAD_OK;
|
||||
if (nt > 0x7fffffff) return RAD_E_SHAPE;
|
||||
|
||||
/* THE WMMA PATH, for a prefill-shaped step: the longest query at least kWmmaMinQ rows and the
|
||||
* mean at least half that -- a decode or verify batch, a few rows a sequence however many
|
||||
* sequences, keeps the scalar kernel and its split-KV below. 16-byte query and output rows.
|
||||
* Both forms agree with libref's attention within 0.02 on the engine's own operands (the op
|
||||
* oracle, Gemma 4 26B-A4B at two ranks); they differ from each other by summation order. */
|
||||
/* WMMA path for prefill-shaped steps: longest query >= kWmmaMinQ rows and mean >= half that.
|
||||
* Decode and verify batches keep the scalar kernel and its split-KV. Needs 16-byte aligned
|
||||
* query and output rows. Both kernels agree with libref within 0.02 (Gemma 4 26B-A4B operands)
|
||||
* and differ from each other only in summation order. */
|
||||
{
|
||||
int64_t qmax_w = qlen_u;
|
||||
if (cu) {
|
||||
@@ -1067,7 +1045,7 @@ static int launch_attn(const RadArgs* a, RadStream stream) {
|
||||
}
|
||||
}
|
||||
|
||||
/* SPLIT-KV: only where (tile, kv head) pairs are too few to fill the card */
|
||||
/* Split-KV only when (tile, kv head) pairs are too few to fill the GPU */
|
||||
int64_t ns = 1;
|
||||
const int64_t pairs = nt * kvh;
|
||||
if (pairs < kTinfoMax) {
|
||||
@@ -1130,8 +1108,8 @@ R4D_WIN_DEF(256, 1) R4D_WIN_DEF(256, 2) R4D_WIN_DEF(256, 4) R4D_WIN_DEF(256, 8)
|
||||
R4D_WIN_DEF(512, 1) R4D_WIN_DEF(512, 2) R4D_WIN_DEF(512, 4) R4D_WIN_DEF(512, 8)
|
||||
#undef R4D_WIN_DEF
|
||||
|
||||
/* Called at declare with the band's bound and no tensors: the split-KV partials are capped at
|
||||
* kPartBudget (tile, head, split) triples whatever the batch, so the answer is a constant. */
|
||||
/* Called at declare with no tensors. Partials are capped at kPartBudget (tile, head, split)
|
||||
* triples for any batch, so the size is a constant. */
|
||||
int64_t r4d_rad_attn_window_h256_scratch(const RadArgs*) { return r4d_win::scratch_need<256>(); }
|
||||
int64_t r4d_rad_attn_window_h512_scratch(const RadArgs*) { return r4d_win::scratch_need<512>(); }
|
||||
|
||||
|
||||
@@ -2,33 +2,27 @@
|
||||
// 128-VGPR accumulator. The query is bf16 and the KV cache is fp8 or bf16; the 16-bit operand
|
||||
// format for both matmuls is f16 (see r4d_dt16.h for why).
|
||||
//
|
||||
// Two families are compiled: all-16-bit (bf16 KV) and 16/8 mixed (bf16 query, fp8 KV). A variant
|
||||
// far off the optimum is not kept behind a flag, so there is no fp8-P variant here.
|
||||
// Two families: all-16-bit (bf16 KV) and 16/8 mixed (bf16 query, fp8 KV). No fp8-P variant.
|
||||
//
|
||||
// The options below each stay separable, so any one of them can be turned off on its own after a
|
||||
// geometry change:
|
||||
// Each option below can be turned off on its own after a geometry change:
|
||||
//
|
||||
// LAZY (always on, and the reason this file exists)
|
||||
// The obvious form rescales all 128 accumulator VGPRs by alpha on EVERY m-tile. Here the
|
||||
// softmax runs against a REFERENCE max instead of a running one: p = 2^(s - m_ref + SHIFT)
|
||||
// with m_ref updated -- and the accumulator rescaled -- only when some row's max exceeds
|
||||
// m_ref by more than the P format can absorb (DT16::GROW octaves). Accuracy is unchanged:
|
||||
// eager rescaling by alpha and lazy accumulation at a shifted scale produce the SAME
|
||||
// relative weighting in an f32 accumulator.
|
||||
// F16 f16 rather than bf16 as the 16-bit operand format. gfx1201 has NO bf16 convert, so an
|
||||
// f32->bf16 is ~6 VALU of software RTNE; v_cvt_pkrtz_f16_f32 does two f32->f16 in ONE.
|
||||
// Both are exact for these operands (fp8 has 3 mantissa bits, bf16 has 7, f16 has 10).
|
||||
// MSKIP Causal masking applied only on m-tiles that straddle the limit. Interior tiles pay
|
||||
// nothing.
|
||||
// FOLDQ scale * k_descale * log2(e) folded into the query ONCE at load.
|
||||
// CONTIG The k axis of a WMMA is only ever CONTRACTED, so relabelling it on BOTH operands is
|
||||
// free; reading eight contiguous elements at 8*h gives one aligned ds_read_b128 per
|
||||
// fragment, deletes 16 address adds, and makes the P fragment lane-local.
|
||||
// PF/SGB Prefetch PF fragments before the matching PF WMMAs, with a hard scheduling barrier
|
||||
// between the two groups. Without the barrier PF is INERT.
|
||||
// DOT2 v_dot2_f32_f16 row sum off the packed f16 P: 4 instructions for 8, and the denominator
|
||||
// becomes the p values the PV matmul actually used.
|
||||
// BTS/KWIDE/GPREV the tile-staging set -- see the comments on each define.
|
||||
// LAZY (always on) Softmax against a reference max instead of a running one:
|
||||
// p = 2^(s - m_ref + SHIFT), with m_ref updated and the 128-VGPR accumulator rescaled only
|
||||
// when a row max exceeds m_ref by more than the P format absorbs (DT16::GROW octaves),
|
||||
// instead of on every m-tile. Same relative weighting in an f32 accumulator.
|
||||
// F16 f16 as the 16-bit operand format. gfx1201 has no bf16 convert (software RTNE is ~6 VALU);
|
||||
// v_cvt_pkrtz_f16_f32 converts two values in one. Exact for these operands (fp8 has 3
|
||||
// mantissa bits, bf16 7, f16 10).
|
||||
// MSKIP Causal masking only on m-tiles that straddle the limit.
|
||||
// FOLDQ scale * k_descale * log2(e) folded into the query once at load.
|
||||
// CONTIG The WMMA k axis is only contracted, so relabelling it on both operands is free. Reading
|
||||
// eight contiguous elements at 8*h gives one aligned ds_read_b128 per fragment, removes 16
|
||||
// address adds and makes the P fragment lane-local.
|
||||
// PF/SGB Load PF fragments before the matching PF WMMAs, with a scheduling barrier between the
|
||||
// groups. Without the barrier PF has no effect.
|
||||
// DOT2 v_dot2_f32_f16 row sum from the packed f16 P: 4 instructions instead of 8, and the
|
||||
// denominator uses the p values the PV matmul used.
|
||||
// BTS/KWIDE/GPREV tile staging; see each define.
|
||||
#include "r4d.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_dt16.h"
|
||||
@@ -42,30 +36,22 @@
|
||||
#define O_PF8 3072
|
||||
#define O_SGB 4096
|
||||
#define O_DOT2 16384
|
||||
// BTS: the block table entries for a tile are TILE/BS values at a WAVE-UNIFORM index, so they
|
||||
// belong in SGPRs. Without this, every staging pass is `global_load_b32` (block table),
|
||||
// `s_wait_loadcnt 0x0`, fourteen instructions of address arithmetic, `global_load_b64` (the KV),
|
||||
// `s_wait_loadcnt 0x0` -- TWO serialised memory round trips, inside a barrier-bounded phase with
|
||||
// nothing else to run. A scalar load hoisted to the top of the tile collapses that to one.
|
||||
// BTS: a tile's TILE/BS block-table entries are at a wave-uniform index, so load them into SGPRs
|
||||
// once per tile. Otherwise each staging pass does two serialised memory round trips (block table,
|
||||
// then KV) inside a barrier-bounded phase with nothing else to run.
|
||||
#define O_BTS 262144
|
||||
// KWIDE: one 16-byte K fetch per thread instead of two 8-byte ones. 768 threads x 16 B is exactly
|
||||
// a 48-key tile, so the staging loop becomes straight-line: half the global loads, half the block
|
||||
// table lookups, half the dependency chains.
|
||||
// The naive assignment (key = tid/16) makes a warp write ONE row at a 32-byte stride, which is a
|
||||
// 4-way LDS bank conflict: bank = 8*ch mod 32 takes only four values. Interleaving two keys across
|
||||
// the warp instead -- key = 2*warp + (lane&1), ch = (lane&31)>>1 -- gives eight distinct 4-bank
|
||||
// groups covering all 32 banks, i.e. the conflict-free minimum, and the global side still reads two
|
||||
// contiguous 256-byte runs.
|
||||
// a 48-key fp8 tile, so staging is straight-line with half the loads and block-table lookups.
|
||||
// key = tid/16 would make a warp write one row at a 32-byte stride (4-way LDS bank conflict, since
|
||||
// 8*ch mod 32 takes four values). key = 2*warp + (lane&1), ch = (lane&31)>>1 interleaves two keys
|
||||
// so the writes cover all 32 banks, while global reads stay two contiguous 256-byte runs.
|
||||
#define O_KWIDE 524288
|
||||
// GPREV: fetch tile ti+1's V into REGISTERS immediately after the second barrier, so its memory
|
||||
// latency is covered by tile ti's 96 WMMAs and only the LDS stores stay between the barriers.
|
||||
// V ONLY. A second prefetch, for K, does not pay at any issue point: this kernel already sits at
|
||||
// 240 VGPRs, so the allocator spills it, and a spilled prefetch is waited on immediately, which is
|
||||
// not a prefetch at all.
|
||||
// GPREV: fetch tile ti+1's V into registers right after the second barrier, so its latency is
|
||||
// hidden by tile ti's 96 WMMAs and only the LDS stores remain between barriers. V only: at
|
||||
// 240 VGPRs a K prefetch would be spilled, and a spilled prefetch is waited on immediately.
|
||||
#define O_GPREV 1048576
|
||||
// LDSB: an LDS-scoped barrier instead of __syncthreads(). See lds_barrier() in r4d_common.h --
|
||||
// the default fence invalidates the vector cache twice per tile for a synchronisation that only
|
||||
// ever orders LDS.
|
||||
// LDSB: an LDS-scoped barrier instead of __syncthreads() (lds_barrier() in r4d_common.h). The
|
||||
// default fence invalidates the vector cache twice per tile, though only LDS needs ordering.
|
||||
#define O_LDSB 2097152
|
||||
|
||||
// bf16 dword -> 16-bit dword in the target format, optionally scaled. Used once per kernel on Q.
|
||||
@@ -76,11 +62,9 @@ __device__ __forceinline__ uint32_t r4d_qcvt(uint32_t w, float s) {
|
||||
__builtin_bit_cast(float, w & 0xffff0000u) * s);
|
||||
}
|
||||
|
||||
// WIN turns on a sliding window (a.window positions, ending at each row's causal limit), the way
|
||||
// the decode kernel's WIN does. The window's lower bound masks the keys before it, and the KV walk
|
||||
// starts at the tile holding the window's first token (taken at query row 0, whose window reaches
|
||||
// furthest back) so the tiles no row can reach are never walked. window <= 0 (or WIN off) is the
|
||||
// full-attention form, unchanged.
|
||||
// WIN enables a sliding window (a.window positions ending at each row's causal limit), as in the
|
||||
// decode kernel. Keys below the window are masked, and the KV walk starts at the tile holding the
|
||||
// workgroup's earliest window token. window <= 0 (or WIN off) is full attention.
|
||||
template<int NWARPS, int TILE, int HEAD_DIM, int GQA, int BS, int KVP, int OPT, int WIN = 0>
|
||||
__global__ __launch_bounds__(NWARPS * 32)
|
||||
void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
@@ -127,9 +111,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
const int ctx = a.seqused_k[seq];
|
||||
if (ctx <= 0) return;
|
||||
|
||||
// Ragged batches: this sequence owns rows [qoff, qoff+qlen) of the dense q and out blocks.
|
||||
// grid.x is sized from the batch MAXIMUM q_len, so a shorter sequence has blocks past its own
|
||||
// end -- they exit here rather than run a full KV walk to write nothing.
|
||||
// Ragged batches: this sequence owns rows [qoff, qoff+qlen) of q and out. grid.x is sized from
|
||||
// the batch maximum q_len, so blocks past a shorter sequence's end exit here.
|
||||
const int qoff = r4d_q_off(a.cu_q, seq, a.q_len);
|
||||
const int qlen = r4d_q_len(a.cu_q, seq, a.q_len);
|
||||
if (qb * BLOCK_Q >= qlen) return;
|
||||
@@ -153,7 +136,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
+ ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NKS; ++t) {
|
||||
// CONTIG reads the same 8 d as ONE run; the split map takes them 4+4.
|
||||
// CONTIG reads the 8 dims as one run; the split map takes them 4+4.
|
||||
const uint2 l0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h : 4 * h));
|
||||
const uint2 h0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h + 4 : 8 + 4 * h));
|
||||
qf[t] = D::mk(make_uint2(r4d_qcvt<D, FOLDQ, F16>(l0.x, mul),
|
||||
@@ -164,9 +147,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
}
|
||||
|
||||
const int klimit = ctx - qlen + qpos;
|
||||
// The window's first key this row may attend to: the causal limit back by the window, floored
|
||||
// at zero. The decode kernel's r4d_attn_wlo is the same formula, inlined here because the
|
||||
// prefill header is compiled before the decode one that defines it.
|
||||
// First key in this row's window, floored at zero. Same formula as r4d_attn_wlo, which is
|
||||
// defined in the decode unit, included after this one.
|
||||
int wlo = (WIN && a.window > 0) ? (ctx - qlen + qpos - a.window + 1) : 0;
|
||||
if (WIN && a.window > 0 && wlo < 0) wlo = 0;
|
||||
|
||||
@@ -180,17 +162,14 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
const int qmax_cta = min(qb * BLOCK_Q + BLOCK_Q - 1, qlen - 1);
|
||||
const int klimit_cta = ctx - qlen + qmax_cta;
|
||||
const int ntiles = (min(klimit_cta + 1, ctx) + TILE - 1) / TILE;
|
||||
// The window's first tile, taken at THIS CTA's first query row (whose window reaches furthest
|
||||
// back among the rows it holds); the walk starts there, so no tile below every row's window is
|
||||
// fetched. Taken at the CHUNK's row 0 instead, the last CTA of an 8192-token chunk walked eight
|
||||
// thousand keys none of its rows can see -- fully masked tiles, so skipping them changes no
|
||||
// value. WIN off (or window <= 0) starts at 0.
|
||||
// First window tile, taken at this workgroup's first query row (the one reaching furthest
|
||||
// back), not the chunk's row 0, so fully masked tiles are never walked. Starts at 0 without a
|
||||
// window.
|
||||
const int wlo0 = (WIN && a.window > 0) ? (ctx - qlen + qb * BLOCK_Q - a.window + 1) : 0;
|
||||
const int tstart = (WIN && a.window > 0 && wlo0 > 0) ? (wlo0 / TILE) : 0;
|
||||
|
||||
// ---- staging, split into a global FETCH (registers) and an LDS STORE ------------------------
|
||||
// Splitting them is what lets GPREV move the fetch out from between the barriers; without
|
||||
// GPREV the two simply run back to back.
|
||||
// ---- staging, split into a global fetch (registers) and an LDS store ------------------------
|
||||
// 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];
|
||||
|
||||
@@ -282,8 +261,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
*(uint2*)(dst) = make_uint2(D::from_bf16w(v.x), D::from_bf16w(v.y));
|
||||
*(uint2*)(dst + 4) = make_uint2(D::from_bf16w(v.z), D::from_bf16w(v.w));
|
||||
} else {
|
||||
// tr_b128 transposes 16-BIT lanes, so each transposed short is two fp8 from
|
||||
// ADJACENT d; v_perm_b32 splits them back into two d rows.
|
||||
// tr_b128 transposes 16-bit lanes, so each short holds two fp8 from adjacent
|
||||
// dims; v_perm_b32 splits them into two dim rows.
|
||||
const uint32_t lo0 = byte_gather(v.x, v.y, 0), lo1 = byte_gather(v.z, v.w, 0);
|
||||
const uint32_t hi0 = byte_gather(v.x, v.y, 1), hi1 = byte_gather(v.z, v.w, 1);
|
||||
uint32_t wl[4], wh[4];
|
||||
@@ -300,14 +279,10 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
}
|
||||
};
|
||||
|
||||
// The block table for tile ti is fetched during tile ti-1, so the scalar load has an entire
|
||||
// store phase and two barriers to complete instead of stalling the KV address chain.
|
||||
// A tile's NB entries are read whole, and when a tile spans several blocks the last one can run
|
||||
// past the sequence's last block -- past the end of its row, and on the last row past the end
|
||||
// of the table. Every key is clamped to ctx - 1 before it picks an entry, so no entry past
|
||||
// `lastb` is ever used and clamping the index there changes no value that is. Only a window
|
||||
// that reaches past `lastb` takes the clamped form, so every other tile keeps its one wide
|
||||
// scalar load; at one block a tile no window can reach past it and the test folds away.
|
||||
// Tile ti's block-table entries are loaded during tile ti-1, off the KV address chain.
|
||||
// A multi-block tile can run past the sequence's last block (on the last row, past the end of
|
||||
// the table). Keys are clamped to ctx - 1, so entries past lastb are never used; only tiles
|
||||
// reaching past lastb take the clamped load. With NB == 1 the test folds away.
|
||||
const int lastb = (ctx - 1) / BS;
|
||||
auto load_bt = [&](int t0, int* out) {
|
||||
if (NB > 1 && t0 + NB - 1 > lastb) {
|
||||
@@ -331,11 +306,11 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
if (LDSB) lds_barrier(); else __syncthreads();
|
||||
fetchK(k0, blk);
|
||||
if (!GPREV) fetchV(k0, blk);
|
||||
storeV(); // V first: its data is already in registers, so it covers K's wait
|
||||
storeV(); // V first: already in registers, so it covers K's load latency
|
||||
storeK();
|
||||
if (LDSB) lds_barrier(); else __syncthreads();
|
||||
// The next tile's global loads are issued HERE, before the 96 WMMAs below, and the wait
|
||||
// that consumes them does not appear until after the next barrier.
|
||||
// Issue the next tile's V loads before the WMMAs below; they are consumed after the next
|
||||
// barrier.
|
||||
if (GPREV && ti + 1 < ntiles) fetchV(k0 + TILE, blkn);
|
||||
|
||||
#pragma unroll 1
|
||||
@@ -343,8 +318,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
v8f s = (v8f){0,0,0,0,0,0,0,0};
|
||||
{
|
||||
const uint16_t* krow = &sK[(mt * 16 + c) * KSTR] + (CTG ? 8 * h : 0);
|
||||
// PF fragments are LOADED before the matching PF WMMAs are ISSUED, so the wait in
|
||||
// front of each WMMA becomes `s_wait_dscnt PF-1` instead of a full drain.
|
||||
// Load PF fragments before issuing their WMMAs, so each WMMA waits on
|
||||
// s_wait_dscnt PF-1 instead of a full drain.
|
||||
#pragma unroll
|
||||
for (int g = 0; g < NKS; g += PF) {
|
||||
frag16 kb[PF];
|
||||
@@ -369,8 +344,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
for (int e = 0; e < 8; ++e) sc[e] = FOLDQ ? s[e] : s[e] * mul;
|
||||
|
||||
const int kbase = k0 + mt * 16 + 8 * h;
|
||||
// The causal bound masks the keys past klimit; the window bound (WIN) also masks the
|
||||
// keys before wlo. MSKIP skips both when an m-tile straddles neither limit.
|
||||
// Mask keys past klimit and, with WIN, before wlo. MSKIP skips tiles straddling neither.
|
||||
if (!MSKIP || wave_any(kbase + 7 > klimit) || (WIN && wave_any(kbase < wlo))) {
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) sc[e] = ((kbase + e <= klimit) && (!WIN || kbase + e >= wlo))
|
||||
@@ -414,8 +388,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
}
|
||||
const uint2 lo = make_uint2(pw[0], pw[1]);
|
||||
const uint2 hi2 = make_uint2(pw[2], pw[3]);
|
||||
// QK leaves lane (c,h) holding keys 8h+e. Under CONTIG that IS the B fragment, so
|
||||
// the cross-half exchange the two-runs-of-four map needed is simply not there.
|
||||
// QK leaves lane (c,h) holding keys 8h+e. Under CONTIG that is already the B
|
||||
// fragment; the split map needs a cross-half exchange.
|
||||
frag16 p16;
|
||||
if (CTG) {
|
||||
p16 = D::mk(lo, hi2);
|
||||
|
||||
@@ -1,34 +1,23 @@
|
||||
// R4D vision-encoder attention: dense, non-causal, head_dim 72, bf16 in and out.
|
||||
//
|
||||
// This is the same transposed core as the paged prefill kernel -- S^T = K.Q^T, so the wave32
|
||||
// column-distributed accumulator gives each lane exactly ONE query row and the softmax state is
|
||||
// lane-private. That choice is worth more here than it is at head_dim 256, because it is what
|
||||
// removes the QK-C-fragment -> PV-A-fragment transpose of P through LDS: the C fragment of S^T
|
||||
// (lane holds query `c`, keys 8h+i) IS the B fragment the PV matmul wants (P^T, key rows,
|
||||
// query columns). A formulation that carries that LDS round trip instead does not get past torch
|
||||
// SDPA for this shape.
|
||||
// Same transposed core as the paged prefill kernel: S^T = K.Q^T, so each lane of the wave32
|
||||
// column-distributed accumulator owns one query row and the softmax state is lane-private. The C
|
||||
// fragment of S^T (lane holds query c, keys 8h+i) is the B fragment of P.V (P^T), so P never goes
|
||||
// through LDS; with that round trip this shape does not beat torch SDPA.
|
||||
//
|
||||
// head_dim 72 is carried natively as 5 k-tiles of 16 = 80, with dims 72..79 structurally zero:
|
||||
// the Q fragment of the last tile is zeroed on the h==1 half, the last 8 columns of every staged
|
||||
// K row are zeroed once, and the last tile's output store is taken only by the h==0 half (the
|
||||
// h==1 half would run off the end of the 72-element row). 80/72 = 11% of padded WMMA work, the
|
||||
// same overhead the 64+16 Triton split pays.
|
||||
// head_dim 72 runs as 5 k-tiles of 16 = 80, with dims 72..79 zero: the last Q tile is zeroed on
|
||||
// the h==1 half, the last 8 columns of every staged K row are zeroed once, and only the h==0 half
|
||||
// stores the last output tile (h==1 would run past the 72-element row). 11% padded WMMA work.
|
||||
//
|
||||
// What differs from the paged kernel, beyond the geometry:
|
||||
// * K and V are contiguous [tokens, heads, 72] bf16, so there is no block table, no descale and
|
||||
// no fp8 widening -- the whole two-round-trip staging problem that cost the paged kernel 20%
|
||||
// is simply absent. K is fetched 16 bytes per thread; V is transposed into LDS with
|
||||
// global_load_tr_b128 exactly as there.
|
||||
// * Non-causal: no per-row key limit. Only the last key tile is masked, and the branch is
|
||||
// workgroup-uniform rather than per-wave.
|
||||
// * Varlen over segments: one launch covers every image in the batch (grid.z), so the caller
|
||||
// does not split by cu_seqlens and concatenate.
|
||||
// Differences from the paged kernel:
|
||||
// * K and V are contiguous [tokens, heads, 72] bf16: no block table, descale or fp8 widening.
|
||||
// K is fetched 16 bytes per thread; V is transposed into LDS with global_load_tr_b128.
|
||||
// * Non-causal: only the last key tile is masked, with a workgroup-uniform branch.
|
||||
// * Varlen: one launch covers every image in the batch (grid.z over cu_seqlens segments).
|
||||
//
|
||||
// The 16-bit operand format is f16, for the reason in r4d_dt16.h: gfx1201 has no bf16 convert, so
|
||||
// the softmax's f32 -> 16-bit pack is 1 instruction per pair instead of ~6. A bf16 operand build
|
||||
// stays reachable (V_O_F16 off) because it makes the K/V staging a pure byte copy; it is the
|
||||
// slower of the two overall, and the option exists so the trade can be re-checked after a geometry
|
||||
// change rather than assumed.
|
||||
// Operands are f16 (r4d_dt16.h: gfx1201 has no bf16 convert, so packing P costs 1 instruction per
|
||||
// pair instead of ~6). A bf16 build (V_O_F16 off) makes K/V staging a byte copy but is slower
|
||||
// overall; it is kept so the trade can be rechecked after a geometry change.
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -43,30 +32,15 @@
|
||||
#define V_O_DOT2 16384 // v_dot2_f32_f16 row sum off the packed P
|
||||
#define V_O_GPREV 1048576 // next tile's V fetched into registers across the m-tile loop
|
||||
#define V_O_LDSB 2097152 // LDS-scoped barrier instead of __syncthreads()
|
||||
// GPREK: the same register prefetch for K. Unlike the paged kernel -- which sits at 240 VGPRs and
|
||||
// spills any second prefetch, so a wait lands on it immediately and it stops being a prefetch --
|
||||
// this geometry runs at ~130, and the K fetch is only three uint4. Without it the tile's global
|
||||
// load is issued between the two barriers with only the V LDS stores to cover it.
|
||||
// GPREK: register prefetch for K too. The paged kernel (240 VGPRs) would spill it; this one runs at
|
||||
// ~130 and the K fetch is three uint4. Without it the K load sits between the barriers with only
|
||||
// the V LDS stores to cover it.
|
||||
#define V_O_GPREK 4194304
|
||||
// MIXFMT: bf16 operands for QK, f16 for PV. The two matmuls have opposite conversion costs. K and
|
||||
// V arrive as bf16 and are staged through LDS, so an f16 LDS carries a bf16 -> f16 convert per
|
||||
// element (3 VALU per dword) on the staging path; but P is produced in f32 by the softmax every
|
||||
// m-tile, and f32 -> bf16 is ~6 VALU of software RTNE against ONE v_cvt_pkrtz_f16_f32. Splitting
|
||||
// the formats takes the cheap side of both: K is copied into LDS as raw bf16 with no conversion
|
||||
// at all and the query is converted once at load, while V and P stay f16. Accuracy is unchanged --
|
||||
// K and V are bf16 sources, so both widenings are exact.
|
||||
// MIXFMT: bf16 operands for QK, f16 for PV. Staging bf16 K into an f16 LDS costs a convert per
|
||||
// element (3 VALU per dword), while packing f32 P to bf16 costs ~6 VALU vs one v_cvt_pkrtz_f16_f32.
|
||||
// So K is copied raw as bf16 (query converted once), and V and P stay f16. Both widenings are exact.
|
||||
#define V_O_MIXFMT 8388608
|
||||
|
||||
// Pricing probes, wrong on purpose. A probe that changes the DATAFLOW measures nothing (making p
|
||||
// constant makes s dead and deletes the QK loop), so each of these deletes work while leaving every
|
||||
// value's producer-consumer chain intact. Count the emitted instructions before believing a number.
|
||||
#ifndef V_ABL
|
||||
#define V_ABL 0
|
||||
#endif
|
||||
#define V_ABL_EXP 1 // the 8 v_exp_f32 per m-tile become the identity
|
||||
#define V_ABL_STAGE 2 // no K/V fetch or LDS store inside the tile loop (barriers kept)
|
||||
#define V_ABL_MAX 4 // no running-max test and no lazy rescale
|
||||
#define V_ABL_LDS 8 // every K/V fragment read once before the tile loop and reused
|
||||
|
||||
// bf16 dword -> 16-bit dword in the target format, with the query scale folded in.
|
||||
template<class D, int FOLDQ, int F16>
|
||||
@@ -90,10 +64,6 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
constexpr int DOT2 = ((OPT & V_O_DOT2) && F16) ? 1 : 0;
|
||||
constexpr int GPREV = (OPT & V_O_GPREV) ? 1 : 0;
|
||||
constexpr int LDSB = (OPT & V_O_LDSB) ? 1 : 0;
|
||||
constexpr int ABL_EXP = (V_ABL & V_ABL_EXP) ? 1 : 0;
|
||||
constexpr int ABL_STAGE = (V_ABL & V_ABL_STAGE) ? 1 : 0;
|
||||
constexpr int ABL_MAX = (V_ABL & V_ABL_MAX) ? 1 : 0;
|
||||
constexpr int ABL_LDS = (V_ABL & V_ABL_LDS) ? 1 : 0;
|
||||
constexpr int GPREK = (OPT & V_O_GPREK) ? 1 : 0;
|
||||
constexpr int MIXF = (OPT & V_O_MIXFMT) ? 1 : 0;
|
||||
typedef DT16<F16> D; // V and P: the format the softmax packs into
|
||||
@@ -108,9 +78,8 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
constexpr int ROWS = NWARPS * 16 * QB;
|
||||
constexpr int MT = TILE / 16;
|
||||
constexpr int NTHR = NWARPS * 32;
|
||||
// Row strides padded by 8 shorts: 16-byte aligned (a 16-byte LDS access at an 8-byte-aligned
|
||||
// address splits back into two b64) and off the bank period, which puts both fragment reads
|
||||
// at the 8-distinct-bank-group minimum.
|
||||
// Row strides padded by 8 shorts: 16-byte aligned (an 8-byte-aligned 16-byte LDS access splits
|
||||
// into two b64) and off the bank period, so both fragment reads hit 8 distinct bank groups.
|
||||
constexpr int KSTR = HDP + 8;
|
||||
constexpr int VSTR = TILE + 8;
|
||||
constexpr int KGRP = TILE / 8; // eight-key groups per tile; a power of two
|
||||
@@ -135,16 +104,14 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
const int s0 = cu[seq], slen = cu[seq + 1] - s0;
|
||||
if (slen <= 0 || qb * ROWS >= slen) return;
|
||||
|
||||
// Elements between consecutive tokens, per operand: heads * HD for a dense [tokens, heads,
|
||||
// 72] tensor, and the projection's row for a column slice of a fused [q|k|v] one.
|
||||
// q_ld, k_ld, v_ld, o_ld are token pitches in elements: heads * HD for a dense tensor, or the
|
||||
// projection row for a column slice of a fused [q|k|v] one.
|
||||
const float mul = scale * 1.44269504089f;
|
||||
|
||||
// ---- the query fragments, held for the life of the workgroup -----------------------------
|
||||
// A warp owns QB tiles of 16 query rows rather than one. Every K and V fragment read out of
|
||||
// LDS is then consumed by QB WMMAs instead of one, which is the point: at QB = 1 this kernel
|
||||
// issues ten ds_load_b128 per ten WMMAs, and LDS delivers less per cycle than the matrix
|
||||
// units consume. The accumulator is only 8 VGPRs per output tile, so the second query tile is
|
||||
// affordable where it would not be at head_dim 256.
|
||||
// A warp owns QB tiles of 16 query rows, so each K/V fragment read from LDS feeds QB WMMAs. At
|
||||
// QB = 1 there is one ds_load_b128 per WMMA, and LDS delivers less per cycle than the matrix
|
||||
// units consume. The accumulator is 8 VGPRs per output tile, so QB > 1 is affordable here.
|
||||
int qpos[QB];
|
||||
bool live[QB];
|
||||
fragK qf[QB][NKS];
|
||||
@@ -156,9 +123,8 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
const uint16_t* qp = gq + (long)(s0 + qrow) * q_ld + (long)hd * HD;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NKS; ++t) {
|
||||
// The padded half of the last k-tile: dims 72..79 do not exist. Zeroing the query
|
||||
// side is not enough on its own -- the K side is zeroed too, because a WMMA
|
||||
// contracts, and NaN * 0 would poison the whole score row rather than one element.
|
||||
// Padded half of the last k-tile (dims 72..79). K is zeroed too: the WMMA contracts,
|
||||
// so a NaN * 0 there would poison the whole score row.
|
||||
if (t == NKS - 1 && h == 1) { qf[b][t] = DK::mk(make_uint2(0, 0), make_uint2(0, 0)); continue; }
|
||||
const uint4 u = *(const uint4*)(qp + 16 * t + 8 * h);
|
||||
qf[b][t] = DK::mk(make_uint2(r4d_vit_qcvt<DK, FOLDQ, MIXF ? 0 : F16>(u.x, mul),
|
||||
@@ -168,7 +134,7 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
}
|
||||
}
|
||||
|
||||
// The padded lanes of the staging buffers, written once: staging only ever fills dims 0..71.
|
||||
// Zero the padding of the staging buffers once; staging only fills dims 0..71.
|
||||
#pragma unroll 1
|
||||
for (int i = tid; i < TILE; i += NTHR) *(uint4*)&sK[i * KSTR + HD] = make_uint4(0, 0, 0, 0);
|
||||
#pragma unroll 1
|
||||
@@ -178,14 +144,14 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
v8f acc[QB][NKS];
|
||||
#pragma unroll
|
||||
for (int b = 0; b < QB; ++b) {
|
||||
m_ref[b] = ABL_MAX ? 0.0f : -3.0e38f;
|
||||
soff[b] = ABL_MAX ? PSHIFT : (PSHIFT + 3.0e38f);
|
||||
m_ref[b] = -3.0e38f;
|
||||
soff[b] = PSHIFT + 3.0e38f;
|
||||
l_i[b] = 0.0f;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NKS; ++t) acc[b][t] = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
}
|
||||
|
||||
// ---- staging, split into a global FETCH (to registers) and an LDS STORE -------------------
|
||||
// ---- staging, split into a global fetch (to registers) and an LDS store -------------------
|
||||
const int vj = tid & 7, lgi = tid >> 3;
|
||||
uint4 kregA[KPA], kregB[KPB], vreg[VPASS];
|
||||
|
||||
@@ -232,9 +198,8 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
}
|
||||
};
|
||||
|
||||
// V is read transposed straight out of global memory: the eight lanes of a group each name a
|
||||
// different key row at the same 8 dims, and global_load_tr_b128 hands lane j the column for
|
||||
// dim d0+j across all eight of them -- one contiguous 16-byte LDS row of V^T per lane.
|
||||
// V is read transposed from global: a group's eight lanes name eight key rows at the same 8
|
||||
// dims, and global_load_tr_b128 gives lane j dim d0+j across all eight, one 16-byte row of V^T.
|
||||
auto fetchV = [&](int k0) {
|
||||
#pragma unroll
|
||||
for (int r = 0; r < VPASS; ++r) {
|
||||
@@ -263,32 +228,22 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
}
|
||||
};
|
||||
|
||||
fragK kb0; frag16 vb0;
|
||||
if (ABL_LDS) {
|
||||
const uint4 u = *(const uint4*)(&sK[c * KSTR] + 8 * h);
|
||||
kb0 = DK::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w));
|
||||
const uint4 w = *(const uint4*)(&sV[c * VSTR] + 8 * h);
|
||||
vb0 = D::mk(make_uint2(w.x, w.y), make_uint2(w.z, w.w));
|
||||
}
|
||||
|
||||
const int ntiles = (slen + TILE - 1) / TILE;
|
||||
if (GPREV && !ABL_STAGE) fetchV(0);
|
||||
if (GPREK && !ABL_STAGE) fetchK(0);
|
||||
if (GPREV) fetchV(0);
|
||||
if (GPREK) fetchK(0);
|
||||
|
||||
for (int ti = 0; ti < ntiles; ++ti) {
|
||||
const int k0 = ti * TILE;
|
||||
const bool tail = (k0 + TILE > slen);
|
||||
if (LDSB) lds_barrier(); else __syncthreads();
|
||||
if (!ABL_STAGE) {
|
||||
if (!GPREK) fetchK(k0);
|
||||
if (!GPREV) fetchV(k0);
|
||||
storeV(); // V first: already in registers, so it covers K's load wait
|
||||
storeK();
|
||||
}
|
||||
if (!GPREK) fetchK(k0);
|
||||
if (!GPREV) fetchV(k0);
|
||||
storeV(); // V first: already in registers, so it covers K's load wait
|
||||
storeK();
|
||||
if (LDSB) lds_barrier(); else __syncthreads();
|
||||
// Issued here, before the WMMAs below; the wait that consumes it is past the next barrier.
|
||||
if (GPREV && !ABL_STAGE && ti + 1 < ntiles) fetchV(k0 + TILE);
|
||||
if (GPREK && !ABL_STAGE && ti + 1 < ntiles) fetchK(k0 + TILE);
|
||||
// Issued before the WMMAs below; consumed after the next barrier.
|
||||
if (GPREV && ti + 1 < ntiles) fetchV(k0 + TILE);
|
||||
if (GPREK && ti + 1 < ntiles) fetchK(k0 + TILE);
|
||||
|
||||
#pragma unroll 1
|
||||
for (int mt = 0; mt < MT; ++mt) {
|
||||
@@ -303,7 +258,6 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PF; ++j) {
|
||||
if (g + j < NKS) {
|
||||
if (ABL_LDS) { kb[j] = kb0; continue; }
|
||||
const uint4 u = *(const uint4*)(krow + 16 * (g + j));
|
||||
kb[j] = DK::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w));
|
||||
}
|
||||
@@ -324,8 +278,7 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) sc[e] = FOLDQ ? s[b][e] : s[b][e] * mul;
|
||||
|
||||
// Non-causal: only the last tile can hold keys past the end of the segment, and
|
||||
// the test is workgroup-uniform rather than per-row.
|
||||
// Non-causal: only the last tile can hold keys past the segment end.
|
||||
if (tail) {
|
||||
const int kbase = k0 + mt * 16 + 8 * h;
|
||||
#pragma unroll
|
||||
@@ -335,7 +288,7 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
float smax = sc[0];
|
||||
#pragma unroll
|
||||
for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]);
|
||||
if (!ABL_MAX && wave_any(smax > m_ref[b] + PGROW)) {
|
||||
if (wave_any(smax > m_ref[b] + PGROW)) {
|
||||
const float rmax = fmaxf(smax, swap16(smax));
|
||||
const float mnew = fmaxf(fmaxf(m_ref[b], rmax), -3.0e38f);
|
||||
const float alpha = ex2(m_ref[b] - mnew);
|
||||
@@ -351,7 +304,7 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
float pv[8], lsum = 0.0f;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const float p = ABL_EXP ? (sc[e] + soff[b]) : ex2(sc[e] + soff[b]);
|
||||
const float p = ex2(sc[e] + soff[b]);
|
||||
pv[e] = p;
|
||||
if (!DOT2) lsum += p;
|
||||
}
|
||||
@@ -367,8 +320,7 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
l_i[b] = __builtin_amdgcn_fdot2(__builtin_bit_cast(v2hf, pw[e]), one,
|
||||
l_i[b], false);
|
||||
}
|
||||
// QK left lane (c,h) holding keys 8h+e of query c. That IS the B fragment of
|
||||
// P^T for the PV matmul, so no exchange and no LDS round trip.
|
||||
// Lane (c,h) holds keys 8h+e of query c, which is already the B fragment of P^T.
|
||||
p16[b] = D::mk(make_uint2(pw[0], pw[1]), make_uint2(pw[2], pw[3]));
|
||||
}
|
||||
|
||||
@@ -380,7 +332,6 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PF; ++j) {
|
||||
if (g + j < NKS) {
|
||||
if (ABL_LDS) { vb[j] = vb0; continue; }
|
||||
const uint4 u = *(const uint4*)(vbase + (g + j) * 16 * VSTR);
|
||||
vb[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w));
|
||||
}
|
||||
@@ -405,8 +356,7 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
uint16_t* op = go + (long)(s0 + qpos[b]) * o_ld + (long)hd * HD;
|
||||
#pragma unroll
|
||||
for (int dt = 0; dt < NKS; ++dt) {
|
||||
// The last tile covers dims 64..79; the h==1 half of it is padding and would store
|
||||
// past the end of a 72-element row.
|
||||
// The last tile's h==1 half (dims 72..79) is padding and would store past the row.
|
||||
if (dt == NKS - 1 && h == 1) continue;
|
||||
uint32_t tw[4];
|
||||
#pragma unroll
|
||||
@@ -419,44 +369,24 @@ void r4d_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __rest
|
||||
}
|
||||
|
||||
// ---- entry point -----------------------------------------------------------------------------
|
||||
// Two instantiations, chosen on the segment length. Both are the same kernel; they differ only in
|
||||
// how many query rows a workgroup owns. ROWS 256 is the argmin from 1K patches upward, but it
|
||||
// quantises badly below that -- at 576 patches it leaves a workgroup two thirds dead and reaches
|
||||
// only 1.33x the Triton kernel where ROWS 128 reaches 1.76x. The crossover sits between 576 and
|
||||
// 1024; 768 is the midpoint and neither instantiation is far off at that length.
|
||||
//
|
||||
// Every geometry constant is overridable, so a retuned build is one -D away, and V_SPLIT = 0
|
||||
// forces every length through the large instantiation.
|
||||
#ifndef V_NWARPS
|
||||
// Two instantiations of the same kernel, chosen by segment length; they differ in query rows per
|
||||
// workgroup. ROWS 256 is fastest from 1K patches up but quantises badly below (at 576 patches a
|
||||
// workgroup is two thirds idle: 1.33x Triton vs 1.76x for ROWS 128). The crossover is between 576
|
||||
// and 1024; V_SPLIT 768 is the midpoint.
|
||||
#define V_NWARPS 16 // large instantiation: ROWS = 256
|
||||
#endif
|
||||
#ifndef V_TILE
|
||||
#define V_TILE 128
|
||||
#endif
|
||||
#ifndef V_QB
|
||||
#define V_QB 1
|
||||
#endif
|
||||
#ifndef V_SNWARPS
|
||||
#define V_SNWARPS 8 // small instantiation: ROWS = 128
|
||||
#endif
|
||||
#ifndef V_STILE
|
||||
#define V_STILE 64
|
||||
#endif
|
||||
#ifndef V_SQB
|
||||
#define V_SQB 1
|
||||
#endif
|
||||
#ifndef V_SPLIT
|
||||
#define V_SPLIT 768
|
||||
#endif
|
||||
// F16 | FOLDQ | PF4 | SGB | DOT2 | GPREV | LDSB | GPREK. MIXFMT is off: it performs identically
|
||||
// here, and one operand format with one WMMA variant is the simpler thing to keep.
|
||||
#ifndef V_OPT
|
||||
// F16 | FOLDQ | PF4 | SGB | DOT2 | GPREV | LDSB | GPREK. MIXFMT is off: same speed, and one
|
||||
// operand format is simpler.
|
||||
#define V_OPT 7362569
|
||||
#endif
|
||||
|
||||
// q, k, v, o are [total_tokens, heads, 72] contiguous bf16; cu_seqlens is [num_seqs + 1] int32 and
|
||||
// bounds one image (or one attention window) per entry, so a whole batch is one launch. max_seqlen
|
||||
// is the host-side bound on those lengths -- the kernel reads the device-side cu_seqlens itself.
|
||||
// q, k, v, o are [total_tokens, heads, 72] contiguous bf16; cu_seqlens is [num_seqs + 1] int32, one
|
||||
// image (or attention window) per segment. max_seqlen is a host-side bound on the lengths; the
|
||||
// kernel reads the device-side cu_seqlens.
|
||||
extern "C" int r4d_attn_vit_h72_bf16(const void* q, const void* k, const void* v, void* o,
|
||||
const void* cu_seqlens, int num_seqs, int max_seqlen,
|
||||
int heads, int head_dim, float scale, void* stream)
|
||||
@@ -466,9 +396,9 @@ extern "C" int r4d_attn_vit_h72_bf16(const void* q, const void* k, const void* v
|
||||
head_dim, scale, ld, ld, ld, ld, stream);
|
||||
}
|
||||
|
||||
// The same, each operand at its own token pitch in elements -- a column slice of a fused [q|k|v]
|
||||
// projection reads at the projection's row. Every pitch and every head offset stays a multiple of
|
||||
// 8 elements, which is what the 16-byte K and V fetches need.
|
||||
// As above, each operand at its own token pitch in elements (e.g. a column slice of a fused
|
||||
// [q|k|v] projection). Pitches and head offsets must be multiples of 8 elements for the 16-byte
|
||||
// K and V fetches.
|
||||
extern "C" int r4d_attn_vit_h72_strided_bf16(const void* q, const void* k, const void* v, void* o,
|
||||
const void* cu_seqlens, int num_seqs, int max_seqlen,
|
||||
int heads, int head_dim, float scale, int q_ld,
|
||||
@@ -489,8 +419,8 @@ extern "C" int r4d_attn_vit_h72_strided_bf16(const void* q, const void* k, const
|
||||
(const int*)cu_seqlens, heads, scale, q_ld, k_ld, v_ld, o_ld); \
|
||||
} while (0)
|
||||
|
||||
if (V_SPLIT > 0 && max_seqlen < V_SPLIT) V_LAUNCH(V_SNWARPS, V_STILE, V_SQB);
|
||||
else V_LAUNCH(V_NWARPS, V_TILE, V_QB);
|
||||
if (max_seqlen < V_SPLIT) V_LAUNCH(V_SNWARPS, V_STILE, V_SQB);
|
||||
else V_LAUNCH(V_NWARPS, V_TILE, V_QB);
|
||||
#undef V_LAUNCH
|
||||
|
||||
hipError_t e = hipGetLastError();
|
||||
@@ -498,8 +428,7 @@ extern "C" int r4d_attn_vit_h72_strided_bf16(const void* q, const void* k, const
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The geometry this build is compiled for: head_dim, the two query-block heights, and the length
|
||||
// at which the launcher switches between them.
|
||||
// Compiled geometry: head_dim, the two query-block heights, and the switch length.
|
||||
extern "C" void r4d_attn_vit_dims(int* head_dim, int* rows_large, int* rows_small, int* split) {
|
||||
if (head_dim) *head_dim = 72;
|
||||
if (rows_large) *rows_large = V_NWARPS * 16 * V_QB;
|
||||
@@ -508,10 +437,6 @@ extern "C" void r4d_attn_vit_dims(int* head_dim, int* rows_large, int* rows_smal
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader is r4d_attn_args.h, a header this kernel family shares because the paged
|
||||
// geometries implement one op and take one operand list. See libr4d/r4d_args.h for why there is no
|
||||
// adapter directory between the core and these launches.
|
||||
|
||||
/* ------------------------------------------------------------------ dense (vision) */
|
||||
|
||||
@@ -526,25 +451,21 @@ extern "C" int r4d_rad_attn_vit(const RadArgs* a, RadStream s) {
|
||||
if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL);
|
||||
if (!r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE);
|
||||
|
||||
/* [tokens, heads, 72] dense, or [tokens, heads * 72] read at its own row pitch -- a column
|
||||
* slice of a fused projection. The width of a row is the operand's; its pitch is what the
|
||||
* kernel steps by. */
|
||||
/* [tokens, heads, 72] dense, or [tokens, heads * 72] at its own row pitch (a column slice of
|
||||
* a fused projection). */
|
||||
const long long head_dim = r4d_geti_or(a, "head_dim", q->rank == 3 ? q->shape[2] : 72);
|
||||
if (head_dim != 72) return R4D_NO(RAD_E_SHAPE);
|
||||
/* Every key of a segment is attended to; a window would be ignored, so it is refused. */
|
||||
if (r4d_geti_or(a, "window", 0) != 0) return R4D_NO(RAD_E_INVAL);
|
||||
auto rows = [&](const RadTensor* t, long long* n_tok, long long* n_head, long long* ld) {
|
||||
long long width = 1;
|
||||
for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i];
|
||||
if (t->rank < 2 || width % head_dim) return false;
|
||||
*n_head = width / head_dim;
|
||||
*ld = r4d_rows_pitch(t, width, n_tok);
|
||||
return *ld >= 0;
|
||||
};
|
||||
/* The kernel attends every key of a segment, its bounds read as they stand, so a window,
|
||||
* blocks or a cu_seqlens in finer units are refused. */
|
||||
if (r4d_geti_or(a, "window", 0) != 0 || r4d_geti_or(a, "block", 0) != 0 ||
|
||||
r4d_geti_or(a, "cu_div", 1) != 1)
|
||||
return R4D_NO(RAD_E_INVAL);
|
||||
long long total = 0, heads = 0, q_ld = 0;
|
||||
long long tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0, to = 0, ho = 0, o_ld = 0;
|
||||
if (!rows(q, &total, &heads, &q_ld) || !rows(k, &tk, &hk, &k_ld) ||
|
||||
!rows(v, &tv, &hv, &v_ld) || !rows(o, &to, &ho, &o_ld))
|
||||
if (!r4d_head_rows(q, head_dim, &total, &heads, &q_ld) ||
|
||||
!r4d_head_rows(k, head_dim, &tk, &hk, &k_ld) ||
|
||||
!r4d_head_rows(v, head_dim, &tv, &hv, &v_ld) ||
|
||||
!r4d_head_rows(o, head_dim, &to, &ho, &o_ld))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
if (hk != heads || hv != heads || ho != heads) return R4D_NO(RAD_E_SHAPE);
|
||||
if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -552,9 +473,8 @@ extern "C" int r4d_rad_attn_vit(const RadArgs* a, RadStream s) {
|
||||
|
||||
const int num_seqs = (int)(cu->shape[0] - 1);
|
||||
|
||||
/* max_seqlen selects the query-block height and is a bound, not a length: the kernel reads the
|
||||
* device-side cu_seqlens itself. Absent, the total token count is a valid bound and picks the
|
||||
* tall instantiation -- a speed choice, never a correctness one. */
|
||||
/* max_seqlen is a bound that selects the query-block height (speed only); the kernel reads
|
||||
* device-side cu_seqlens. Defaults to the total token count. */
|
||||
long long msl = r4d_geti_or(a, "max_seqlen", 0);
|
||||
if (msl <= 0) msl = total;
|
||||
|
||||
@@ -564,5 +484,6 @@ extern "C" int r4d_rad_attn_vit(const RadArgs* a, RadStream s) {
|
||||
num_seqs, (int)msl, (int)heads, (int)head_dim,
|
||||
scale, (int)q_ld, (int)k_ld, (int)v_ld, (int)o_ld,
|
||||
s);
|
||||
return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
|
||||
if (e == 0) return RAD_OK;
|
||||
return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
|
||||
}
|
||||
+78
-114
@@ -1,34 +1,26 @@
|
||||
// Shared device-side machinery for R4D. Everything here is layout algebra verified on hardware
|
||||
// by targeted layout probes. Do not "fix" any of it from a vendor doc.
|
||||
// Shared device-side machinery for R4D. The layout algebra here was verified on hardware with
|
||||
// targeted probes; do not "fix" it from a vendor doc.
|
||||
#pragma once
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <cstdint>
|
||||
|
||||
// THE W4A8 SCALE GROUP LIVES HERE, not in either GEMM, because BOTH of them read the same packed
|
||||
// artifact and a build where they disagree is silently wrong rather than a link error. The
|
||||
// plugin build passes -DR4D_GEMM_W4A8_GROUP to every W4 translation unit; this is the fallback for
|
||||
// a translation unit built without it, and it has to be the same number for all of them.
|
||||
#ifndef R4D_GEMM_W4A8_GROUP
|
||||
// The W4A8 scale group lives here, not in either GEMM, because both read the same packed weight and
|
||||
// a disagreement would be silently wrong, not a link error. r4d_gemm_args.h restates it and checks
|
||||
// it against the layout constant.
|
||||
#define R4D_GEMM_W4A8_GROUP 128 // K per scale
|
||||
#endif
|
||||
|
||||
// ---- ragged query batches ----------------------------------------------------------------------
|
||||
// A paged-attention batch may present a DIFFERENT query length per sequence: see R4DArgs::cu_q in
|
||||
// r4d.h for why that is the ordinary case rather than an exotic one. These are the two lookups
|
||||
// every kernel that indexes the dense q or out block needs, plus the inverse the split-KV combine
|
||||
// needs because it walks output rows rather than sequences.
|
||||
//
|
||||
// The uniform case -- cu_q null -- compiles to one multiply and no load. The branch is
|
||||
// wave-uniform (cu_q is a kernel argument), so it is a scalar test, and the loads it guards are
|
||||
// scalar too.
|
||||
// A paged-attention batch may have a different query length per sequence (R4DArgs::cu_q in r4d.h).
|
||||
// These are the two lookups every kernel indexing the dense q or out block needs, plus the inverse
|
||||
// for the split-KV combine, which walks output rows rather than sequences. With cu_q null they
|
||||
// compile to one multiply and no load; the branch is wave-uniform (cu_q is a kernel argument).
|
||||
__device__ __forceinline__ int r4d_q_off(const int* cu_q, int seq, int q_len) {
|
||||
return cu_q ? cu_q[seq] : seq * q_len;
|
||||
}
|
||||
__device__ __forceinline__ int r4d_q_len(const int* cu_q, int seq, int q_len) {
|
||||
return cu_q ? (cu_q[seq + 1] - cu_q[seq]) : q_len;
|
||||
}
|
||||
// num_seqs is at most a few tens, so the search is three or four scalar loads, taken once per
|
||||
// block rather than per lane.
|
||||
// num_seqs is at most a few tens, so the search is a few scalar loads, once per block.
|
||||
__device__ __forceinline__ int r4d_q_seq(const int* cu_q, int num_seqs, int q_len, int tok) {
|
||||
if (!cu_q) return tok / q_len;
|
||||
int lo = 0, hi = num_seqs; // invariant: cu_q[lo] <= tok < cu_q[hi]
|
||||
@@ -40,24 +32,21 @@ __device__ __forceinline__ int r4d_q_seq(const int* cu_q, int num_seqs, int q_le
|
||||
}
|
||||
|
||||
// ---- the occupancy a kernel is built for ---------------------------------------------------------
|
||||
// R4D_WAVES(n) fixes the waves a SIMD the compiler schedules a kernel for. Left to itself the
|
||||
// scheduler picks that target, trading registers for occupancy or the reverse, and the choice
|
||||
// moves between compiler releases: LLVM 24 serialises a GEMM's loads to win one more wave a SIMD,
|
||||
// paying a load round trip per WMMA, and elsewhere hoists more loads and gives a wave up. A kernel
|
||||
// whose speed rests on a register budget states the budget with this, so the source and not the
|
||||
// compiler version decides it. `n` may depend on template arguments.
|
||||
// R4D_WAVES(n) fixes the waves per SIMD the compiler schedules a kernel for. Otherwise the
|
||||
// scheduler picks that target itself and the choice moves between compiler releases (LLVM 24
|
||||
// serialises a GEMM's loads to win one more wave, paying a load round trip per WMMA). A kernel
|
||||
// whose speed rests on a register budget states it here. `n` may depend on template arguments.
|
||||
#define R4D_WAVES(n) __attribute__((amdgpu_waves_per_eu((n), (n))))
|
||||
|
||||
typedef short v8s __attribute__((ext_vector_type(8)));
|
||||
typedef float v8f __attribute__((ext_vector_type(8)));
|
||||
typedef float v2f __attribute__((ext_vector_type(2))); // what cvt_pk_f32_fp8 actually returns
|
||||
|
||||
/* A 16-BYTE STAGING REGISTER AS A NATIVE VECTOR. HIP's uint4 is a class template wrapping a union,
|
||||
* and an array of them that a K loop carries -- the next tile's chunks, loaded while this tile is
|
||||
* computed -- is not promoted to registers: LLVM 22 and LLVM 24 both keep it in scratch, so every
|
||||
* staged chunk goes global load, scratch store, scratch load, LDS store. The same array of an
|
||||
* ext_vector_type is promoted. Loaded and stored whole only; r4d_dflash_conv_body.h declares the
|
||||
* same type for a source that is also compiled without this header. */
|
||||
/* A 16-byte staging register as a native vector. HIP's uint4 is a class template wrapping a
|
||||
* union, and an array of them carried across a K loop (the next tile's chunks) is kept in scratch
|
||||
* by LLVM 22 and 24, adding a scratch store and load per chunk; an ext_vector_type array is
|
||||
* promoted to registers. Loaded and stored whole only. r4d_dflash_conv_body.h declares the same
|
||||
* type for a source also compiled without this header. */
|
||||
typedef unsigned int r4d_u32x4 __attribute__((ext_vector_type(4)));
|
||||
|
||||
// exp2 with the hardware transcendental.
|
||||
@@ -70,36 +59,34 @@ __device__ __forceinline__ float ex2(float x) {
|
||||
#endif
|
||||
}
|
||||
|
||||
// f32 -> bf16, round-to-nearest-even. gfx1201 has NO bf16 convert instruction, so this is the
|
||||
// software form (verified absent: v_cvt_pk_bf16_f32).
|
||||
// f32 -> bf16, round-to-nearest-even, in software: gfx1201 has no v_cvt_pk_bf16_f32.
|
||||
__device__ __forceinline__ uint16_t f32_to_bf16(float f) {
|
||||
uint32_t u = __builtin_bit_cast(uint32_t, f);
|
||||
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
|
||||
// ...and back, which is a shift and not a conversion: every bf16 is exactly a float.
|
||||
// And back: a shift, since every bf16 is exactly a float.
|
||||
__device__ __forceinline__ float bf16_to_f32(uint16_t h) {
|
||||
return __builtin_bit_cast(float, (uint32_t)h << 16);
|
||||
}
|
||||
|
||||
// ---- 16-bit values held in whole registers -------------------------------------------------------
|
||||
// LLVM 24 gives gfx12 real 16-bit registers: a value of a 16-bit type lives in one HALF of a VGPR.
|
||||
// Two bf16 assembled into a word then cost a shift and a half move each pair where LLVM 22 used one
|
||||
// v_perm_b32, a bf16 widened to a float costs a half move and a shift, and a 16-bit load goes into a
|
||||
// half (global_load_d16_b16), so it depends on the register's earlier contents and the waitcnt pass
|
||||
// waits for them. The helpers below keep bf16 data in whole 32-bit registers from load to store,
|
||||
// which compiles to the same code under both compilers. The bits are the same as the 16-bit forms.
|
||||
// LLVM 24 gives gfx12 real 16-bit registers: a 16-bit value lives in one half of a VGPR. Packing
|
||||
// two bf16 then costs a shift and a half move per pair instead of one v_perm_b32, widening costs a
|
||||
// half move and a shift, and a 16-bit load into a half (global_load_d16_b16) depends on the
|
||||
// register's earlier contents, so the waitcnt pass waits for them. The helpers below keep bf16 data
|
||||
// in whole 32-bit registers from load to store, which compiles the same under LLVM 22 and 24 and
|
||||
// gives the same bits as the 16-bit forms.
|
||||
|
||||
// f32 -> bf16 rounded to nearest even, as the HIGH half of a word whose low half is not zero:
|
||||
// f32_to_bf16 before its final shift. A NaN can round to infinity here, as there.
|
||||
// f32 -> bf16 rounded to nearest even, as the high half of a word whose low half is not zero
|
||||
// (f32_to_bf16 before its final shift). A NaN can round to infinity, as there.
|
||||
__device__ __forceinline__ uint32_t bf16_hi_rne(float f) {
|
||||
const uint32_t u = __float_as_uint(f);
|
||||
return u + 0x7fffu + ((u >> 16) & 1u);
|
||||
}
|
||||
// The same as (__hip_bfloat16)f computes it (LLVM's own expansion of the conversion): a NaN stays
|
||||
// a NaN, made quiet, and everything else rounds to nearest even. Both results are formed before
|
||||
// the choice so it compiles to one v_cndmask: written as `nan ? u | 0x400000 : u + ...`, the
|
||||
// rounding is too long to speculate and each element becomes an exec-masked branch.
|
||||
// Rounds as (__hip_bfloat16)f does (LLVM's expansion): a NaN stays NaN, quieted; everything else
|
||||
// rounds to nearest even. Both results are formed before the select so it compiles to one
|
||||
// v_cndmask; `nan ? u | 0x400000 : u + ...` makes each element an exec-masked branch.
|
||||
__device__ __forceinline__ uint32_t bf16_hi_rne_nan(float f) {
|
||||
const uint32_t u = __float_as_uint(f);
|
||||
const uint32_t r = u + 0x7fffu + ((u >> 16) & 1u), q = u | 0x400000u;
|
||||
@@ -122,23 +109,20 @@ __device__ __forceinline__ float bf16w_lo(uint32_t w) { return __uint_as_float(w
|
||||
__device__ __forceinline__ float bf16w_hi(uint32_t w) { return __uint_as_float(w & 0xffff0000u); }
|
||||
|
||||
// One 16-bit element of global memory, zero-extended into a whole register (global_load_u16).
|
||||
// Read as a uint16_t and widened afterwards, it is loaded into a register half instead
|
||||
// (global_load_d16_b16, or d16_hi_b16 straight into the bf16's float position), which waits for
|
||||
// the register's other half; through a generic pointer it is a flat load as well. The pointer
|
||||
// must address global memory.
|
||||
// Loaded as uint16_t it would go into a register half (global_load_d16_b16 or d16_hi_b16) and wait
|
||||
// for the other half; through a generic pointer it would also be a flat load. The pointer must
|
||||
// address global memory.
|
||||
typedef __attribute__((address_space(1))) const uint16_t* r4d_gu16;
|
||||
__device__ __forceinline__ uint32_t ldg_u16(const uint16_t* p) { return *(r4d_gu16)p; }
|
||||
// The same element as a bf16 widened to float.
|
||||
__device__ __forceinline__ float ldg_bf16(const uint16_t* p) { return bf16w_lo(ldg_u16(p)); }
|
||||
|
||||
// `lane ^ N` WITHOUT THE LDS PIPE. `__shfl_xor` lowers to `ds_bpermute_b32` plus an
|
||||
// `s_wait_dscnt` -- an LDS round trip, and when the exchange sits on a dependency chain (a dot
|
||||
// product closed inside a token loop, say) that latency is the loop. gfx10 and up carry ROW_XMASK
|
||||
// (0x160 | N) in DPP16, so for N < 16 the partner read is a MODIFIER on the VALU op that consumes
|
||||
// it and costs nothing at all: the compiler emits `v_add_f32_dpp ... row_xmask:2`. N = 16 crosses
|
||||
// the two 16-lane rows of a wave32 and takes v_permlanex16, still one VALU op.
|
||||
// Identical arithmetic to the shuffle it replaces -- same lane mapping, same value -- on a wave
|
||||
// whose lanes are all active, which is every caller's case: a butterfly is a whole-wave step.
|
||||
// `lane ^ N` without the LDS pipe. `__shfl_xor` lowers to `ds_bpermute_b32` plus `s_wait_dscnt`,
|
||||
// an LDS round trip that dominates a dependency chain (e.g. a dot product closed in a token loop).
|
||||
// gfx10+ DPP16 has ROW_XMASK (0x160 | N), so for N < 16 the partner read is a modifier on the
|
||||
// consuming VALU op (`v_add_f32_dpp ... row_xmask:2`). N = 16 crosses the two 16-lane rows of a
|
||||
// wave32 and uses v_permlanex16, still one VALU op. Same lane mapping and value as the shuffle,
|
||||
// provided all lanes are active, which every caller's whole-wave butterfly guarantees.
|
||||
template <int N>
|
||||
__device__ __forceinline__ uint32_t r4d_xor_lane_u32(uint32_t v) {
|
||||
static_assert(N >= 1 && N <= 16 && (N & (N - 1)) == 0, "a lane xor within the wave");
|
||||
@@ -154,8 +138,7 @@ __device__ __forceinline__ float r4d_xor_lane(float v) {
|
||||
return __uint_as_float(r4d_xor_lane_u32<N>(__float_as_uint(v)));
|
||||
}
|
||||
|
||||
// A 64-bit value's partner: the two halves exchanged separately, which is what a 64-bit
|
||||
// `__shfl_xor` does too.
|
||||
// A 64-bit value's partner: the halves exchanged separately, as a 64-bit `__shfl_xor` does.
|
||||
template <int N>
|
||||
__device__ __forceinline__ unsigned long long r4d_xor_lane_u64(unsigned long long v) {
|
||||
const uint32_t lo = r4d_xor_lane_u32<N>((uint32_t)v);
|
||||
@@ -163,29 +146,20 @@ __device__ __forceinline__ unsigned long long r4d_xor_lane_u64(unsigned long lon
|
||||
return ((unsigned long long)hi << 32) | lo;
|
||||
}
|
||||
|
||||
// Exchange a value between lane L and lane L^16 (the two halves a wave32 WMMA fragment splits a
|
||||
// row across). v_permlanex16_b32 needs IDENTITY selectors to act as a swap: each 4-bit field names
|
||||
// the source lane in the other half. sel0 covers lanes 0-7, sel1 lanes 8-15. Zero selectors would
|
||||
// broadcast lane 0, which is silently wrong rather than obviously wrong.
|
||||
// Exchange between lane L and lane L^16 (the two halves a wave32 WMMA fragment splits a row
|
||||
// across). v_permlanex16_b32 swaps only with identity selectors (each 4-bit field names the source
|
||||
// lane in the other half; sel0 covers lanes 0-7, sel1 lanes 8-15); zero selectors would silently
|
||||
// broadcast lane 0.
|
||||
__device__ __forceinline__ float swap16(float x) { return r4d_xor_lane<16>(x); }
|
||||
|
||||
// A WAVE32 SUM, WITHOUT THE LDS CROSSBAR. `__shfl_xor` lowers to `ds_bpermute_b32` on gfx1201
|
||||
// whatever the offset is, and a bpermute is an LDS-pipe instruction: it queues behind every other
|
||||
// LDS access and its latency is LDS latency. On a kernel whose arithmetic between reductions is
|
||||
// small, a five-stage shuffle butterfly is most of the run -- the reductions cost more than the
|
||||
// work between them.
|
||||
// A wave32 sum on DPP instead of the LDS crossbar. `__shfl_xor` is a `ds_bpermute_b32` on gfx1201
|
||||
// at any offset, queued behind other LDS traffic; where little arithmetic separates reductions, a
|
||||
// five-stage shuffle butterfly dominates the run. Offsets 8..1 use row_xmask (dpp_ctrl 0x160 | N)
|
||||
// as a modifier on the add; 16 uses v_permlanex16_b32 (see swap16).
|
||||
//
|
||||
// DPP does the exchange as a MODIFIER ON THE ADD, in the VALU, and gfx10 and later carry
|
||||
// `row_xmask` (dpp_ctrl 0x160 | N) which is an XOR within each row of sixteen -- so four of the
|
||||
// five butterfly offsets are expressible and only 16 crosses rows, where `v_permlanex16_b32` with
|
||||
// IDENTITY selectors is the exchange (see swap16 above on why the selectors must be identity).
|
||||
//
|
||||
// THE LANES EXCHANGED AND THE ORDER OF THE ADDS ARE THE SAME AS THE SHUFFLE LOOP'S, so this is
|
||||
// bit-identical and not merely equivalent: a kernel may be moved onto it without its generated
|
||||
// text changing at any context length.
|
||||
//
|
||||
// Row and bank masks are all-ones because every lane participates; `bound_ctrl` only decides what
|
||||
// a lane with no partner reads, and inside a full wave every lane has one.
|
||||
// The lanes exchanged and the order of the adds match the shuffle loop, so this is bit-identical
|
||||
// and a kernel can move onto it without its output changing. Row and bank masks are all-ones since
|
||||
// every lane participates; `bound_ctrl` is moot because every lane has a partner.
|
||||
template <int CTRL>
|
||||
__device__ __forceinline__ float r4d_dpp_xor_add(float v) {
|
||||
return v + __builtin_bit_cast(float,
|
||||
@@ -201,10 +175,9 @@ __device__ __forceinline__ float r4d_wave_sum(float v) {
|
||||
return v;
|
||||
}
|
||||
|
||||
// THE SAME BUTTERFLY OVER A GROUP OF W LANES, W a power of two up to the wave, for a reduction that
|
||||
// closes over fewer lanes than the wave as well as over all of it: the exchanges the loop
|
||||
// `for (o = W / 2; o; o >>= 1) v = op(v, __shfl_xor(v, o))` makes, in its order, so bit-identical
|
||||
// to that loop for the reason r4d_wave_sum gives.
|
||||
// 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.
|
||||
template <int W>
|
||||
__device__ __forceinline__ float r4d_xor_sum(float v) {
|
||||
static_assert(W >= 1 && W <= 32 && (W & (W - 1)) == 0, "a power-of-two group within the wave");
|
||||
@@ -229,11 +202,10 @@ __device__ __forceinline__ float r4d_xor_max(float v) {
|
||||
|
||||
__device__ __forceinline__ float r4d_wave_max(float v) { return r4d_xor_max<32>(v); }
|
||||
|
||||
/* A WAVE'S INCLUSIVE PREFIX AND SUFFIX SUMS, in registers: row_shr (or row_shl) 1, 2, 4 and 8
|
||||
* within each row of sixteen, then the other row's total from one readlane. Lane L ends holding
|
||||
* the sum over lanes 0..L (prefix) or L..31 (suffix). For the scans a workgroup would otherwise run
|
||||
* as step-doubling rounds through LDS, two barriers a round; integer sums, so the order the lanes
|
||||
* combine in does not matter. Every lane of the wave must be active. */
|
||||
/* A wave's inclusive prefix and suffix sums in registers: row_shr (or row_shl) 1, 2, 4 and 8
|
||||
* within each row of sixteen, then the other row's total from one readlane. Lane L ends with the
|
||||
* sum over lanes 0..L (prefix) or L..31 (suffix). Replaces LDS step-doubling scans (two barriers a
|
||||
* round); integer sums, so combine order does not matter. Every lane must be active. */
|
||||
__device__ __forceinline__ uint32_t r4d_wave_prefix_u32(uint32_t x, int lane) {
|
||||
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x111, 0xF, 0xF, true); /* row_shr:1 */
|
||||
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x112, 0xF, 0xF, true); /* row_shr:2 */
|
||||
@@ -255,10 +227,8 @@ __device__ __forceinline__ uint32_t r4d_wave_suffix_u32(uint32_t x, int lane) {
|
||||
// 8x8 transpose of 16-bit elements across each group of 8 lanes. Lane j receives element j from
|
||||
// each of the 8 lanes in its group; the 8 addresses may be arbitrarily strided.
|
||||
__device__ __forceinline__ v8s load_tr_b128(const void* p) {
|
||||
// This builtin requires a GLOBAL (address_space(1)) pointer from ROCm 7.2 / LLVM 22 on: a
|
||||
// generic pointer does not convert implicitly and the library does not compile without the
|
||||
// cast. The cast is sound here: every caller passes a global address, which is what
|
||||
// "global_load" means.
|
||||
// This builtin requires a global (address_space(1)) pointer from ROCm 7.2 / LLVM 22 on; a
|
||||
// generic pointer does not convert implicitly. Every caller passes a global address.
|
||||
return __builtin_amdgcn_global_load_tr_b128_v8i16(
|
||||
(__attribute__((address_space(1))) v8s*)const_cast<void*>(p));
|
||||
}
|
||||
@@ -275,11 +245,10 @@ __device__ __forceinline__ uint32_t byte_gather(uint32_t w0, uint32_t w1, int se
|
||||
|
||||
__device__ __forceinline__ void sched_barrier() { __builtin_amdgcn_sched_barrier(0); }
|
||||
|
||||
// __syncthreads() is a workgroup-scope acquire-release fence over ALL address spaces, so on gfx12
|
||||
// it emits `global_inv scope:SCOPE_SE` on both sides of the barrier -- a vector-cache invalidate.
|
||||
// Every one of those throws away the L0/L1 lines the next tile's KV loads would have hit. These
|
||||
// barriers only ever order LDS traffic, so scoping the fence to the local address space makes
|
||||
// the invalidate disappear.
|
||||
// __syncthreads() is a workgroup-scope acquire-release fence over all address spaces, so on gfx12
|
||||
// it emits `global_inv scope:SCOPE_SE` on both sides, discarding the L0/L1 lines the next tile's
|
||||
// KV loads would hit. These barriers only order LDS traffic, so the fence is scoped to the local
|
||||
// address space and the invalidate disappears.
|
||||
__device__ __forceinline__ void lds_barrier() {
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local");
|
||||
__builtin_amdgcn_s_barrier();
|
||||
@@ -293,26 +262,21 @@ __device__ __forceinline__ uint2 swap16_u2p(uint2 v) {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// WORKGROUP WIDTH FOR THE ACTIVATION-PATH KERNELS
|
||||
// Workgroup width for the activation-path kernels
|
||||
//
|
||||
// All four of them (had_quant_act_i8, rmsnorm_had_quant_i8, gated_had_quant_i8,
|
||||
// gdn_gated_norm_had_quant_i8) launch ONE workgroup per row, so at a decode batch the grid is a few
|
||||
// tens of workgroups on a 64-CU part and they are latency bound, not bandwidth bound: a row moves
|
||||
// tens of kilobytes and costs a small multiple of the launch floor. Widening the workgroup is the
|
||||
// only knob that adds parallelism without changing the algorithm, and it is the large win at small
|
||||
// M.
|
||||
// had_quant_act_i8, rmsnorm_had_quant_i8, gated_had_quant_i8 and gdn_gated_norm_had_quant_i8 launch
|
||||
// one workgroup per row, so at decode batch sizes the grid is a few tens of workgroups on a 64-CU
|
||||
// part and they are latency bound. Widening the workgroup is the only knob that adds parallelism,
|
||||
// and it is the large win at small M.
|
||||
//
|
||||
// It stops paying, and then reverses hard, once the grid alone fills the machine. At 1024 threads
|
||||
// there is a RESIDENCY CLIFF just past M=32 -- the wider workgroup stops fitting and the cost
|
||||
// roughly doubles. It is a residency effect and not an address effect; the buffer's placement does
|
||||
// not move it. So 1024 is taken only where there is clearance below the cliff, because a batch
|
||||
// that lands just above it would pay multiples of what the narrow width costs.
|
||||
// It reverses once the grid alone fills the machine. At 1024 threads there is a residency cliff
|
||||
// just past M=32 where the wider workgroup stops fitting and the cost roughly doubles, so 1024 is
|
||||
// used only with clearance below it.
|
||||
//
|
||||
// WHERE 512 STOPS PAYING MOVES WITH K, because the LDS a row needs (K floats) is what caps how
|
||||
// many of these workgroups a CU can hold. At K=8704 only one fits at either width, so the wider
|
||||
// workgroup is simply more waves per SIMD and it wins out to large M. At K=3072 five fit, the grid
|
||||
// fills the part on its own, and past M~72 the narrow one is even. The thresholds below are those
|
||||
// crossovers.
|
||||
// Where 512 stops paying depends on K, because the K floats of LDS a row needs cap how many
|
||||
// workgroups a CU holds. At K=8704 only one fits at either width, so wider wins out to large M; at
|
||||
// K=3072 five fit, the grid fills the part, and past M~72 the narrow width is even. The thresholds
|
||||
// below are those crossovers.
|
||||
__host__ __device__ __forceinline__ int r4d_act_threads(int M, int K) {
|
||||
if (M <= 32) return 1024;
|
||||
const int lim = K >= 8192 ? (1 << 24) : (K >= 4096 ? 120 : 72);
|
||||
|
||||
@@ -1,30 +1,24 @@
|
||||
// r4d_dequant_w4_bf16.hip - r4d_dequant_w4_bf16: the packed 4-bit weight back to a plain row-major
|
||||
// bf16 [N, K].
|
||||
//
|
||||
// WHY THIS EXISTS. W4A8 buys nothing at prefill: the iu8 and fp8 matrix rates are within a couple
|
||||
// of percent of each other and the shape is compute-bound. But once the weights are STORED at 4
|
||||
// bits there is no fp8 copy to fall back on, so the requirement at prefill is "do not regress", not
|
||||
// "win" -- and the skinny W4A8 GEMM cannot meet even that, because a block owns 64 rows and
|
||||
// therefore re-reads the whole weight slice once per 64 output rows. Its rate is flat in M for
|
||||
// that reason; it is structural and no choice of geometry fixes it. Dequantising one layer into a
|
||||
// scratch buffer and handing it to the tuned bf16 GEMM costs one extra write and read of the bf16
|
||||
// weight, a few percent of the GEMM it feeds.
|
||||
// Used at prefill. W4A8 gains nothing there (iu8 and fp8 matrix rates are within a few percent and
|
||||
// the shape is compute-bound), and the skinny W4A8 GEMM re-reads the whole weight slice once per
|
||||
// 64 output rows, so its rate is flat in M. Dequantising one layer into scratch and running the
|
||||
// tuned bf16 GEMM costs one extra write and read of the bf16 weight, a few percent of the GEMM.
|
||||
//
|
||||
// TWO ENCODINGS SHARE THESE BYTES AND THEY DIFFER BY BIT 3, so the caller has to say which. The
|
||||
// symmetric grid stores a TWO'S COMPLEMENT code -- that is what lets the int8 GEMM read the
|
||||
// high-nibble byte signed and get 16*q directly -- and its value is (n^8)-8, i.e. n=8 means -8.
|
||||
// The asymmetric grid stores an UNSIGNED nibble and subtracts a per-group zero, which is what lets
|
||||
// the same GEMM read it unsigned and correct with an activation row-sum. Feeding one to the other
|
||||
// is silently wrong rather than obviously wrong: it agrees for n<8 and is off by 16 above.
|
||||
// Two encodings share these bytes and differ by bit 3, so the caller must say which. The
|
||||
// symmetric grid stores a two's complement code, value (n^8)-8, so the int8 GEMM can read the
|
||||
// high-nibble byte signed and get 16*q. The asymmetric grid stores an unsigned nibble minus a
|
||||
// per-group zero, corrected in the GEMM by an activation row-sum. Mixing them up agrees for n<8
|
||||
// and is off by 16 above.
|
||||
//
|
||||
// It is very nearly lossless: the stored value is a 4-bit code times an f16 scale, and bf16's
|
||||
// 8-bit mantissa holds that to within a ULP.
|
||||
// Nearly lossless: a 4-bit code times an f16 scale fits bf16's 8-bit mantissa to within a ULP.
|
||||
//
|
||||
// UNDOING THE FRAGMENT ORDER. radiance_w4.pack lays a dword out as [t][kb][lh][r][s] with eight
|
||||
// nibbles along i, where t = n/16, r = n%16, kb = k/64, s = (k%64)/16, and the k inside the step is
|
||||
// 4*lh + _KOFF[i] with _KOFF = {0,8,1,9,2,10,3,11}. One thread per dword scatters its eight
|
||||
// nibbles; the scale dword lives at [t][g][r] and carries the f16 scale low and -(1024+zero) high,
|
||||
// so the same routine serves the symmetric grid (zero == 8) and the asymmetric one.
|
||||
// Fragment order: radiance_w4.pack lays a dword out as [t][kb][lh][r][s] with eight nibbles along
|
||||
// i, where t = n/16, r = n%16, kb = k/64, s = (k%64)/16, and the k inside the step is
|
||||
// 4*lh + _KOFF[i] with _KOFF = {0,8,1,9,2,10,3,11}. One thread per dword scatters its eight
|
||||
// nibbles. The scale dword at [t][g][r] holds the f16 scale low and -(1024+zero) high, so one
|
||||
// routine serves the symmetric grid (zero == 8) and the asymmetric one.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
@@ -63,8 +57,8 @@ __global__ __launch_bounds__(R4D_DQ_THREADS) void r4d_dequant_w4_bf16_kernel(
|
||||
for (int i = 0; i < 8; i++) {
|
||||
const int n = (int)((w >> (4 * i)) & 0xF);
|
||||
const float q = twos ? (float)((n ^ 8) - 8) : (float)n;
|
||||
// 4*lh is part of the k, not just of the scale lookup: position (lh, i) holds
|
||||
// kk = 4*lh + _KOFF[i], so lh=0 covers {0,8,1,9,2,10,3,11} and lh=1 the other eight.
|
||||
// Position (lh, i) holds kk = 4*lh + _KOFF[i]: lh=0 covers {0,8,1,9,2,10,3,11}, lh=1
|
||||
// the other eight.
|
||||
const int k = kbase + r4d_dq_koff[i];
|
||||
Out[(size_t)row_n * K + k] = __float2bfloat16((q - (twos ? 0.f : zero)) * sc);
|
||||
}
|
||||
@@ -86,8 +80,7 @@ void r4d_dequant_w4_bf16(long wq, long ws, long out, int N, int K, int group, in
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why an
|
||||
// entry point takes the ABI's own argument list directly rather than going through an adapter.
|
||||
// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h.
|
||||
/* ------------------------------------------------------------------ dequant */
|
||||
|
||||
enum { D_WQ = 0, D_WS, D_Y };
|
||||
|
||||
@@ -1,28 +1,26 @@
|
||||
// DFlash2 grouped dynamic depthwise convolution -- device math only.
|
||||
//
|
||||
// Deliberately free of <hip/hip_runtime.h> so the identical source can be compiled standalone to
|
||||
// gfx1201 assembly with a stock clang (no ROCm install) for ISA review, and as part of libr4d.so.
|
||||
// Free of <hip/hip_runtime.h> so the same source compiles standalone to gfx1201 assembly with a
|
||||
// stock clang (no ROCm) for ISA review, as well as into libr4d.so.
|
||||
//
|
||||
// The op, per DFlash2's _grouped_conv with taps=2, group_size=16:
|
||||
//
|
||||
// out[t,h] = (base[0,h] + delta[t,0,g]) * x[t,h]
|
||||
// + (base[1,h] + delta[t,1,g]) * x[t-1,h] * ((t % block) >= 1) g = h / group
|
||||
//
|
||||
// The reference builds this as ~6 full [T,H] elementwise passes plus a materialised
|
||||
// [T, taps, num_groups, group] coefficient tensor. Every one of those intermediates is consumed
|
||||
// exactly once, so the fused form reads x, delta and base once and writes out once.
|
||||
// The reference uses ~6 [T,H] elementwise passes plus a materialised [T, taps, num_groups, group]
|
||||
// coefficient tensor; the fused form reads x, delta and base once and writes out once.
|
||||
#pragma once
|
||||
|
||||
typedef unsigned int r4d_u32;
|
||||
typedef unsigned short r4d_u16;
|
||||
typedef r4d_u32 r4d_u32x4 __attribute__((ext_vector_type(4)));
|
||||
|
||||
// A 16-byte load addressed both ways. The subscript must come off a union member and never off a
|
||||
// vector via __builtin_bit_cast: bit-casting a vector SUBSCRIPT silently yields element 0's bits.
|
||||
// A 16-byte load addressed both ways. Subscript the union member, never a bit-cast vector:
|
||||
// bit-casting a vector subscript silently yields element 0's bits.
|
||||
union R4dV8 { r4d_u32x4 v; r4d_u16 h[8]; };
|
||||
|
||||
// Under hipcc these are device functions; the standalone ISA harness compiles the same source with
|
||||
// a plain clang targeting amdgcn, where there is no __device__ and everything is already device code.
|
||||
// Device functions under hipcc; plain always-inline functions under a standalone amdgcn clang.
|
||||
#ifndef R4D_DEV
|
||||
#ifdef __HIP__
|
||||
#define R4D_DEV __device__ __forceinline__
|
||||
@@ -41,9 +39,8 @@ R4D_DEV r4d_u16 r4d_f2bf(float f) {
|
||||
return (r4d_u16)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
|
||||
// One thread owns 8 contiguous channels: a single dwordx4 in and out. group_size 16 divides that
|
||||
// span, so the group index -- and therefore both delta scalars -- are uniform over the thread's 8
|
||||
// channels and are loaded once rather than per channel.
|
||||
// One thread owns 8 contiguous channels (one dwordx4 in and out). The group size (16) is a multiple
|
||||
// of 8, so the group index and both delta scalars are uniform per thread and loaded once.
|
||||
template <int TAPS, int GROUP>
|
||||
R4D_DEV void r4d_dflash_conv_body(const r4d_u16* __restrict__ x,
|
||||
const r4d_u16* __restrict__ delta,
|
||||
@@ -53,16 +50,13 @@ R4D_DEV void r4d_dflash_conv_body(const r4d_u16* __restrict__ x,
|
||||
int blockmask, int t, int hv) {
|
||||
if (hv >= vpr) return;
|
||||
|
||||
// Split every address into a wave-uniform pointer and a lane offset the backend can keep in a
|
||||
// single 32-bit VGPR -- gfx12's saddr form. Two things are load-bearing:
|
||||
//
|
||||
// * the mask. The backend will only fold a lane offset into saddr if it can prove the
|
||||
// byte-scaled offset stays inside 32 bits. A lane index built from workgroup_id has no
|
||||
// known bound, so it widens the address to a 64-bit vector add and pays a
|
||||
// v_add_co_u32 / v_add_co_ci_u32 pair per load. __builtin_assume does NOT propagate here;
|
||||
// the AND does, for one cheap VALU op.
|
||||
// * pointer + offset, NOT a vector-typed array indexed by lane. The array form makes the
|
||||
// backend materialise a separate 64-bit address per pointer instead of sharing one offset.
|
||||
// Split each address into a wave-uniform pointer and a 32-bit lane offset (gfx12 saddr form).
|
||||
// Do not change either of these:
|
||||
// * The mask: the backend folds a lane offset into saddr only if it can prove the byte offset
|
||||
// fits 32 bits. Without it each load pays a 64-bit v_add_co_u32/v_add_co_ci_u32 pair;
|
||||
// __builtin_assume does not propagate here, the AND does.
|
||||
// * Pointer + offset, not a vector-typed array indexed by lane, which makes the backend
|
||||
// materialise a 64-bit address per pointer.
|
||||
const unsigned off = ((unsigned)hv & 0xFFFFFu) * 8u;
|
||||
const unsigned g = off / (unsigned)GROUP;
|
||||
|
||||
@@ -79,17 +73,13 @@ R4D_DEV void r4d_dflash_conv_body(const r4d_u16* __restrict__ x,
|
||||
for (int j = 0; j < 8; ++j)
|
||||
acc[j] = (r4d_bf2f(b0.h[j]) + d0) * r4d_bf2f(x0.h[j]);
|
||||
|
||||
// Tap `tap` contributes only where the position within the block is at least `tap`. t is the
|
||||
// workgroup's y index, so the predicate is wave-uniform and the skip is a scalar branch --
|
||||
// and on the rows it skips, the shifted load is never issued at all.
|
||||
// Tap `tap` contributes only where the position within the block is >= tap. t is the
|
||||
// workgroup's y index, so this is a scalar branch and skipped rows issue no shifted load.
|
||||
#pragma unroll
|
||||
for (int tap = 1; tap < TAPS; ++tap) {
|
||||
// Same rule as above, applied to the shifted operands: every uniform term folds into its
|
||||
// own pointer so the only thing left varying per lane is the bounded offset. Adding tap*NG
|
||||
// into the delta INDEX instead of the pointer is enough to lose saddr again. These are
|
||||
// hoisted OUT of the predicate: they are scalar address arithmetic on a path the backend
|
||||
// will not fold into saddr from inside a branch, and an address that is merely formed and
|
||||
// never dereferenced costs nothing.
|
||||
// Same saddr rule: uniform terms go into the pointer (adding tap*NG to the delta index
|
||||
// instead loses saddr). The pointers are formed outside the branch, because the backend
|
||||
// does not fold them into saddr from inside it; an unused address costs nothing.
|
||||
const r4d_u16* __restrict__ xprev = xrow - (long)tap * H;
|
||||
const r4d_u16* __restrict__ btap = base + (long)tap * H;
|
||||
const r4d_u16* __restrict__ dtap = drow + (long)tap * NG;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// DFlash2 grouped dynamic depthwise convolution, fused.
|
||||
//
|
||||
// The device math lives in r4d_dflash_conv_body.h, deliberately free of HIP headers so the same
|
||||
// source compiles standalone to gfx1201 assembly with a stock clang for ISA review.
|
||||
// Device math is in r4d_dflash_conv_body.h (HIP-header-free for standalone ISA review).
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "r4d_gdn_args.h"
|
||||
#include "r4d_dflash_conv_body.h"
|
||||
@@ -21,11 +20,11 @@ __global__ __launch_bounds__(DFC_THREADS) void r4d_dflash_conv_kernel(
|
||||
}
|
||||
|
||||
// x [T, H] bf16, row pitch H
|
||||
// delta [T, taps, NG] bf16, row pitch dpitch -- this is a SLICE of the [T, 2, taps, NG] kernel
|
||||
// projection, so dpitch is 2*taps*NG, not taps*NG. Passing the packed pitch
|
||||
// silently reads the other side's coefficients; it is not a shape error.
|
||||
// delta [T, taps, NG] bf16, row pitch dpitch: a slice of the [T, 2, taps, NG] kernel projection,
|
||||
// so dpitch is 2*taps*NG. The packed pitch (taps*NG) would silently read the
|
||||
// other half's coefficients.
|
||||
// base [taps, H] bf16, contiguous
|
||||
// out [T, H] bf16. Must not alias x -- tap 1 of row t reads row t-1 of the INPUT.
|
||||
// out [T, H] bf16. Must not alias x: tap 1 of row t reads input row t-1.
|
||||
extern "C" int r4d_dflash_conv_t2_g16_bf16(
|
||||
const void* x, const void* delta, const void* base, void* out,
|
||||
int T, int H, int dpitch, int NG, int taps, int group, int block_size, void* stream)
|
||||
@@ -44,9 +43,7 @@ extern "C" int r4d_dflash_conv_t2_g16_bf16(
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The shared operand helpers are r4d_gdn_args.h. See libr4d/r4d_args.h for why there is no
|
||||
// adapter directory between the core and these launches.
|
||||
// Shared operand helpers: r4d_gdn_args.h.
|
||||
/* ------------------------------------------------------------------ dflash conv */
|
||||
|
||||
enum { DC_X = 0, DC_DELTA, DC_BASE, DC_OUT };
|
||||
@@ -60,16 +57,15 @@ extern "C" int r4d_rad_dflash_conv(const RadArgs* a, RadStream s) {
|
||||
if (x->rank != 2 || o->rank != 2 || d->rank < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!r4d_contig(x) || !r4d_contig(o) || !r4d_contig(bs)) return R4D_NO(RAD_E_STRIDE);
|
||||
|
||||
/* "out must not alias x" is in the entry point's own contract and nothing downstream checks
|
||||
* it -- the kernel reads x while writing out, so an alias is silent corruption. */
|
||||
/* out must not alias x (the kernel reads x while writing out); nothing downstream checks it. */
|
||||
if (x->data == o->data) return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
const long long T = x->shape[0];
|
||||
const long long H = x->shape[1];
|
||||
if (o->shape[0] != T || o->shape[1] != H) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* delta is a SLICE of the [T, 2, taps, NG] kernel projection, so its row pitch is 2*taps*NG
|
||||
* and not the slice's own width. Reading it off stride[0] is what makes the slice legal. */
|
||||
/* delta is a slice of the [T, 2, taps, NG] projection: its row pitch (from stride[0]) is
|
||||
* 2*taps*NG, not the slice width. */
|
||||
const long long dpitch = r4d_row_pitch(d);
|
||||
if (dpitch < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
|
||||
@@ -78,14 +74,12 @@ extern "C" int r4d_rad_dflash_conv(const RadArgs* a, RadStream s) {
|
||||
const int NG = (int)r4d_geti_or(a, "NG", 0);
|
||||
const int bsz = (int)r4d_geti_or(a, "block_size", 0);
|
||||
if (NG <= 0 || bsz <= 0) return R4D_NO(RAD_E_INVAL);
|
||||
/* block_size is masked with block_size-1 in the kernel body, so only a power of two is
|
||||
* admissible. That is a property of the VALUE and not a bound a constraint can express, which
|
||||
* is why libr4d's registry leaves it out of the predicates and the entry point rejects it --
|
||||
* except that libr4d's entry point does not, so this shim does. */
|
||||
/* The kernel masks with block_size-1, so block_size must be a power of two; a row constraint
|
||||
* cannot express that, so it is checked here. */
|
||||
if (bsz & (bsz - 1)) return R4D_NO(RAD_E_INVAL);
|
||||
if (dpitch != 2LL * taps * NG) return R4D_NO(RAD_E_STRIDE);
|
||||
|
||||
return r4d_dflash_conv_t2_g16_bf16(x->data, d->data, bs->data, o->data,
|
||||
(int)T, (int)H, (int)dpitch, NG, taps, group, bsz, s);
|
||||
return R4D_RAW(r4d_dflash_conv_t2_g16_bf16(x->data, d->data, bs->data, o->data, (int)T,
|
||||
(int)H, (int)dpitch, NG, taps, group, bsz, s));
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
// DFlash2's candidate selector: the edge scores and the path walk, one workgroup a sequence.
|
||||
// DFlash2's candidate selector: edge scores and the path walk, one workgroup per sequence.
|
||||
//
|
||||
// A block-diffusion drafter proposes every position of a block in ONE backbone pass, so it has no
|
||||
// way to condition position l+1 on what it chose at position l -- the two were computed together.
|
||||
// The selector is what puts that dependence back. Each position keeps the draft head's top K
|
||||
// candidates and a low-rank bilinear form scores every (predecessor, candidate) EDGE between
|
||||
// consecutive positions; a greedy walk over those edges picks one token per position.
|
||||
// A block-diffusion drafter proposes every position of a block in one backbone pass, so position
|
||||
// l+1 cannot condition on the choice at l. The selector restores that dependence: each position
|
||||
// keeps the draft head's top K candidates, a low-rank bilinear form scores each (predecessor,
|
||||
// candidate) edge between consecutive positions, and a greedy walk picks one token per position.
|
||||
//
|
||||
// score[s, l, c] = unary[s, l, c]
|
||||
// + sum_r pred[pid(s,l)][r] * hp[s,l][r] * succ[cand[s,l,c]][r]
|
||||
@@ -12,26 +11,20 @@
|
||||
// pid(s, 0) = anchor[s * anchor_stride] the token the target just committed
|
||||
// pid(s, l) = cand[s, l-1, chosen(s, l-1)] the walk's own previous pick
|
||||
//
|
||||
// `hp` IS OPTIONAL, AND ABSENT IT IS ONES -- which drops the trilinear form to a plain BIGRAM one,
|
||||
// score = unary + <pred[pid], succ[cand]>, with no dependence on the hidden state at all. That is
|
||||
// not a degenerate case: it is exactly DSpark's Markov head, a rank-256 learned
|
||||
// bigram bias `markov_w2 @ markov_w1[prev]` added to the draft logits, whose previous token is the
|
||||
// anchor at position 0 and the drafter's own last pick after it. The head is a full-vocabulary
|
||||
// [rank, n_vocab] GEMM per position in the reference and it is SERIAL in exactly the way this walk
|
||||
// already is, so running it here costs the candidate rows of two codebooks instead of seven passes
|
||||
// over 66 MiB -- and the greedy argmax over the base head's top K is what makes that exact enough
|
||||
// to matter only to acceptance (a draft is verified; see the 2-bit head's argument).
|
||||
// `hp` is optional; absent means ones, giving the bigram form score = unary + <pred[pid],
|
||||
// succ[cand]>. That is DSpark's Markov head (a rank-256 learned bigram bias
|
||||
// markov_w2 @ markov_w1[prev] on the draft logits, prev = anchor at position 0, then the last
|
||||
// pick). The reference runs it as a full-vocabulary [rank, n_vocab] GEMM per position, serially;
|
||||
// here it costs only the candidate rows of two codebooks. Restricting to the base head's top K
|
||||
// affects only acceptance, since drafts are verified.
|
||||
//
|
||||
// THE WALK IS SERIAL IN l and that is the whole reason this is a kernel and not a batched GEMM
|
||||
// followed by an argmax. The reference materialises the full [steps, K, K] score tensor -- vLLM's
|
||||
// `_score_edges` einsum -- of which exactly one row per step is ever read, because the predecessor
|
||||
// index is not known until the previous step has been decided. Scoring K*K edges to use K of them
|
||||
// is 16x the work and a round trip per step; here the predecessor's codebook row is fetched after
|
||||
// the previous step's argmax, inside one workgroup, with no launch between.
|
||||
// The walk is serial in l, which is why this is a kernel rather than a batched GEMM plus argmax.
|
||||
// The reference (vLLM's _score_edges einsum) materialises [steps, K, K] scores and reads one row
|
||||
// per step, since the predecessor is only known after the previous step. Here the predecessor's
|
||||
// codebook row is fetched after the previous argmax, inside one workgroup.
|
||||
//
|
||||
// The arithmetic is tiny -- steps * K * R multiply-adds a sequence, 28K at the shipped 7/16/256 --
|
||||
// so this is a latency kernel, not a throughput one. It is written for one workgroup a sequence
|
||||
// with no global synchronisation at all.
|
||||
// The arithmetic is tiny (steps * K * R multiply-adds per sequence, 28K at 7/16/256), so this is a
|
||||
// latency kernel: one workgroup per sequence, no global synchronisation.
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "r4d_gdn_args.h"
|
||||
#include "r4d_dflash_conv_body.h" // r4d_bf2f, r4d_u16
|
||||
@@ -51,11 +44,9 @@
|
||||
// succ [vocab, R] bf16 successor codebook
|
||||
// out [M, out_ld] i32 the chosen token per step
|
||||
//
|
||||
// AN ID OUTSIDE [0, V) IS NOT A CODEBOOK ROW, and one reaches this kernel: row_topk_merge reports a
|
||||
// slot no rank could fill as id -1, and step 0's predecessor is whatever the anchor plane holds. So
|
||||
// the codebook reads are guarded exactly as ref_dflash_select guards them -- a predecessor out of
|
||||
// range contributes nothing, and a candidate out of range scores its unary term alone -- rather
|
||||
// than gathering a row from before or past the codebook.
|
||||
// Ids outside [0, V) do occur (row_topk_merge reports an unfilled slot as -1, and step 0's
|
||||
// predecessor is whatever the anchor plane holds). As in ref_dflash_select, an out-of-range
|
||||
// predecessor contributes nothing and an out-of-range candidate scores its unary term alone.
|
||||
__global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
|
||||
const int* __restrict__ cand, const float* __restrict__ unary,
|
||||
const r4d_u16* __restrict__ hp, const int* __restrict__ anchor,
|
||||
@@ -68,21 +59,19 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
|
||||
const int lane = tid & (DSL_WAVE - 1);
|
||||
const int wave = tid / DSL_WAVE;
|
||||
|
||||
// a[r] = pred[pid][r] * hp[r] -- the half of the bilinear form that does not depend on the
|
||||
// candidate, so it is computed once per step and read K times out of LDS.
|
||||
// a[r] = pred[pid][r] * hp[r]: the candidate-independent half, computed once per step.
|
||||
__shared__ float sa[DSL_MAX_R];
|
||||
__shared__ float ssc[DSL_MAX_K];
|
||||
__shared__ int spid; // the token the previous step chose: this step's predecessor
|
||||
|
||||
// THE CANDIDATES A WAVE SCORES, at most this many: c = wave, wave + DSL_WAVES, ...
|
||||
// Candidates per wave, at most: c = wave, wave + DSL_WAVES, ...
|
||||
constexpr int CPW = (DSL_MAX_K + DSL_WAVES - 1) / DSL_WAVES;
|
||||
|
||||
for (int l = 0; l < steps; ++l) {
|
||||
const long row = (long)s * steps + l;
|
||||
// THE STEP'S OWN READS GO FIRST. The candidates' ids and unary scores do not depend on the
|
||||
// predecessor, so they are in flight with its codebook row instead of behind the barrier, each
|
||||
// a round trip of its own in a walk that is nothing but round trips. A wave past K re-reads
|
||||
// the last candidate and scores nothing.
|
||||
// Candidate ids and unary scores do not depend on the predecessor, so load them first,
|
||||
// overlapping the codebook row fetch. A wave past K re-reads the last candidate and scores
|
||||
// nothing.
|
||||
int cid[CPW];
|
||||
float un[CPW];
|
||||
#pragma unroll
|
||||
@@ -92,15 +81,13 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
|
||||
cid[i] = cand[at];
|
||||
un[i] = unary[at];
|
||||
}
|
||||
// Step 0's predecessor is the committed anchor; every later step's is the token this walk
|
||||
// picked last time round, which thread 0 left in LDS before the barrier that ended that step.
|
||||
// Step 0's predecessor is the committed anchor; later steps use the previous pick, left in
|
||||
// LDS by thread 0 before the barrier that ended that step.
|
||||
const int pid = (l == 0) ? anchor[(long)s * anchor_stride] : spid;
|
||||
const bool pid_ok = pid >= 0 && pid < V;
|
||||
|
||||
const r4d_u16* __restrict__ prow = pred + (long)(pid_ok ? pid : 0) * R;
|
||||
/* hp absent is hp == 1: the predecessor's codebook row goes in untouched. Branching outside
|
||||
* the loop rather than multiplying by a materialised plane of ones keeps the bigram case from
|
||||
* reading R bf16 a step for a number it already knows. */
|
||||
/* hp absent means ones: the predecessor's row is used as is, without reading a plane. */
|
||||
if (!pid_ok) {
|
||||
for (int r = tid; r < R; r += DSL_THREADS) sa[r] = 0.0f;
|
||||
} else if (hp) {
|
||||
@@ -113,10 +100,9 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
// One wave a candidate. R is a multiple of the wave, so the strided loop is balanced and the
|
||||
// reduction is five xor-butterfly steps with no barrier inside it. A candidate out of range
|
||||
// reads codebook row 0 and drops the sum, so the row's loads are never in a branch of their
|
||||
// own; its score is its unary term alone either way.
|
||||
// One wave per candidate. R is a multiple of the wave size, so the reduction is a barrier-free
|
||||
// xor butterfly. An out-of-range candidate reads row 0 and drops the sum, keeping the loads
|
||||
// out of a branch.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < CPW; ++i) {
|
||||
const int c = wave + i * DSL_WAVES;
|
||||
@@ -132,9 +118,9 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
// K is at most 32 and the walk is serial anyway, so the argmax is one thread. Ties go to the
|
||||
// lower index, which is `row_topk`'s own tie rule and therefore the more likely candidate.
|
||||
// Seeded below every score, as ref seeds it, so a NaN in the first slot cannot win by position.
|
||||
// K <= 32 and the walk is serial, so one thread does the argmax. Ties go to the lower index
|
||||
// (row_topk's rule, the more likely candidate). Seeded at -inf, as in ref, so a NaN in the
|
||||
// first slot cannot win by position.
|
||||
if (tid == 0) {
|
||||
int best = 0;
|
||||
float bv = -INFINITY;
|
||||
@@ -144,8 +130,7 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
|
||||
spid = tok;
|
||||
out[(long)s * out_ld + l] = tok;
|
||||
}
|
||||
// Both directions: the next step reads `spid` and overwrites `sa`, and every other thread
|
||||
// is still reading this step's.
|
||||
// The next step reads spid and overwrites sa, which other threads may still be reading.
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
@@ -161,7 +146,7 @@ extern "C" int r4d_dflash_select_bf16(
|
||||
if (R < DSL_WAVE || R > DSL_MAX_R || (R % DSL_WAVE)) return -1;
|
||||
if (V < 1) return -1;
|
||||
if (cand_ld < K || out_ld < steps || anchor_stride < 1) return -1;
|
||||
/* `hp` may be null -- the bigram form -- and then there is no plane to have a pitch. */
|
||||
/* hp may be null (the bigram form); then hp_ld is unused. */
|
||||
if (hp && hp_ld < R) return -1;
|
||||
|
||||
hipLaunchKernelGGL(r4d_dflash_select_kernel, dim3(M), dim3(DSL_THREADS), 0, (hipStream_t)stream,
|
||||
@@ -172,16 +157,14 @@ extern "C" int r4d_dflash_select_bf16(
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The shared operand helpers are r4d_gdn_args.h. See libr4d/r4d_args.h for why there is no
|
||||
// adapter directory between the core and these launches.
|
||||
// Shared operand helpers: r4d_gdn_args.h.
|
||||
/* ------------------------------------------------------------------ dflash select */
|
||||
|
||||
enum { DS_CAND = 0, DS_UNARY, DS_HP, DS_ANCHOR, DS_PRED, DS_SUCC, DS_OUT };
|
||||
|
||||
/* A rank-2 [rows, width] operand whose row pitch libr4d takes explicitly. `width` is checked
|
||||
* rather than derived: this op reads three planes at the SAME row index and a plane whose width is
|
||||
* not what the parameters say would still have a plausible number of rows. */
|
||||
/* A rank-2 [rows, width] operand with an explicit row pitch. `width` is checked, not derived:
|
||||
* three planes are read at the same row index, and a wrong-width plane could still have a
|
||||
* plausible row count. */
|
||||
static long long ds_plane(const RadTensor* t, uint32_t dtype, long long width, long long rows) {
|
||||
if (!t || !t->data || t->rank != 2) return -1;
|
||||
if (t->dtype != dtype) return -1;
|
||||
@@ -198,57 +181,49 @@ extern "C" int r4d_rad_dflash_select(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* pr = r4d_opt(a, DS_PRED);
|
||||
const RadTensor* sc = r4d_opt(a, DS_SUCC);
|
||||
const RadTensor* out = r4d_opt(a, DS_OUT);
|
||||
/* `hp` is the one that may be absent; every other operand is load-bearing. */
|
||||
/* Only hp may be absent. */
|
||||
if (!cand || !un || !anc || !pr || !sc || !out) return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
const long long steps = r4d_geti_or(a, "steps", 0);
|
||||
const long long K = r4d_geti_or(a, "top_k", 0);
|
||||
const long long R = r4d_geti_or(a, "rank", 0);
|
||||
const long long V = r4d_geti_or(a, "n_vocab", 0);
|
||||
/* M IS THE OPERAND'S ROW COUNT AND NOT THE PARAMETER'S. RadArgs carries the geometry with its
|
||||
* RANGES COLLAPSED -- `M` here is the band's bound, max_seqs, and not the sequence count this
|
||||
* step issued (the same trap fill_paged spells out for q_len). Reading the parameter would
|
||||
* make the selector demand max_seqs * steps rows of candidates on a one-sequence step and
|
||||
* refuse every launch. The output plane is one row a sequence, so it is the count. */
|
||||
/* M comes from the output plane (one row per sequence), not the parameter: RadArgs carries the
|
||||
* band's bound (max_seqs) for M, as for q_len in fill_paged. The parameter would demand
|
||||
* max_seqs * steps candidate rows on a one-sequence step. */
|
||||
if (out->rank != 2) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long M = out->shape[0];
|
||||
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || V <= 0) return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
/* The three input planes are read at row s*steps+l, so between them they must hold M*steps
|
||||
* rows -- a short one is a walk that reads another sequence's candidates and proposes a
|
||||
* perfectly plausible draft belonging to the wrong request. */
|
||||
/* The input planes are read at row s*steps+l and must hold M*steps rows; a short plane would
|
||||
* silently draft from another request's candidates. */
|
||||
const long long rows = M * steps;
|
||||
const long long cand_ld = ds_plane(cand, RAD_I32, K, rows);
|
||||
const long long un_ld = ds_plane(un, RAD_F32, K, rows);
|
||||
const long long out_ld = ds_plane(out, RAD_I32, steps, M);
|
||||
/* ABSENT IS A NULL `data`, NOT A MISSING OPERAND: operands are positional, so a graph that
|
||||
* does not use the hidden projection still passes it, empty. Both spellings arrive here and
|
||||
* both mean the bigram form. */
|
||||
/* Absent hp may arrive as a missing operand or as an empty one with null data (operands are
|
||||
* positional); both mean the bigram form. */
|
||||
const bool has_hp = hp && hp->data;
|
||||
const long long hp_ld = has_hp ? ds_plane(hp, RAD_BF16, R, rows) : 0;
|
||||
if (cand_ld < 0 || un_ld < 0 || hp_ld < 0 || out_ld < 0) return R4D_NO(RAD_E_SHAPE);
|
||||
/* One pitch for both, because the kernel indexes them with the same expression. */
|
||||
/* The kernel indexes cand and unary with one pitch. */
|
||||
if (cand_ld != un_ld) return R4D_NO(RAD_E_STRIDE);
|
||||
|
||||
/* The codebooks are gathered by GLOBAL token id, so a row-sharded one would let a rank score
|
||||
* only the candidates that happen to land in its own vocabulary slice -- and the candidates
|
||||
* arrive already merged across ranks. Both are declared replicated at the whole vocabulary;
|
||||
* this is where that would otherwise fail silently. */
|
||||
/* The codebooks are gathered by global token id, and candidates arrive merged across ranks, so
|
||||
* both must be replicated over the whole vocabulary; a row-sharded one would fail silently. */
|
||||
if (pr->dtype != RAD_BF16 || sc->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
|
||||
if (!r4d_contig(pr) || !r4d_contig(sc)) return R4D_NO(RAD_E_STRIDE);
|
||||
if (r4d_numel(pr) < V * R || r4d_numel(sc) < V * R) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* `anchor` is usually the step's own token_ids, which carries `block` ids a sequence with the
|
||||
* anchor first -- so the stride is a parameter and a packed [M] array is the stride-1 case. */
|
||||
/* anchor is usually the step's token_ids (`block` ids per sequence, anchor first), hence the
|
||||
* stride; a packed [M] array is stride 1. */
|
||||
const long long astr = r4d_geti_or(a, "anchor_stride", 1);
|
||||
if (anc->dtype != RAD_I32 && anc->dtype != RAD_U32) return R4D_NO(RAD_E_DTYPE);
|
||||
if (astr < 1 || !r4d_contig(anc)) return R4D_NO(RAD_E_SHAPE);
|
||||
if (r4d_numel(anc) < (M - 1) * astr + 1) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
|
||||
return r4d_dflash_select_bf16(cand->data, un->data, has_hp ? hp->data : nullptr,
|
||||
anc->data, pr->data, sc->data,
|
||||
out->data, (int)M, (int)steps, (int)K, (int)R, (int)V,
|
||||
(int)cand_ld, (int)hp_ld, (int)out_ld, (int)astr, s) == 0
|
||||
? RAD_OK : RAD_E_DEVICE;
|
||||
return R4D_RAW(r4d_dflash_select_bf16(cand->data, un->data, has_hp ? hp->data : nullptr,
|
||||
anc->data, pr->data, sc->data,
|
||||
out->data, (int)M, (int)steps, (int)K, (int)R, (int)V,
|
||||
(int)cand_ld, (int)hp_ld, (int)out_ld, (int)astr, s));
|
||||
}
|
||||
+11
-13
@@ -1,11 +1,10 @@
|
||||
// 16-bit operand traits. The QK and PV matmuls both take a 16-bit A/B pair; which 16-bit format is
|
||||
// a free choice because BOTH sources are exactly representable in either:
|
||||
// * an fp8 e4m3 K/V has 3 mantissa bits, so widening to bf16 (7) or f16 (10) is exact;
|
||||
// * a bf16 query has 7, so bf16->f16 is exact for |q| in [6.1e-5, 65504].
|
||||
// The formats are NOT equal in cost. gfx1201 has NO bf16 convert instruction, so every f32->bf16
|
||||
// is ~6 VALU of software RTNE, while v_cvt_pkrtz_f16_f32 does TWO f32->f16 in ONE. On the softmax
|
||||
// path that is 24 VALU per 8-element P fragment against 4. f16 also carries 3 more mantissa bits.
|
||||
// What f16 gives up is exponent range, and that is exactly what GROW below prices.
|
||||
// 16-bit operand traits. The QK and PV matmuls take a 16-bit A/B pair, and both sources are exact
|
||||
// in either format: an fp8 e4m3 K/V has 3 mantissa bits (bf16 has 7, f16 10), and a bf16 query's
|
||||
// 7 bits are exact in f16 for |q| in [6.1e-5, 65504].
|
||||
// The costs differ. gfx1201 has no bf16 convert, so each f32->bf16 is ~6 VALU of software RTNE,
|
||||
// while v_cvt_pkrtz_f16_f32 converts two f32 in one; on the softmax path that is 24 VALU per
|
||||
// 8-element P fragment against 4. f16 also has 3 more mantissa bits; it gives up exponent range,
|
||||
// which GROW below accounts for.
|
||||
#pragma once
|
||||
#include "r4d_common.h"
|
||||
|
||||
@@ -13,11 +12,10 @@ typedef __bf16 v8bf __attribute__((ext_vector_type(8)));
|
||||
typedef __fp16 v8hf __attribute__((ext_vector_type(8))); // what the f16 WMMA builtin takes
|
||||
typedef __fp16 v2hf __attribute__((ext_vector_type(2))); // what cvt_pkrtz returns
|
||||
|
||||
// GROW = how many octaves the running row max may exceed the REFERENCE max before the
|
||||
// accumulator has to be rescaled. p = 2^(s - m_ref) must stay inside the format, so GROW is
|
||||
// log2(format max) with margin. This is the whole point of the lazy-rescale scheme: the eager
|
||||
// online-softmax form pays 128 multiplies EVERY m-tile; with a reference max it pays them only
|
||||
// when the max moves more than GROW, which at long context is almost never.
|
||||
// GROW = how many octaves the running row max may exceed the reference max before the accumulator
|
||||
// must be rescaled. p = 2^(s - m_ref) must stay inside the format, so GROW is log2(format max) with
|
||||
// margin. Eager online softmax pays 128 multiplies every m-tile; with a reference max they are paid
|
||||
// only when the max moves by more than GROW, which at long context is rare.
|
||||
template<int F16> struct DT16;
|
||||
|
||||
template<> struct DT16<0> { // bf16: exponent range of f32
|
||||
|
||||
+40
-146
@@ -1,26 +1,10 @@
|
||||
// r4d_emit.h -- one launch, two destinations: the stream, or a description of it.
|
||||
// r4d_emit.h -- the one launch path every libr4d kernel goes through.
|
||||
//
|
||||
// ============================== WHY A SINK ==============================
|
||||
//
|
||||
// ABI v10 lets a kernel DESCRIBE its dispatch (`RadDescribeFn`) so the runtime can replay a
|
||||
// repeatedly issued sequence as a graph instead of submitting it node by node. That gives every
|
||||
// shim two entry points, and the typedef's comment names the trap they create: `launch` and
|
||||
// `describe` must dispatch the SAME kernel with the SAME arguments, nothing can check that, and a
|
||||
// divergence is not a crash -- it is a wrong number produced only after a capture, which reads as
|
||||
// a numerics bug anywhere but here.
|
||||
//
|
||||
// The structural answer is to make the two paths unable to disagree: ONE body computes the
|
||||
// geometry and emits into a sink, and the sink is either a stream or a descriptor array. Neither
|
||||
// path can drift, because there is only one of them.
|
||||
//
|
||||
// ============================== THE COPY HAZARD ==============================
|
||||
//
|
||||
// `RadLaunchDesc::params[i]` points INTO `RadLaunchDesc::blob`. Pack into a local and copy the
|
||||
// struct into place and every pointer still aims at the dead local -- garbage, and only on the
|
||||
// graph path. So `r4d_emit` packs DIRECTLY into the destination and the launch path uses a
|
||||
// descriptor of its own rather than a separate argument list. That is also why the launch path
|
||||
// goes through `hipLaunchKernel` (which takes kernelParams) rather than the triple-chevron: the
|
||||
// two paths then share not just the arithmetic but the marshalling.
|
||||
// `hipLaunchKernel` takes the arguments as an array of pointers (kernelParams) and copies each
|
||||
// slot's bytes without conversion, so a `long long` passed for a `uint32_t` parameter would fill a
|
||||
// four-byte slot with eight bytes and corrupt every later argument. r4d_emit takes the kernel
|
||||
// typed, converts every argument to its declared parameter type, and checks the arity at compile
|
||||
// time. It also traces each dispatch under RAD_R4D_TRACE and feeds r4d_record_dispatches (r4d.h).
|
||||
|
||||
#ifndef R4D_EMIT_H
|
||||
#define R4D_EMIT_H
|
||||
@@ -34,152 +18,62 @@
|
||||
#include "rad_abi.h"
|
||||
#include "r4d_args.h"
|
||||
|
||||
/* Where a described launch goes. `desc` null means PERFORM the dispatch; otherwise append to
|
||||
* `desc[0..cap)` and count it in `*n`.
|
||||
*
|
||||
* `stream` is set either way, and is not redundant when describing: a shim whose launch depends on
|
||||
* which stream it is going onto -- the split-K GEMM takes its arrival counter from a per-stream
|
||||
* pool -- must make the same choice in both modes, or the description is of a launch that never
|
||||
* happens. */
|
||||
struct R4dSink;
|
||||
static inline R4dSink r4d_stream_sink(RadStream s);
|
||||
/* r4d_record_dispatches' log (r4d_rows.cpp): while `r4d_dispatch_log` is set, each launch appends
|
||||
* its function and counts it in `r4d_dispatch_n`, which may run past `r4d_dispatch_cap`. */
|
||||
extern const void** r4d_dispatch_log;
|
||||
extern int r4d_dispatch_cap;
|
||||
extern int r4d_dispatch_n;
|
||||
|
||||
struct R4dSink {
|
||||
RadStream stream = nullptr;
|
||||
RadLaunchDesc* desc = nullptr;
|
||||
int cap = 0;
|
||||
int* n = nullptr;
|
||||
};
|
||||
|
||||
/* A sink that only launches, for a caller that has a stream and no descriptor. */
|
||||
static inline R4dSink r4d_stream_sink(RadStream s) { R4dSink k; k.stream = s; return k; }
|
||||
|
||||
/* Pack one argument into `d` at the next aligned offset and point `params[i]` at it. */
|
||||
template <class T>
|
||||
inline bool r4d_pack_one(RadLaunchDesc& d, size_t& off, int& i, const T& v) {
|
||||
static_assert(__is_trivially_copyable(T), "a kernel argument must be trivially copyable");
|
||||
off = (off + alignof(T) - 1) & ~(size_t)(alignof(T) - 1);
|
||||
if (i >= RAD_MAX_KPARAMS || off + sizeof(T) > RAD_KPARAM_BLOB) return false;
|
||||
memcpy(d.blob + off, &v, sizeof(T));
|
||||
d.param_size[i] = (uint16_t)sizeof(T);
|
||||
d.params[i++] = d.blob + off;
|
||||
off += sizeof(T);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* A kernel's parameter list as r4d_pack_one lays it out -- each value at its own alignment, in
|
||||
* declaration order -- so that a kernel whose list runs close to RAD_KPARAM_BLOB or
|
||||
* RAD_MAX_KPARAMS can assert at compile time that it fits, rather than meet RAD_E_FULL at its
|
||||
* first launch. `F` is the kernel's function type: `decltype(kernel)`, or for a template
|
||||
* `decltype(kernel<args>)`. */
|
||||
template <class F> struct R4dParams;
|
||||
template <class... P> struct R4dParams<void(P...)> {
|
||||
static constexpr size_t count = sizeof...(P);
|
||||
static constexpr size_t bytes() {
|
||||
size_t off = 0;
|
||||
((off = ((off + alignof(P) - 1) & ~(size_t)(alignof(P) - 1)) + sizeof(P)), ...);
|
||||
return off;
|
||||
}
|
||||
};
|
||||
|
||||
/* THE ONE EMIT, AND IT TAKES THE KERNEL TYPED.
|
||||
*
|
||||
* `hipLaunchKernelGGL` type-checks its arguments against the kernel's signature and CONVERTS them
|
||||
* -- pass a `long long` where the kernel declares `uint32_t` and the compiler narrows it at the
|
||||
* call. `hipLaunchKernel` takes `kernelParams`, which is raw bytes: the same call would copy eight
|
||||
* bytes into a slot the kernel reads as four and corrupt every argument after it, silently, with
|
||||
* no diagnostic anywhere. Over a library's worth of shims that is a defect generator.
|
||||
*
|
||||
* So the kernel arrives as `void (*)(P...)`, which deduces its parameter types, and every argument
|
||||
* is packed as the P the kernel actually declares. The arity is checked too. What the chevron
|
||||
* launch does for free is done explicitly here, and a mismatch is a compile error rather than a
|
||||
* wrong number.
|
||||
*
|
||||
* `func` is the kernel's host stub -- for a template instantiation, its own symbol, which is the
|
||||
* point: an instantiation chosen by a parameter moves the FUNCTION and not merely an argument, and
|
||||
* the runtime has to rebuild rather than update such a node. */
|
||||
/* `func` is the kernel's host stub; for a template, the instantiation's own symbol. */
|
||||
template <class... P, class... A>
|
||||
inline int r4d_emit(const R4dSink& sk, void (*kernel)(P...), dim3 grid, dim3 block,
|
||||
inline int r4d_emit(RadStream stream, void (*kernel)(P...), dim3 grid, dim3 block,
|
||||
uint32_t shared_bytes, const A&... args) {
|
||||
static_assert(sizeof...(P) == sizeof...(A),
|
||||
"a kernel argument list must match the kernel's parameter list");
|
||||
const void* func = (const void*)kernel;
|
||||
RadLaunchDesc local;
|
||||
RadLaunchDesc* dst = &local;
|
||||
if (sk.desc) {
|
||||
if (!sk.n || *sk.n >= sk.cap) return RAD_E_FULL;
|
||||
dst = &sk.desc[*sk.n];
|
||||
}
|
||||
RadLaunchDesc& d = *dst;
|
||||
d.func = func;
|
||||
d.grid[0] = grid.x; d.grid[1] = grid.y; d.grid[2] = grid.z;
|
||||
d.block[0] = block.x; d.block[1] = block.y; d.block[2] = block.z;
|
||||
d.shared_bytes = shared_bytes;
|
||||
d.n_params = 0;
|
||||
|
||||
size_t off = 0;
|
||||
int i = 0;
|
||||
bool ok = true;
|
||||
/* Converted to the kernel's declared type FIRST, then packed -- see the note above. Left to
|
||||
* right, so slot i is parameter i. */
|
||||
std::tuple<P...> vals(static_cast<P>(args)...);
|
||||
std::apply([&](const P&... v) { ((ok = ok && r4d_pack_one(d, off, i, v)), ...); }, vals);
|
||||
if (!ok) return RAD_E_FULL;
|
||||
d.n_params = (uint32_t)i;
|
||||
void* params[sizeof...(P) + 1];
|
||||
std::apply([&](P&... v) {
|
||||
int i = 0;
|
||||
((params[i++] = (void*)&v), ...);
|
||||
}, vals);
|
||||
params[sizeof...(P)] = nullptr;
|
||||
|
||||
if (sk.desc) { ++*sk.n; return RAD_OK; }
|
||||
/* THE LAST THING SUBMITTED, NAMED BEFORE IT IS SUBMITTED. A launch that faults inside the
|
||||
* driver leaves a backtrace through this frame and nothing else: the geometry is in registers
|
||||
* that -O3 has reused and the kernel is a stub address. Printing it first costs a line per
|
||||
* dispatch under a flag nobody sets in production, and it is the difference between a shape
|
||||
* to reproduce and a stack of question marks. Flushed, because the fault is the next
|
||||
* instruction. */
|
||||
/* THE LAST THING SUBMITTED, NAMED BEFORE IT IS SUBMITTED. A launch that faults inside the
|
||||
* driver leaves a backtrace through this frame and nothing else: the geometry is in registers
|
||||
* that -O3 has reused and the kernel is a stub address. Printed first, so an `emit` with no
|
||||
* `ret` after it IS the faulting dispatch.
|
||||
*
|
||||
* ONE WRITE A LINE, BECAUSE EVERY RANK IS A THREAD. A line assembled by a sequence of
|
||||
* fprintf calls interleaves with the other rank's, and the trace then shows dispatches that
|
||||
* never returned next to returns that belong to nothing -- which is worse than no trace,
|
||||
* because it reads as evidence. */
|
||||
if (r4d_dispatch_log) {
|
||||
if (r4d_dispatch_n < r4d_dispatch_cap) r4d_dispatch_log[r4d_dispatch_n] = func;
|
||||
++r4d_dispatch_n;
|
||||
}
|
||||
/* Trace the dispatch before submitting it: a fault inside the driver leaves only this frame,
|
||||
* with the geometry in reused registers and the kernel a stub address. An `emit` with no
|
||||
* `ret` after it is the faulting dispatch; flushed because the fault may be next. Each line is
|
||||
* one write, since every rank is a thread and piecewise fprintf calls would interleave. */
|
||||
if (r4d_trace_on()) {
|
||||
static constexpr size_t kSize[] = { sizeof(P)..., 0 };
|
||||
char line[1024];
|
||||
int o = snprintf(line, sizeof line,
|
||||
"[r4d] emit %p grid=%ux%ux%u block=%ux%ux%u lds=%u np=%u",
|
||||
func, grid.x, grid.y, grid.z, block.x, block.y, block.z,
|
||||
shared_bytes, d.n_params);
|
||||
for (uint32_t k = 0; k < d.n_params && o > 0 && o < (int)sizeof line - 32; ++k) {
|
||||
shared_bytes, (unsigned)sizeof...(P));
|
||||
for (size_t k = 0; k < sizeof...(P) && o > 0 && o < (int)sizeof line - 32; ++k) {
|
||||
unsigned long long v = 0;
|
||||
memcpy(&v, d.params[k], d.param_size[k] > 8 ? 8 : d.param_size[k]);
|
||||
o += snprintf(line + o, sizeof line - (size_t)o, " %u:%llx", d.param_size[k], v);
|
||||
memcpy(&v, params[k], kSize[k] > 8 ? 8 : kSize[k]);
|
||||
o += snprintf(line + o, sizeof line - (size_t)o, " %u:%llx", (unsigned)kSize[k], v);
|
||||
}
|
||||
std::fprintf(stderr, "%s\n", line);
|
||||
std::fflush(stderr);
|
||||
}
|
||||
const int rc = hipLaunchKernel(func, grid, block, d.params, shared_bytes,
|
||||
(hipStream_t)sk.stream) == hipSuccess ? RAD_OK : RAD_E_DEVICE;
|
||||
const int rc = hipLaunchKernel(func, grid, block, params, shared_bytes,
|
||||
(hipStream_t)stream) == hipSuccess ? RAD_OK : RAD_E_DEVICE;
|
||||
if (r4d_trace_on()) { std::fprintf(stderr, "[r4d] ret %p %d\n", func, rc); std::fflush(stderr); }
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* `kernel` is named, not passed as a value, so a template instantiation is spelled at the call
|
||||
* site exactly as the triple-chevron spelled it. */
|
||||
#define R4D_EMIT(sink, kernel, grid, block, lds, ...) \
|
||||
r4d_emit((sink), (kernel), (grid), (block), (uint32_t)(lds), __VA_ARGS__)
|
||||
|
||||
/* The two entry points, from one body. `body` is `int (*)(const RadArgs*, const R4dSink&)`. */
|
||||
#define R4D_ENTRY(sym, body) \
|
||||
extern "C" int sym(const RadArgs* a, RadStream s) { \
|
||||
R4dSink sk; sk.stream = s; \
|
||||
return body(a, sk); \
|
||||
} \
|
||||
extern "C" int sym##_describe(const RadArgs* a, RadStream s, RadLaunchDesc* d, \
|
||||
int cap, int* n) { \
|
||||
if (!n) return RAD_E_INVAL; \
|
||||
*n = 0; \
|
||||
R4dSink sk; sk.stream = s; sk.desc = d; sk.cap = cap; sk.n = n; \
|
||||
return body(a, sk); \
|
||||
}
|
||||
* site exactly as the triple-chevron spelled it. A test may define R4D_EMIT to drive the same
|
||||
* sources through a host SIMT emulator, as with R4D_KLAUNCH (r4d_launch.h). */
|
||||
#ifndef R4D_EMIT
|
||||
#define R4D_EMIT(stream, kernel, grid, block, lds, ...) \
|
||||
r4d_emit((stream), (kernel), (grid), (block), (uint32_t)(lds), __VA_ARGS__)
|
||||
#endif
|
||||
|
||||
#endif /* R4D_EMIT_H */
|
||||
+10
-12
@@ -1,9 +1,8 @@
|
||||
/* r4d_enc.h -- what libr4d's relayouts check of an encoding before they rearrange it.
|
||||
/* r4d_enc.h -- the encoding checks libr4d's relayouts make before rearranging a weight.
|
||||
*
|
||||
* A container holds encodings; libr4d's kernels each read a few. A relayout that met an encoding
|
||||
* its kernel does not read and rearranged it anyway would hand the kernel bytes that decode to
|
||||
* other numbers -- the failure the layout hook exists to refuse, by name, at declare. These are the
|
||||
* questions it asks. Pure host C++, like the rest of the declaration side.
|
||||
* A relayout that rearranged an encoding its kernel does not read would hand the kernel bytes
|
||||
* that decode to other numbers; the layout hook refuses such a declaration by name instead. Pure
|
||||
* host C++, like the rest of the declaration side.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_abi.h"
|
||||
@@ -32,10 +31,10 @@ inline bool affine(const RadEncoding* e, uint32_t codes, uint32_t scale, int64_t
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The same with a SCALAR CODEBOOK: `codes` indexing a `table` plane of `entries` values of dtype
|
||||
* `tab`, the `scale` as above, `transform` exactly, and no other plane. What the table HOLDS is not
|
||||
* in an encoding -- a declaration has no plane bytes -- so a kernel that decodes one fixed table
|
||||
* compares the plane with it when it relayouts. */
|
||||
/* The same with a scalar codebook: `codes` indexing a `table` plane of `entries` values of dtype
|
||||
* `tab`, the `scale` as above, `transform` exactly, and no other plane. A declaration carries no
|
||||
* plane bytes, so a kernel that decodes one fixed table compares the plane's contents at
|
||||
* relayout. */
|
||||
inline bool affine_table(const RadEncoding* e, uint32_t codes, uint32_t scale, int64_t br,
|
||||
int64_t bc, uint32_t tab, int64_t entries, const char* transform = "") {
|
||||
if (!e || !rad_enc_is(e, "affine")) return false;
|
||||
@@ -50,9 +49,8 @@ inline bool affine_table(const RadEncoding* e, uint32_t codes, uint32_t scale, i
|
||||
e->plane[t].extent[0] == 1 && e->plane[t].extent[1] == entries;
|
||||
}
|
||||
|
||||
/* affine_table's codebook with a SECOND SCALE LEVEL beside the first: `scale.1` of dtype `scale2`,
|
||||
* one value for the whole tensor (libquant's block2=*x*). Four planes: codes, scale, scale.1,
|
||||
* table. */
|
||||
/* affine_table's codebook with a second scale level: `scale.1` of dtype `scale2`, one value for
|
||||
* the whole tensor (libquant's block2=*x*). Four planes: codes, scale, scale.1, table. */
|
||||
inline bool affine_table2(const RadEncoding* e, uint32_t codes, uint32_t scale, int64_t br,
|
||||
int64_t bc, uint32_t scale2, uint32_t tab, int64_t entries,
|
||||
const char* transform = "") {
|
||||
|
||||
+256
-96
@@ -1,9 +1,8 @@
|
||||
// The small ops an encoder issues between its GEMMs and its attention: a gated activation over two
|
||||
// operands, the QK(V)-norm-and-rotary preamble over a fused projection, mean pooling over
|
||||
// cu_seqlens segments, and the bf16 -> f32 widening of a pooled row. r4d_model_bf16.hip's rules
|
||||
// hold here too: each kernel equals a libref function, reductions accumulate in f32 (seg_mean in
|
||||
// f64, as ref does) and only the store narrows, and the transcendental functions are the accurate
|
||||
// libm forms.
|
||||
// Small encoder ops between GEMMs and attention: gated activation over two operands, QK(V) norm +
|
||||
// rotary over a fused projection, mean pooling over cu_seqlens segments, bf16 -> f32 widening,
|
||||
// and the audio tower's ops. As in r4d_model_bf16.hip, each kernel equals a libref function:
|
||||
// reductions accumulate in f32 (seg_mean in f64, as ref does), only the store narrows, and
|
||||
// transcendentals use the accurate libm forms.
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -31,9 +30,8 @@ __device__ __forceinline__ float act_of(float g) {
|
||||
return 0.5f * g * (1.0f + tanhf(0.7978845608028654f * (g + 0.044715f * g * g * g)));
|
||||
}
|
||||
|
||||
// THE ROW AXIS IS GRID-STRIDED. A grid's y extent stops at 65535, and an elementwise op over the
|
||||
// audio subsampler's (time, frequency) rows is 96000 of them: a launch of y = M runs nothing past
|
||||
// row 65535. A row kernel takes M, launches min(M, kGridYMax) and walks the rest.
|
||||
// The row axis is grid-strided: grid y is capped at 65535, and the audio subsampler's
|
||||
// (time, frequency) rows reach 96000. Row kernels launch min(M, kGridYMax) and loop over the rest.
|
||||
constexpr uint32_t kGridYMax = 65535;
|
||||
static inline uint32_t grid_rows(int64_t M) {
|
||||
return (uint32_t)(M < (int64_t)kGridYMax ? M : (int64_t)kGridYMax);
|
||||
@@ -82,20 +80,18 @@ __global__ __launch_bounds__(kThreads) void seg_mean_kernel(
|
||||
// RMS-normed against its gain and rounded to bf16 (the unfused pair stores the norm), then
|
||||
// rotated; with v_norm each v head is RMS-normed with a unit gain and not rotated.
|
||||
//
|
||||
// ONE WORKGROUP A TOKEN, A WAVE A HEAD, THE HEAD IN REGISTERS. Lane l holds the head's elements
|
||||
// l, l+32, l+64, ... (neox) or the pairs 2l, 2l+1, 2l+64, 2l+65, ... (gptj), which puts both
|
||||
// halves of every rotary pair in the same lane: the norm is a wave sum and the rotation needs no
|
||||
// exchange at all. The token's sin/cos are computed once into LDS for all its heads -- 4 KiB, so
|
||||
// occupancy is not what LDS decides. A first form staged the token's whole fused row in LDS
|
||||
// (12 KiB a workgroup at head_dim 512) and ran slower than a workgroup a (token, head).
|
||||
// One workgroup per token, one wave per head, the head in registers. Lane l holds elements
|
||||
// l, l+32, l+64, ... (neox) or pairs 2l, 2l+1, 2l+64, 2l+65, ... (gptj), so both halves of every
|
||||
// rotary pair are in one lane: the norm is a wave sum and the rotation needs no exchange. The
|
||||
// token's sin/cos are computed once into LDS (4 KiB, not an occupancy limit).
|
||||
//
|
||||
// The layout needs head_dim a multiple of 32 and, for neox, rotary_dim / 2 a multiple of 32 (for
|
||||
// gptj, head_dim a multiple of 64); the launcher refuses anything else.
|
||||
// Requires head_dim a multiple of 32 and, for neox, rotary_dim / 2 a multiple of 32 (gptj:
|
||||
// head_dim a multiple of 64); the launcher refuses anything else.
|
||||
constexpr uint32_t kQkThreads = 256;
|
||||
constexpr uint32_t kQkMaxHalf = 512; // rotary pairs a head
|
||||
constexpr int kQkMaxE = 32; // elements a lane: head_dim up to 1024
|
||||
|
||||
/* The `blocks` mode's sections: pairs a section, and the position component each one reads. */
|
||||
/* `blocks` mode sections: pairs per section and the position component each reads. */
|
||||
struct QkBlocks {
|
||||
int n = 0;
|
||||
int sec[8] = {};
|
||||
@@ -217,13 +213,13 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// The `blocks` mode at any head_dim and section size (Gemma 4's vision tower: 72-wide heads, two
|
||||
// sections of 18 pairs) -- what the register layout above cannot hold. A wave a head and a lane a
|
||||
// rotated pair: the norm's sum of squares first, then each lane re-reads its pair, norms, gains,
|
||||
// rounds (the norm rounded before the rotation, as above) and rotates it. Channels past `rot`
|
||||
// are normed only; a v head (v_norm) is normed at unit gain.
|
||||
// Section modes at any head_dim and section size, which the register layout above cannot hold
|
||||
// (e.g. Gemma 4's vision tower: 72-wide heads, two sections of 18 pairs). One wave per head, one
|
||||
// lane per rotated pair: sum of squares first, then each lane re-reads its pair, norms, applies
|
||||
// the gain, rounds (before rotation, as above) and rotates. Channels past `rot` are normed only;
|
||||
// a v head (v_norm) is normed at unit gain.
|
||||
//
|
||||
// `pm` picks the pairing, which is all that separates three rotaries over the same table:
|
||||
// `pm` selects the pairing:
|
||||
// 0 blocks a section's pairs are (start + j, start + sec + j), its own ladder
|
||||
// 1 gptj_blocks a section's pairs are ADJACENT, (start + 2j, start + 2j + 1), its own ladder:
|
||||
// the complex-number form of a 3-axis image rotary (Qwen-Image)
|
||||
@@ -298,7 +294,7 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel(
|
||||
|
||||
// ---------------------------------------------------------------------------- pool_rows
|
||||
// ref_pool_rows: row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to
|
||||
// bf16, then times `mult` and rounded again. A workgroup an output row, a thread a column.
|
||||
// bf16, then times `mult` and rounded again. One thread per column.
|
||||
__global__ __launch_bounds__(kThreads) void pool_rows_kernel(
|
||||
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t k, float mult,
|
||||
uint32_t x_ld, uint32_t y_ld, uint32_t M) {
|
||||
@@ -323,11 +319,11 @@ __global__ __launch_bounds__(kThreads) void widen_kernel(
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- the audio tower
|
||||
// Gemma 4's USM conformer: an elementwise rectifier and clamp, the subsampler's segment-wise
|
||||
// Gemma 4's USM conformer: elementwise rectifier and clamp, the subsampler's segment-wise
|
||||
// convolution, the light-conv block's causal depthwise convolution, the relative-position table,
|
||||
// and the local attention with a relative term. An audio pass is at most a few thousand frames
|
||||
// (750 tokens for 30 s), so each kernel is the plain form -- a workgroup a row, a thread an
|
||||
// element -- and equal to its libref function in arithmetic: f32 throughout, one rounding.
|
||||
// and local attention with a relative term. An audio pass is at most a few thousand frames
|
||||
// (750 tokens for 30 s), so each kernel is the plain form (a workgroup per row, a thread per
|
||||
// element) and matches its libref function: f32 throughout, one rounding.
|
||||
|
||||
// ref_relu.
|
||||
__global__ __launch_bounds__(kThreads) void relu_kernel(
|
||||
@@ -341,8 +337,8 @@ __global__ __launch_bounds__(kThreads) void relu_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// ref_silu: x * sigmoid(x) with the sigmoid taken first, libref's act_silu term for term. The
|
||||
// audio tower's feed-forward issues it on its own between two clipped linears.
|
||||
// ref_silu: x * sigmoid(x) with the sigmoid taken first, as libref's act_silu. Used standalone
|
||||
// between two clipped linears in the audio feed-forward.
|
||||
__global__ __launch_bounds__(kThreads) void silu_kernel(
|
||||
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld,
|
||||
uint32_t y_ld, uint32_t M) {
|
||||
@@ -372,15 +368,33 @@ __global__ __launch_bounds__(kThreads) void clamp_kernel(
|
||||
|
||||
struct ConvGeom {
|
||||
int W, cin, cout, kh, kw, st, pad, cdiv, vst, Wo, S;
|
||||
int tl; /* the weight is [cout, cin, kw, kh]: time last */
|
||||
int gelu; /* the epilogue's activation */
|
||||
};
|
||||
|
||||
// ref_conv2d. A workgroup an OUTPUT time row of the pass: it finds the segment whose output rows
|
||||
// hold it (a scan over cu_seqlens, which is a handful of entries), and a thread computes output
|
||||
// elements (width, channel) of that row. Rows no segment covers are left alone, as libref does.
|
||||
// Kernel tap (i over time, j over width) of channel pair (co, ci), in either weight layout; the
|
||||
// next input channel is kh * kw further on in both.
|
||||
__device__ __forceinline__ size_t conv_w(const ConvGeom& g, int co, int ci, int i, int j) {
|
||||
return g.tl ? (((size_t)co * g.cin + ci) * g.kw + j) * g.kh + i
|
||||
: (((size_t)co * g.cin + ci) * g.kh + i) * g.kw + j;
|
||||
}
|
||||
|
||||
// ref_conv2d's epilogue: the sum plus the bias, one rounding; gelu of the rounded value, a second
|
||||
// rounding.
|
||||
__device__ __forceinline__ uint16_t conv_out(const ConvGeom& g, float acc,
|
||||
const uint16_t* __restrict__ bias, int co) {
|
||||
if (bias) acc += bf2f(bias[co]);
|
||||
const uint16_t r = f32_to_bf16(acc);
|
||||
return g.gelu ? f32_to_bf16(act_of<1>(bf2f(r))) : r;
|
||||
}
|
||||
|
||||
// ref_conv2d. One workgroup per output time row: it finds the covering segment (a scan over the
|
||||
// few cu_seqlens entries), and threads compute the row's (width, channel) outputs. Rows no
|
||||
// segment covers are left untouched, as in libref.
|
||||
__global__ __launch_bounds__(kThreads) void conv2d_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const int* __restrict__ cu,
|
||||
const int* __restrict__ valid, uint16_t* __restrict__ y, ConvGeom g, uint32_t x_ld,
|
||||
uint32_t y_ld) {
|
||||
const int* __restrict__ valid, const uint16_t* __restrict__ bias, uint16_t* __restrict__ y,
|
||||
ConvGeom g, uint32_t x_ld, uint32_t y_ld) {
|
||||
const int r = (int)blockIdx.x;
|
||||
int t0 = -1, T = 0, to = 0;
|
||||
for (int s = 0; s < g.S; ++s) {
|
||||
@@ -406,30 +420,64 @@ __global__ __launch_bounds__(kThreads) void conv2d_kernel(
|
||||
const int wi = wo * g.st - g.pad + j;
|
||||
if (wi < 0 || wi >= g.W) continue;
|
||||
const uint16_t* xv = xr + (size_t)wi * g.cin;
|
||||
const uint16_t* wv = w + (((size_t)co * g.cin) * g.kh + i) * g.kw + j;
|
||||
const uint16_t* wv = w + conv_w(g, co, 0, i, j);
|
||||
for (int ci = 0; ci < g.cin; ++ci)
|
||||
acc += bf2f(xv[ci]) * bf2f(wv[(size_t)ci * g.kh * g.kw]);
|
||||
}
|
||||
}
|
||||
y[(size_t)r * y_ld + e] = f32_to_bf16(acc);
|
||||
y[(size_t)r * y_ld + e] = conv_out(g, acc, bias, co);
|
||||
}
|
||||
}
|
||||
|
||||
// conv2d_kernel's arithmetic with each kernel row's input row and weights staged in LDS: the form
|
||||
// for the audio subsampler's second convolution, 64 x 128 channels in and 32 x 32 out a row,
|
||||
// where the plain kernel re-reads every weight from global memory for every output and spends
|
||||
// 6 ms on a 30 s clip. Weights sit [j][ci][co] so the lanes of a wave -- consecutive output
|
||||
// channels -- read consecutive LDS words, and each input element is one broadcast. A thread owns
|
||||
// kConvEpt outputs strided by the workgroup, all of one output channel. The sum runs over i, j,
|
||||
// ci in the plain kernel's order.
|
||||
// ref_conv2d_unfold. One workgroup per output time row, found as conv2d_kernel finds it, and one
|
||||
// thread per (wo, k) element of its Wo unfolded rows: the tap value conv2d would multiply weight
|
||||
// column k by, or zero in the padding and on a masked row. Columns are in the weight's order, so a
|
||||
// row's writes are consecutive.
|
||||
__global__ __launch_bounds__(kThreads) void conv2d_unfold_kernel(
|
||||
const uint16_t* __restrict__ x, const int* __restrict__ cu, const int* __restrict__ valid,
|
||||
uint16_t* __restrict__ y, ConvGeom g, uint32_t x_ld, uint32_t y_ld) {
|
||||
const int r = (int)blockIdx.x;
|
||||
int t0 = -1, T = 0, to = 0;
|
||||
for (int s = 0; s < g.S; ++s) {
|
||||
const int c0 = cu[s], c1 = cu[s + 1];
|
||||
if (c0 % g.cdiv || c1 % g.cdiv || (c0 / g.cdiv) % g.st || c1 < c0) continue;
|
||||
const int a = c0 / g.cdiv, Ts = c1 / g.cdiv - a;
|
||||
if (Ts <= 0) continue;
|
||||
const int To = (Ts + 2 * g.pad - g.kh) / g.st + 1, o0 = a / g.st;
|
||||
if (r >= o0 && r < o0 + To) { t0 = a; T = Ts; to = r - o0; break; }
|
||||
}
|
||||
if (t0 < 0) return;
|
||||
const int K = g.cin * g.kh * g.kw, nel = g.Wo * K;
|
||||
for (int e = threadIdx.x; e < nel; e += kThreads) {
|
||||
const int wo = e / K, k = e % K;
|
||||
int ci, i, j;
|
||||
if (g.tl) { i = k % g.kh; j = (k / g.kh) % g.kw; ci = k / (g.kh * g.kw); }
|
||||
else { j = k % g.kw; i = (k / g.kw) % g.kh; ci = k / (g.kh * g.kw); }
|
||||
const int ti = to * g.st - g.pad + i, wi = wo * g.st - g.pad + j;
|
||||
uint16_t v = 0;
|
||||
if (ti >= 0 && ti < T && wi >= 0 && wi < g.W) {
|
||||
const int tg = t0 + ti;
|
||||
if (!valid || valid[(size_t)tg * g.vst] != 0)
|
||||
v = x[(size_t)tg * x_ld + (size_t)wi * g.cin + ci];
|
||||
}
|
||||
y[((size_t)r * g.Wo + wo) * y_ld + k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
// conv2d_kernel's arithmetic with each kernel row's input row and weights staged in LDS, for the
|
||||
// audio subsampler's second convolution (64 x 128 channels in, 32 x 32 out per row), where the
|
||||
// plain kernel re-reads every weight from global per output (6 ms on a 30 s clip). Weights are
|
||||
// [j][ci][co] so a wave's lanes (consecutive output channels) read consecutive LDS words and each
|
||||
// input element is a broadcast. A thread owns kConvEpt outputs strided by the workgroup, all of
|
||||
// one output channel. Summation order (i, j, ci) matches the plain kernel.
|
||||
constexpr int kConvEpt = 4;
|
||||
constexpr int kConvXs = 8192; /* W * cin, one input row */
|
||||
constexpr int kConvWs = 12288; /* kw * cin * cout, one kernel row's weights */
|
||||
|
||||
__global__ __launch_bounds__(kThreads) void conv2d_lds_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const int* __restrict__ cu,
|
||||
const int* __restrict__ valid, uint16_t* __restrict__ y, ConvGeom g, uint32_t x_ld,
|
||||
uint32_t y_ld) {
|
||||
const int* __restrict__ valid, const uint16_t* __restrict__ bias, uint16_t* __restrict__ y,
|
||||
ConvGeom g, uint32_t x_ld, uint32_t y_ld) {
|
||||
__shared__ uint16_t xs[kConvXs];
|
||||
__shared__ uint16_t ws[kConvWs];
|
||||
const int r = (int)blockIdx.x;
|
||||
@@ -458,7 +506,7 @@ __global__ __launch_bounds__(kThreads) void conv2d_lds_kernel(
|
||||
for (int e = tid; e < nx; e += kThreads) xs[e] = xr[e];
|
||||
for (int e = tid; e < nw; e += kThreads) {
|
||||
const int co = e % g.cout, rest = e / g.cout, ci = rest % g.cin, j = rest / g.cin;
|
||||
ws[e] = w[(((size_t)co * g.cin + ci) * g.kh + i) * g.kw + j];
|
||||
ws[e] = w[conv_w(g, co, ci, i, j)];
|
||||
}
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
@@ -480,11 +528,11 @@ __global__ __launch_bounds__(kThreads) void conv2d_lds_kernel(
|
||||
#pragma unroll
|
||||
for (int q = 0; q < kConvEpt; ++q) {
|
||||
const int e = tid + q * kThreads;
|
||||
if (e < nel) y[(size_t)r * y_ld + e] = f32_to_bf16(acc[q]);
|
||||
if (e < nel) y[(size_t)r * y_ld + e] = conv_out(g, acc[q], bias, e % g.cout);
|
||||
}
|
||||
}
|
||||
|
||||
// ref_conv1d_dw. A thread a (row, channel); the segment found by a scan over cu_seqlens.
|
||||
// ref_conv1d_dw. One thread per (row, channel); the segment is found by a scan over cu_seqlens.
|
||||
__global__ __launch_bounds__(kThreads) void conv1d_dw_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const int* __restrict__ cu,
|
||||
uint16_t* __restrict__ y, int C, int K, int cdiv, int S, uint32_t x_ld, uint32_t y_ld,
|
||||
@@ -521,8 +569,29 @@ __global__ __launch_bounds__(kThreads) void rel_sinusoid_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// ref_attn_local_rel. A workgroup a (query row, head), a thread a head dimension; each of the at
|
||||
// most left + 1 logits is a workgroup sum, then the softmax over them and the weighted sum of v.
|
||||
// ref_seg_sinusoid: rel_sinusoid's table at position (r - segment start) mod period. One workgroup
|
||||
// per row; its segment is found by a scan over the few cu_seqlens entries, and rows no segment
|
||||
// covers are left untouched, as in libref.
|
||||
__global__ __launch_bounds__(kThreads) void seg_sinusoid_kernel(
|
||||
const int* __restrict__ cu, uint16_t* __restrict__ y, uint32_t h, float inc, uint32_t y_ld,
|
||||
int S, int cdiv, int period) {
|
||||
const int r = (int)blockIdx.x;
|
||||
int p = -1;
|
||||
for (int s = 0; s < S; ++s) {
|
||||
const int r0 = cu[s] / cdiv, r1 = cu[s + 1] / cdiv;
|
||||
if (r >= r0 && r < r1) { p = (r - r0) % period; break; }
|
||||
}
|
||||
if (p < 0) return;
|
||||
for (uint32_t i = threadIdx.x; i < h; i += kThreads) {
|
||||
const float inv = expf((float)i * -inc);
|
||||
const float ang = (float)p * inv;
|
||||
y[(size_t)r * y_ld + i] = f32_to_bf16(sinf(ang));
|
||||
y[(size_t)r * y_ld + h + i] = f32_to_bf16(cosf(ang));
|
||||
}
|
||||
}
|
||||
|
||||
// ref_attn_local_rel. One workgroup per (query row, head), one thread per head dimension. Each of
|
||||
// the at most left + 1 logits is a workgroup sum, followed by the softmax and the weighted sum of v.
|
||||
constexpr uint32_t kLrThreads = 128;
|
||||
constexpr int kLrMaxKeys = 64;
|
||||
|
||||
@@ -624,7 +693,7 @@ extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M
|
||||
(rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || mode < 0 || mode > 4)
|
||||
return -2;
|
||||
if (mode >= 3) {
|
||||
/* The two forms only the general kernel takes: its pair table is built per mode. */
|
||||
/* gptj_blocks and imrope: general kernel only (its pair table is built per mode). */
|
||||
if (!blk || blk->n <= 0 || blk->n > 8) return -2;
|
||||
int total = 0;
|
||||
for (int c = 0; c < blk->n; ++c) {
|
||||
@@ -645,7 +714,7 @@ extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M
|
||||
if (mode == 1 && head_dim % 64) return -2;
|
||||
if (mode == 0 && (rot / 2) % 32) return -2;
|
||||
QkBlocks b{};
|
||||
bool any = false; /* the blocks mode outside the register layout: qk_norm_rope_any_kernel */
|
||||
bool any = false; /* blocks mode outside the register layout: use qk_norm_rope_any_kernel */
|
||||
if (mode == 2) {
|
||||
if (!blk || blk->n <= 0 || blk->n > 8) return -2;
|
||||
b = *blk;
|
||||
@@ -729,10 +798,9 @@ extern "C" int r4d_clamp_bf16(long x, long lo, long hi, int b_f32, long y, int M
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
/* `rows_out` is the output operand's rows: a workgroup each, every one a segment does not cover
|
||||
* returning at once. */
|
||||
extern "C" int r4d_conv2d_bf16(long x, long w, long cu, long valid, long y, int rows_out,
|
||||
const ConvGeom* g, int x_ld, int y_ld, long stream) {
|
||||
/* One workgroup per output row (`rows_out`); rows no segment covers return at once. */
|
||||
extern "C" int r4d_conv2d_bf16(long x, long w, long cu, long valid, long bias, long y,
|
||||
int rows_out, const ConvGeom* g, int x_ld, int y_ld, long stream) {
|
||||
if (!x || !w || !cu || !y || !g) return -1;
|
||||
if (rows_out <= 0 || g->Wo <= 0 || g->S <= 0) return -2;
|
||||
const bool lds = g->W * g->cin <= kConvXs && g->kw * g->cin * g->cout <= kConvWs &&
|
||||
@@ -740,13 +808,24 @@ extern "C" int r4d_conv2d_bf16(long x, long w, long cu, long valid, long y, int
|
||||
if (lds)
|
||||
hipLaunchKernelGGL(conv2d_lds_kernel, dim3((uint32_t)rows_out), dim3(kThreads), 0,
|
||||
(hipStream_t)stream, (const uint16_t*)x, (const uint16_t*)w,
|
||||
(const int*)cu, (const int*)valid, (uint16_t*)y, *g, (uint32_t)x_ld,
|
||||
(uint32_t)y_ld);
|
||||
(const int*)cu, (const int*)valid, (const uint16_t*)bias, (uint16_t*)y,
|
||||
*g, (uint32_t)x_ld, (uint32_t)y_ld);
|
||||
else
|
||||
hipLaunchKernelGGL(conv2d_kernel, dim3((uint32_t)rows_out), dim3(kThreads), 0,
|
||||
(hipStream_t)stream, (const uint16_t*)x, (const uint16_t*)w,
|
||||
(const int*)cu, (const int*)valid, (uint16_t*)y, *g, (uint32_t)x_ld,
|
||||
(uint32_t)y_ld);
|
||||
(const int*)cu, (const int*)valid, (const uint16_t*)bias, (uint16_t*)y,
|
||||
*g, (uint32_t)x_ld, (uint32_t)y_ld);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
/* One workgroup per output time row (`rows_out`, the operand's rows over Wo). */
|
||||
extern "C" int r4d_conv2d_unfold_bf16(long x, long cu, long valid, long y, int rows_out,
|
||||
const ConvGeom* g, int x_ld, int y_ld, long stream) {
|
||||
if (!x || !cu || !y || !g) return -1;
|
||||
if (rows_out <= 0 || g->Wo <= 0 || g->S <= 0) return -2;
|
||||
hipLaunchKernelGGL(conv2d_unfold_kernel, dim3((uint32_t)rows_out), dim3(kThreads), 0,
|
||||
(hipStream_t)stream, (const uint16_t*)x, (const int*)cu,
|
||||
(const int*)valid, (uint16_t*)y, *g, (uint32_t)x_ld, (uint32_t)y_ld);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
@@ -773,6 +852,18 @@ extern "C" int r4d_rel_sinusoid_bf16(long y, int rows, int n, double max_timesca
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_seg_sinusoid_bf16(long cu, int S, long y, int rows, int n, int period, int cdiv,
|
||||
double max_timescale, int y_ld, long stream) {
|
||||
if (!cu || !y) return -1;
|
||||
if (rows <= 0 || n <= 0 || (n & 1) || period <= 0 || cdiv <= 0 || S <= 0) return -2;
|
||||
const int h = n / 2;
|
||||
const float inc = (float)(std::log(max_timescale / 1.0) / (double)(h - 1 > 1 ? h - 1 : 1));
|
||||
hipLaunchKernelGGL(seg_sinusoid_kernel, dim3((uint32_t)rows), dim3(kThreads), 0,
|
||||
(hipStream_t)stream, (const int*)cu, (uint16_t*)y, (uint32_t)h, inc,
|
||||
(uint32_t)y_ld, S, cdiv, period);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_attn_local_rel_bf16(long q, long k, long v, long rk, long pds, long cu, long o,
|
||||
int rows, const LocalRelGeom* g, long stream) {
|
||||
if (!q || !k || !v || !rk || !pds || !cu || !o || !g) return -1;
|
||||
@@ -791,6 +882,13 @@ static inline int dt_bf16(const RadTensor* t) {
|
||||
}
|
||||
#define R4D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R4D_NO(_s); } while (0)
|
||||
|
||||
/* The entry points above return 0, -4 for a failed launch, or another negative code for a shape
|
||||
* they do not serve. */
|
||||
static inline int enc_status(int rc) {
|
||||
if (rc == 0) return RAD_OK;
|
||||
return R4D_NO(rc == -4 ? RAD_E_DEVICE : RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ act_mul */
|
||||
extern "C" int r4d_rad_act_mul(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* A = r4d_opt(a, 0);
|
||||
@@ -815,9 +913,8 @@ extern "C" int r4d_rad_act_mul(const RadArgs* a, RadStream s) {
|
||||
const long long b_ld = r4d_rows_pitch(B, n, &Mb);
|
||||
if (y_ld < 0 || a_ld < 0 || b_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || Ma < M || Mb < M) return R4D_NO(RAD_E_SHAPE);
|
||||
return r4d_act_mul_bf16(r4d_addr(A), r4d_addr(B), r4d_addr(Y), (int)M, (int)n, ai, (int)a_ld,
|
||||
(int)b_ld, (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK
|
||||
: RAD_E_DEVICE;
|
||||
return enc_status(r4d_act_mul_bf16(r4d_addr(A), r4d_addr(B), r4d_addr(Y), (int)M, (int)n, ai,
|
||||
(int)a_ld, (int)b_ld, (int)y_ld, (long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ seg_mean */
|
||||
@@ -837,8 +934,8 @@ extern "C" int r4d_rad_seg_mean(const RadArgs* a, RadStream s) {
|
||||
const long long y_ld = r4d_rows_pitch(Y, n, &My);
|
||||
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (My < S) return R4D_NO(RAD_E_SHAPE);
|
||||
return r4d_seg_mean_bf16(r4d_addr(X), r4d_addr(cu), r4d_addr(Y), (int)S, (int)n, (int)x_ld,
|
||||
(int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
return enc_status(r4d_seg_mean_bf16(r4d_addr(X), r4d_addr(cu), r4d_addr(Y), (int)S, (int)n,
|
||||
(int)x_ld, (int)y_ld, (long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ qk_norm_rope */
|
||||
@@ -873,8 +970,7 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) {
|
||||
const long long rot = r4d_geti_or(a, "rotary_dim", hd);
|
||||
if (hd <= 0 || nh <= 0 || nkv <= 0 || r4d_numel(qw) < hd || r4d_numel(kw) < hd)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
/* A head lives in a wave's registers with both halves of a rotary pair in one lane (or, for a
|
||||
* 16-pair block, in the two half-waves): head_dim a multiple of 32 up to 1024. */
|
||||
/* The register layout holds head_dim up to 1024 (32 lanes x kQkMaxE). */
|
||||
if (hd > 1024 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
|
||||
const char* mode = r4d_gets(a, "mode");
|
||||
int md = 0;
|
||||
@@ -888,7 +984,7 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) {
|
||||
QkBlocks blk{};
|
||||
long long M = 0, pplane = 0;
|
||||
if (md == 4) {
|
||||
/* Interleaved M-RoPE reads three position planes, its sections only bound the
|
||||
/* Interleaved M-RoPE reads three position planes; its sections only bound the
|
||||
* interleave. */
|
||||
blk.n = parse_ints(r4d_gets(a, "sections"), blk.sec, 8);
|
||||
if (blk.n < 3 || pos->rank != 2 || pos->shape[0] < 3) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -922,7 +1018,7 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) {
|
||||
(float)r4d_getf(a, "wadd", 0.0), (int)ld, &blk,
|
||||
(int)pplane, (long)(uintptr_t)s);
|
||||
if (e == -2) return R4D_NO(RAD_E_SHAPE);
|
||||
return e == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
return enc_status(e);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ pool_rows */
|
||||
@@ -939,9 +1035,9 @@ extern "C" int r4d_rad_pool_rows(const RadArgs* a, RadStream s) {
|
||||
const long long y_ld = r4d_rows_pitch(Y, n, &My);
|
||||
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (Mx <= 0 || Mx % k || My < Mx / k) return R4D_NO(RAD_E_SHAPE);
|
||||
return r4d_pool_rows_bf16(r4d_addr(X), r4d_addr(Y), (int)(Mx / k), (int)n, (int)k,
|
||||
(float)r4d_getf(a, "mult", 1.0), (int)x_ld, (int)y_ld,
|
||||
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
return enc_status(r4d_pool_rows_bf16(r4d_addr(X), r4d_addr(Y), (int)(Mx / k), (int)n, (int)k,
|
||||
(float)r4d_getf(a, "mult", 1.0), (int)x_ld, (int)y_ld,
|
||||
(long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ cast bf16 -> f32 */
|
||||
@@ -958,8 +1054,8 @@ extern "C" int r4d_rad_cast_widen(const RadArgs* a, RadStream s) {
|
||||
const long long x_ld = r4d_rows_pitch(x, n, &Mx);
|
||||
if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE);
|
||||
return r4d_widen_bf16_f32(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 enc_status(r4d_widen_bf16_f32(r4d_addr(x), r4d_addr(y), (int)M, (int)n, (int)x_ld,
|
||||
(int)y_ld, (long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the audio tower */
|
||||
@@ -977,8 +1073,8 @@ extern "C" int r4d_rad_relu(const RadArgs* a, RadStream s) {
|
||||
const long long x_ld = r4d_rows_pitch(X, n, &Mx);
|
||||
if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE);
|
||||
return r4d_relu_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 enc_status(r4d_relu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld,
|
||||
(long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_silu(const RadArgs* a, RadStream s) {
|
||||
@@ -994,8 +1090,8 @@ extern "C" int r4d_rad_silu(const RadArgs* a, RadStream s) {
|
||||
const long long x_ld = r4d_rows_pitch(X, n, &Mx);
|
||||
if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE);
|
||||
return r4d_silu_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 enc_status(r4d_silu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld,
|
||||
(long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_clamp(const RadArgs* a, RadStream s) {
|
||||
@@ -1016,9 +1112,9 @@ extern "C" int r4d_rad_clamp(const RadArgs* a, RadStream s) {
|
||||
const long long x_ld = r4d_rows_pitch(X, n, &Mx);
|
||||
if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE);
|
||||
return r4d_clamp_bf16(r4d_addr(X), r4d_addr(L), r4d_addr(H), L->dtype == RAD_F32,
|
||||
r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld,
|
||||
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
return enc_status(r4d_clamp_bf16(r4d_addr(X), r4d_addr(L), r4d_addr(H), L->dtype == RAD_F32,
|
||||
r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld,
|
||||
(long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_conv2d(const RadArgs* a, RadStream s) {
|
||||
@@ -1027,10 +1123,12 @@ extern "C" int r4d_rad_conv2d(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* cu = r4d_opt(a, 2);
|
||||
const RadTensor* V = r4d_opt(a, 3);
|
||||
const RadTensor* Y = r4d_opt(a, 4);
|
||||
const RadTensor* B = r4d_opt(a, 5);
|
||||
if (!X || !Wt || !cu || !Y) return R4D_NO(RAD_E_INVAL);
|
||||
R4D_NEED(dt_bf16(X));
|
||||
R4D_NEED(dt_bf16(Wt));
|
||||
R4D_NEED(dt_bf16(Y));
|
||||
if (B && (dt_bf16(B) != RAD_OK || !r4d_contig(B))) return R4D_NO(RAD_E_DTYPE);
|
||||
if (cu->dtype != RAD_I32 || !r4d_contig(cu) || r4d_numel(cu) < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
if (V && (V->dtype != RAD_I32 || !r4d_contig(V))) return R4D_NO(RAD_E_DTYPE);
|
||||
if (!r4d_contig(Wt)) return R4D_NO(RAD_E_STRIDE);
|
||||
@@ -1044,6 +1142,11 @@ extern "C" int r4d_rad_conv2d(const RadArgs* a, RadStream s) {
|
||||
g.pad = (int)r4d_geti_or(a, "pad", 0);
|
||||
g.cdiv = (int)r4d_geti_or(a, "cu_div", 1);
|
||||
g.vst = (int)r4d_geti_or(a, "valid_stride", 1);
|
||||
g.tl = r4d_geti_or(a, "t_last", 0) != 0 ? 1 : 0;
|
||||
const char* act = r4d_gets(a, "act");
|
||||
if (!act) act = "none";
|
||||
g.gelu = !std::strcmp(act, "gelu") ? 1 : 0;
|
||||
if (!g.gelu && std::strcmp(act, "none")) return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
if (g.W <= 0 || g.cin <= 0 || g.cout <= 0 || g.kh <= 0 || g.kw <= 0 || g.st <= 0 || g.pad < 0 ||
|
||||
g.cdiv <= 0 || g.vst <= 0)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -1051,14 +1154,52 @@ extern "C" int r4d_rad_conv2d(const RadArgs* a, RadStream s) {
|
||||
g.S = (int)(r4d_numel(cu) - 1);
|
||||
if (g.Wo <= 0 || r4d_numel(Wt) < (long long)g.cout * g.cin * g.kh * g.kw)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
if (B && r4d_numel(B) < g.cout) return R4D_NO(RAD_E_SHAPE);
|
||||
long long Mx = 0, My = 0;
|
||||
const long long x_ld = r4d_rows_pitch(X, (long long)g.W * g.cin, &Mx);
|
||||
const long long y_ld = r4d_rows_pitch(Y, (long long)g.Wo * g.cout, &My);
|
||||
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (Mx <= 0 || My <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
return r4d_conv2d_bf16(r4d_addr(X), r4d_addr(Wt), r4d_addr(cu), V ? r4d_addr(V) : 0,
|
||||
r4d_addr(Y), (int)My, &g, (int)x_ld, (int)y_ld,
|
||||
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
return enc_status(r4d_conv2d_bf16(r4d_addr(X), r4d_addr(Wt), r4d_addr(cu), V ? r4d_addr(V) : 0,
|
||||
B ? r4d_addr(B) : 0, r4d_addr(Y), (int)My, &g, (int)x_ld,
|
||||
(int)y_ld, (long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_conv2d_unfold(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* X = r4d_opt(a, 0);
|
||||
const RadTensor* cu = r4d_opt(a, 1);
|
||||
const RadTensor* V = r4d_opt(a, 2);
|
||||
const RadTensor* Y = r4d_opt(a, 3);
|
||||
if (!X || !cu || !Y) return R4D_NO(RAD_E_INVAL);
|
||||
R4D_NEED(dt_bf16(X));
|
||||
R4D_NEED(dt_bf16(Y));
|
||||
if (cu->dtype != RAD_I32 || !r4d_contig(cu) || r4d_numel(cu) < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
if (V && (V->dtype != RAD_I32 || !r4d_contig(V))) return R4D_NO(RAD_E_DTYPE);
|
||||
ConvGeom g{};
|
||||
g.W = (int)r4d_geti_or(a, "width", 0);
|
||||
g.cin = (int)r4d_geti_or(a, "cin", 0);
|
||||
g.cout = 1;
|
||||
g.kh = (int)r4d_geti_or(a, "kh", 0);
|
||||
g.kw = (int)r4d_geti_or(a, "kw", 0);
|
||||
g.st = (int)r4d_geti_or(a, "stride", 1);
|
||||
g.pad = (int)r4d_geti_or(a, "pad", 0);
|
||||
g.cdiv = (int)r4d_geti_or(a, "cu_div", 1);
|
||||
g.vst = (int)r4d_geti_or(a, "valid_stride", 1);
|
||||
g.tl = r4d_geti_or(a, "t_last", 0) != 0 ? 1 : 0;
|
||||
if (g.W <= 0 || g.cin <= 0 || g.kh <= 0 || g.kw <= 0 || g.st <= 0 || g.pad < 0 ||
|
||||
g.cdiv <= 0 || g.vst <= 0)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
g.Wo = (g.W + 2 * g.pad - g.kw) / g.st + 1;
|
||||
g.S = (int)(r4d_numel(cu) - 1);
|
||||
if (g.Wo <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
long long Mx = 0, My = 0;
|
||||
const long long x_ld = r4d_rows_pitch(X, (long long)g.W * g.cin, &Mx);
|
||||
const long long y_ld = r4d_rows_pitch(Y, (long long)g.cin * g.kh * g.kw, &My);
|
||||
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (Mx <= 0 || My <= 0 || My % g.Wo) return R4D_NO(RAD_E_SHAPE);
|
||||
return enc_status(r4d_conv2d_unfold_bf16(r4d_addr(X), r4d_addr(cu), V ? r4d_addr(V) : 0,
|
||||
r4d_addr(Y), (int)(My / g.Wo), &g, (int)x_ld,
|
||||
(int)y_ld, (long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_conv1d_dw(const RadArgs* a, RadStream s) {
|
||||
@@ -1080,9 +1221,10 @@ extern "C" int r4d_rad_conv1d_dw(const RadArgs* a, RadStream s) {
|
||||
const long long y_ld = r4d_rows_pitch(Y, C, &My);
|
||||
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (My <= 0 || Mx < My) return R4D_NO(RAD_E_SHAPE);
|
||||
return r4d_conv1d_dw_bf16(r4d_addr(X), r4d_addr(Wt), r4d_addr(cu), r4d_addr(Y), (int)My,
|
||||
(int)C, (int)K, (int)cdiv, (int)(r4d_numel(cu) - 1), (int)x_ld,
|
||||
(int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
return enc_status(r4d_conv1d_dw_bf16(r4d_addr(X), r4d_addr(Wt), r4d_addr(cu), r4d_addr(Y),
|
||||
(int)My, (int)C, (int)K, (int)cdiv,
|
||||
(int)(r4d_numel(cu) - 1), (int)x_ld, (int)y_ld,
|
||||
(long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_rel_sinusoid(const RadArgs* a, RadStream s) {
|
||||
@@ -1095,11 +1237,29 @@ extern "C" int r4d_rad_rel_sinusoid(const RadArgs* a, RadStream s) {
|
||||
const long long y_ld = r4d_rows_pitch(Y, n, &M);
|
||||
if (y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
/* libref reads the parameter as a float before widening it; the same here, so a timescale
|
||||
* that is not a float is rounded in both. */
|
||||
/* Round through float, as libref reads the parameter, so both agree. */
|
||||
const double mt = (double)(float)r4d_getf(a, "max_timescale", 10000.0);
|
||||
return r4d_rel_sinusoid_bf16(r4d_addr(Y), (int)M, (int)n, mt, (int)y_ld,
|
||||
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
return enc_status(r4d_rel_sinusoid_bf16(r4d_addr(Y), (int)M, (int)n, mt, (int)y_ld,
|
||||
(long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_seg_sinusoid(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* cu = r4d_opt(a, 0);
|
||||
const RadTensor* Y = r4d_opt(a, 1);
|
||||
if (!cu || !Y) return R4D_NO(RAD_E_INVAL);
|
||||
R4D_NEED(dt_bf16(Y));
|
||||
if (cu->dtype != RAD_I32 || !r4d_contig(cu) || r4d_numel(cu) < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long n = r4d_geti_or(a, "n", 0), period = r4d_geti_or(a, "period", 0);
|
||||
const long long cdiv = r4d_geti_or(a, "cu_div", 1);
|
||||
if (n <= 0 || (n & 1) || period <= 0 || cdiv <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
long long M = 0;
|
||||
const long long y_ld = r4d_rows_pitch(Y, n, &M);
|
||||
if (y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
const double mt = (double)(float)r4d_getf(a, "max_timescale", 10000.0);
|
||||
return enc_status(r4d_seg_sinusoid_bf16(r4d_addr(cu), (int)(r4d_numel(cu) - 1), r4d_addr(Y),
|
||||
(int)M, (int)n, (int)period, (int)cdiv, mt, (int)y_ld,
|
||||
(long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_attn_local_rel(const RadArgs* a, RadStream s) {
|
||||
@@ -1142,7 +1302,7 @@ extern "C" int r4d_rad_attn_local_rel(const RadArgs* a, RadStream s) {
|
||||
g.ks = (float)(std::log(1.0 + std::exp(1.0)) / std::log(2.0));
|
||||
g.q_ld = (uint32_t)q_ld; g.k_ld = (uint32_t)k_ld; g.v_ld = (uint32_t)v_ld;
|
||||
g.r_ld = (uint32_t)r_ld; g.o_ld = (uint32_t)o_ld;
|
||||
return r4d_attn_local_rel_bf16(r4d_addr(q), r4d_addr(k), r4d_addr(v), r4d_addr(rk),
|
||||
r4d_addr(pds), r4d_addr(cu), r4d_addr(o), (int)Mo, &g,
|
||||
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
return enc_status(r4d_attn_local_rel_bf16(r4d_addr(q), r4d_addr(k), r4d_addr(v), r4d_addr(rk),
|
||||
r4d_addr(pds), r4d_addr(cu), r4d_addr(o), (int)Mo, &g,
|
||||
(long)(uintptr_t)s));
|
||||
}
|
||||
@@ -1,16 +1,14 @@
|
||||
/* r4d_expert_scale_bf16.hip -- expert_scale: each routing weight times its expert's own scale, in place.
|
||||
*
|
||||
* Gemma 4's router renormalises its top-k and then multiplies each weight by per_expert_scale of
|
||||
* the expert it chose. Said in the conventional vocabulary that is two launches a MoE layer -- an
|
||||
* `embed_lookup` of the [n_expert, 1] scale table by the expert ids, then a `mul` into the weights
|
||||
* -- each a few dozen elements behind a full dispatch at decode. This is the pair as one:
|
||||
* Gemma 4's router renormalises its top-k, then multiplies each weight by its expert's
|
||||
* per_expert_scale. Unfused that is two launches per MoE layer (`embed_lookup` of the [n_expert, 1]
|
||||
* scale table by expert id, then `mul`), each a few dozen elements at decode. Fused:
|
||||
*
|
||||
* ew[t, k] = bf16( ew[t, k] * scale[ids[t, k]] )
|
||||
*
|
||||
* THE CHAIN'S VALUE, BIT FOR BIT: the lookup copies a bf16 scale and the multiply is one f32
|
||||
* product rounded once to nearest even, which is all this does. An id outside the table reads a
|
||||
* zero scale, as embed_lookup writes a zero row for an id it does not hold, and the product's sign
|
||||
* survives it the same way. One thread an element; a decode step is a handful of rows.
|
||||
* Bit-identical to the pair: one f32 product of two bf16 values, rounded once to nearest even. An
|
||||
* id outside the table reads a zero scale, as embed_lookup writes a zero row, so the product's
|
||||
* sign matches too. One thread per element.
|
||||
*/
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
|
||||
+21
-38
@@ -1,10 +1,8 @@
|
||||
/* r4d_fp8_args.h -- the block-scaled fp8 family's operand list, read once for five kernels.
|
||||
/* r4d_fp8_args.h -- operand list of the block-scaled fp8 GEMM family.
|
||||
*
|
||||
* Every kernel that reads `<linear>.weight` as the checkpoint stores it -- F8_E4M3 [N][K] with a
|
||||
* BF16 scale on a [ceil(N/128)][ceil(K/128)] grid -- takes the same five operands in the same
|
||||
* order, because they implement the same op at different M. The reader belongs to the family, so
|
||||
* it is a header beside them rather than an adapter between them and the core. See
|
||||
* libr4d/r4d_args.h.
|
||||
* Every kernel that reads `<linear>.weight` as the checkpoint stores it (F8_E4M3 [N][K] with a
|
||||
* BF16 scale on a [ceil(N/128)][ceil(K/128)] grid) implements the same op at a different M and
|
||||
* takes the same five operands in the same order. See libr4d/r4d_args.h.
|
||||
*/
|
||||
#ifndef R4D_FP8_ARGS_H
|
||||
#define R4D_FP8_ARGS_H
|
||||
@@ -15,38 +13,29 @@
|
||||
enum { F_A = 0, F_ASCALE = 1, F_B = 2, F_BSCALE = 3, F_Y = 4 };
|
||||
/* ...and for `quant_act_fp8` and `sample_chain`. */
|
||||
enum { QF_X = 0, QF_Q = 1, QF_S = 2 };
|
||||
/* The two fused forms. Shaped on their int8 siblings (`rmsnorm_had_quant_i8`,
|
||||
* `gated_had_quant_i8`) minus the operands the rotation needs, so an architecture that switches
|
||||
* activation format changes op names and not operand order. */
|
||||
/* The fused forms follow their int8 siblings (`rmsnorm_had_quant_i8`, `gated_had_quant_i8`)
|
||||
* minus the rotation's operands, so switching activation format changes op names only. */
|
||||
enum { RQ_X = 0, RQ_RES = 1, RQ_W = 2, RQ_Q = 3, RQ_S = 4, RQ_Y = 5 };
|
||||
enum { GQ_GU = 0, GQ_Q = 1, GQ_S = 2, GQ_Y = 3 };
|
||||
enum { TQ_G = 0, TQ_X = 1, TQ_Q = 2, TQ_S = 3, TQ_Y = 4 };
|
||||
enum { SC_LOGITS = 0, SC_QUERY = 1, SC_U = 2, SC_DRAW = 3 };
|
||||
|
||||
/* A required integer parameter, or 0. Distinct from r4d_geti_or's defaulting because these three
|
||||
* have no sensible default: a geometry without M, N and K is not a geometry. */
|
||||
static inline long long aff_or(const RadArgs* a, const char* k) { return r4d_geti_or(a, k, 0); }
|
||||
|
||||
struct Fp8Ops {
|
||||
const RadTensor *a, *ascale, *b, *bscale, *y;
|
||||
long long M, N, K, nkb;
|
||||
long a_ld, sa_ld, w_ld, sw_ld; /* a_ld / w_ld in ELEMENTS here; see the note at each use */
|
||||
long a_ld, sa_ld, w_ld, sw_ld; /* a_ld / w_ld in elements here; see the note at each use */
|
||||
};
|
||||
|
||||
/* Pitches, and the one place this family's two operand pitches are read.
|
||||
*
|
||||
* libr4d takes the WEIGHT pitch in BYTES and the SCALE pitch in ELEMENTS, which is not an
|
||||
* inconsistency: an E4M3 row is bytes and a bf16 scale row is not, and giving both the same unit
|
||||
* would make one of the two conversions invisible at the call site. Restated here so the shim
|
||||
* cannot get it wrong quietly. */
|
||||
/* The weight's scale plane: per 128x128 tile (block E4M3), or per ROW per 128 K (the int8 twins). */
|
||||
/* Reads this family's operands and pitches. libr4d takes the weight pitch in bytes and the scale
|
||||
* pitch in elements: an E4M3 row is bytes, a bf16 scale row is not. */
|
||||
/* The weight's scale plane: per 128x128 tile (block E4M3), or per row per 128 K (the int8 twins). */
|
||||
enum { FP8_OPS_BLOCK_SCALE = 0, FP8_OPS_ROW_SCALE = 1 };
|
||||
|
||||
static inline int fp8_ops(const RadArgs* a, Fp8Ops* g, int want_ascale,
|
||||
int wscale = FP8_OPS_BLOCK_SCALE) {
|
||||
std::memset(g, 0, sizeof(*g));
|
||||
/* No fp8 or int8 block GEMM reads a partitioned weight's `pb1`/`pb2`; refused, not ignored (see
|
||||
* gemm_ops). */
|
||||
/* No fp8 or int8 block GEMM reads a partitioned weight's `pb1`/`pb2`; refuse rather than
|
||||
* ignore (see gemm_ops). */
|
||||
if (r4d_geti_or(a, "pb1", 0) > 0 || r4d_geti_or(a, "pb2", 0) > 0) return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
g->a = r4d_opt(a, F_A);
|
||||
g->ascale = r4d_opt(a, F_ASCALE);
|
||||
@@ -57,27 +46,23 @@ static inline int fp8_ops(const RadArgs* a, Fp8Ops* g, int want_ascale,
|
||||
if (want_ascale && !g->ascale) return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
if (g->b->rank != 2 || g->bscale->rank != 2) return R4D_NO(RAD_E_SHAPE);
|
||||
/* ROWS ARE DIM 0 AND EVERYTHING AFTER IT IS THE ROW -- the same reading r4d_rad_quant_act_fp8
|
||||
* takes of its input, and for the same reason. A gated attention block's q|gate projection is
|
||||
* declared [tokens, heads, 2*head_dim] because the de-interleaving that follows needs the head
|
||||
* axis; its N is heads*2*head_dim and the GEMM neither knows nor cares. Demanding rank 2 here
|
||||
* would refuse that projection, which is the first thing a gated attention layer does. */
|
||||
/* Rows are dim 0 and everything after it is the row, as in r4d_rad_quant_act_fp8. A gated
|
||||
* attention q|gate projection is declared [tokens, heads, 2*head_dim] for the de-interleave
|
||||
* that follows; to the GEMM its N is heads*2*head_dim, so rank > 2 must be accepted. */
|
||||
if (g->y->rank < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
g->M = g->y->shape[0];
|
||||
if (g->M < 1 || r4d_numel(g->y) % g->M) return R4D_NO(RAD_E_SHAPE);
|
||||
g->N = r4d_numel(g->y) / g->M;
|
||||
g->K = g->b->shape[1];
|
||||
if (g->b->shape[0] != g->N) return R4D_NO(RAD_E_SHAPE);
|
||||
if (g->M < 1 || g->N < 1 || g->K < 1) return R4D_NO(RAD_E_SHAPE);
|
||||
if (g->N < 1 || g->K < 1) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* The layout hook and the .rad it wrote are built against R4D_FP8_BLOCK; libr4d compiles its
|
||||
* own copy in. A scalar compare against a constant costs nothing and the alternative is a
|
||||
* silently wrong scale grid. */
|
||||
/* The layout hook and the .rad it wrote use R4D_FP8_BLOCK and libr4d compiles its own copy;
|
||||
* 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;
|
||||
/* The scale plane's own extents, checked rather than assumed: this is the operand a converter
|
||||
* is most likely to hand over at the wrong grid, and a wrong grid reads a plausible number. */
|
||||
/* Check the scale plane's extents: a wrong grid still reads plausible numbers. */
|
||||
if (g->bscale->shape[0] != (wscale == FP8_OPS_ROW_SCALE ? g->N : (g->N + blk - 1) / blk))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
if (g->bscale->shape[1] != g->nkb) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -102,10 +87,8 @@ static inline int fp8_ops(const RadArgs* a, Fp8Ops* g, int want_ascale,
|
||||
if (asp < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
g->sa_ld = asp;
|
||||
}
|
||||
/* 16, not 128. The widest weight load in the family is a uint4 in the matvec and a 32-byte
|
||||
* staged pair in the GEMM, both at a 16-byte offset from the row base. A 128-byte demand would
|
||||
* be a claim about the cacheline, which is 256 on this part and is not an alignment rule of any
|
||||
* load here. */
|
||||
/* 16 bytes: the widest weight load in the family is a uint4 (matvec) or a 32-byte staged pair
|
||||
* (GEMM), both at a 16-byte offset from the row base. */
|
||||
if (!r4d_aligned(g->a->data, 16) || !r4d_aligned(g->b->data, 16)) return R4D_NO(RAD_E_ALIGN);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+15
-38
@@ -1,34 +1,21 @@
|
||||
// r4d_fp8_frag.h -- where a byte of a block-scaled FP8 WEIGHT lives once it is stored in WMMA
|
||||
// FRAGMENT ORDER, and nothing else. Pure C++: no HIP, no r4d.h, so the host layout hook and the
|
||||
// device kernels can include the same arithmetic instead of writing it twice and drifting.
|
||||
// r4d_fp8_frag.h -- where a byte of a block-scaled FP8 weight lives in WMMA fragment order. Pure
|
||||
// C++ (no HIP, no r4d.h) so the host layout hook and the device kernels share one definition.
|
||||
//
|
||||
// ---- why the weight is permuted at all -----------------------------------------------------
|
||||
// Why permute: the fp8a8 GEMMs read operands through r4d_fp8::frag(), which wants lane `l` to hold
|
||||
// row `l & 15` of a 16-row tile at k `(l >> 4) * 8`, eight bytes. From a row-major weight those
|
||||
// sixteen rows are `K` bytes apart, so a wave's load is sixteen transactions; the kernels stage
|
||||
// through LDS to transpose, at the cost of a barrier, 36 KiB per block and a second pass over the
|
||||
// weight. In fragment order the bytes are already in lane order.
|
||||
//
|
||||
// The fp8a8 GEMMs read both operands through r4d_fp8::frag(), which wants lane `l` to hold ROW
|
||||
// `l & 15` of a 16-row tile at k `(l >> 4) * 8`, eight bytes. A row-major weight cannot deliver
|
||||
// that from a coalesced load: a wave's sixteen rows are `K` bytes apart, so asking for them
|
||||
// together is sixteen separate transactions off a 256-byte cacheline, and reaches well under the
|
||||
// rate a wide contiguous read does. That is why the kernels stage through LDS -- the LDS round
|
||||
// trip IS the 16-row transpose -- and the staging costs a barrier, 36 KiB a block, and a second
|
||||
// pass over every weight byte.
|
||||
// Why 64 k and not 16: a single fragment (16 rows x 16 k = 256 bytes) gives a wave one 256-byte
|
||||
// cacheline per request, which loses even to LDS staging. Four fragments give each lane 32
|
||||
// contiguous bytes and the wave a 1 KiB request, which beats both at every N and K in the family.
|
||||
//
|
||||
// Stored in fragment order the same bytes are already in lane order and none of it is needed.
|
||||
//
|
||||
// ---- the shape of it, and why it is 64 k and not 16 ------------------------------------------
|
||||
//
|
||||
// The obvious layout is one fragment: 16 rows x 16 k = 256 bytes, lane `l` taking bytes
|
||||
// `l * 8`. A wave then asks for 256 contiguous bytes, which LOSES even to the staged path: a
|
||||
// 256-byte request is a single cacheline and the memory system wants more in flight than one
|
||||
// cacheline a wave. FOUR fragments together give each lane 32 contiguous bytes and the wave a
|
||||
// 1 KiB request, which beats both the 8-byte form and LDS staging at every N and K in this family.
|
||||
//
|
||||
// So the unit is a (16 row, 64 k) TILE of 1024 bytes, laid out as 32 lanes x 32 bytes, and lane
|
||||
// `l`'s 32 bytes are its four fragments back to back: bytes `8t` are fragment `t`, which covers
|
||||
// The unit is a (16 row, 64 k) tile of 1024 bytes, laid out as 32 lanes x 32 bytes. Lane `l`'s
|
||||
// 32 bytes are its four fragments back to back: bytes `8t` are fragment `t`, covering
|
||||
// k `t*16 + (l>>4)*8` of row `l & 15`.
|
||||
//
|
||||
// K must be a multiple of 64 and N a multiple of 16. Every fp8 weight in this family already
|
||||
// satisfies both by a wide margin -- the constraint rows demand K and N divisible by 128, because
|
||||
// that is the scale block -- so this adds no restriction anyone can hit.
|
||||
// K must be a multiple of 64 and N of 16; the 128 scale block already guarantees both.
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
@@ -39,18 +26,8 @@ enum { kFragRows = 16, kFragK = 16, kSuperK = 64, kTileBytes = 1024, kLaneBytes
|
||||
// Bytes one [N][K] weight occupies in fragment order: exactly N*K, since this is a permutation.
|
||||
inline int64_t frag_bytes(int64_t N, int64_t K) { return N * K; }
|
||||
|
||||
// The 1 KiB tile holding row tile `rt` and k supertile `ks`, in bytes from the plane's base.
|
||||
// `ksuper` is K / 64 -- the number of supertiles a row tile spans.
|
||||
inline int64_t frag_tile_off(int64_t rt, int64_t ks, int64_t ksuper) {
|
||||
return (rt * ksuper + ks) * (int64_t)kTileBytes;
|
||||
}
|
||||
|
||||
// ...and within that tile, the 32 bytes lane `l` owns. Its four fragments are at +0, +8, +16, +24.
|
||||
inline int64_t frag_lane_off(int64_t lane) { return lane * (int64_t)kLaneBytes; }
|
||||
|
||||
// The source element a given (tile, lane, fragment, byte) came from, as a row and a k. This is the
|
||||
// ONE definition of the permutation; the host transform walks it forwards and the device kernels
|
||||
// index it backwards, and both are wrong together or right together.
|
||||
// The source (row, k) of a given (tile, lane, fragment, byte). The single definition of the
|
||||
// permutation: the host transform walks it forwards, the device kernels index it backwards.
|
||||
inline void frag_src(int64_t rt, int64_t ks, int64_t lane, int64_t t, int64_t j,
|
||||
int64_t* row, int64_t* k) {
|
||||
*row = rt * (int64_t)kFragRows + (lane & 15);
|
||||
|
||||
+49
-57
@@ -1,41 +1,37 @@
|
||||
/* r4d_fp8_layout.cpp -- what libr4d's FP8 kernels store for a weight, and the relayouts that
|
||||
/* r4d_fp8_layout.cpp -- the stored form of libr4d's FP8 and int8 weights, and the relayouts that
|
||||
* produce it from the weight's canonical planes (spec.md §4.3). Pure host C++: nothing here
|
||||
* includes r4d.h or <hip/hip_runtime.h>, so it compiles and can be exercised on a box with no
|
||||
* ROCm, which is where a packing bug is cheapest to find.
|
||||
* includes r4d.h or <hip/hip_runtime.h>, so packing can be tested without ROCm.
|
||||
*
|
||||
* ================================================================= what they read
|
||||
*
|
||||
* The block-scaled linears read the encoding a block-FP8 checkpoint ships, `fp8_e4m3*bf16[128x128]`:
|
||||
*
|
||||
* codes F8_E4M3, [N][K] -- exactly as safetensors stores `X.weight`
|
||||
* scale BF16, [ceil(N/128)][ceil(K/128)] -- exactly `X.weight_scale_inv`
|
||||
* codes F8_E4M3, [N][K] -- as safetensors stores `X.weight`
|
||||
* scale BF16, [ceil(N/128)][ceil(K/128)] -- as `X.weight_scale_inv`
|
||||
*
|
||||
* In a Qwen3.8-27B-FP8 checkpoint, `mlp.gate_proj.weight` is F8_E4M3 [17408, 5120] with
|
||||
* `mlp.gate_proj.weight_scale_inv` BF16 [136, 40], and 17408/136 = 5120/40 = 128. The kernels
|
||||
* index `S[(row / 128) * sc_cols + (c / 128)]`, which is that grid, so the scale plane is stored as
|
||||
* it is and only the codes move: into WMMA fragment order for the fp8a8 GEMMs, which read a lane's
|
||||
* own bytes straight from a coalesced load, and nowhere at all for the fp8a16 matvec, which reads
|
||||
* sixteen consecutive k of one row. The two cannot share a stored form, so a weight is declared
|
||||
* for one or the other and the builder refuses the pair.
|
||||
* E.g. Qwen3.8-27B-FP8 `mlp.gate_proj.weight` is F8_E4M3 [17408, 5120] with a BF16 [136, 40]
|
||||
* scale. The kernels index `S[(row / 128) * sc_cols + (c / 128)]`, so the scale plane is stored
|
||||
* unchanged and only the codes move: into WMMA fragment order for the fp8a8 GEMMs (a lane reads
|
||||
* its own bytes from one coalesced load), and not at all for the fp8a16 matvec, which reads
|
||||
* sixteen consecutive k of one row. The two forms differ, so a weight is declared for one or the
|
||||
* other and the builder refuses the pair.
|
||||
*
|
||||
* The lm_head carries each row's block scales in the row's own tail, because it has one operand
|
||||
* and is ROW-sharded: [K codes][K/128 bf16 scales], the row padded to 16 bytes so a uint4 load of
|
||||
* the next row is aligned (r4d_fp8_lm.h). hc_read's mixing matrices and mtp_enter's fc are the
|
||||
* same with an f32 scale per group of the row (r4d_hc_fp8.h).
|
||||
* The lm_head is a single row-sharded operand, so each row carries its block scales in its own
|
||||
* tail: [K codes][K/128 bf16 scales], padded to 16 bytes so a uint4 load of the next row is
|
||||
* aligned (r4d_fp8_lm.h). hc_read's mixing matrices and mtp_enter's fc use the same form with an
|
||||
* f32 scale per group of the row (r4d_hc_fp8.h).
|
||||
*
|
||||
* ================================================================= BF16 scales, not UE8M0
|
||||
*
|
||||
* Some block-FP8 checkpoints carry a UE8M0 exponent BYTE per tile rather than a bf16. Converting
|
||||
* to it is not free: UE8M0 stores an exponent and nothing else, so rounding a bf16 scale into it
|
||||
* changes the tile's gain, and correcting for that means requantising every E4M3 byte against the
|
||||
* new power-of-two scale. And nothing is gained -- decoding either is one shift and one bitcast.
|
||||
* The bf16 plane is 0.02% of its weight.
|
||||
* Some block-FP8 checkpoints carry a UE8M0 exponent byte per tile instead of a bf16. Converting to
|
||||
* UE8M0 rounds each scale to a power of two, which changes the tile's gain and would mean
|
||||
* requantising every E4M3 byte. Decoding either costs one shift and one bitcast, and the bf16
|
||||
* plane is 0.02% of its weight.
|
||||
*
|
||||
* Choosing the numbers is not this file's job: a checkpoint's own planes are served as they are,
|
||||
* and anything quantised -- a bf16 lm_head made fp8 -- was quantised by a quantiser before the
|
||||
* container was written (libquant's `rtn` over `fp8_e4m3` with a 128x128 bf16 block, whose rule is
|
||||
* the one these kernels' activation quantiser uses: amax/448 rounded to bf16, a zero block scaled
|
||||
* by one).
|
||||
* This file chooses no numbers: a checkpoint's planes are served as they are, and anything
|
||||
* quantised (e.g. a bf16 lm_head made fp8) was quantised before the container was written, by
|
||||
* libquant's `rtn` over `fp8_e4m3` with a 128x128 bf16 block. Its rule matches these kernels'
|
||||
* activation quantiser: amax/448 rounded to bf16, a zero block scaled by one.
|
||||
*/
|
||||
|
||||
#include "r4d_plugin.h"
|
||||
@@ -48,20 +44,19 @@
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
/* Operand indices for `gemm_nt_q`. Named rather than literal because the schema is positional and a
|
||||
* reorder in r4d_rows.cpp is otherwise a silent miscompile here. */
|
||||
/* Operand indices of `gemm_nt_q`. The schema is positional, so these must follow its order in
|
||||
* r4d_rows.cpp. */
|
||||
enum { FL_A = 0, FL_ASCALE = 1, FL_B = 2, FL_BSCALE = 3, FL_Y = 4 };
|
||||
|
||||
/* The k a fragment-order tile spans, which libr4d compiles in. */
|
||||
/* K span of one fragment-order tile, compiled into libr4d. */
|
||||
enum { R4D_FP8_SUPER_K = r4d_fp8::kSuperK };
|
||||
|
||||
namespace {
|
||||
|
||||
/* THE WALK BOTH DIRECTIONS SHARE: the fragment-order plane front to back, eight bytes at a time,
|
||||
* each with the row-major offset of the [N][K] weight it holds. A fragment is eight consecutive k
|
||||
* of one row -- r4d_fp8_frag.h's frag_src over j = 0..7 -- so it moves as one word, and the
|
||||
* stored side is written or read in order. A byte at a time, with the divisions that place it,
|
||||
* the same permutation is most of the CPU a block-FP8 model's load spends. */
|
||||
/* Walks the fragment-order plane front to back, eight bytes at a time, passing each word's
|
||||
* row-major offset in the [N][K] weight; used in both directions. A fragment is eight consecutive
|
||||
* k of one row (r4d_fp8_frag.h frag_src over j = 0..7), so it moves as one word. Placing each byte
|
||||
* separately would dominate the CPU cost of loading a block-FP8 model. */
|
||||
template <typename Move>
|
||||
void frag_walk(long long N, long long K, Move move) {
|
||||
constexpr int kLanes = r4d_fp8::kTileBytes / r4d_fp8::kLaneBytes;
|
||||
@@ -84,9 +79,8 @@ int fgeom(const RadParam* p, int n_p, FGeom* g) {
|
||||
g->N = r4d_pgeti_or(p, n_p, "N", 0);
|
||||
g->K = r4d_pgeti_or(p, n_p, "K", 0);
|
||||
if (g->N <= 0 || g->K <= 0) return RAD_E_SHAPE;
|
||||
/* The block is compiled into the kernels as `>> 7`. A geometry that asks for another group is
|
||||
* asking for a format nothing here reads; the constraint table already refused it, and this is
|
||||
* the second line of defence for a tool calling the hook without going through selection. */
|
||||
/* The block is compiled into the kernels as `>> 7`. The constraint table already refuses
|
||||
* other groups; this catches a caller that invokes the hook without selection. */
|
||||
if (r4d_pgeti_or(p, n_p, "group", R4D_FP8_BLOCK) != R4D_FP8_BLOCK) return RAD_E_SHAPE;
|
||||
g->sn = (g->N + R4D_FP8_BLOCK - 1) / R4D_FP8_BLOCK;
|
||||
g->sk = (g->K + R4D_FP8_BLOCK - 1) / R4D_FP8_BLOCK;
|
||||
@@ -152,12 +146,12 @@ int mgeom(const RadParam* p, int n_p, int operand, HGeom* g) {
|
||||
|
||||
/* ==================================================================== the hooks
|
||||
*
|
||||
* Each checks the encoding its kernel reads and refuses any other with RAD_E_DTYPE, which is the
|
||||
* declare-time error a mis-converted container meets; then it moves bits and chooses none. */
|
||||
* Each checks the encoding its kernel reads and refuses any other with RAD_E_DTYPE (the
|
||||
* declare-time error for a mis-converted container). They move bits and choose none. */
|
||||
|
||||
namespace {
|
||||
|
||||
/* gemm_nt_q's weight and scale over block fp8: e4m3 codes with a bf16 scale a 128x128 block. */
|
||||
/* gemm_nt_q's block-fp8 weight: e4m3 codes with a bf16 scale per 128x128 block. */
|
||||
bool fp8_block_enc(const RadEncoding* e) {
|
||||
return r4d_enc::affine(e, RAD_F8E4M3, RAD_BF16, R4D_FP8_BLOCK, R4D_FP8_BLOCK);
|
||||
}
|
||||
@@ -227,14 +221,14 @@ extern "C" int r4d_rad_unrelayout_fp8_block(const RadParam* p, int n_p, int oper
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- the int8 twin: i8 codes in the same fragment order, with a bf16 scale per ROW per 128 K.
|
||||
* The codes move exactly as E4M3 codes do -- the permutation does not read them.
|
||||
/* ---- the int8 twin: i8 codes in the same fragment order as E4M3, with a bf16 scale per row per
|
||||
* 128 K.
|
||||
*
|
||||
* THE SCALE PLANE IS TILE-MAJOR, [N/16][K/128][16]: the sixteen rows of a fragment tile side by side
|
||||
* for one 128-K block. On the narrow path a lane's eight accumulator rows are eight CONSECUTIVE
|
||||
* rows of one tile, so their scales are one 16-byte load in the fold where the row-major plane
|
||||
* would need eight scattered ones -- which, if-converted into every k step, cost the decode
|
||||
* kernel 70% at M = 4. The prefill tile reads one row's scale a lane, from either form. */
|
||||
* The scale plane is tile-major, [N/16][K/128][16]: the sixteen rows of a fragment tile side by
|
||||
* side for one 128-K block. On the narrow path a lane's eight accumulator rows are eight
|
||||
* consecutive rows of one tile, so their scales are one 16-byte load. A row-major plane needs
|
||||
* eight scattered loads, which if-converted into every k step cost the decode kernel 70% at
|
||||
* M = 4. The prefill tile reads one row's scale per lane and works with either form. */
|
||||
namespace {
|
||||
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) {
|
||||
@@ -316,9 +310,8 @@ extern "C" int r4d_rad_unrelayout_i8_block(const RadParam* p, int n_p, int opera
|
||||
/* ---- the lm_head: codes and scales in one row, the scales of the row's 128-row block repeated
|
||||
* into its tail. */
|
||||
namespace {
|
||||
/* `i8`: the int8 head (logits_gemm_i8) -- i8 codes with a bf16 scale a row per 128 columns, the
|
||||
* same stored row with each row's OWN scales in its tail where the E4M3 head repeats its 128-row
|
||||
* block's. */
|
||||
/* `i8` selects the int8 head (logits_gemm_i8): i8 codes with a bf16 scale per row per 128
|
||||
* columns. Same stored row, but each row's tail holds its own scales instead of its block's. */
|
||||
int lm_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out, FGeom* gout, bool i8 = false) {
|
||||
if (!out || !pl) return RAD_E_INVAL;
|
||||
@@ -436,8 +429,8 @@ extern "C" int r4d_rad_unrelayout_i8_logits(const RadParam* p, int n_p, int oper
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- hc_read's mixing matrices and mtp_enter's fc: e4m3 codes with an f32 scale a group of the
|
||||
* row, the scales in the row's tail and the row padded to 16 bytes. */
|
||||
/* ---- hc_read's mixing matrices and mtp_enter's fc: e4m3 codes with an f32 scale per group of
|
||||
* the row, the scales in the row's tail and the row padded to 16 bytes. */
|
||||
namespace {
|
||||
int hcrows_enc_layout(const HGeom& g, const char* tag, const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out) {
|
||||
@@ -542,11 +535,10 @@ extern "C" int r4d_rad_unrelayout_mtp_e4m3(const RadParam* p, int n_p, int opera
|
||||
|
||||
/* ================================================================= embed_lookup_q's table
|
||||
*
|
||||
* The gather reads the table AS IT IS, so this hook only answers whether it can: E4M3 codes with
|
||||
* ONE bf16 scale for the whole table (`fp8_e4m3*bf16[*x*]`, the n-gram table's recipe), or the
|
||||
* table as the checkpoint ships it, plain bf16 with no scale. The same two forms libavx's host
|
||||
* gather accepts (avx_layout_ngram), checked the same way, so a model whose table one of them
|
||||
* reads is never refused by the other at declare. */
|
||||
* The gather reads the table as stored, so this hook only checks that it can: E4M3 codes with one
|
||||
* bf16 scale for the whole table (`fp8_e4m3*bf16[*x*]`, the n-gram table's recipe), or plain bf16
|
||||
* as the checkpoint ships it. libavx's host gather (avx_layout_ngram) accepts the same two forms
|
||||
* with the same checks, so neither refuses at declare a table the other reads. */
|
||||
extern "C" int r4d_rad_layout_embed_q(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out) {
|
||||
|
||||
+14
-35
@@ -1,53 +1,32 @@
|
||||
// r4d_fp8_lm.h -- the STORED ROW GEOMETRY of the fp8 lm_head, and nothing else. Pure C++: no HIP,
|
||||
// no r4d.h, so the host layout hook (r4d_fp8_layout.cpp), the device entry point
|
||||
// (r4d_gemm_fp8a16_nt_m1.hip) and the selftest all derive the row width from the same line instead
|
||||
// of writing `K + 2 * (K / 128)` four times and drifting.
|
||||
// r4d_fp8_lm.h -- stored row geometry of the fp8 lm_head. Pure C++ (no HIP, no r4d.h) so the
|
||||
// layout hook (r4d_fp8_layout.cpp), the entry point (r4d_gemm_fp8a16_nt_m1.hip) and the selftest
|
||||
// derive the row width from one definition.
|
||||
//
|
||||
// WHY THE ROW LOOKS LIKE THIS AT ALL is r4d_rad_layout_fp8_logits' argument and is not repeated
|
||||
// here: `logits_gemm` carries ONE weight operand, so the block scales have nowhere to go but the
|
||||
// row's own tail, and that is what keeps a row-sharded lm_head a plain byte range under tensor
|
||||
// parallelism.
|
||||
// `logits_gemm` carries one weight operand, so the block scales live in each row's tail (see
|
||||
// r4d_rad_layout_fp8_logits); a row-sharded lm_head stays a plain byte range under TP.
|
||||
//
|
||||
// ---- THE PADDING, which is the only thing this header adds to `K + 2*nkb` ---------------------
|
||||
//
|
||||
// Both kernels that read this plane -- the M <= 2 matvec and the WMMA tile above it -- load the
|
||||
// weight SIXTEEN BYTES AT A TIME through a uint4, at `row * w_ld + (a multiple of 16)`. So the row
|
||||
// pitch has to be a multiple of 16 or every odd row is misaligned, and the unpadded width is a
|
||||
// multiple of 16 only when
|
||||
// Padding: both kernels that read this plane (the M <= 2 matvec and the WMMA tile) load the weight
|
||||
// as uint4 at `row * w_ld + (a multiple of 16)`, so the row pitch must be a multiple of 16. The
|
||||
// unpadded width is one only when
|
||||
//
|
||||
// K + 2*(K/128) = 130m (K = 128m) is 0 mod 16 <=> m is 0 mod 8 <=> K is 0 mod 1024
|
||||
//
|
||||
// which is a property of the MODEL, not of anything the kernel chose. K = 5120 has it; K = 2560
|
||||
// does not. Without the pad such a head cannot be served in fp8 at all: it falls to the bf16
|
||||
// projection, which reads twice the bytes and is then the single largest op in the step -- for
|
||||
// want of eight bytes a row.
|
||||
// e.g. K = 5120 qualifies, K = 2560 does not. The pad costs under 16 bytes per row (0.3% at
|
||||
// K = 2560) and is a no-op when K is a multiple of 1024, where the plane is byte-identical to the
|
||||
// unpadded one.
|
||||
//
|
||||
// So pad. The cost is under 16 bytes on a row that is already K + K/64 long -- 0.3% at K = 2560,
|
||||
// and ZERO at every K that is a multiple of 1024, where the rounding is a no-op and the plane is
|
||||
// byte-for-byte the unpadded one. **The padding never changes a valid container's plane**, and
|
||||
// that is not luck: the layout hook refuses a K without the property rather than writing a plane
|
||||
// its own kernels would fault on, so every K a container can already hold is one the rounding
|
||||
// leaves alone.
|
||||
//
|
||||
// This is NOT the padding r4d_gemm_fp8a16_nt_m1.hip's header prices and rejects. That one is about
|
||||
// padding an ALREADY-ALIGNED 5200-byte row out to 5376 to make it 128-aligned, chasing the
|
||||
// cacheline straddle, and it loses to FK = 256. This is 16-byte alignment, which is a correctness
|
||||
// floor rather than a tuning knob, and it is what decides whether the row can be served at all.
|
||||
// This is a 16-byte correctness floor, unrelated to the 128-byte row padding that
|
||||
// r4d_gemm_fp8a16_nt_m1.hip's header evaluates and rejects.
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
namespace r4d_fp8 {
|
||||
|
||||
// BYTES one stored lm_head row occupies: K E4M3 codes, then K/128 bf16 block scales, then the
|
||||
// Bytes one stored lm_head row occupies: K E4M3 codes, then K/128 bf16 block scales, then the
|
||||
// alignment tail. K must be a multiple of 128 (the scale block); the caller checks that.
|
||||
inline int64_t lm_row_bytes(int64_t K) {
|
||||
const int64_t used = K + 2 * (K / 128);
|
||||
return (used + 15) & ~(int64_t)15;
|
||||
}
|
||||
|
||||
// ...and where the pad starts, which is the only part of the row nothing reads. The transform
|
||||
// zeroes it so that a container's bytes are a function of its weights and not of what the
|
||||
// allocator happened to leave there.
|
||||
inline int64_t lm_row_used(int64_t K) { return K + 2 * (K / 128); }
|
||||
|
||||
} // namespace r4d_fp8
|
||||
+69
-128
@@ -1,50 +1,40 @@
|
||||
// Shared device-side machinery for the BLOCK-SCALED FP8 family: the 16x16x16 fp8 WMMA fragment
|
||||
// map, the E4M3 decoders, and the bf16 block-scale load. Named for what it is rather than for a
|
||||
// kernel, like r4d_common.h and r4d_gdn_wmma.h, because it provides none.
|
||||
// Shared device code for the block-scaled FP8 family: the 16x16x16 fp8 WMMA fragment map, the
|
||||
// E4M3 decoders and the bf16 block-scale load.
|
||||
//
|
||||
// ---- the lane->element mapping, which AMD does not document ------------------------------------
|
||||
// ---- lane->element mapping (undocumented by AMD; ROCm issue #6025) ------------------------------
|
||||
//
|
||||
// AMD does not publish it, and ROCm issue #6025, which asks for it, is closed without an answer.
|
||||
// With lane `l`, `c = l % 16`, `h = l / 16` it is:
|
||||
// With lane `l`, `c = l % 16`, `h = l / 16`:
|
||||
//
|
||||
// A, row-major A[m][k] lane l holds A[c][h*8 + j], j = 0..7
|
||||
// B, row-major B[k][n] lane l holds B[h*8 + j][c], j = 0..7
|
||||
// C/D accumulator acc[j] IS D[h*8 + j][c]
|
||||
//
|
||||
// The accumulator is COLUMN-distributed: a lane owns one column and eight consecutive rows, lanes
|
||||
// 0-15 rows 0-7 and lanes 16-31 rows 8-15. The intuitive "a lane owns a row" is wrong, produces a
|
||||
// silently transposed tile, and gives no compile or runtime error.
|
||||
// The accumulator is column-distributed: a lane owns one column and eight consecutive rows (lanes
|
||||
// 0-15 rows 0-7, lanes 16-31 rows 8-15). Assuming a lane owns a row gives a silently transposed
|
||||
// tile. Identity, diagonal and symmetric test matrices cannot detect that; tests of fragment code
|
||||
// must use asymmetric operands.
|
||||
//
|
||||
// IDENTITY, DIAGONAL AND SYMMETRIC TEST MATRICES CANNOT TELL THE TWO APART -- both give 0 errors.
|
||||
// Any test of fragment code here must use asymmetric operands.
|
||||
// ---- K labelling --------------------------------------------------------------------------------
|
||||
//
|
||||
// ---- the K labelling ---------------------------------------------------------------------------
|
||||
// The hardware K-order is not contiguous: lanes 0-15 hold k = 0,1,2,3,8,9,10,11. Labelling slot j
|
||||
// of lane-half h as "k = 8h + j" is a permutation of K applied identically to A and B, so the
|
||||
// product is bit-identical. Two rules keep it that way:
|
||||
//
|
||||
// The canonical hardware K-order is not contiguous: lanes 0-15 really hold k = 0,1,2,3,8,9,10,11.
|
||||
// Calling slot j of lane-half h "k = 8h + j" above is a permutation of K applied IDENTICALLY to A
|
||||
// and B, and D = sum_k A[m][k] B[k][n] is invariant under it, so the product is bit-identical. Two
|
||||
// rules keep it that way:
|
||||
// 1. Both operands must use this labelling. Mixing GLOBAL_LOAD_TR_B128 (canonical order) with a
|
||||
// plain load misaligns K silently. Every kernel here stages both operands through `stage8`
|
||||
// and reads both through `r4d_fp8::frag`.
|
||||
// 2. A sparse path may not use it: SWMMAC's index bits are tied to the hardware K groups.
|
||||
//
|
||||
// 1. BOTH OPERANDS must use this labelling. If one ever comes from GLOBAL_LOAD_TR_B128 (which
|
||||
// emits the canonical order) and the other from a plain load, the K labels do not line up and
|
||||
// the result is silently wrong. Every kernel in this family stages both operands through the
|
||||
// same `stage8` and reads both through `r4d_fp8_frag`, which is what makes that safe.
|
||||
// 2. A SPARSE path may NOT use this labelling: SWMMAC's index bits are tied to the hardware K
|
||||
// groups. Nothing in this family is sparse.
|
||||
// ---- hazards ------------------------------------------------------------------------------------
|
||||
//
|
||||
// ---- hazards -----------------------------------------------------------------------------------
|
||||
// A WMMA whose A, B or index overlaps the previous WMMA's D needs an independent VALU instruction
|
||||
// in between (required for correctness; the compiler inserts it). Feeding D back as C of the same
|
||||
// opcode is exempt, so these kernels keep one accumulator chain of a single opcode.
|
||||
//
|
||||
// A WMMA whose A, B or index overlaps the PREVIOUS WMMA's D needs at least one independent VALU
|
||||
// instruction in between -- required for correct function, not a perf hint. The compiler inserts it
|
||||
// for these intrinsics. Feeding D straight back as C of the same opcode is the fast path and is
|
||||
// exempt, which is why these kernels keep one long accumulator chain of a single opcode rather than
|
||||
// mixing WMMA types in the inner loop.
|
||||
//
|
||||
// And WMMA does NOT co-issue with VALU on RDNA4, for every opcode. Dequantisation and address math
|
||||
// inside a wave are serial with its matrix work. That is the whole argument for an fp8 GEMM whose
|
||||
// inner loop converts nothing: v_wmma_f32_16x16x16_fp8_fp8 issues at 412 TF/s (2.99 cycles), the
|
||||
// same rate as v_wmma_i32_16x16x16_iu8, and here it is reached because both operands are already
|
||||
// E4M3 bytes and nothing is unpacked between the LDS read and the mma.
|
||||
// WMMA does not co-issue with VALU on RDNA4, so dequantisation and address math are serial with
|
||||
// matrix work. v_wmma_f32_16x16x16_fp8_fp8 issues at 412 TF/s (2.99 cycles), the same rate as
|
||||
// v_wmma_i32_16x16x16_iu8, and is reached here because both operands are already E4M3 bytes and
|
||||
// nothing is unpacked between the LDS read and the mma.
|
||||
#pragma once
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_fp8_frag.h"
|
||||
@@ -54,24 +44,22 @@
|
||||
|
||||
namespace r4d_fp8 {
|
||||
|
||||
// A/B operand widths are the RDNA4 ones -- half of RDNA3's, because RDNA4 dropped the cross-half
|
||||
// replication. Passing a gfx11-width vector compiles for gfx1100 and fails here, which is the
|
||||
// intended way to find out the unsuffixed builtin was used.
|
||||
// A/B operand widths are RDNA4's: half of RDNA3's, since RDNA4 dropped the cross-half
|
||||
// replication. A gfx11-width vector fails to compile here.
|
||||
typedef int i2v __attribute__((ext_vector_type(2))); // fp8 A or B, 2 VGPRs
|
||||
typedef float f8v __attribute__((ext_vector_type(8))); // f32 accumulator, 8 VGPRs
|
||||
|
||||
constexpr uint32_t kM = 16, kN = 16, kK = 16;
|
||||
|
||||
// Always the _gfx12-suffixed builtin. The unsuffixed name is the RDNA3 form with different operand
|
||||
// widths; it does not compile for gfx1201, which is the good outcome.
|
||||
// Always the _gfx12-suffixed builtin; the unsuffixed RDNA3 form has different operand widths.
|
||||
__device__ __forceinline__ f8v mma(i2v a, i2v b, f8v c) {
|
||||
return __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c);
|
||||
}
|
||||
|
||||
// THE INT8 TWIN, for the same kernels at i8 codes: v_wmma_i32_16x16x16_iu8, both operands signed,
|
||||
// at the fp8 instruction's rate. Its int32 accumulator rides in the f8v registers as bits, so one
|
||||
// accumulator type serves both instantiations; acc_val reads a slot back as the number it holds.
|
||||
// A 128-K scale block of products is at most 128 * 127 * 127, far inside int32.
|
||||
// Int8 twin for the same kernels at i8 codes: v_wmma_i32_16x16x16_iu8, both operands signed, at
|
||||
// the fp8 rate. The int32 accumulator is carried in f8v registers as bits so one accumulator type
|
||||
// serves both; acc_val reads a slot back as a number. A 128-K block sums at most 128 * 127 * 127,
|
||||
// well inside int32.
|
||||
typedef int i8v __attribute__((ext_vector_type(8)));
|
||||
template <bool I8>
|
||||
__device__ __forceinline__ f8v mma8(i2v a, i2v b, f8v c) {
|
||||
@@ -103,17 +91,12 @@ __device__ __forceinline__ f8v acc_zero() {
|
||||
|
||||
// ---- E4M3 -> f32 -------------------------------------------------------------------------------
|
||||
//
|
||||
// ONE INSTRUCTION on gfx1201: v_cvt_f32_fp8. The software form is ~11 VALU ops and is the fallback
|
||||
// for a target without the builtin. Over all 256 byte values the two agree on 254. The two that
|
||||
// differ are 0x7F and 0xFF, E4M3-fn's NaN encodings -- the hardware returns NaN, as the format
|
||||
// says, and the software form returns +-480. Nothing here writes those bytes (both quantisers
|
||||
// clamp to +-448 = 0x7E), so the difference is inert on real data and turns a silent 480 into a
|
||||
// visible NaN if that ever stops being true.
|
||||
// One instruction on gfx1201 (v_cvt_f32_fp8); the software fallback is ~11 VALU ops. They agree on
|
||||
// all bytes except 0x7F and 0xFF, E4M3-fn's NaN encodings: hardware returns NaN, the fallback
|
||||
// +-480. Both quantisers clamp to +-448 = 0x7E, so real data never holds them.
|
||||
//
|
||||
// There is no subnormal-free fast path here. That path is only
|
||||
// correct where the encoder clamps entries to exponent 1..7 by construction, as an expert codebook
|
||||
// can; an arbitrary checkpoint weight has no such precondition, and for a subnormal that path
|
||||
// silently returns 2^-7 * 1.MMM instead of MMM * 2^-9. The hardware instruction handles them.
|
||||
// No subnormal-free fast path: a checkpoint weight may hold subnormals, which such a path would
|
||||
// decode as 2^-7 * 1.MMM instead of MMM * 2^-9.
|
||||
__device__ __forceinline__ float e4m3(uint32_t b) {
|
||||
#if __has_builtin(__builtin_amdgcn_cvt_f32_fp8)
|
||||
return __builtin_amdgcn_cvt_f32_fp8(b, 0);
|
||||
@@ -127,10 +110,9 @@ __device__ __forceinline__ float e4m3(uint32_t b) {
|
||||
#endif
|
||||
}
|
||||
|
||||
// TWO E4M3 bytes of a packed dword to two f32 in ONE instruction -- v_cvt_pk_f32_fp8, which gfx1201
|
||||
// has because RDNA4 carries the fp8 WMMA path. `HI` selects bytes 2,3 over bytes 0,1 and must be a
|
||||
// template parameter because the builtin's word select is a constant. Returns r4d_common.h's `v2f`,
|
||||
// which is what the builtin actually returns.
|
||||
// Two E4M3 bytes of a packed dword to two f32 in one instruction (v_cvt_pk_f32_fp8). `HI` selects
|
||||
// bytes 2,3 over 0,1 and is a template parameter because the builtin's word select is a constant.
|
||||
// Returns r4d_common.h's `v2f`, the builtin's own return type.
|
||||
template <bool HI>
|
||||
__device__ __forceinline__ v2f e4m3_pk(uint32_t q) {
|
||||
#if __has_builtin(__builtin_amdgcn_cvt_pk_f32_fp8)
|
||||
@@ -144,59 +126,42 @@ __device__ __forceinline__ v2f e4m3_pk(uint32_t q) {
|
||||
#endif
|
||||
}
|
||||
|
||||
// ---- THE BLOCK SCALE: why the checkpoint's bf16 scales are read natively ------------------------
|
||||
// ---- block scale --------------------------------------------------------------------------------
|
||||
//
|
||||
// Qwen3.8-27B-FP8 carries a BF16 `weight_scale_inv`, one per 128x128 tile in row-major order, and
|
||||
// the decode is `__uint_as_float(s << 16)` -- ONE SHIFT, ONE BITCAST.
|
||||
//
|
||||
// The alternative encoding is one UE8M0 exponent BYTE per tile, decoded
|
||||
// `__uint_as_float(e ? (e << 23) : 0u)`: the same shift and bitcast at a different
|
||||
// distance. Converting to it would round every tile's gain to a power of two, and correcting for
|
||||
// that means requantising the E4M3 bytes against the new scale -- half a bit off a 3-bit mantissa,
|
||||
// everywhere, to save nothing. The scale plane is 21.8 KiB against an 89 MiB weight at gate_proj's
|
||||
// shape.
|
||||
//
|
||||
// No zero test, unlike the UE8M0 form: exponent 0 encodes 2^-127 in that format's convention and
|
||||
// needs one, while bf16 encodes zero as zero and `0u << 16` is +0.0f.
|
||||
// The checkpoint's BF16 `weight_scale_inv` (one per 128x128 tile, row-major) is read natively:
|
||||
// decode is one shift and one bitcast. Converting to UE8M0 would round every tile's gain to a
|
||||
// power of two and force requantising the E4M3 bytes, for no saving (the scale plane is 21.8 KiB
|
||||
// against an 89 MiB weight at gate_proj's shape). Unlike UE8M0, bf16 needs no zero test:
|
||||
// `0u << 16` is +0.0f.
|
||||
__device__ __forceinline__ float bscale(uint16_t s) {
|
||||
return __uint_as_float((uint32_t)s << 16);
|
||||
}
|
||||
/* The same scale held zero-extended in a whole register: the form a 16-bit value should stay in
|
||||
* from its load on (see u16_load_w in r4d_moe.hip). The upper sixteen bits must be zero. */
|
||||
/* The same scale zero-extended in a full register (see u16_load_w in r4d_moe.hip). The upper
|
||||
* sixteen bits must be zero. */
|
||||
__device__ __forceinline__ float bscale(uint32_t s) {
|
||||
return __uint_as_float(s << 16);
|
||||
}
|
||||
|
||||
// ---- LDS staging, shared by both fp8a8 instantiations -------------------------------------------
|
||||
//
|
||||
// An fp8 fragment is 8 bytes a lane, so the granule is 8 B and a 64 B row holds 8 of them. A
|
||||
// fragment read is ONE granule column over SIXTEEN CONSECUTIVE ROWS, and the whole question is
|
||||
// which bank each of those rows lands in.
|
||||
// A fragment is 8 B per lane, so a 64 B row holds 8 granules, and a fragment read is one granule
|
||||
// column over sixteen consecutive rows. LDS has 32 banks of 4 B; a row pitch of P bytes puts row r
|
||||
// at bank (r * P/4) % 32. With the tile width as pitch (64 or 256 B) rows collide and the read
|
||||
// serialises.
|
||||
//
|
||||
// THE ROW PITCH IS NOT THE TILE WIDTH, and that is the point. LDS has 32 banks of 4 B, so bank =
|
||||
// (byte address / 4) % 32 and a row pitch of P bytes puts row r at bank (r * P/4) % 32. With the
|
||||
// tile width itself as the pitch -- 64 or 256, both multiples of 128 B -- that is 16r % 32 or
|
||||
// 0, so rows 8 apart (or all of them) collide and the read serialises.
|
||||
// An XOR granule swizzle `(k >> 3) ^ (row & 7)` only permutes within a row, so it separates at most
|
||||
// 8 rows: rows r and r+8 still collide and the read takes two bank cycles.
|
||||
//
|
||||
// An XOR granule swizzle -- `(k >> 3) ^ (row & 7)` -- does not solve it. It
|
||||
// permutes only WITHIN a row, and a 64 B row holds 8 granules, so it can separate at most 8 rows:
|
||||
// rows r and r+8 still land together and the sixteen lanes of a fragment read take two bank cycles
|
||||
// rather than one. Fragment reads are a large share of this kernel's time, so the second cycle is
|
||||
// not a small cost.
|
||||
//
|
||||
// A PADDED PITCH separates all sixteen instead, and needs no permutation at all. P = FK + 8 gives
|
||||
// P/4 = 18 words at FK = 64, and 18r % 32 over r = 0..15 is
|
||||
// A padded pitch P = FK + 8 separates all sixteen. At FK = 64, P/4 = 18 words and 18r % 32 over
|
||||
// r = 0..15 is
|
||||
//
|
||||
// 0 18 4 22 8 26 12 30 16 2 20 6 24 10 28 14
|
||||
//
|
||||
// -- sixteen distinct even banks, so the sixteen lanes cover all 32 banks exactly once and the
|
||||
// read is one bank cycle. At FK = 256 it is 66 words and 66r % 32 = 2r % 32, distinct likewise.
|
||||
// The pad must be a multiple of 8 to keep the 8 B granule aligned for ds_read_b64; +8 is the
|
||||
// smallest that works, and a larger pad only costs LDS without separating any better -- +16 is
|
||||
// four words, and 4r % 32 has period 8, so it collides again.
|
||||
//
|
||||
// Cost is 8 B a row of LDS: the prefill tile is 36 KiB a block rather than 32, which leaves room
|
||||
// for 3 resident blocks a WGP rather than 4. The bank cycle saved outweighs the lost block.
|
||||
// sixteen distinct even banks, so the read is one bank cycle. At FK = 256, 66r % 32 = 2r % 32,
|
||||
// likewise distinct. The pad must be a multiple of 8 to keep the granule aligned for ds_read_b64;
|
||||
// +16 (4r % 32, period 8) collides again. The cost is 8 B per row: the prefill tile is 36 KiB per
|
||||
// block instead of 32, allowing 3 resident blocks per WGP instead of 4, which the saved bank
|
||||
// cycle outweighs.
|
||||
template <uint32_t FK>
|
||||
__device__ __forceinline__ constexpr uint32_t lds_pitch() { return FK + 8u; }
|
||||
|
||||
@@ -213,17 +178,12 @@ __device__ __forceinline__ i2v frag(const uint8_t* __restrict__ lds, uint32_t ro
|
||||
}
|
||||
|
||||
// The 32 bytes a thread stages, held in registers between the global load and the LDS store.
|
||||
//
|
||||
// They are SPLIT into a load and a store because of what sits between them. Issued as one call, the
|
||||
// load is followed immediately by the barrier that publishes it, so a thread has exactly one
|
||||
// 32-byte request in flight and then waits -- and the K loop becomes a chain of memory latencies
|
||||
// rather than a stream. The symptom is a block sweep that saturates well below the card's coalesced
|
||||
// ceiling and then does not move when the block count doubles.
|
||||
// Load and store are split so the next load can be issued before the barrier; as one call, a
|
||||
// thread has a single 32-byte request in flight and the K loop becomes a chain of latencies.
|
||||
struct Stage8 { uint4 v, w; };
|
||||
|
||||
// One of the FOUR fragments held in a 32-byte fragment-order load. `t` selects which: bytes 8t,
|
||||
// and a Stage8 is two uint4, so fragment 0 and 1 come out of `v` and 2 and 3 out of `w`. `t` is a
|
||||
// constant at every call site after unrolling, so this is a register rename and not a branch.
|
||||
// Fragment `t` (bytes 8t) of a 32-byte fragment-order load: 0 and 1 from `v`, 2 and 3 from `w`.
|
||||
// `t` is constant after unrolling, so this is a register rename, not a branch.
|
||||
__device__ __forceinline__ i2v frag_of(const Stage8& s, uint32_t t) {
|
||||
const uint2 g[4] = { make_uint2(s.v.x, s.v.y), make_uint2(s.v.z, s.v.w),
|
||||
make_uint2(s.w.x, s.w.y), make_uint2(s.w.z, s.w.w) };
|
||||
@@ -233,39 +193,20 @@ __device__ __forceinline__ i2v frag_of(const Stage8& s, uint32_t t) {
|
||||
return f;
|
||||
}
|
||||
|
||||
/* `NT` asks the cache to evict this line first. It is for an operand THE KERNEL READS ONCE AND NO
|
||||
* OTHER BLOCK READS AT ALL -- the weight -- and it exists to stop that stream from evicting the one
|
||||
* operand every block DOES share. `__builtin_nontemporal_load` will not take `uint4`: that is a
|
||||
* HIP_vector_type class template, not a native vector, so the hinted load goes through an
|
||||
* ext_vector_type and the WHOLE value is bit-cast back (never a subscript of it, which
|
||||
* miscompiles). Nothing about the bytes changes -- this is a cache hint and the arithmetic that
|
||||
* follows is identical. */
|
||||
typedef unsigned r4d_f8_ntu4 __attribute__((ext_vector_type(4)));
|
||||
|
||||
template <bool NT = false>
|
||||
__device__ __forceinline__ Stage8 stage8_load(const uint8_t* __restrict__ src, bool live) {
|
||||
Stage8 r;
|
||||
r.v = make_uint4(0, 0, 0, 0);
|
||||
r.w = make_uint4(0, 0, 0, 0);
|
||||
if (live) {
|
||||
if constexpr (NT) {
|
||||
r.v = __builtin_bit_cast(uint4,
|
||||
__builtin_nontemporal_load((const r4d_f8_ntu4*)src));
|
||||
r.w = __builtin_bit_cast(uint4,
|
||||
__builtin_nontemporal_load((const r4d_f8_ntu4*)(src + 16)));
|
||||
} else {
|
||||
r.v = *(const uint4*)src;
|
||||
r.w = *(const uint4*)(src + 16);
|
||||
}
|
||||
r.v = *(const uint4*)src;
|
||||
r.w = *(const uint4*)(src + 16);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
// The fragment-order counterpart: the 32 bytes a lane holds in a (16 row, 64 k) tile are four
|
||||
// granules of ONE row at k `k0 + t*16`, not four consecutive ones. So a fragment-order operand is
|
||||
// de-permuted on the way INTO LDS and everything downstream -- the padded pitch, the bank layout,
|
||||
// frag() itself -- is untouched. That matters: the pitch is what makes a fragment read one bank
|
||||
// cycle, and reading fragment order straight out of LDS would put eight lanes on one bank.
|
||||
// Fragment-order counterpart: a lane's 32 bytes in a (16 row, 64 k) tile are four granules of one
|
||||
// row at k `k0 + t*16`. They are de-permuted on the way into LDS, so the padded pitch and frag()
|
||||
// apply unchanged; reading fragment order straight from LDS would put eight lanes on one bank.
|
||||
template <uint32_t FK>
|
||||
__device__ __forceinline__ void stage8_store_frag(uint8_t* __restrict__ lds, uint32_t row,
|
||||
uint32_t k0, Stage8 r) {
|
||||
|
||||
+196
-325
@@ -1,132 +1,89 @@
|
||||
/* r4d_fuse.cpp -- what chain of conventional ops does this kernel compute in one launch.
|
||||
/* r4d_fuse.cpp -- the chain of unfused ops each fused kernel computes in one launch.
|
||||
*
|
||||
* `RadKernelInfo::replaces` (rad_abi.h) turns a claim that sixteen rows of this plugin make in
|
||||
* PROSE -- "byte-identical to the two ops it replaces" -- into something a tool can execute. The
|
||||
* value is an ORACLE: eleven of libr4d's fusions have no libref kernel at all, so rad-kbench
|
||||
* otherwise skips them BY NAME. A fused row that names its chain can be run against that chain
|
||||
* built out of THIS PLUGIN'S OWN unfused rows, and the answer should not be within a tolerance --
|
||||
* it should be the same bytes.
|
||||
* `RadKernelInfo::replaces` (rad_abi.h) makes a fused row's claim to be byte-identical to the ops
|
||||
* it replaces executable. Eleven of libr4d's fusions have no libref kernel, so this is their only
|
||||
* oracle: a caller runs the fused row against its chain built from this plugin's own unfused rows,
|
||||
* and expects identical bytes, not a tolerance.
|
||||
*
|
||||
* THE AUTHORITY FOR EVERY CHAIN BELOW IS THE DEVICE KERNEL, not the row's prose and not this file.
|
||||
* A fusion is exact or it is not, and the difference is one `f2bf` in a kernel body: the fp8 folds
|
||||
* round their intermediate to bf16 and read it back precisely so that the fused and unfused forms
|
||||
* agree, and the int8 folds deliberately do NOT, because their reference is a different pair. So
|
||||
* each chain below names the libr4d source and the line that decides it, and a reader can check
|
||||
* one against the other. That is not decoration. `qk_norm_rope_gate` is the worked counter-example
|
||||
* -- it folds a sum of squares over one wave per head where `rmsnorm` folds it over
|
||||
* r4d_act_threads(M, n) threads, so the two differ by a ULP and it publishes NO HOOK -- and the ABI
|
||||
* says why: "a kernel that is merely close to the sequence it names should publish no hook at all",
|
||||
* because a false failure is worse than a skip and drowns the true ones.
|
||||
* The authority for each chain is the device kernel, not the row's prose, and each chain names the
|
||||
* source that decides it. Exactness often comes down to one `f2bf`: the fp8 folds round their
|
||||
* intermediate to bf16 and read it back so the fused and unfused forms agree; the int8 folds do
|
||||
* not, because their reference is a different pair. A kernel that is merely close to a sequence
|
||||
* publishes no hook (rad_abi.h): a false failure is worse than a skip.
|
||||
*
|
||||
* ============================================================ WHICH OPERANDS THE CALL PASSES
|
||||
* ============================================================ operand presence
|
||||
*
|
||||
* `rmsnorm_quant_fp8` computes `add` then `rmsnorm` then the quantiser when it is given a residual,
|
||||
* and `rmsnorm` then the quantiser when it is not: THE CHAIN LENGTH DEPENDS ON AN OPERAND. That is
|
||||
* the reason the chain is a hook rather than a table, and the reason the hook has to be told which
|
||||
* operands the call carries rather than only `(p, n_p)`.
|
||||
* `rmsnorm_quant_fp8` computes `add` + `rmsnorm` + quantiser when given a residual, and `rmsnorm`
|
||||
* + quantiser when not, so the chain length depends on an operand. That is why the chain is a hook
|
||||
* rather than a table, and why the hook receives `present`: one bit per fused operand, read with
|
||||
* RAD_FUSE_HAS(). Two alternatives are wrong:
|
||||
*
|
||||
* Two other ways of deciding it look plausible and both are wrong:
|
||||
* - Deriving it from a parameter: there is none. `wadd` is GemmaRMSNorm's `1 +`, a property of
|
||||
* the gain, and arch/common/rad_fp8.h passes it in both forms.
|
||||
* - Marking the operands RAD_FUSE_NONE: that marks an optional operand a step does not pass.
|
||||
* Here the operands that vary are required ones (`add`'s `b`, `rmsnorm`'s `x`) and the chain
|
||||
* length itself changes.
|
||||
*
|
||||
* DERIVE IT FROM A PARAMETER. There is no such parameter, and `wadd` in particular is not one.
|
||||
* `wadd` is GemmaRMSNorm's `1 +` -- a property of the norm GAIN, not of the residual -- and
|
||||
* arch/common/rad_fp8.h:369 passes it unconditionally in both forms. Keying on it would
|
||||
* answer "three steps" for a Gemma-style model that passes no residual and "two steps" for a
|
||||
* Llama-style one that does, which is a wrong chain rather than a missing one.
|
||||
* A caller that does not know passes RAD_FUSE_PRESENT_ALL, meaning every operand this plugin's own
|
||||
* description lists; r4d_shape_rmsnorm_quant_fp8 publishes all six as present. Where a fold's step
|
||||
* carries the same optional operands as the fold (ar_rmsnorm_quant_fp8 below), absence propagates
|
||||
* through the wiring and `present` need not be read. Prefer that shape where there is a choice.
|
||||
*
|
||||
* DECLARE BOTH WIRINGS WITH RAD_FUSE_NONE. That spelling marks an OPTIONAL operand of a STEP
|
||||
* that this chain does not pass. It cannot express this difference, because the operands that
|
||||
* vary are REQUIRED ones -- `add`'s `b` and `rmsnorm`'s `x` -- and because the CHAIN LENGTH
|
||||
* itself changes, which no per-operand marker reaches.
|
||||
* ============================================================ rows with no hook
|
||||
*
|
||||
* So the ABI carries it: `present` is a bit per operand of the fused op, and this file reads it
|
||||
* with RAD_FUSE_HAS(). A caller that genuinely does not know passes RAD_FUSE_PRESENT_ALL, which
|
||||
* means "answer for every operand your own description says exists" -- and that is a contract
|
||||
* rather than a coupling, because this plugin's `r4d_shape_rmsnorm_quant_fp8` publishes all six as
|
||||
* present and is the list a cold caller allocated from.
|
||||
*
|
||||
* Note how the question VANISHES wherever a fold's step carries the same optional operand the fold
|
||||
* does: `ar_rmsnorm_quant_fp8` below wires its residual and its out_bf16 straight through to a
|
||||
* `rmsnorm_quant_fp8` step where both are optional as well, so absence propagates and that chain
|
||||
* needs no knowledge of presence at all. That is worth preferring where a chain has the choice.
|
||||
*
|
||||
* ============================================================ WHAT IS DECLINED, AND WHY
|
||||
*
|
||||
* A decline is a real answer here, the same way it is in r4d_shapes.cpp: the caller counts the row
|
||||
* as uncovered, which is true, where a chain that is merely close produces a FAILURE that means
|
||||
* nothing. These rows carry a null `replaces` deliberately.
|
||||
* These rows carry a null `replaces`; the caller counts them as uncovered.
|
||||
*
|
||||
* rmsnorm_had_quant_i8, gated_had_quant_i8, gdn_gated_norm_had_quant_i8
|
||||
* NOT because the vocabulary has no `hadamard` op -- it does not, but that is not what stops
|
||||
* these. The rotation is inside `had_quant_act_i8`, which IS an op, so the algebra
|
||||
* `rmsnorm` + `had_quant_act_i8` is available and it still does not hold. The reason is the
|
||||
* fusion's own trick: r4d_rmsnorm_had_quant_i8.hip runs the FWHT on `x * (w + wadd)` BEFORE
|
||||
* the norm closes -- legitimate, since the transform is linear and `inv_rms` is a per-row
|
||||
* scalar that the int8 codes cancel -- and folds `inv_rms` into `S[row]` instead. So the
|
||||
* codes are taken over values that were never normalised and never rounded to bf16, while
|
||||
* the unfused pair would rotate a stored bf16 norm output. That file states the gap itself
|
||||
* ("normalising from a bf16-rounded sum produces thousands of +/-1 code errors and a 1e-3
|
||||
* scale error against 5e-7") and calls storing bf16 correct and normalising from it not.
|
||||
* r4d_gated_had_quant_i8.hip is the same shape and says so outright: "silu(x) = x *
|
||||
* sigmoid(x) is computed in fp32. Doing it in bf16 would cost more than the quantiser that
|
||||
* follows" -- which is the exact opposite of the fp8 sibling's bargain, and it is what makes
|
||||
* `silu_mul` + `had_quant_act_i8` a different function. That row also reads a CLIP from the
|
||||
* environment (R4D_CLIP_MLP_DOWN), so it is not even a pure function of the geometry.
|
||||
* `rmsnorm` + `had_quant_act_i8` is expressible but does not hold.
|
||||
* r4d_rmsnorm_had_quant_i8.hip runs the FWHT on `x * (w + wadd)` before the norm closes
|
||||
* (valid: the transform is linear and the int8 codes cancel the per-row `inv_rms`) and folds
|
||||
* `inv_rms` into `S[row]`. Its codes come from values never normalised or rounded to bf16,
|
||||
* while the unfused pair rotates a stored bf16 norm output. r4d_gated_had_quant_i8.hip
|
||||
* likewise computes silu(x) in fp32, which `silu_mul` + `had_quant_act_i8` does not.
|
||||
*
|
||||
* had_quant_act_i8, quant_act_i8, quant_act_fp8
|
||||
* NOT FUSIONS. They are primitive ops of the vocabulary with nothing to decompose into: the
|
||||
* rotation has no op name of its own, and a chain of one step naming the op itself would be
|
||||
* a tautology that inflates the coverage metric and checks nothing.
|
||||
* Primitive ops, not fusions. A one-step chain naming the op itself would check nothing.
|
||||
*
|
||||
* ar_ln_had_quant_i8
|
||||
* The collective's half is expressible -- `all_reduce` then `rmsnorm_had_quant_i8`, both ops
|
||||
* -- and the arithmetic is not. r4d_ar_ln_had_quant_i8.hip states its whole design as "the
|
||||
* all-reduce OUTPUT never exists ... the peer's contribution is simply a second operand on
|
||||
* the norm's load -- `t = mine + peer + residual`": one f32 expression, with no bf16 round
|
||||
* between the reduce and the add. The pair it would replace has one, because the standalone
|
||||
* all-reduce stores bf16. Its `ARN_W6_MATCH` makes only the COMPRESSED wire round, and only
|
||||
* to match the compressed all-reduce. The fp8 sibling below took the opposite decision --
|
||||
* `a = f2bf(bf2f(xr[i]) + bf2f(pr[i])); xr[i] = a;` -- and that one difference is why one of
|
||||
* these two rows gets a hook and the other does not.
|
||||
* `all_reduce` + `rmsnorm_had_quant_i8` is expressible but the arithmetic differs: the kernel
|
||||
* computes `t = mine + peer + residual` in f32 with no bf16 round after the reduce, while the
|
||||
* standalone all-reduce stores bf16 (the compressed wire rounds to bf16, to match the
|
||||
* compressed all-reduce). The fp8 sibling ar_rmsnorm_quant_fp8 rounds there and has a hook.
|
||||
*
|
||||
* qk_norm_rope_gate
|
||||
* Stated in docs/OPS.md and in the row itself: "It is not byte-identical to the four kernels
|
||||
* it replaces", the summation partition differs, and selecting it is a rebaseline.
|
||||
* Not byte-identical to the four kernels it replaces (docs/OPS.md): it folds a sum of
|
||||
* squares over one wave per head where `rmsnorm` folds over r4d_act_threads(M, n) threads,
|
||||
* so the two differ by a ULP.
|
||||
*
|
||||
* sample_chain
|
||||
* It "stands beside the decomposed stages rather than replacing them" (r4d_rows.cpp). One
|
||||
* workgroup walking an L2-resident row is not eight launches over a 248K vocabulary in any
|
||||
* rounding sense, nothing in this project implements those eight on a device, and the fused
|
||||
* row additionally produces `tok_excl` and `p_query`, which no chain of them writes.
|
||||
* Stands beside the decomposed sampling stages rather than replacing them: one workgroup
|
||||
* over an L2-resident row does not round like separate launches, and the fused row also
|
||||
* writes `tok_excl` and `p_query`, which no chain of them produces.
|
||||
*
|
||||
* dflash_conv, dflash_select, the five gdn_* rows
|
||||
* "Neither op has an unfused equivalent in the vocabulary" (r4d_shapes.cpp), and the GDN
|
||||
* preamble's constituents -- a causal conv against a state cache, an L2 norm, a per-chunk
|
||||
* gate cumsum -- have no op names either.
|
||||
* No unfused equivalent in the vocabulary. The GDN preamble's parts (a causal conv against a
|
||||
* state cache, an L2 norm, a per-chunk gate cumsum) have no op names.
|
||||
*
|
||||
* NO TUNED AXIS IS READ HERE, for the reason r4d_shapes.cpp gives about extents: no axis this
|
||||
* plugin declares changes WHAT a kernel computes. They name tile shapes, split counts, wave
|
||||
* counts and all-reduce launch geometry. An axis that changed the chain would be read from `p`,
|
||||
* where the core appends the chosen point alongside the geometry.
|
||||
* No tuned axis is read here: this plugin's axes (tile shapes, split counts, wave counts,
|
||||
* all-reduce launch geometry) do not change what a kernel computes. An axis that did would be read
|
||||
* from `p`, where the core appends the chosen point.
|
||||
*
|
||||
* Pure host code: no r4d.h, no HIP. It is in the CMake `SOURCES` list beside r4d_rows.cpp,
|
||||
* r4d_layout.cpp and r4d_shapes.cpp for the reason that split exists -- the tables a transcription
|
||||
* error hides in should compile and be readable on a box with no ROCm.
|
||||
* Pure host code (no r4d.h, no HIP), like r4d_rows.cpp, r4d_layout.cpp and r4d_shapes.cpp, so the
|
||||
* tables compile and can be read without ROCm.
|
||||
*/
|
||||
|
||||
#include "r4d_plugin.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <initializer_list>
|
||||
|
||||
namespace {
|
||||
|
||||
/* ==================================================================== reading the fused geometry
|
||||
*
|
||||
* NOT r4d_pgeti_or(), and the difference is the one r4d_shapes.cpp spells out: that reader takes
|
||||
* RAD_P_INT only, which is right for a LAUNCH -- by then the core has collapsed every range to the
|
||||
* band's value -- and wrong here, because this hook, like `opd_shape`, can be called with a
|
||||
* geometry whose ranges are still ranges. A RAD_P_RANGE reads as its HIGH bound wherever a scalar
|
||||
* is needed, which is the same reading the operand descriptions take and therefore the reading a
|
||||
* caller's buffers were sized under. */
|
||||
* Not r4d_pgeti_or(): that reads RAD_P_INT only, which suits a launch (every range has collapsed
|
||||
* to the band's value), but this hook, like `opd_shape`, can see ranges still open. A RAD_P_RANGE
|
||||
* reads as its high bound, as in the operand descriptions the caller's buffers were sized from. */
|
||||
int64_t pi(const RadParam* p, int n_p, const char* k, int64_t dflt = 0) {
|
||||
if (!p || !k) return dflt;
|
||||
for (int i = 0; i < n_p; ++i) {
|
||||
@@ -138,19 +95,19 @@ int64_t pi(const RadParam* p, int n_p, const char* k, int64_t dflt = 0) {
|
||||
return dflt;
|
||||
}
|
||||
|
||||
/* Fused operand i when `present` has it, else RAD_FUSE_NONE: the wiring of an optional operand. */
|
||||
int16_t opt_opd(uint64_t present, int i) {
|
||||
return RAD_FUSE_HAS(present, i) ? (int16_t)i : (int16_t)RAD_FUSE_NONE;
|
||||
}
|
||||
|
||||
/* ==================================================================== building one step
|
||||
*
|
||||
* A step is built by naming its op, then its parameters in the STEP op's own spelling, then its
|
||||
* operand wiring in the STEP op's schema order. Building it in that order rather than filling a
|
||||
* struct field by field is what makes the operand COUNT checkable by eye against the schema in
|
||||
* r4d_rows.cpp -- the ABI checks it too, and a hook that has drifted from its schema is a
|
||||
* diagnosable error rather than a silent misfire, but a list a reader can count is the half that
|
||||
* stops the drift happening.
|
||||
* A step names its op, then its parameters in the step op's spelling, then its operand wiring in
|
||||
* the step op's schema order, so the operand count can be checked by eye against r4d_rows.cpp
|
||||
* (the ABI checks it too).
|
||||
*
|
||||
* `ok` carries a required parameter the fused geometry did not have. It is checked once, at
|
||||
* `wire()`, for the reason r4d_shapes.cpp checks its whole operand list before handing out one
|
||||
* entry: a chain whose second step is missing an `eps` is a chain a caller would run and compare,
|
||||
* and a step resolved at the wrong geometry produces a difference that reads as the kernel's.
|
||||
* `ok` records a required parameter the fused geometry lacks, and wire() refuses the step. A step
|
||||
* resolved at the wrong geometry would produce a difference that reads as a kernel fault.
|
||||
*/
|
||||
struct Step {
|
||||
RadFuseStep* s;
|
||||
@@ -161,11 +118,9 @@ struct Step {
|
||||
s->op = op;
|
||||
}
|
||||
|
||||
/* Copy a parameter of the fused op VERBATIM, kind and all. Verbatim matters: `M` is the ranged
|
||||
* parameter of every op in these chains, and re-emitting a range as its collapsed high bound
|
||||
* would hand the step a different BAND from the one the fused kernel was selected for -- which
|
||||
* for a banded family like the fp8 GEMMs is a different kernel with a different summation
|
||||
* order. `eps` and `wadd` are RAD_P_F64 and would be destroyed by an integer reader. */
|
||||
/* Copies a fused-op parameter verbatim, kind included. `M` is ranged on every op here, and
|
||||
* collapsing it would select a different band, which for a banded family like the fp8 GEMMs
|
||||
* is a different kernel and summation order. `eps` and `wadd` are RAD_P_F64. */
|
||||
Step& mirror(const RadParam* p, int n_p, const char* key) {
|
||||
const RadParam* f = rad_param_find(p, n_p, key);
|
||||
if (!f || s->n_p >= RAD_MAX_FUSE_PARAMS) { ok = false; return *this; }
|
||||
@@ -173,19 +128,17 @@ struct Step {
|
||||
return *this;
|
||||
}
|
||||
|
||||
/* The same, for a parameter that is OPTIONAL in both ops: absent stays absent rather than
|
||||
* becoming an explicit default. The two are not the same thing to a constraint -- libr4d's
|
||||
* rule is that a constraint whose key the geometry does not carry does not hold -- so
|
||||
* inventing `wadd = 0` where the caller supplied none could route a step to a different row. */
|
||||
/* As mirror(), for a parameter optional in both ops: absent stays absent. A constraint whose
|
||||
* key the geometry lacks does not hold, so inventing `wadd = 0` could route the step to a
|
||||
* different row. */
|
||||
Step& mirror_opt(const RadParam* p, int n_p, const char* key) {
|
||||
const RadParam* f = rad_param_find(p, n_p, key);
|
||||
if (!f) return *this;
|
||||
return mirror(p, n_p, key);
|
||||
}
|
||||
|
||||
/* Built field by field rather than through rad_types.h's RAD_INT / RAD_STR: those are compound
|
||||
* literals, which are C and only a GNU extension in C++, and this file is ordinary host C++
|
||||
* that has to compile with or without ROCm present. */
|
||||
/* Built field by field: rad_types.h's RAD_INT / RAD_STR are C compound literals, only a GNU
|
||||
* extension in C++. */
|
||||
Step& pint(const char* key, long long v) {
|
||||
if (s->n_p >= RAD_MAX_FUSE_PARAMS) { ok = false; return *this; }
|
||||
RadParam q{};
|
||||
@@ -206,9 +159,9 @@ struct Step {
|
||||
return *this;
|
||||
}
|
||||
|
||||
/* ONE ENTRY PER OPERAND OF THE STEP'S OP, in its schema's order. A non-negative value is an
|
||||
* operand index of the FUSED kernel, RAD_FUSE_TMP(t) a temporary this chain passes between its
|
||||
* own steps, RAD_FUSE_NONE an optional operand this step does not pass. */
|
||||
/* One entry per operand of the step's op, in schema order: a fused-kernel operand index,
|
||||
* RAD_FUSE_TMP(t) for a temporary between steps, or RAD_FUSE_NONE for an optional operand the
|
||||
* step does not pass. */
|
||||
int wire(std::initializer_list<int> from) {
|
||||
if (!ok) return RAD_E_UNSUPPORTED;
|
||||
if (from.size() > RAD_MAX_FUSE_OPD) return RAD_E_INVAL;
|
||||
@@ -217,22 +170,18 @@ struct Step {
|
||||
}
|
||||
};
|
||||
|
||||
/* The activation a gated fold applies, in the vocabulary's spelling. `act` is OPTIONAL on both
|
||||
* quantiser ops and the two shims default it DIFFERENTLY -- r4d_fp8.cpp reads `mode` 0 (silu) for
|
||||
* `gated_quant_fp8` and `mode` 1 (sigmoid) for `gate_quant_fp8`, because the first serves
|
||||
* down_proj's input and the second a gated attention's o_proj -- so the default is the caller's,
|
||||
* not this file's, and each hook passes its own. An `act` this plugin does not compile is
|
||||
* RAD_E_UNSUPPORTED at the launch too, so a chain for it would be a chain for a kernel that
|
||||
* refuses the call. */
|
||||
/* Whether a gated fold's `act` (vocabulary spelling) is `want`. `act` is optional and the shims
|
||||
* default it differently: r4d_fused_quant_fp8.hip uses `mode` 0 (silu) for `gated_quant_fp8`, which feeds
|
||||
* down_proj, and `mode` 1 (sigmoid) for `gate_quant_fp8`, which feeds a gated attention's o_proj.
|
||||
* Each hook passes its row's default. */
|
||||
bool act_is(const RadParam* p, int n_p, const char* dflt, const char* want) {
|
||||
const char* a = r4d_pgets(p, n_p, "act");
|
||||
return std::strcmp(a ? a : dflt, want) == 0;
|
||||
}
|
||||
|
||||
/* Every fp8 fold in this file quantises on the CHECKPOINT'S scale grid and refuses anything else
|
||||
* by name -- the shims test `group` against r4d_quant_act_fp8_group() and so do the operand
|
||||
* descriptions. A geometry that declares a different one has no fused kernel, so it has no chain
|
||||
* either, and saying so here keeps the two hooks answering the same set. */
|
||||
/* The fp8 folds quantise only on the checkpoint's scale grid: the shims and the operand
|
||||
* descriptions test `group` against r4d_quant_act_fp8_group(). Any other group has no fused kernel
|
||||
* and so no chain. */
|
||||
bool fp8_geometry_ok(const RadParam* p, int n_p, int64_t M, int64_t n) {
|
||||
return M > 0 && n > 0 && pi(p, n_p, "group", R4D_FP8_BLOCK) == R4D_FP8_BLOCK;
|
||||
}
|
||||
@@ -241,53 +190,35 @@ bool fp8_geometry_ok(const RadParam* p, int n_p, int64_t M, int64_t n) {
|
||||
|
||||
/* ==========================================================================================
|
||||
* rmsnorm_quant_fp8 -- the RMS norm and the fp8 activation quantiser in one pass.
|
||||
* (kernel: libr4d/r4d_fused_quant_fp8.hip, rmsnorm_quant_fp8_kernel; shim: r4d_fp8.cpp)
|
||||
* (kernel: libr4d/r4d_fused_quant_fp8.hip, rmsnorm_quant_fp8_kernel and its shim)
|
||||
*
|
||||
* Operands: [0] x [1] residual? [2] w [3] q [4] scale [5] out_bf16?
|
||||
*
|
||||
* THE CHAIN IS `add` + `rmsnorm` + `quant_act_fp8`, AND IT IS NOT `rmsnorm_add` + `quant_act_fp8`.
|
||||
* That distinction is the reason to read the kernel rather than the row's prose: the other choice
|
||||
* produces a chain that fails a byte comparison for no visible reason. The two candidates differ
|
||||
* in ONE place -- which value the sum of squares is taken over:
|
||||
* The chain is `add` + `rmsnorm` + `quant_act_fp8`, not `rmsnorm_add` + `quant_act_fp8`. The two
|
||||
* differ in which value the sum of squares is taken over:
|
||||
*
|
||||
* this kernel `h = f2bf(bf2f(rr[i]) + bf2f(xr[i])); rr[i] = h; v = bf2f(h); ss += v * v;`
|
||||
* The sum is rounded to bf16, STORED, and read back before the variance. Its own
|
||||
* entry point says so in as many words: "`res += x` in f32, ROUNDED TO BF16 and
|
||||
* stored, and the norm is then taken of the stored value -- which is bit-for-bit
|
||||
* the `add` + `rmsnorm` pair this replaces".
|
||||
* The sum is rounded to bf16, stored, and read back before the variance: the
|
||||
* `add` + `rmsnorm` pair bit for bit.
|
||||
*
|
||||
* rmsnorm_add `float v = ldt(x, ..) + ldt(res, ..); ss += v * v; stt(ro, .., v);`
|
||||
* (libref/ref_elementwise.cpp). The variance comes off the UNROUNDED f32 sum
|
||||
* and only the multiply reads the stored value back. That file calls the choice
|
||||
* "THE ROUNDING IS THE CONTRACT" and is right to -- it is vLLM's
|
||||
* fused_add_rms_norm -- but it is a different function from this kernel's, by
|
||||
* half a ULP on every channel, and the whole point of the declaration is that a
|
||||
* caller may compare the bytes.
|
||||
* (libref/ref_elementwise.cpp, matching vLLM's fused_add_rms_norm). The variance
|
||||
* uses the unrounded f32 sum, half a ULP away on every channel.
|
||||
*
|
||||
* So the residual add is spelled as the op that actually matches, and the payoff is larger than
|
||||
* correctness alone: `add`, `rmsnorm` and `quant_act_fp8` are all rows of THIS plugin
|
||||
* (add_bf16, rmsnorm_bf16, quant_act_fp8), so the chain can be checked libr4d-against-libr4d,
|
||||
* which is the byte-identical comparison the ABI describes rather than a tolerance against a host
|
||||
* oracle. `rmsnorm_add` has no libr4d row at all and would have forced the check cross-plugin.
|
||||
* All three steps are libr4d rows (add_bf16, rmsnorm_bf16, quant_act_fp8), so the check stays
|
||||
* within libr4d; `rmsnorm_add` has no libr4d row.
|
||||
*
|
||||
* THE BYTE-IDENTITY RESTS ON THE WORKGROUP WIDTH AGREEING, which is worth knowing because it is
|
||||
* the thing most likely to break silently. Both kernels pick their thread count from
|
||||
* `r4d_act_threads(M, n)` and the width decides which columns a thread folds into the sum of
|
||||
* squares; r4d_model_bf16.hip's launcher says "r4d_rmsnorm_quant_fp8 calls the SAME function, and
|
||||
* it has to". `M` is mirrored verbatim below for exactly that reason.
|
||||
* Byte identity depends on the workgroup width agreeing: both kernels take their thread count from
|
||||
* `r4d_act_threads(M, n)`, which decides the columns each thread folds into the sum of squares
|
||||
* (see the launcher in r4d_model_bf16.hip). `M` is mirrored verbatim for that reason.
|
||||
*
|
||||
* Step 0 writes its output INTO the fused residual operand, which is both its own `b` and the
|
||||
* fused kernel's INOUT residual. That is not an accident of the wiring: the fused kernel overwrites
|
||||
* the residual in place, so a chain that wrote the sum anywhere else would leave a different set of
|
||||
* buffers behind and the comparison would miss the difference. `add_bf16` is safe in place --
|
||||
* binary_kernel reads a[i] and b[i] and writes y[i], one element per thread, no neighbours.
|
||||
* Step 0 writes the sum into the fused residual operand, both its own `b` and the fused kernel's
|
||||
* in-place residual, so both sides leave the same buffers behind. `add_bf16` is safe in place:
|
||||
* one element per thread, no neighbours.
|
||||
*
|
||||
* Step 1's `y` is fused operand 5 rather than a temporary, and the ABI's own note explains why:
|
||||
* the fold still WRITES its intermediate when asked to, precisely so that the fused and unfused
|
||||
* forms leave the same buffers behind. `norm_quant_row` stores exactly the bf16 it then quantises
|
||||
* (`h = f2bf(bf2f(nr[c]) * rs * (g + wadd)); if (yr) yr[c] = h; v[j] = bf2f(h);`), so operand 5 is
|
||||
* not an optimisation the chain can route around -- it IS the value the codes were taken over. See
|
||||
* the file header for why passing it is assumed rather than observed.
|
||||
* The norm writes fused operand 5 when present. The kernel stores exactly the bf16 it quantises
|
||||
* (`h = f2bf(bf2f(nr[c]) * rs * (g + wadd)); if (yr) yr[c] = h; v[j] = bf2f(h);`), so the codes
|
||||
* are taken over that buffer.
|
||||
*/
|
||||
extern "C" int r4d_fuse_rmsnorm_quant_fp8(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
@@ -296,30 +227,23 @@ extern "C" int r4d_fuse_rmsnorm_quant_fp8(const RadParam* p, int n_p, uint64_t p
|
||||
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
|
||||
if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED;
|
||||
|
||||
/* The two optional operands, read off the call rather than assumed. `residual` decides whether
|
||||
* there is an `add` at all -- and therefore how long the chain is -- and `out_bf16` decides
|
||||
* whether the bf16 the codes are taken over is a buffer the caller can see or one the chain
|
||||
* has to make for itself. */
|
||||
/* `residual` decides whether there is an `add` step; `out_bf16` decides whether the norm
|
||||
* output is a caller-visible buffer or a temporary. */
|
||||
const bool has_res = RAD_FUSE_HAS(present, 1) != 0;
|
||||
const bool has_out = RAD_FUSE_HAS(present, 5) != 0;
|
||||
/* The value the quantiser reads: the fused kernel's own out_bf16 where it has one, so both
|
||||
* sides leave the same buffers behind, and a temporary where it does not. The kernel writes
|
||||
* that bf16 either way (`h = f2bf(...); if (yr) yr[c] = h; v[j] = bf2f(h);`) -- operand 5 is
|
||||
* not an optimisation the chain can route around, it IS the value the codes were taken over. */
|
||||
const int16_t mid = has_out ? (int16_t)5 : RAD_FUSE_TMP(0);
|
||||
/* Without a residual there is no `add`, so every step shifts down by one. */
|
||||
/* Without a residual there is no `add`, so the steps shift down by one. */
|
||||
const int s = has_res ? step : step + 1;
|
||||
|
||||
switch (s) {
|
||||
case 0: {
|
||||
/* residual = x + residual, rounded to bf16 -- the store the norm then reads back. */
|
||||
/* residual = x + residual, rounded to bf16; the norm reads this store back. */
|
||||
Step st(out, "add");
|
||||
st.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "dtype");
|
||||
return st.wire({ 0, 1, 1 }); /* a, b, y */
|
||||
}
|
||||
case 1: {
|
||||
/* The norm of the STORED sum -- or of `x` itself when nothing was added to it. `wadd` is
|
||||
* mirrored only when the caller supplied it. */
|
||||
/* The norm of the stored sum, or of `x` without a residual. `wadd` only if supplied. */
|
||||
Step st(out, "rmsnorm");
|
||||
st.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "eps")
|
||||
.mirror(p, n_p, "dtype").mirror_opt(p, n_p, "wadd");
|
||||
@@ -342,30 +266,19 @@ extern "C" int r4d_fuse_rmsnorm_quant_fp8(const RadParam* p, int n_p, uint64_t p
|
||||
*
|
||||
* Operands: [0] gate_up [1] q [2] scale [3] out_bf16?
|
||||
*
|
||||
* `act` silu IS expressible and `act` sigmoid is NOT, and the reason is not the one it looks like.
|
||||
* Both `sigmoid` and `mul` are ops of the vocabulary and both have libr4d rows (sigmoid_bf16,
|
||||
* mul_bf16), so the missing piece is not an activation -- it is that `gate_up` is ONE [M, 2n]
|
||||
* buffer whose halves are the gate and the up, and NOTHING IN THE OPERAND WIRING CAN NAME HALF OF
|
||||
* AN OPERAND. `silu_mul` is the one op in the vocabulary that takes the packed plane and does the
|
||||
* split itself, which is what makes the silu form reachable; there is no `sigmoid_mul` beside it.
|
||||
* Only `act` silu has a chain. `gate_up` is one [M, 2n] buffer (gate half, then up half), and the
|
||||
* wiring cannot name half an operand. `silu_mul` splits the packed plane itself; there is no
|
||||
* `sigmoid_mul`.
|
||||
*
|
||||
* There is a second, independent reason, and it is the one that would still bite if such an op
|
||||
* were added carelessly. This kernel keeps the activation in f32 through the product and rounds
|
||||
* ONCE:
|
||||
* The kernel also keeps the activation in f32 through the product and rounds once:
|
||||
*
|
||||
* const float a = ACT == 0 ? g / (1.0f + expf(-g)) : 1.0f / (1.0f + expf(-g));
|
||||
* const uint16_t h = f2bf(a * bf2f(gr[n + c]));
|
||||
*
|
||||
* which is `silu_mul_bf16` element for element -- `f32_to_bf16((g / (1.0f + expf(-g))) * bf2f(gr[n
|
||||
* + i]))` in r4d_model_bf16.hip -- and is NOT `sigmoid` followed by `mul`, which would round the
|
||||
* activation to bf16 in between. Its sibling `gate_quant_fp8` below rounds there deliberately,
|
||||
* because ITS reference is two kernels; this one's is one. A `sigmoid_mul` op would have to make
|
||||
* the same choice this kernel did or the chain would be a different function again.
|
||||
*
|
||||
* So the sigmoid form gets RAD_E_UNSUPPORTED -- an honest decline, and the vocabulary gap it names
|
||||
* is a `sigmoid_mul` over a packed [M, 2n] plane that rounds once, not a missing `sigmoid`.
|
||||
* Nothing is lost: cGemmNtQGatedFp8 and the arch both reach the sigmoid gate through
|
||||
* `gate_quant_fp8`, whose operands are two buffers rather than one plane.
|
||||
* That matches `silu_mul_bf16` in r4d_model_bf16.hip element for element, and differs from
|
||||
* `sigmoid` + `mul`, which round the activation in between. A future `sigmoid_mul` op would have to
|
||||
* round once too. The sigmoid gate is reached through `gate_quant_fp8` instead (cGemmNtQGatedFp8
|
||||
* and the arch use it), whose gate is a separate operand.
|
||||
*/
|
||||
extern "C" int r4d_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
@@ -373,7 +286,7 @@ extern "C" int r4d_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t pre
|
||||
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;
|
||||
/* r4d_fp8.cpp's shim defaults this row's `mode` to 0, which is silu. */
|
||||
/* The shim (r4d_fused_quant_fp8.hip) defaults this row's `mode` to 0 (silu). */
|
||||
if (!act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED;
|
||||
|
||||
switch (step) {
|
||||
@@ -399,33 +312,23 @@ extern "C" int r4d_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t pre
|
||||
*
|
||||
* Operands: [0] gate [1] x [2] q [3] scale [4] out_bf16?
|
||||
*
|
||||
* THIS ONE IS EXPRESSIBLE AND ITS SIBLING ABOVE IS NOT, which is the opposite of what the operand
|
||||
* lists suggest, and the kernel says why in a comment written for exactly this question:
|
||||
* Unlike the packed sibling above, this has a chain. The kernel rounds the activation before the
|
||||
* multiply, because its reference is `sigmoid` then `mul`, two kernels with a bf16 buffer between:
|
||||
*
|
||||
* const uint16_t ab = f2bf(ACT == 0 ? gv / (1.0f + expf(-gv)) : 1.0f / (1.0f + expf(-gv)));
|
||||
* const uint16_t h = f2bf(bf2f(ab) * bf2f(xr[c]));
|
||||
* // THE ACTIVATION IS ROUNDED BEFORE THE MULTIPLY, which is the one place this differs from
|
||||
* // gated_quant_fp8 above and it is not an oversight. [...] This one's is `sigmoid` then
|
||||
* // `mul`, TWO kernels with a bf16 buffer between them -- so the round trip is part of the
|
||||
* // arithmetic being replaced, and skipping it changes the model's output. [...]
|
||||
*
|
||||
* That round trip is the chain. `sigmoid_bf16` computes `f32_to_bf16(1.0f / (1.0f +
|
||||
* expf(-bf2f(xr[i]))))` and `mul_bf16` computes `f32_to_bf16(bf2f(a) * bf2f(b))`, which are the
|
||||
* two lines above term for term, and the gate arrives as its own [M, n] operand so there is no
|
||||
* half-of-an-operand problem. Three launches an attention layer becoming one is what the fusion
|
||||
* bought; the three are named here.
|
||||
* `sigmoid_bf16` (`f32_to_bf16(1.0f / (1.0f + expf(-bf2f(xr[i]))))`) and `mul_bf16`
|
||||
* (`f32_to_bf16(bf2f(a) * bf2f(b))`) match those two lines term for term.
|
||||
*
|
||||
* `act` silu IS DECLINED because the arithmetic differs in the last bit. The chain's `silu` step
|
||||
* resolves to silu_bf16 or libref, and both compute libref's `act_silu(x)`, `x * act_sigmoid(x)`
|
||||
* -- two f32 roundings where this kernel does one divide, `f2bf(gv / (1.0f + expf(-gv)))`. A
|
||||
* chain checked against it would report a difference in the last bit of many elements and call it
|
||||
* a fault in the kernel, and a false failure is worse than a skip. Accepting silu needs this
|
||||
* kernel to take the sigmoid first as well. Nothing in the tree issues this row with silu -- the gated attention's gate is a
|
||||
* sigmoid, which is why the shim's `mode` defaults to 1.
|
||||
* `act` silu is declined: the chain's `silu` step (silu_bf16 or libref) computes libref's
|
||||
* `x * act_sigmoid(x)`, two f32 roundings, where this kernel does one divide, so many elements
|
||||
* would differ in the last bit. Accepting silu needs the kernel to take the sigmoid first as well.
|
||||
* The gated attention's gate is a sigmoid, so nothing issues this row with silu and the shim's
|
||||
* `mode` defaults to 1.
|
||||
*
|
||||
* TMP(0) is act(gate): an [M, n] bf16 plane the fusion genuinely never writes, so it is a
|
||||
* temporary rather than an operand. `out_bf16` is not -- the kernel stores the product there when
|
||||
* asked, and the codes are taken over those same bytes.
|
||||
* TMP(0) is act(gate), an [M, n] bf16 plane the fusion never writes. `out_bf16` is an operand: the
|
||||
* kernel stores the product there when asked and takes the codes over those bytes.
|
||||
*/
|
||||
extern "C" int r4d_fuse_gate_quant_fp8(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
@@ -433,12 +336,12 @@ extern "C" int r4d_fuse_gate_quant_fp8(const RadParam* p, int n_p, uint64_t pres
|
||||
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;
|
||||
/* r4d_fp8.cpp's shim defaults this row's `mode` to 1, which is sigmoid. */
|
||||
/* The shim (r4d_fused_quant_fp8.hip) defaults this row's `mode` to 1 (sigmoid). */
|
||||
if (!act_is(p, n_p, "sigmoid", "sigmoid")) return RAD_E_UNSUPPORTED;
|
||||
|
||||
switch (step) {
|
||||
case 0: {
|
||||
/* The gate through the logistic, rounded to bf16 -- the buffer the pair had between them. */
|
||||
/* sigmoid(gate) rounded to bf16: the buffer the unfused pair had between them. */
|
||||
Step s(out, "sigmoid");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "dtype");
|
||||
return s.wire({ 0, RAD_FUSE_TMP(0) }); /* x, y */
|
||||
@@ -460,43 +363,32 @@ 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_fp8.cpp)
|
||||
* (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?
|
||||
*
|
||||
* The row already states the claim -- "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, which is exact and order-free however it is regrouped across the waves" -- and this
|
||||
* is that sentence made executable. Both steps are libr4d rows, so the check is
|
||||
* libr4d-against-libr4d.
|
||||
* 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 ONE GENUINE TEMPORARY IN THIS FILE: the [M, N] bf16 plane the unfused pair passed
|
||||
* between the GEMM and the quantiser, and the plane whose non-existence is the entire point of the
|
||||
* fusion ("no [M, 2n] tensor is ever written"). Its extents come from step 0's own `opd_shape`,
|
||||
* which is the ABI's rule for a temporary, and `r4d_shape_gemm_nt_q` answers [M, N] bf16 for
|
||||
* operand 4 while `r4d_shape_gated_quant_fp8` answers [M, 2n] for operand 0 -- the same plane,
|
||||
* since `n` below is N/2.
|
||||
* 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 PLACES WHERE A PARAMETER CANNOT SIMPLY BE COPIED, and both are the kind of thing that
|
||||
* resolves to a plausible wrong kernel rather than to an error:
|
||||
* Two parameters are not copies:
|
||||
*
|
||||
* `n` is N/2 and not N. `N` on the fused op is the WEIGHT'S ROWS -- twice the fused width,
|
||||
* gate then up -- which is exactly why this op has a schema of its own rather than a
|
||||
* flag on `gemm_nt_q`. The quantiser's row is the OUTPUT width.
|
||||
* `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 "bf16" on the quantiser step and "fp8a8" on the GEMM step, from one key on the
|
||||
* fused op. `dtype` names the operand COMBINATION for a GEMM and the width of the
|
||||
* tensor an activation op READS, and the constraint rows disagree accordingly:
|
||||
* cGemmNtQGatedFp8 has `C_IN("dtype", "fp8a8")` and cGatedQuantFp8 has
|
||||
* `C_IN("dtype", "bf16")`. Mirroring the fused value into step 1 would match no row of
|
||||
* this plugin, and the chain would be unresolvable rather than wrong -- but only
|
||||
* because nothing else declares a bf16-named `gated_quant_fp8`, which is not a
|
||||
* guarantee worth relying on.
|
||||
* `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` and `b_ref` are the two operands libr4d appended after `gemm_nt_q`'s `y`, and an fp8
|
||||
* grid has neither -- `a_sum` belongs to the asymmetric integer grids and `b_ref` to mxfp4, and
|
||||
* r4d_shape_gemm_nt_q says the same by describing both as absent. They are RAD_FUSE_NONE and not
|
||||
* simply omitted, because ONE ENTRY PER SCHEMA OPERAND is what makes the count a drift check.
|
||||
* `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) {
|
||||
@@ -507,13 +399,13 @@ extern "C" int r4d_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t pre
|
||||
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 the quantiser's, because only the silu form is compiled -- an
|
||||
* optional parameter would let the row resolve for a gate it cannot serve. */
|
||||
/* 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 plane, into the bf16 that never exists. */
|
||||
/* 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");
|
||||
@@ -521,7 +413,7 @@ extern "C" int r4d_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t pre
|
||||
return s.wire({ 0, 1, 2, 3, RAD_FUSE_TMP(0), RAD_FUSE_NONE, RAD_FUSE_NONE });
|
||||
}
|
||||
case 1: {
|
||||
/* The gate, the multiply and the codes over the accumulator plane, at half its width. */
|
||||
/* 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");
|
||||
@@ -541,14 +433,12 @@ extern "C" int r4d_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t pre
|
||||
* [8] dt_bias [9] state [10] state_idx [11] num_accepted [12] cu [13] z
|
||||
* [14] norm_w [15] o [16] o_q [17] o_scale
|
||||
*
|
||||
* The pair's q, k and v are the three temporaries. Every parameter is the step's own under the
|
||||
* same name, so the chain is copies: the convolution's four, then the recurrent update's. */
|
||||
* The pair's q, k and v are the three temporaries. Every parameter has the same name in the step
|
||||
* op, so each step mirrors its own: the convolution's four, then the recurrent update's. */
|
||||
extern "C" int r4d_fuse_gdn_conv_recurrent_update(const RadParam* p, int n_p, uint64_t present,
|
||||
int step, RadFuseStep* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
const int16_t cb = RAD_FUSE_HAS(present, 2) ? 2 : RAD_FUSE_NONE;
|
||||
const int16_t oq = RAD_FUSE_HAS(present, 16) ? 16 : RAD_FUSE_NONE;
|
||||
const int16_t os = RAD_FUSE_HAS(present, 17) ? 17 : RAD_FUSE_NONE;
|
||||
const int16_t cb = opt_opd(present, 2), oq = opt_opd(present, 16), os = opt_opd(present, 17);
|
||||
switch (step) {
|
||||
case 0: {
|
||||
Step s(out, "gdn_conv_update");
|
||||
@@ -587,9 +477,7 @@ extern "C" int r4d_fuse_gdn_conv_recurrent_update(const RadParam* p, int n_p, ui
|
||||
extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, uint64_t present,
|
||||
int step, RadFuseStep* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
auto opt = [&](int i) -> int16_t {
|
||||
return RAD_FUSE_HAS(present, i) ? (int16_t)i : (int16_t)RAD_FUSE_NONE;
|
||||
};
|
||||
auto opt = [present](int i) { return opt_opd(present, i); };
|
||||
switch (step) {
|
||||
case 0: {
|
||||
Step s(out, "qk_norm_rope_gate");
|
||||
@@ -612,51 +500,6 @@ extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, u
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* ar_rmsnorm_quant_fp8 -- the two-rank all-reduce with the norm and the quantiser folded on.
|
||||
* (kernel: libr4d/r4d_fused_quant_fp8.hip, ar_rmsnorm_quant_fp8_kernel; shim: r4d_ar.cpp)
|
||||
*
|
||||
* Operands: [0] x (inout) [1] residual? [2] w [3] q [4] scale [5] out_bf16?
|
||||
*
|
||||
* THE CHEAPEST HONEST CHAIN IN THE FILE, and the one that needs no assumption about optional
|
||||
* operands at all. Its second step is `rmsnorm_quant_fp8`, which is itself an op of the vocabulary
|
||||
* and carries the SAME two optional operands in the same positions -- so `residual` and `out_bf16`
|
||||
* are wired straight through and absence propagates through the wiring rather than having to be
|
||||
* observed. That is worth noticing as a design rule: a fold whose tail is itself a declared op
|
||||
* hands the discrimination to the step, and the ABI gap described in the file header disappears.
|
||||
*
|
||||
* BOTH WIRES, and the kernel earns the claim rather than approximating it. On the exact wire pass
|
||||
* one is `a = f2bf(bf2f(xr[i]) + bf2f(pr[i])); xr[i] = a;` -- the standalone one-shot's own f32 sum
|
||||
* stored as bf16, written back into `x` so that "a reader of `x` that is not this norm still finds
|
||||
* the same bytes". On the compressed wire the reduce loop stores the inverse-rotated sum into `x`
|
||||
* as bf16 "which is what the standalone compressed all-reduce wrote, so pass two below reads the
|
||||
* bytes it would have read". Everything after the handshake is `norm_quant_row`, the same device
|
||||
* function the standalone fold above runs. Contrast `ar_ln_had_quant_i8`, which takes the opposite
|
||||
* decision (`t = mine + peer + residual` with no round between) and therefore publishes no hook.
|
||||
*
|
||||
* THREE PARAMETERS THAT ARE NOT COPIES, and each of them decides which all-reduce row serves the
|
||||
* step:
|
||||
*
|
||||
* `numel` is M * n. The fused op declares the message by its [M, n] operand and
|
||||
* `all_reduce` declares it as an element count -- and as THE LARGEST message the
|
||||
* instance will carry, not the one a step passes, which is why the band's high
|
||||
* bound is the right value and `pi` reads a range as one.
|
||||
*
|
||||
* `exact` is the fused `wire` inverted. It is REQUIRED on `all_reduce` and it is the
|
||||
* predicate that separates cArExact from cArWht6; a caller that does not declare it
|
||||
* gets no kernel at all.
|
||||
*
|
||||
* `min_bytes` is 0, and ONLY on the compressed wire. The wht6 shim serves a message below its
|
||||
* floor with the EXACT kernel instead -- safe, because both kernels share the
|
||||
* instance's scratch and flag space -- and the fused kernel has no such fallback: a
|
||||
* `wire` of 6 is 6 at every size. Its comment names the spelling for this exact
|
||||
* case: "A caller that needs the rotated wire unconditionally asks for a floor of
|
||||
* 0." Leaving the key out would let a small message go out exact on one side of the
|
||||
* comparison and rotated on the other.
|
||||
*
|
||||
* `hops` is not emitted: no libr4d row reads it, and two ranks have only the one-shot. `y` is
|
||||
* RAD_FUSE_NONE: the fused kernel reduces in place into `x`, as every all-reduce row does.
|
||||
*/
|
||||
/* ==========================================================================================
|
||||
* attn_paged_gate_quant -- attn_paged, then gate_quant_fp8 over its output.
|
||||
* (row: attn_decode_gq_h256_gqa12_fp8kv; kernels: libr4d/r4d_attn_decode_h256_gqa6.hip, the
|
||||
@@ -665,16 +508,14 @@ extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, u
|
||||
* Operands: [0] q [1] kv_cache [2] block_table [3] seqused [4] k_descale? [5] v_descale?
|
||||
* [6] cu_seqlens? [7] out [8] gate [9] q8 [10] q8_scale
|
||||
*
|
||||
* No temporaries: gate_quant_fp8 reads `out` and writes its bf16 product back over it, which is
|
||||
* the 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 all its shim reads it as -- and
|
||||
* its `n` is `head_dim`. */
|
||||
* No temporaries: gate_quant_fp8 reads `out` and writes its bf16 product back over it, the
|
||||
* 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) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
auto opt = [&](int i) -> int16_t {
|
||||
return RAD_FUSE_HAS(present, i) ? (int16_t)i : (int16_t)RAD_FUSE_NONE;
|
||||
};
|
||||
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");
|
||||
const int64_t hd = pi(p, n_p, "head_dim"), seqs = pi(p, n_p, "max_seqs", 1);
|
||||
if (q_len <= 0 || nh <= 0 || hd <= 0 || seqs <= 0) return RAD_E_UNSUPPORTED;
|
||||
@@ -707,15 +548,14 @@ extern "C" int r4d_fuse_attn_paged_gate_quant(const RadParam* p, int n_p, uint64
|
||||
* Operands: [0] y_expert [1] expert_w [2] sorted_tok [3] shared? [4] shared_gate? [5] y (inout)
|
||||
* [6] inj [7] h (inout)
|
||||
*
|
||||
* Two declared ops and nothing in between: the gather writes `y`, which is the reduction's message
|
||||
* and is then reduced in place and written into the streams. The shared-arm pair is optional in
|
||||
* both ops at the same positions, so its absence propagates through the wiring. `wire` is the
|
||||
* reducing write's, and it goes to that step unchanged; so does `world_size`, which at four selects
|
||||
* ar_hc_write_4rank, the reduction and write the four-rank row runs.
|
||||
* Two declared ops with nothing in between: the gather writes `y`, the message that is then
|
||||
* reduced in place and written into the streams. The shared-arm pair is optional at the same
|
||||
* positions in both ops, so its absence propagates through the wiring. `wire` and `world_size` go
|
||||
* to the reducing step unchanged; `world_size` 4 selects ar_hc_write_4rank, as the four-rank row
|
||||
* runs.
|
||||
*/
|
||||
extern "C" int r4d_fuse_ar_gather_hc_write(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
(void)present;
|
||||
if (!out) return RAD_E_INVAL;
|
||||
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), k = pi(p, n_p, "top_k");
|
||||
if (M <= 0 || n <= 0 || k <= 0) return RAD_E_UNSUPPORTED;
|
||||
@@ -737,6 +577,38 @@ extern "C" int r4d_fuse_ar_gather_hc_write(const RadParam* p, int n_p, uint64_t
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* ar_rmsnorm_quant_fp8 -- the two-rank all-reduce with the norm and the quantiser folded on.
|
||||
* (kernel: libr4d/r4d_fused_quant_fp8.hip, ar_rmsnorm_quant_fp8_kernel; shim: r4d_ar_entry.hip)
|
||||
*
|
||||
* Operands: [0] x (inout) [1] residual? [2] w [3] q [4] scale [5] out_bf16?
|
||||
*
|
||||
* The second step is `rmsnorm_quant_fp8`, an op with the same two optional operands in the same
|
||||
* positions, so `residual` and `out_bf16` are wired straight through and absence propagates
|
||||
* without reading `present`.
|
||||
*
|
||||
* Both wires match exactly. On the exact wire, pass one stores the standalone one-shot's f32 sum
|
||||
* as bf16 back into `x` (`a = f2bf(bf2f(xr[i]) + bf2f(pr[i])); xr[i] = a;`). On the compressed
|
||||
* wire the reduce loop stores the inverse-rotated sum into `x` as bf16, as the standalone
|
||||
* compressed all-reduce does. After the handshake both run `norm_quant_row`, the device function
|
||||
* of rmsnorm_quant_fp8. Contrast ar_ln_had_quant_i8, which does not round and has no hook.
|
||||
*
|
||||
* Three parameters are not copies, and each selects which all-reduce row serves the step:
|
||||
*
|
||||
* `numel` is M * n. `all_reduce` declares the largest message the instance carries, as an
|
||||
* element count, so the band's high bound (how `pi` reads a range) is right.
|
||||
*
|
||||
* `exact` is the fused `wire` inverted. It is required on `all_reduce` and separates
|
||||
* cArExact from cArWht6.
|
||||
*
|
||||
* `min_bytes` is 0, on the compressed wire only. The wht6 shim serves a message below its floor
|
||||
* with the exact kernel (both share the instance's scratch and flag space), but the
|
||||
* fused kernel has no such fallback. Without the key a small message could go out
|
||||
* exact on one side of the comparison and rotated on the other.
|
||||
*
|
||||
* `hops` is not emitted: no libr4d row reads it, and two ranks have only the one-shot. `y` is
|
||||
* RAD_FUSE_NONE: the fused kernel reduces in place into `x`, as every all-reduce row does.
|
||||
*/
|
||||
extern "C" int r4d_fuse_ar_rmsnorm_quant_fp8(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
|
||||
@@ -745,8 +617,7 @@ extern "C" int r4d_fuse_ar_rmsnorm_quant_fp8(const RadParam* p, int n_p, uint64_
|
||||
const int64_t world = pi(p, n_p, "world_size");
|
||||
const int64_t wire = pi(p, n_p, "wire", 0);
|
||||
if (!fp8_geometry_ok(p, n_p, M, n) || world <= 0) return RAD_E_UNSUPPORTED;
|
||||
/* The entry point serves 0 and 6 and refuses anything else; a chain for a wire that has no
|
||||
* kernel would name a payload neither side can produce. */
|
||||
/* The entry point serves wires 0 and 6 only; any other has no kernel and so no chain. */
|
||||
if (wire != 0 && wire != 6) return RAD_E_UNSUPPORTED;
|
||||
|
||||
switch (step) {
|
||||
|
||||
+207
-318
@@ -1,49 +1,34 @@
|
||||
// r4d_fused_quant_fp8.hip - the two producers that already have an activation row in registers,
|
||||
// with r4d_quant_act_fp8 riding along on the same pass.
|
||||
// r4d_fused_quant_fp8.hip - producers that already hold an activation row in registers, fused with
|
||||
// r4d_quant_act_fp8's per-(row, 128) E4M3 quantisation.
|
||||
//
|
||||
// WHY FUSE, AND WHY THESE TWO. The fp8a8 GEMMs need an E4M3 activation with an f32 scale per
|
||||
// (row, 128 columns) in front of EVERY quantised linear, and `activation_scheme: dynamic` means
|
||||
// there is no shipped scale to skip it with. A decode step of this model issues ~300 of those
|
||||
// quantisers -- one per activation per layer, on both ranks -- each costing microseconds on a step
|
||||
// budgeted in tens of milliseconds. That is not bandwidth: the row is 8 tokens by 5120 channels,
|
||||
// 82 KiB, which is 0.13 us of a 638 GB/s card. It is a launch, a grid fill and a second pass over
|
||||
// a row some other kernel had in registers a moment earlier.
|
||||
// The fp8a8 GEMMs need a quantised activation before every linear (`activation_scheme: dynamic`,
|
||||
// so no shipped scale). A decode step issues ~300 quantisers; each costs a launch, a grid fill and
|
||||
// a second pass over a row another kernel just had in registers, not bandwidth. Fused producers:
|
||||
//
|
||||
// Two of the three producers hand the quantiser a row they have just computed:
|
||||
// rmsnorm -> quant the input of every attention, GDN and MLP linear
|
||||
// silu_mul -> quant down_proj's input
|
||||
//
|
||||
// rmsnorm -> quant the input of every attention, GDN and MLP linear. ~128 a step.
|
||||
// silu_mul -> quant down_proj's input. ~64 a step.
|
||||
// A GEMM output feeding the next linear stays a separate launch. The int8 path has the same fusion
|
||||
// (r4d_rmsnorm_had_quant_i8, r4d_gated_had_quant_i8), where the rotation is required to survive one
|
||||
// scale per row; a 128-wide block scale does not need it.
|
||||
//
|
||||
// The third (a GEMM's own output feeding the next linear) is not fusable this way and stays a
|
||||
// launch of its own. The int8 path carries the same fusion -- r4d_rmsnorm_had_quant_i8 and
|
||||
// r4d_gated_had_quant_i8 -- and this is the fp8 form of it, minus the rotation, which is what the
|
||||
// int8 grid needs to survive one scale per row and a 128-wide block scale does not.
|
||||
// Bit-identical to the unfused pair it replaces (generated text is compared byte for byte across
|
||||
// builds). The pair writes a bf16 norm output and the quantiser reads it back, so amax and codes
|
||||
// are taken over bf16-rounded values; these kernels round to bf16 first and quantise the
|
||||
// round-tripped float.
|
||||
//
|
||||
// BIT-IDENTICAL TO THE PAIR IT REPLACES, and that is a hard requirement rather than a nicety,
|
||||
// because the engine's generated text is compared byte for byte across builds. The unfused pair
|
||||
// writes a BF16 norm output and the quantiser then reads those bf16 bytes back, so the amax and
|
||||
// the codes are taken over
|
||||
// bf16-ROUNDED values. Both kernels here round to bf16 first and quantise the round-tripped float,
|
||||
// which costs one v_cvt per element and is the difference between "the same text" and "very nearly
|
||||
// the same text".
|
||||
// The norm re-reads its row for the second pass, with or without the residual. Unlike
|
||||
// r4d_rmsnorm_had_quant_i8 (which normalises the f32 sum), the sum is rounded to bf16 and stored
|
||||
// first, matching `add` writing a bf16 residual that `rmsnorm` reads back; the re-read is L1-hot.
|
||||
//
|
||||
// THE NORM RE-READS ITS ROW FOR THE SECOND PASS rather than keeping it in registers or LDS, and
|
||||
// that stays true WITH the residual, which is where this differs from r4d_rmsnorm_had_quant_i8.
|
||||
// That kernel keeps the row because it normalises the f32 sum, and re-reading would normalise a
|
||||
// bf16-rounded one, which costs thousands of +/-1 codes. This one rounds the sum to bf16 and
|
||||
// stores it FIRST, because that is what the pair it replaces does: `add` writes a bf16 residual and
|
||||
// `rmsnorm` reads those bytes back. So the value normalised here is the value normalised there,
|
||||
// the re-read is L1-hot, and the output does not move. Less accurate than the int8 path's choice,
|
||||
// and bit-identical to the pair it replaces, which is the property that matters here.
|
||||
// The residual may alias `out_bf16`, and every caller here does so: a block reads the previous
|
||||
// block's delta from the shared `h` buffer and writes its norm output back into it. Pass one reads
|
||||
// every `x` element before the block_sum barrier and pass two writes `y` after it, so they never
|
||||
// race.
|
||||
//
|
||||
// THE RESIDUAL MAY ALIAS `out_bf16`, and every caller in this tree makes it do so: a block reads
|
||||
// the PREVIOUS block's delta out of the shared `h` buffer and writes its own norm output back into
|
||||
// it. Pass one reads every `x` element before the block_sum barrier and pass two writes `y` only
|
||||
// after it, so the two never race.
|
||||
//
|
||||
// `wadd` IS ADDED TO EVERY GAIN IN f32, for the reason r4d_rmsnorm_had_quant_i8 gives at length:
|
||||
// Qwen3.5's norms are GemmaRMSNorm over a zero-centred gamma, and forming `1 + w` in bf16 first is
|
||||
// a systematic 0.3% per channel. Pass 0 for a plain RMS norm.
|
||||
// `wadd` is added to every gain in f32 (see r4d_rmsnorm_had_quant_i8): Qwen3.5's GemmaRMSNorm uses
|
||||
// a zero-centred gamma, and forming `1 + w` in bf16 is a systematic 0.3% error. Pass 0 for a plain
|
||||
// RMS norm.
|
||||
//
|
||||
// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip.
|
||||
|
||||
@@ -62,16 +47,15 @@ constexpr uint32_t kGroup = 128;
|
||||
|
||||
__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); }
|
||||
|
||||
// Round-to-nearest-even, the same three lines every bf16 store in this library uses.
|
||||
// Round-to-nearest-even, as every bf16 store in this library rounds.
|
||||
__device__ __forceinline__ uint16_t f2bf(float f) {
|
||||
const uint32_t u = __float_as_uint(f);
|
||||
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
|
||||
// Both reductions exchange through DPP and permlanex16 (r4d_xor_lane, r4d_wave_sum) rather than
|
||||
// `__shfl_xor`, which gfx1201 lowers to ds_bpermute_b32 -- an LDS round trip a stage, five a
|
||||
// reduction, with nothing else in flight on the wave to hide them. Same partners in the same order,
|
||||
// so the same bits.
|
||||
// Both reductions use DPP and permlanex16 (r4d_xor_lane, r4d_wave_sum) rather than `__shfl_xor`,
|
||||
// which gfx1201 lowers to ds_bpermute_b32, an LDS round trip per stage. Same partners in the same
|
||||
// order, so the same bits.
|
||||
__device__ __forceinline__ float wave_max(float v) {
|
||||
v = fmaxf(v, r4d_xor_lane<16>(v));
|
||||
v = fmaxf(v, r4d_xor_lane<8>(v));
|
||||
@@ -93,15 +77,11 @@ __device__ __forceinline__ float block_sum(float v, float* lds) {
|
||||
return s;
|
||||
}
|
||||
|
||||
// One 128-column group's worth of quantisation, given the four bf16-rounded values a lane owns.
|
||||
// Lifted out because both kernels below end the same way, and because getting the clamp wrong is
|
||||
// the failure r4d_quant_act_fp8.hip spends a paragraph on: v_cvt_pk_fp8_f32 answers an
|
||||
// out-of-range input with a NaN rather than saturating, and `amax * (1/scale)` is 448 in exact
|
||||
// arithmetic but can land an ulp above it in float -- so without the fmin every block containing
|
||||
// its own maximum produces a NaN.
|
||||
// Quantise one 128-column group from the four bf16-rounded values a lane owns. The clamp in
|
||||
// q8_pack4 is required (see r4d_q8.h): v_cvt_pk_fp8_f32 returns NaN out of range, and
|
||||
// `amax * (1/scale)` can land an ulp above 448.
|
||||
//
|
||||
// I8 writes int8 codes at amax / 127 instead (r4d_q8.h), the codes quant_act_i8g would take over
|
||||
// the same bf16 values: an int8 linear reads them where an fp8 one reads the E4M3 pair.
|
||||
// I8 writes int8 codes at amax / 127 instead (r4d_q8.h), the same codes quant_act_i8g produces.
|
||||
template <bool I8 = false>
|
||||
__device__ __forceinline__ void quant_group(const float v[4], float* __restrict__ s,
|
||||
uint8_t* __restrict__ q, size_t s_at, uint32_t c0,
|
||||
@@ -112,17 +92,15 @@ __device__ __forceinline__ void quant_group(const float v[4], float* __restrict_
|
||||
if (lane == 0) s[s_at] = sc;
|
||||
const float inv = 1.0f / sc;
|
||||
const uint32_t pk = q8_pack4<I8>(v[0], v[1], v[2], v[3], inv);
|
||||
// A ragged last group is written zero-padded rather than partially, exactly as
|
||||
// r4d_quant_act_fp8 does, and the caller owns `n` rounded up to 4 bytes of `q`.
|
||||
// A ragged last group is written zero-padded, as in r4d_quant_act_fp8; the caller owns `n`
|
||||
// rounded up to 4 bytes of `q`.
|
||||
if (c0 < n) *(uint32_t*)(q + c0) = pk;
|
||||
}
|
||||
|
||||
// Pass two, shared by every kernel in this file that ends in a block-scaled fp8 activation: give
|
||||
// each wave a whole 128-column group and each lane four consecutive columns of it, which is what
|
||||
// makes the group's amax a wave reduction and the E4M3 store a single dword. `nr` is the row the
|
||||
// norm was taken OF, already in memory -- rounding it to bf16 and reading it back is the whole
|
||||
// bit-identity argument at the top of this file, and it is written once here so that the fused
|
||||
// all-reduce below cannot drift from the standalone norm above it.
|
||||
// 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
|
||||
// the fused all-reduce cannot drift from the standalone norm.
|
||||
template <bool WF32, uint32_t THR>
|
||||
__device__ __forceinline__ void norm_quant_row(
|
||||
const uint16_t* __restrict__ nr, const void* __restrict__ w, uint16_t* __restrict__ yr,
|
||||
@@ -132,10 +110,8 @@ __device__ __forceinline__ void norm_quant_row(
|
||||
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 refuses an `n` that is not a multiple of
|
||||
// four, so a lane's columns are all in the row or all past it. Guarded one column at a
|
||||
// time, each load sits in its own branch with its use straight after it and the compiler
|
||||
// waits for every one before issuing the next; under one branch they all issue first.
|
||||
// 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];
|
||||
@@ -146,8 +122,7 @@ __device__ __forceinline__ void norm_quant_row(
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
// THE BF16 ROUND TRIP IS THE POINT. The unfused quantiser reads these bytes, not
|
||||
// the f32 that produced them.
|
||||
// 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);
|
||||
@@ -158,9 +133,7 @@ __device__ __forceinline__ void norm_quant_row(
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- rmsnorm -> quant
|
||||
// One block a row. Pass one is the sum of squares across all 256 threads; pass two gives each wave
|
||||
// a whole 128-column group and each lane four consecutive columns of it, which is what makes the
|
||||
// group's amax a wave reduction and the E4M3 store a single dword.
|
||||
// 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>
|
||||
__global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
|
||||
const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
|
||||
@@ -171,14 +144,12 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
|
||||
const uint32_t row = blockIdx.x;
|
||||
const uint16_t* __restrict__ xr = x + (size_t)row * x_ld;
|
||||
uint16_t* __restrict__ rr = RES ? res + (size_t)row * r_ld : nullptr;
|
||||
// What the norm is taken OF: the residual once there is one, the input otherwise.
|
||||
// The norm is taken of the residual when there is one, else of the input.
|
||||
const uint16_t* __restrict__ nr = RES ? rr : xr;
|
||||
|
||||
// FOUR STRIDES OF THE ROW ARE LOADED BEFORE ANY IS USED. A plain `i += THR` loop waits for
|
||||
// each stride's load before issuing the next, one round trip per stride; here a stride past
|
||||
// the row reloads this thread's first column, which is always in the row, and is skipped
|
||||
// below. The sum still takes this thread's columns in the order `i = tid; i += THR` does,
|
||||
// which is the order every kernel sharing r4d_act_threads' partition takes them in.
|
||||
// Four strides are loaded before any is used, avoiding one round trip per stride. A stride past
|
||||
// the row reloads this thread's first column and is skipped below. The summation order is still
|
||||
// that of `i = tid; i += THR`, shared by every kernel using r4d_act_threads' partition.
|
||||
constexpr uint32_t kU = 4;
|
||||
float ss = 0.0f;
|
||||
for (uint32_t i0 = threadIdx.x; i0 < n; i0 += kU * THR) {
|
||||
@@ -212,23 +183,16 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- gate -> quant
|
||||
// silu(gate) * up, or sigmoid(gate) * up, then the same quantiser. No reduction across the row, so
|
||||
// there is no first pass and no barrier: one wave, one group, done.
|
||||
// silu(gate) * up or sigmoid(gate) * up, then the same quantiser. No row reduction, so no first
|
||||
// pass and no barrier: one wave per group.
|
||||
//
|
||||
// ROT INSERTS THE WIDTH-128 HADAMARD between the product and the absmax, which is where it has to
|
||||
// go: the benefit of a rotation is entirely that the maximum the grid is scaled by gets smaller.
|
||||
// It is free here for the same reason it is free in r4d_quant_act_fp8 -- this kernel's mapping,
|
||||
// one wave a 128-group and four consecutive values a lane, IS r4d_fwht_wave<128>'s, so the seven
|
||||
// stages are register arithmetic and five shuffles on a launch already being paid.
|
||||
// ROT inserts the width-128 Hadamard between the product and the absmax, in registers, since this
|
||||
// mapping (one wave per group, four values per lane) is r4d_fwht_wave<128>'s. `y` still receives
|
||||
// the unrotated product: it is for a bf16 consumer, and the rotation belongs to the quantised pair
|
||||
// only.
|
||||
//
|
||||
// `y` STILL RECEIVES THE UNROTATED PRODUCT, and that is not an inconsistency. `y` exists for a
|
||||
// bf16 consumer of the silu output; the rotation is a property of the QUANTISED pair alone, and
|
||||
// the weight that undoes it never sees `y`.
|
||||
//
|
||||
// A WAVE A GROUP, AND NO IDLE WAVES. With no reduction across the row the workgroup's width changes
|
||||
// nothing but how many groups run at once, so the launcher sizes it to the row's groups, capped at
|
||||
// r4d_act_threads' width, and the kernel reads the width from blockDim. A fixed width leaves most
|
||||
// of the waves of a narrow row with nothing to do: at 1024 threads and three groups, 29 of 32.
|
||||
// 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>
|
||||
__global__ __launch_bounds__(1024) void gated_quant_fp8_kernel(
|
||||
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q,
|
||||
@@ -243,8 +207,7 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel(
|
||||
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, so all eight loads issue before any is waited on; see
|
||||
// norm_quant_row.
|
||||
// One branch for all four columns; see norm_quant_row.
|
||||
if (c0 < n) {
|
||||
uint16_t gb[4], ub[4];
|
||||
#pragma unroll
|
||||
@@ -261,8 +224,7 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel(
|
||||
v[j] = bf2f(h);
|
||||
}
|
||||
}
|
||||
// The rotated launcher refuses an n that is not a multiple of the group, so no block that
|
||||
// reaches this line mixes real values with the padding zeros above.
|
||||
// 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);
|
||||
}
|
||||
@@ -270,15 +232,12 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel(
|
||||
|
||||
// -------------------------------------------------- gate . x -> quant, two source buffers
|
||||
//
|
||||
// THE SAME EPILOGUE WITH THE GATE SOMEWHERE ELSE. A gated attention's output gate is not packed
|
||||
// beside the thing it scales: `x` is the attention output [T, n_head * head_dim] and the gate is a
|
||||
// COLUMN SLICE of the [q|gate] projection, [T * n_head, 2 * head_dim] with the gate half at
|
||||
// `g_off`. So the row is a (token, head) pair rather than a token, which is the whole trick: at
|
||||
// that shape `x` is contiguous, the gate is a fixed stride apart, and the fp8 scale plane of
|
||||
// [T * n_head, head_dim / 128] is byte-for-byte the [T, n_head * head_dim / 128] the out
|
||||
// projection reads. Three launches an attention layer -- sigmoid, the multiply, the quantiser --
|
||||
// become one, and at a decode batch the dispatch gap between those three is comparable to the work
|
||||
// they do.
|
||||
// The same epilogue with the gate in a separate buffer. For gated attention, `x` is the attention
|
||||
// output [T, n_head * head_dim] and the gate is a column slice of the [q|gate] projection,
|
||||
// [T * n_head, 2 * head_dim] with the gate half at `g_off`. A row is a (token, head) pair: `x` is
|
||||
// then contiguous, the gate a fixed stride apart, and the scale plane [T * n_head, head_dim / 128]
|
||||
// is byte-identical to the [T, n_head * head_dim / 128] the out projection reads. Replaces three
|
||||
// launches (sigmoid, multiply, quantise) per attention layer.
|
||||
template <int ACT, bool I8 = false>
|
||||
__global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
|
||||
const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
|
||||
@@ -294,8 +253,7 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
|
||||
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, so all eight loads issue before any is waited on; see
|
||||
// norm_quant_row.
|
||||
// One branch for all four columns; see norm_quant_row.
|
||||
if (c0 < n) {
|
||||
uint16_t gb[4], xb[4];
|
||||
#pragma unroll
|
||||
@@ -306,13 +264,9 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
const float gv = bf2f(gb[j]);
|
||||
// THE ACTIVATION IS ROUNDED BEFORE THE MULTIPLY, which is the one place this
|
||||
// differs from gated_quant_fp8 above and it is not an oversight. That kernel's
|
||||
// unfused reference is silu_mul_bf16, ONE kernel that keeps the activation in f32
|
||||
// through the product. This one's is `sigmoid` then `mul`, TWO kernels with a
|
||||
// bf16 buffer between them -- so the round trip is part of the arithmetic being
|
||||
// replaced, and skipping it changes the model's output: the emitted text moves and
|
||||
// the drafter's acceptance rate falls.
|
||||
// The activation is rounded to bf16 before the multiply, unlike gated_quant_fp8:
|
||||
// the unfused reference here is `sigmoid` then `mul` with a bf16 buffer between
|
||||
// them (silu_mul_bf16 keeps f32). Skipping the round trip changes the output.
|
||||
const uint16_t ab =
|
||||
f2bf(ACT == 0 ? gv / (1.0f + expf(-gv)) : 1.0f / (1.0f + expf(-gv)));
|
||||
const uint16_t h = f2bf(bf2f(ab) * bf2f(xb[j]));
|
||||
@@ -326,59 +280,37 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
|
||||
|
||||
// -------------------------------------------------------- all-reduce -> rmsnorm -> quant
|
||||
//
|
||||
// The same norm again, with the tensor-parallel all-reduce that always precedes it folded in.
|
||||
// Every row-parallel linear's output is all-reduced and then immediately normalised -- o_proj,
|
||||
// out_proj and down_proj, 128 of each on a 64-layer decode step, always adjacent and always in
|
||||
// that order. The norm's own body is a small fraction of what the pair costs; the rest is a launch,
|
||||
// a dispatch gap and a round trip through memory for a tensor that exists for one kernel. The int8
|
||||
// path carries the same fusion (r4d_ar_ln_had_quant_i8); this is the fp8 form of it, minus the
|
||||
// rotation.
|
||||
// The same norm with the tensor-parallel all-reduce that always precedes it folded in (o_proj,
|
||||
// out_proj and down_proj outputs are all-reduced, then normalised). Saves a launch, a dispatch gap
|
||||
// and a round trip through memory. The int8 path has the same fusion (r4d_ar_ln_had_quant_i8).
|
||||
//
|
||||
// THE PARTITION IS BY ROW, for the reason that file gives at length: r4d_ar_oneshot_2rank_exact
|
||||
// hands block b a contiguous chunk of 16B WORDS with an independent flag and no grid barrier
|
||||
// anywhere, and a norm cannot use that partition because a sum of squares closes only over a whole
|
||||
// row -- but rows are contiguous, so a contiguous range of ROWS is a contiguous range of words.
|
||||
// Both ranks compute the same range from (M, gridDim.x), so the handshake stays per-block.
|
||||
// Partitioned by row: r4d_ar_oneshot_2rank_exact gives block b a contiguous range of 16B words with
|
||||
// its own flag and no grid barrier, but a sum of squares needs whole rows. Rows are contiguous, so a
|
||||
// row range is a word range; both ranks derive it from (M, gridDim.x), keeping the handshake
|
||||
// per block.
|
||||
//
|
||||
// BIT-IDENTICAL TO THE PAIR IT REPLACES, and by construction rather than by inspection. Pass two
|
||||
// is norm_quant_row above, the same code the standalone kernel runs. Pass one reproduces the
|
||||
// all-reduce's own arithmetic exactly -- an f32 sum STORED AS BF16 (r4d_ar_oneshot_2rank_exact's
|
||||
// vadd) and then read as the norm's input -- and stores it back into `x`, which is not bookkeeping:
|
||||
// it is what the kernel this replaces wrote, so a reader of `x` that is not this norm still finds
|
||||
// the same bytes. The column partition of the sum of squares is `i = tid; i += THR` on both, which
|
||||
// is the agreement r4d_act_threads exists to keep.
|
||||
// Bit-identical to the pair it replaces. Pass two is norm_quant_row. Pass one reproduces the
|
||||
// all-reduce's arithmetic (an f32 sum stored as bf16, as in r4d_ar_oneshot_2rank_exact's vadd) and
|
||||
// stores it back into `x`, as the replaced kernel did, so other readers of `x` see the same bytes.
|
||||
// Both sum the squares in r4d_act_threads' `i = tid; i += THR` order.
|
||||
//
|
||||
// BOTH WIRES ARE SERVED, and the compressed one is why this kernel is worth its size. Above
|
||||
// --tp-wire-min-kb the message goes out 6-bit rotated, and that payload is worth more than the
|
||||
// launch a fusion saves. A kernel that served only the exact wire would hand every message above
|
||||
// the floor back to the standalone pair, and the fusion would run at one sequence and nowhere
|
||||
// else -- which is the wrong band, because a step carries n_seq * (1 + n_spec) rows, so the message
|
||||
// crosses the floor at the SECOND concurrent sequence and stays across it. Serving WIRE == 6 here
|
||||
// is what lets the two wins compose.
|
||||
// Both wires are served. Above --tp-wire-min-kb the message is sent 6-bit rotated; a step carries
|
||||
// n_seq * (1 + n_spec) rows, so it crosses that floor from the second concurrent sequence on, and
|
||||
// an exact-wire-only fusion would rarely apply.
|
||||
//
|
||||
// The wire is r4d_ar_oneshot_2rank_wht6's format and arithmetic unchanged -- orthonormal
|
||||
// Walsh-Hadamard over a group of 64, amax-scaled, 6 uniform bits plus a bf16 scale -- packed at a
|
||||
// CHUNK of 512 elements instead of 2048. The chunk size is not numerics: the rotation and the amax
|
||||
// close over a GROUP, and a group is 64 elements at either chunking, so the codes and the scales
|
||||
// are the same bytes. What it decides is who owns what. A chunk may not straddle a row, or a
|
||||
// block's rows would not be a whole number of chunks and the two ranks would disagree about which
|
||||
// bytes a block owns; and a wave owns a whole chunk, so a smaller chunk puts more waves to work,
|
||||
// which is why a chunk is 8 groups and not 32 (see r4d_ar_ln_had_quant_i8.hip).
|
||||
// The compressed wire is r4d_ar_oneshot_2rank_wht6's format (orthonormal Walsh-Hadamard over 64,
|
||||
// amax-scaled, 6 uniform bits plus a bf16 scale) packed in chunks of 512 elements instead of 2048.
|
||||
// Rotation and amax close over a 64-element group, so the bytes are identical; the chunk size only
|
||||
// sets ownership. A chunk may not straddle a row (both ranks must agree on a block's bytes), and a
|
||||
// wave owns a whole chunk, so a smaller chunk employs more waves (see r4d_ar_ln_had_quant_i8.hip).
|
||||
//
|
||||
// THE REDUCED ROW GOES BACK TO GLOBAL `x`, not to an LDS staging slice. The int8 twin stages it,
|
||||
// because its norm needs the row again for a rotation it performs in place; this one does not --
|
||||
// pass two re-reads the row it just wrote, which is the same re-read the standalone norm does and
|
||||
// the same L1-hot argument the top of this file makes. It costs a bf16 round trip that the int8
|
||||
// form avoids and buys back all of the LDS.
|
||||
// The reduced row goes back to global `x`, not LDS: unlike the int8 twin this norm needs no
|
||||
// in-place rotation, and pass two re-reads the row L1-hot as the standalone norm does.
|
||||
//
|
||||
// AND THIS RANK'S OWN PACKED HALF GOES TO GLOBAL TOO, in the side buffer the standalone kernel
|
||||
// already allocates (`loc_pack`), rather than to LDS. LDS cannot hold it, and the failure only a
|
||||
// long enough prompt shows: LDS is 64 KiB and a row's packed half is ~4 KiB at n = 5120, so a block
|
||||
// holds fifteen rows where a PREFILL chunk is two thousand. The launch is then refused with a shape
|
||||
// error, which in this engine aborts the step and fails the requests in it. A bound that depends on
|
||||
// the block count is not a bound this op gets to have: the same op serves M = 8 and
|
||||
// M = 2048. The side buffer costs 0.75 bytes an element written and read straight back, which is
|
||||
// under half a microsecond at decode width and stays in L2.
|
||||
// This rank's own packed half also goes to global, in the standalone kernel's side buffer
|
||||
// (`loc_pack`). LDS (64 KiB) holds only ~15 rows of ~4 KiB packed halves at n = 5120, while one op
|
||||
// serves M = 8 through a 2048-row prefill chunk; a refused launch would abort the step. The side
|
||||
// buffer costs 0.75 bytes per element, written and read back from L2.
|
||||
#define R4D_ARQ_SPIN_MAX 4000000000ULL
|
||||
|
||||
#define ARQ_GROUP 64
|
||||
@@ -396,8 +328,8 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
|
||||
#define ARQ_QMIN (-(1 << (ARQ_BITS - 1)))
|
||||
#define ARQ_MASK ((1u << ARQ_BITS) - 1u)
|
||||
|
||||
// `lo ? (v + o) : (o - v)` written as `o + (lo ? v : -v)`: the sign flip is one XOR against a mask
|
||||
// uniform over the stage, so the select disappears. Bit-identical -- IEEE negation is exact.
|
||||
// `lo ? (v + o) : (o - v)` written as `o + (lo ? v : -v)`: the sign flip is one XOR with a mask
|
||||
// uniform over the stage, removing the select. Bit-identical, since IEEE negation is exact.
|
||||
template <int M>
|
||||
__device__ __forceinline__ void arq_xstage(float* v, int lig) {
|
||||
const unsigned int sm = (lig & M) ? 0x80000000u : 0u;
|
||||
@@ -445,8 +377,8 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
|
||||
const uint32_t tid = threadIdx.x;
|
||||
/* Integer arithmetic only, so both ranks land on the same split. */
|
||||
const int r0 = (int)(((long)b * M) / nb), r1 = (int)(((long)(b + 1) * M) / nb);
|
||||
/* Chunks a row spans, and this block's window into the message's global chunk numbering. Both
|
||||
* ranks derive them from the same (M, nb, n), so neither has to be told. */
|
||||
/* Chunks per row and this block's window into the global chunk numbering, derived identically
|
||||
* on both ranks from (M, nb, n). */
|
||||
const int cpr = WIRE ? (int)(n / ARQ_CE) : 0;
|
||||
const int c00 = r0 * cpr, cpb = (r1 - r0) * cpr;
|
||||
const uint32_t lane = tid & (ARQ_WV - 1), wave = tid / ARQ_WV;
|
||||
@@ -456,34 +388,31 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
|
||||
const unsigned int sq = s_seq;
|
||||
int4* const ps = peer_base + (size_t)s_slot * slot_stride16;
|
||||
const int4* const ms = my_base + (size_t)s_slot * slot_stride16;
|
||||
/* The slot is split exactly as the standalone compressed all-reduce splits it: packed symbols
|
||||
* from the base, bf16 group scales from half way up. Group indices are GLOBAL over the whole
|
||||
* [M][n] message, so a block simply addresses the groups its rows cover. */
|
||||
/* The slot is split as in the standalone compressed all-reduce: packed symbols from the base,
|
||||
* bf16 group scales from half way up. Group indices are global over the [M][n] message. */
|
||||
char* const p_pay = (char*)ps;
|
||||
const char* const m_pay = (const char*)ms;
|
||||
unsigned short* const p_sc =
|
||||
(unsigned short*)((char*)ps + (size_t)(slot_stride16 >> 1) * 16);
|
||||
const unsigned short* const m_sc =
|
||||
(const unsigned short*)((const char*)ms + (size_t)(slot_stride16 >> 1) * 16);
|
||||
/* This rank's own packed half, in the side buffer split exactly as the peer slot is: symbols
|
||||
* from the base, scales from `loc_scale_off`. Indexed by the GLOBAL chunk and group number, so
|
||||
* a block writes and reads only what its own rows cover and no two blocks overlap. */
|
||||
/* This rank's own packed half, laid out like the peer slot (symbols from the base, scales from
|
||||
* `loc_scale_off`) and indexed by global chunk and group, so blocks never overlap. */
|
||||
unsigned int* const Lpk = (unsigned int*)loc_pack;
|
||||
float* const Lsc = (float*)(loc_pack + loc_scale_off);
|
||||
|
||||
if constexpr (WIRE == 0) {
|
||||
/* Push my rows into the peer's slot. `x` is a tight [M][n] of bf16 -- the launcher refuses
|
||||
* a pitched one -- so a row range is a 16B-word range. */
|
||||
/* Push my rows into the peer's slot. `x` is a tight [M][n] of bf16 (the launcher refuses a
|
||||
* pitched one), so a row range is a 16B-word range. */
|
||||
const int wpr = (int)(n >> 3);
|
||||
const int wend = r1 * wpr;
|
||||
const int4* const in4 = (const int4*)x;
|
||||
for (int k = r0 * wpr + (int)tid; k < wend; k += (int)THR) ps[k] = in4[k];
|
||||
} else {
|
||||
/* Rotate, amax, quantise and pack straight into the peer's slot, keeping the same words in
|
||||
* LDS. A wave owns whole chunks, so every lane emits exactly ARQ_NWORD dwords a chunk and
|
||||
* the flush is lane-uniform. No group is ever partial: n is a whole number of chunks and a
|
||||
* block owns whole rows, so the `live` guard the standalone kernel needs is not needed
|
||||
* here -- which is also why every cross-lane stage below is wholly active. */
|
||||
/* Rotate, amax, quantise and pack straight into the peer's slot. A wave owns whole chunks,
|
||||
* so every lane emits ARQ_NWORD dwords per chunk and the flush is lane-uniform. No group is
|
||||
* partial (n is whole chunks, a block owns whole rows), so the standalone kernel's `live`
|
||||
* guard is unnecessary and every cross-lane stage is fully active. */
|
||||
for (int ci = (int)wave; ci < cpb; ci += (int)(THR / ARQ_WV)) {
|
||||
const int c = c00 + ci;
|
||||
unsigned int acc[ARQ_NWORD];
|
||||
@@ -536,8 +465,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
|
||||
Lpk[((size_t)c * ARQ_NWORD + wi) * ARQ_WV + lane] = acc[wi];
|
||||
}
|
||||
}
|
||||
/* The drain modes are r4d_ar_oneshot_2rank_exact's, and the variant table picks between them
|
||||
* for the same reasons; the kernel only has to honour them identically. */
|
||||
/* The drain modes are r4d_ar_oneshot_2rank_exact's, selected by the same variant table. */
|
||||
if (drain == 1) __threadfence_system();
|
||||
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
|
||||
__syncthreads();
|
||||
@@ -545,8 +473,8 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
|
||||
if (drain == 2) __threadfence_system();
|
||||
arq_store_rel(&peer_flags[b], sq);
|
||||
unsigned long long z = 0;
|
||||
/* A handshake that cannot complete is a lockstep violation: norming a slot the peer never
|
||||
* filled would hand stale bytes on as a sum, so it traps instead. */
|
||||
/* A handshake that cannot complete is a lockstep violation; trap rather than sum a slot the
|
||||
* peer never filled. */
|
||||
while (r4d_ar_seq_behind(arq_load_acq(&my_flags[b]), sq)) {
|
||||
if (++z > R4D_ARQ_SPIN_MAX) __builtin_trap();
|
||||
}
|
||||
@@ -555,10 +483,8 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
|
||||
if (acq) __threadfence_system();
|
||||
|
||||
if constexpr (WIRE == 6) {
|
||||
/* REDUCE: unpack both halves of every chunk this block owns, add in fp32, inverse-rotate,
|
||||
* and store the bf16 sum back into `x` -- which is what the standalone compressed
|
||||
* all-reduce wrote, so pass two below reads the bytes it would have read and a reader of
|
||||
* `x` that is not this norm still finds the same ones. */
|
||||
/* Reduce: unpack both halves of every chunk this block owns, add in fp32, inverse-rotate,
|
||||
* and store the bf16 sum into `x`, as the standalone compressed all-reduce does. */
|
||||
for (int ci = (int)wave; ci < cpb; ci += (int)(THR / ARQ_WV)) {
|
||||
const int c = c00 + ci;
|
||||
const char* const pb = m_pay + (size_t)c * ARQ_CBYTES;
|
||||
@@ -593,9 +519,9 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
|
||||
psy |= pac[wi + 1] << (32 - bo);
|
||||
lsy |= lac[wi + 1] << (32 - bo);
|
||||
}
|
||||
/* The two ranks fold the identical pair in OPPOSITE order; fp32 add commutes
|
||||
* exactly, so they stay bit-identical as long as neither product is contracted
|
||||
* into an FMA. libr4d/CMakeLists.txt passes -ffp-contract=off for exactly this. */
|
||||
/* The two ranks add the pair in opposite order; fp32 add commutes exactly, so
|
||||
* they agree bit for bit as long as neither product is contracted into an FMA
|
||||
* (libr4d/CMakeLists.txt passes -ffp-contract=off for this). */
|
||||
v[i] = (float)((int)(psy & ARQ_MASK) + ARQ_QMIN) * psc
|
||||
+ (float)((int)(lsy & ARQ_MASK) + ARQ_QMIN) * lsc;
|
||||
}
|
||||
@@ -605,12 +531,11 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
|
||||
for (int i = 0; i < ARQ_EPL; ++i) x[off + i] = f2bf(v[i]);
|
||||
}
|
||||
}
|
||||
/* Pass two reads `x` across the whole row and a wave only wrote its own chunks of it. */
|
||||
/* Pass two reads all of `x`'s row; each wave wrote only its own chunks. */
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
/* The peer's rows are now in MY scratch, in the same [M][n] layout as x -- WIRE == 0 only;
|
||||
* the compressed wire has already reduced into `x` above. */
|
||||
/* WIRE == 0: the peer's rows are now in this rank's scratch, in x's [M][n] layout. */
|
||||
const uint16_t* __restrict__ P = (const uint16_t*)ms;
|
||||
|
||||
for (int row = r0; row < r1; ++row) {
|
||||
@@ -622,8 +547,8 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
|
||||
(void)pr;
|
||||
float ss = 0.0f;
|
||||
for (uint32_t i = tid; i < n; i += THR) {
|
||||
/* The exact wire reduces HERE, on the norm's own pass; the compressed one has already
|
||||
* reduced into `x` and this reads what it stored. */
|
||||
/* The exact wire reduces here, in the norm's first pass; the compressed one already
|
||||
* reduced into `x`. */
|
||||
uint16_t a;
|
||||
if constexpr (WIRE == 0) { a = f2bf(bf2f(xr[i]) + bf2f(pr[i])); xr[i] = a; }
|
||||
else { a = xr[i]; }
|
||||
@@ -636,26 +561,24 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
|
||||
const float rs = rsqrtf(block_sum<THR / kWave>(ss, lds) / (float)n + eps);
|
||||
norm_quant_row<WF32, THR>(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 re-used by the next row this block owns, and a thread still reading it for this
|
||||
* row would otherwise race the next row's write. The one-row-a-block kernel above never
|
||||
* needed this barrier and that is the only structural difference between them. */
|
||||
/* 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();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// `w` is the norm gain, f32 when `w_f32` and bf16 otherwise -- every gain in this project's
|
||||
// architecture plugins is declared f32, and the width is the caller's to state for the reason
|
||||
// r4d_model_bf16's rmsnorm gives. `y` may be null on a layer with no bf16 consumer of the
|
||||
// post-norm tensor; every caller in this tree has one, because the fp8a16 matvec reads it at M = 1.
|
||||
// `w` is the norm gain, f32 when `w_f32` and bf16 otherwise (see r4d_model_bf16's rmsnorm). `y`
|
||||
// may be null when nothing reads the bf16 post-norm tensor; every current caller has a reader (the
|
||||
// fp8a16 matvec at M = 1).
|
||||
//
|
||||
// `res`, when given, is the fused_add_rms_norm form: `res += x` in f32, ROUNDED TO BF16 and stored,
|
||||
// and the norm is then taken of the stored value -- which is bit-for-bit the `add` + `rmsnorm` pair
|
||||
// this replaces. Pass 0 for the plain form. It may alias `y`; see the note at the top of the file.
|
||||
// `res`, when given, is the fused_add_rms_norm form: `res += x` in f32, rounded to bf16 and stored,
|
||||
// and the norm is taken of the stored value, bit-identical to `add` + `rmsnorm`. Pass 0 for the
|
||||
// plain form. It may alias `y`; see the note at the top of the file.
|
||||
//
|
||||
// x [M][n] bf16, `x_ld` elements a row (0 = n)
|
||||
// res [M][n] bf16, `r_ld` elements a row (0 = n), optional, READ AND WRITTEN
|
||||
// res [M][n] bf16, `r_ld` elements a row (0 = n), optional, read and written
|
||||
// w [n] f32 or bf16
|
||||
// y [M][n] bf16, `y_ld` elements a row (0 = n), optional
|
||||
// q [M][n] E4M3, `q_ld` bytes a row (0 = n), rounded up to 4
|
||||
@@ -673,16 +596,11 @@ extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, l
|
||||
const int nkb = (n + (int)kGroup - 1) / (int)kGroup;
|
||||
if (!s_ld) s_ld = nkb;
|
||||
|
||||
// ONE WORKGROUP A ROW, so at a decode batch the grid is 8-72 workgroups on a 64-CU part and
|
||||
// the kernel is latency bound rather than bandwidth bound: it moves ~205 KiB, which is far less
|
||||
// work than the ~2.6 us launch floor costs. Widening the workgroup is the only knob that adds
|
||||
// parallelism without changing the algorithm. r4d_act_threads holds the crossover table, and
|
||||
// the reasoning behind it is written out with it.
|
||||
// One workgroup per row, so a decode batch is 8-72 workgroups and the kernel is latency bound;
|
||||
// the workgroup width is the parallelism knob (crossover table in r4d_act_threads).
|
||||
//
|
||||
// rmsnorm_bf16 PICKS THE SAME WIDTH FROM THE SAME FUNCTION, and it has to: the width decides
|
||||
// which columns a thread accumulates into the sum of squares, so two kernels that disagree
|
||||
// about it produce sums that differ in the last bits. This fusion is required to be
|
||||
// byte-identical to the pair it replaces, which is exactly that agreement.
|
||||
// rmsnorm_bf16 must pick the same width from the same function: the width decides which
|
||||
// columns a thread sums, so a different width changes the last bits and breaks bit identity.
|
||||
const int thr = r4d_act_threads(M, n);
|
||||
#define R4D_RQ_T(wf, rs, T) \
|
||||
hipLaunchKernelGGL((rmsnorm_quant_fp8_kernel<wf, rs, T>), dim3((uint32_t)M), dim3(T), 0, \
|
||||
@@ -701,20 +619,18 @@ extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, l
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
// `mode` is 0 for silu (down_proj's input) and 1 for sigmoid (a gated attention o_proj's), the same
|
||||
// spelling r4d_gated_had_quant_i8 takes.
|
||||
// `mode` is 0 for silu (down_proj's input) and 1 for sigmoid (a gated attention o_proj's), as in
|
||||
// r4d_gated_had_quant_i8.
|
||||
//
|
||||
// gu [M][2n] bf16, gate first then up, `gu_ld` elements a row (0 = 2n)
|
||||
// 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))
|
||||
//
|
||||
// `rot` is a STRICTER call, not a flag on the same one: a ragged last group is legal unrotated
|
||||
// (it is written zero-padded and the GEMM's bounds guard stops the padding reaching anything) and
|
||||
// is not legal rotated, because a butterfly that mixed real values with padding has no matching
|
||||
// weight block on the other side.
|
||||
// `rot` additionally requires n % 128 == 0: a ragged last group is fine unrotated (zero-padded,
|
||||
// masked by the GEMM) but a butterfly mixing real values with padding has no matching weight block.
|
||||
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, const R4dSink& sk,
|
||||
int gu_ld, int y_ld, int q_ld, int s_ld, RadStream stream,
|
||||
bool rot, bool i8 = false) {
|
||||
int emit_rc = RAD_OK;
|
||||
if (!gu || !q || !s) return -1;
|
||||
@@ -729,13 +645,12 @@ static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n,
|
||||
if (!q_ld) q_ld = n;
|
||||
const int nkb = (n + (int)kGroup - 1) / (int)kGroup;
|
||||
if (!s_ld) s_ld = nkb;
|
||||
// A wave a group, capped at r4d_act_threads' width; see the kernel. There is no cross-row
|
||||
// reduction here, so the width changes nothing numerically -- only how many waves share the
|
||||
// groups. The ROTATION is wave-local too (r4d_fwht.h), so that stays true with it.
|
||||
// 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(sk, (gated_quant_fp8_kernel<a, R, I>), dim3((uint32_t)M), dim3(thr), 0, \
|
||||
(const uint16_t*)gu, (uint16_t*)y, (uint8_t*)q, \
|
||||
emit_rc = R4D_EMIT(stream, (gated_quant_fp8_kernel<a, R, I>), 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(a) \
|
||||
@@ -747,25 +662,24 @@ static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n,
|
||||
#undef R4D_GQ
|
||||
#undef R4D_GQ_R
|
||||
if (emit_rc != RAD_OK) return -4;
|
||||
return (!sk.desc && hipGetLastError() != hipSuccess) ? -4 : 0;
|
||||
return (hipGetLastError() != hipSuccess) ? -4 : 0;
|
||||
}
|
||||
|
||||
extern "C" int r4d_gated_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,
|
||||
r4d_stream_sink((RadStream)(uintptr_t)stream), false);
|
||||
(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,
|
||||
r4d_stream_sink((RadStream)(uintptr_t)stream), true);
|
||||
(RadStream)(uintptr_t)stream, true);
|
||||
}
|
||||
|
||||
// act . x, with the gate and the thing it scales in DIFFERENT buffers -- see the kernel above for
|
||||
// why the row is a (token, head) pair. `mode` is spelled as r4d_gated_quant_fp8 spells it. The
|
||||
// activation is ROUNDED TO BF16 before the product, because the pair this replaces is two kernels
|
||||
// with a bf16 buffer between them -- unlike r4d_gated_quant_fp8, whose reference is one.
|
||||
// act . x with the gate and x in separate buffers; see the kernel for why a row is a (token, head)
|
||||
// pair and why the activation is rounded to bf16 before the product. `mode` as in
|
||||
// r4d_gated_quant_fp8.
|
||||
//
|
||||
// g [M][.] bf16, `g_ld` elements a row; the gate starts at element 0 of the row,
|
||||
// so a caller with a [q|gate] projection passes g already offset
|
||||
@@ -775,7 +689,7 @@ extern "C" int r4d_gated_had_quant_fp8(long gu, long y, long q, long s, int M, i
|
||||
// s [M][ceil(n/128)] f32, `s_ld` elements a row (0 = ceil(n/128))
|
||||
static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, int n, int mode,
|
||||
int g_ld, int x_ld, int y_ld, int q_ld, int s_ld,
|
||||
const R4dSink& sk, bool i8 = false) {
|
||||
RadStream stream, bool i8 = false) {
|
||||
int emit_rc = RAD_OK;
|
||||
if (!g || !x || !q || !s) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
@@ -790,7 +704,7 @@ static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, in
|
||||
// A wave a group, capped at r4d_act_threads' width, as gated_quant_fp8 above.
|
||||
const int thr = std::min(nkb, r4d_act_threads(M, n) / (int)kWave) * (int)kWave;
|
||||
#define R4D_GTQ_I(a, I) \
|
||||
emit_rc = R4D_EMIT(sk, (gate_quant_fp8_kernel<a, I>), dim3((uint32_t)M), dim3(thr), 0, \
|
||||
emit_rc = R4D_EMIT(stream, (gate_quant_fp8_kernel<a, I>), dim3((uint32_t)M), dim3(thr), 0, \
|
||||
(const uint16_t*)g, (const uint16_t*)x, \
|
||||
(uint16_t*)y, (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)nkb, \
|
||||
(uint32_t)g_ld, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)q_ld, \
|
||||
@@ -801,27 +715,24 @@ static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, in
|
||||
#undef R4D_GTQ
|
||||
#undef R4D_GTQ_I
|
||||
if (emit_rc != RAD_OK) return -4;
|
||||
return (!sk.desc && hipGetLastError() != hipSuccess) ? -4 : 0;
|
||||
return (hipGetLastError() != hipSuccess) ? -4 : 0;
|
||||
}
|
||||
|
||||
extern "C" int r4d_gate_quant_fp8(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, long stream) {
|
||||
R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream;
|
||||
return gate_quant_fp8_emit(g, x, y, q, s, M, n, mode, g_ld, x_ld, y_ld, q_ld, s_ld, sk);
|
||||
return gate_quant_fp8_emit(g, x, y, q, s, M, n, mode, g_ld, x_ld, y_ld, q_ld, s_ld,
|
||||
(RadStream)(uintptr_t)stream);
|
||||
}
|
||||
|
||||
// The fused all-reduce. The IPC arguments are r4d_ar_oneshot_2rank_exact's -- the same
|
||||
// double-buffered scratch, per-block flags and device-resident sequence counters -- and everything
|
||||
// after them is r4d_rmsnorm_quant_fp8's, with two differences the caller has to know about:
|
||||
// The fused all-reduce. The IPC arguments are r4d_ar_oneshot_2rank_exact's (double-buffered
|
||||
// scratch, per-block flags, device-resident sequence counters); the rest are r4d_rmsnorm_quant_fp8's,
|
||||
// except:
|
||||
//
|
||||
// * `x` HAS NO PITCH. It is the all-reduce's message as well as the norm's input, and a block
|
||||
// pushes its rows as a range of 16B words; a pitched x would make the two ranks disagree about
|
||||
// which bytes a block owns. Refused rather than silently strided.
|
||||
// * `nblocks` IS CLAMPED TO M, because a block owns whole rows. At a decode batch that is 8 to
|
||||
// 64 blocks, which is the range the standalone all-reduce asks for anyway.
|
||||
// * `x` has no pitch: it is also the all-reduce message, pushed as a range of 16B words, and a
|
||||
// pitch would make the ranks disagree about a block's bytes.
|
||||
// * `nblocks` is clamped to M, since a block owns whole rows.
|
||||
//
|
||||
// `res` is the fused_add_rms_norm form and behaves exactly as it does there. Returns 0, or a
|
||||
// negative code for a shape it does not serve.
|
||||
// `res` behaves as in r4d_rmsnorm_quant_fp8. Returns 0, or a negative code for an unserved shape.
|
||||
extern "C" int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void) { return ARQ_CE; }
|
||||
|
||||
extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flags,
|
||||
@@ -834,11 +745,11 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long
|
||||
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;
|
||||
if (n % 4) return -3; // a lane owns four columns; see norm_quant_row
|
||||
if (n % 8) return -5; // n bf16 is a whole number of 16B words; see the push
|
||||
// n % 8: n bf16 is a whole number of 16B words (see the push), which also gives every lane its
|
||||
// four columns (see norm_quant_row).
|
||||
if (n % 8) return -5;
|
||||
if (wire != 0 && wire != 6) return -7;
|
||||
// A chunk may not straddle a row, or a block's rows would not be a whole number of chunks and
|
||||
// the two ranks would disagree about which bytes a block owns.
|
||||
// A chunk may not straddle a row, or the ranks would disagree about a block's bytes.
|
||||
if (wire == 6 && (n % ARQ_CE)) return -8;
|
||||
if (wire == 6 && (!loc_pack || loc_scale_off <= 0)) return -9;
|
||||
if (!r_ld) r_ld = n;
|
||||
@@ -851,9 +762,7 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long
|
||||
if (nb > M) nb = M;
|
||||
const int nbw = r4d_ar_max_blocks(); // the counter capacity; see r4d_ar_seq.h
|
||||
if (nb > nbw) nb = nbw;
|
||||
// The width is r4d_act_threads for the reason the standalone norm gives: it decides which
|
||||
// columns a thread accumulates into the sum of squares, so a fused kernel that picked a
|
||||
// different one would produce a different sum in the last bits and a different token stream.
|
||||
// The width must be r4d_act_threads', as for the standalone norm (it fixes the summation order).
|
||||
const int thr = nthreads ? nthreads : r4d_act_threads(M, n);
|
||||
if (thr != 256 && thr != 512 && thr != 1024) return -6;
|
||||
#define R4D_ARQ_T(wf, rs, T, W) \
|
||||
@@ -882,14 +791,11 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The shared operand reader is r4d_fp8_args.h. See libr4d/r4d_args.h for why there is no adapter
|
||||
// directory between the core and these launches.
|
||||
// The shared operand reader is r4d_fp8_args.h; see libr4d/r4d_args.h.
|
||||
/* ================================================================== the two fused quantisers
|
||||
*
|
||||
* The shape rules are the standalone quantiser's, applied to the operand that PRODUCES the row
|
||||
* rather than to the row itself, plus the one thing the fusion adds: the bf16 output is optional
|
||||
* because a layer with no bf16 consumer of the post-norm tensor should not pay for the store, and
|
||||
* every caller in this tree has one anyway (the fp8a16 matvec reads it at M = 1). */
|
||||
* The standalone quantiser's shape rules, applied to the operand that produces the row. The bf16
|
||||
* output is optional so a layer without a bf16 consumer skips the store. */
|
||||
|
||||
extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* x = r4d_opt(a, RQ_X);
|
||||
@@ -899,9 +805,9 @@ extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* sc = r4d_opt(a, RQ_S);
|
||||
const RadTensor* y = r4d_opt(a, RQ_Y);
|
||||
if (!x || !w || !q || !sc) return R4D_NO(RAD_E_INVAL);
|
||||
/* Rank 2 on the input too, unlike the standalone quantiser: a norm has a gain per channel, so
|
||||
* "everything after dim 0 is the row" would put one gain across several heads. The GDN block's
|
||||
* rank-3 activation is quantised by the standalone op, and its gated norm by its own kernel. */
|
||||
if (q->dtype != RAD_F8E4M3) return R4D_NO(RAD_E_DTYPE);
|
||||
/* Rank 2 on the input too, unlike the standalone quantiser: a norm has one gain per channel,
|
||||
* and folding trailing dims would spread a gain across heads. */
|
||||
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];
|
||||
@@ -913,9 +819,8 @@ extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
|
||||
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);
|
||||
if (y && (y->shape[0] != M || y->shape[1] != K)) return R4D_NO(RAD_E_SHAPE);
|
||||
/* The residual is the same extent as the input and is READ AND WRITTEN. It is allowed to alias
|
||||
* `out_bf16` -- every caller in this tree makes it do so -- which is safe because pass one
|
||||
* reads all of `x` before the kernel's only barrier and pass two writes `y` after it. */
|
||||
/* The residual has the input's extent and is read and written. It may alias `out_bf16` (see
|
||||
* the note at the top of the file). */
|
||||
if (rs && (rs->rank != 2 || rs->shape[0] != M || rs->shape[1] != K)) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc);
|
||||
const long long yp = y ? r4d_row_pitch(y) : 0, rp = rs ? r4d_row_pitch(rs) : 0;
|
||||
@@ -929,7 +834,17 @@ extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
|
||||
return e == 0 ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
static int rad_gated_quant_fp8(const RadArgs* a, const R4dSink& sk, bool rot) {
|
||||
/* The gate's activation: `act` by name overrides `mode` (libr4d's integer: 0 silu, 1 sigmoid) when
|
||||
* both are given, as for r4d_gated_had_quant_i8. Returns -1 for an unknown name. */
|
||||
static int act_mode(const RadArgs* a, int dflt) {
|
||||
const char* act = r4d_gets(a, "act");
|
||||
if (!act) return (int)r4d_geti_or(a, "mode", dflt);
|
||||
if (!std::strcmp(act, "silu")) return 0;
|
||||
if (!std::strcmp(act, "sigmoid")) return 1;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int rad_gated_quant_fp8(const RadArgs* a, RadStream stream, bool rot) {
|
||||
const RadTensor* gu = r4d_opt(a, GQ_GU);
|
||||
const RadTensor* q = r4d_opt(a, GQ_Q);
|
||||
const RadTensor* sc = r4d_opt(a, GQ_S);
|
||||
@@ -944,8 +859,7 @@ static int rad_gated_quant_fp8(const RadArgs* a, const R4dSink& sk, bool rot) {
|
||||
const long long grp = r4d_quant_act_fp8_group();
|
||||
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] and the halves are gate then up -- one buffer, because that is
|
||||
* how the fused gate_up projection writes it and splitting would be a copy. */
|
||||
/* 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);
|
||||
if (sc->shape[0] != M || sc->shape[1] != nkb) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -953,60 +867,45 @@ static int rad_gated_quant_fp8(const RadArgs* a, const R4dSink& sk, bool rot) {
|
||||
const long long gp = r4d_row_pitch(gu), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc);
|
||||
const long long yp = y ? r4d_row_pitch(y) : 0;
|
||||
if (gp < 0 || qp < 0 || sp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
/* `act` is the vocabulary's name and `mode` is libr4d's integer spelling of the same choice;
|
||||
* `act` wins where both are given, which is what r4d_gated_had_quant_i8's row promises. */
|
||||
const char* act = r4d_gets(a, "act");
|
||||
int mode = (int)r4d_geti_or(a, "mode", 0);
|
||||
if (act) {
|
||||
if (!std::strcmp(act, "silu")) mode = 0;
|
||||
else if (!std::strcmp(act, "sigmoid")) mode = 1;
|
||||
else return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
}
|
||||
const int mode = act_mode(a, 0); /* silu: the gated MLP */
|
||||
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, sk, rot, q->dtype == RAD_I8);
|
||||
(int)qp, (int)sp, stream, rot, q->dtype == RAD_I8);
|
||||
return e == 0 ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
static int rad_gated_quant_fp8_body(const RadArgs* a, const R4dSink& sk) {
|
||||
return rad_gated_quant_fp8(a, sk, false);
|
||||
extern "C" int r4d_rad_gated_quant_fp8(const RadArgs* a, RadStream stream) {
|
||||
return rad_gated_quant_fp8(a, stream, false);
|
||||
}
|
||||
R4D_ENTRY(r4d_rad_gated_quant_fp8, rad_gated_quant_fp8_body)
|
||||
|
||||
/* THE ROTATED FORM, a different op for the same reason had_quant_act_fp8 is: the codes it writes
|
||||
* are not the codes the other one writes, so a graph with one substituted for the other is a
|
||||
* different model that still runs and still answers. It pairs with a down-projection weight
|
||||
* stored at dtype w4a8h and with nothing else. */
|
||||
static int rad_gated_had_quant_fp8_body(const RadArgs* a, const R4dSink& sk) {
|
||||
return rad_gated_quant_fp8(a, sk, true);
|
||||
/* 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);
|
||||
}
|
||||
R4D_ENTRY(r4d_rad_gated_had_quant_fp8, rad_gated_had_quant_fp8_body)
|
||||
|
||||
/* Elements between consecutive `width`-wide rows, the same rule r4d_gdn.cpp's gn_row_pitch uses:
|
||||
* a [.., heads, width] operand steps a row with the stride of the axis above the last, and a
|
||||
* flattened one is contiguous and steps by `width`. It is the only way to read a column view of
|
||||
* an interleaved projection, which is what a gated attention's gate is. */
|
||||
/* Elements between consecutive `width`-wide rows, as r4d_gdn.cpp's gn_row_pitch: a
|
||||
* [.., heads, width] operand steps by the stride of the second-to-last axis; a flattened one is
|
||||
* contiguous and steps by `width`. This reads a column view of an interleaved projection (a gated
|
||||
* attention's gate). */
|
||||
static long long tq_pitch(const RadTensor* t, long long width) {
|
||||
if (!t || t->rank < 1) return -1;
|
||||
if (t->shape[t->rank - 1] != width) return r4d_contig(t) ? width : -1;
|
||||
if (t->stride[t->rank - 1] != 1) return -1;
|
||||
if (t->rank == 1) return width;
|
||||
/* AND THE ROWS HAVE TO BE UNIFORMLY THAT FAR APART, which the width test alone does not say.
|
||||
* A [T, n_head, head_dim] column view of the [q|gate] projection flattens to T * n_head rows
|
||||
* only if T's stride is exactly n_head of them -- true here, because the narrowing shrank the
|
||||
* last axis and left every stride alone, and false for anything that also sliced an axis
|
||||
* above it. Refusing is the only safe answer: a wrong pitch reads the next head's gate. */
|
||||
/* Rows must also be uniformly spaced: a [T, n_head, head_dim] column view flattens to
|
||||
* T * n_head rows only if T's stride is n_head of them, which fails if an outer axis was also
|
||||
* sliced. Refuse otherwise; a wrong pitch would read the next head's gate. */
|
||||
for (int i = (int)t->rank - 2; i >= 1; --i)
|
||||
if (t->stride[i - 1] != t->shape[i] * t->stride[i]) return -1;
|
||||
return t->stride[t->rank - 2];
|
||||
}
|
||||
|
||||
/* THE SAME EPILOGUE WITH THE GATE SOMEWHERE ELSE. A gated attention's output gate is not packed
|
||||
* beside the thing it scales -- `x` is the attention output [M][n] and the gate is a COLUMN SLICE
|
||||
* of the [q|gate] projection -- so this takes two operands where gated_quant_fp8 takes one. The
|
||||
* caller narrows the gate to its own columns with a column view and the shim reads the offset off
|
||||
* the tensor, which is why there is no `gate_offset` parameter. */
|
||||
static int rad_gate_quant_fp8_body(const RadArgs* a, const R4dSink& sk) {
|
||||
/* Two-operand form of gated_quant_fp8 for gated attention: `x` is the attention output and the
|
||||
* gate a column view of the [q|gate] projection. The gate offset comes from the view, so there is
|
||||
* no `gate_offset` parameter. */
|
||||
extern "C" int r4d_rad_gate_quant_fp8(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* g = r4d_opt(a, TQ_G);
|
||||
const RadTensor* x = r4d_opt(a, TQ_X);
|
||||
const RadTensor* q = r4d_opt(a, TQ_Q);
|
||||
@@ -1014,12 +913,8 @@ static int rad_gate_quant_fp8_body(const RadArgs* a, const R4dSink& sk) {
|
||||
const RadTensor* y = r4d_opt(a, TQ_Y);
|
||||
if (!g || !x || !q || !sc) return R4D_NO(RAD_E_INVAL);
|
||||
if (q->dtype != RAD_F8E4M3 && q->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE);
|
||||
/* M IS COUNTED OFF `x`, NOT READ OUT OF THE PARAMETERS. `M` is the row's RANGED parameter, so
|
||||
* what arrives here is the band's declared maximum and not the issue -- a shim that trusts it
|
||||
* refuses every real step. And shape[0] is no better: the row here is a (token, head) pair and
|
||||
* neither operand spells it that way, the gate being a [T, n_head, head_dim] column view of
|
||||
* the [q|gate] projection and x a flat [T, n_head * head_dim]. The element count over the
|
||||
* known width is the one reading both agree on. */
|
||||
/* 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();
|
||||
if (K <= 0 || r4d_numel(x) % K) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -1034,18 +929,12 @@ static int rad_gate_quant_fp8_body(const RadArgs* a, const R4dSink& sk) {
|
||||
const long long qp = tq_pitch(q, K), sp = tq_pitch(sc, nkb);
|
||||
const long long yp = y ? tq_pitch(y, K) : 0;
|
||||
if (gp < 0 || xp < 0 || qp < 0 || sp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
const char* act = r4d_gets(a, "act");
|
||||
int mode = (int)r4d_geti_or(a, "mode", 1);
|
||||
if (act) {
|
||||
if (!std::strcmp(act, "silu")) mode = 0;
|
||||
else if (!std::strcmp(act, "sigmoid")) mode = 1;
|
||||
else return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
}
|
||||
const int mode = act_mode(a, 1); /* sigmoid: gated attention */
|
||||
if (mode < 0) return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
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, sk,
|
||||
(int)gp, (int)xp, (int)yp, (int)qp, (int)sp, stream,
|
||||
q->dtype == RAD_I8);
|
||||
return e == 0 ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
R4D_ENTRY(r4d_rad_gate_quant_fp8, rad_gate_quant_fp8_body)
|
||||
|
||||
+14
-19
@@ -1,30 +1,25 @@
|
||||
// r4d_fwht.h - a wave-local fast Walsh-Hadamard transform, in registers, with no LDS and no barrier.
|
||||
// r4d_fwht.h - a wave-local fast Walsh-Hadamard transform in registers, with no LDS and no barrier.
|
||||
//
|
||||
// WHY IT IS IN REGISTERS. Staging the row in LDS and running the butterfly there costs seven
|
||||
// stages, each a read-modify-write of every element plus a __syncthreads() -- roughly 28 LDS
|
||||
// operations and 7 barriers per element. The transform's own ARITHMETIC is a fraction of a percent
|
||||
// of a rotated quantiser; the LDS traffic and the barriers around it are what a butterfly staged in
|
||||
// LDS actually costs, and they are several times the rest of the kernel. None of that is the
|
||||
// transform, so none of it is paid here.
|
||||
// A butterfly staged in LDS costs seven stages, each a read-modify-write of every element plus a
|
||||
// __syncthreads() (about 28 LDS operations and 7 barriers per element), several times the rest of
|
||||
// a rotated quantiser; the transform's arithmetic is a fraction of a percent.
|
||||
//
|
||||
// THE MAPPING. Give one wave a `HAD`-wide block, VPL = HAD/32 contiguous values per lane, so lane l
|
||||
// holds indices l*VPL .. l*VPL+VPL-1. A butterfly at stride h pairs index i with i+h:
|
||||
// Mapping: one wave holds a `HAD`-wide block, VPL = HAD/32 contiguous values per lane, so lane l
|
||||
// holds indices l*VPL .. l*VPL+VPL-1. A butterfly at stride h pairs index i with i+h:
|
||||
//
|
||||
// h < VPL both indices are in the SAME lane -- plain register arithmetic, no communication
|
||||
// h >= VPL the partner is lane l + h/VPL -- one lane exchange with mask h/VPL
|
||||
// h < VPL both indices in the same lane -- plain register arithmetic
|
||||
// h >= VPL the partner is lane l + h/VPL -- one lane exchange with mask h/VPL
|
||||
//
|
||||
// Since HAD/VPL is always 32, the cross-lane masks are exactly 1, 2, 4, 8, 16 whatever HAD is: five
|
||||
// exchanges per register (r4d_xor_lane, DPP rather than LDS) and no barrier at any width. The lane holding the LOW index of a pair keeps
|
||||
// (v + partner) and the high one keeps (partner - v), which is the same butterfly written twice.
|
||||
//
|
||||
// The caller still needs one barrier before a whole-row reduction, but ONE, not seven.
|
||||
// HAD/VPL is always 32, so the cross-lane masks are 1, 2, 4, 8, 16 at any HAD: five exchanges per
|
||||
// register (r4d_xor_lane, DPP) and no barrier. The lane holding the low index keeps (v + partner),
|
||||
// the high one (partner - v). The caller still needs one barrier before a whole-row reduction.
|
||||
#pragma once
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "r4d_common.h"
|
||||
|
||||
// `hi ? (o - v) : (v + o)` written as `o + (hi ? -v : v)`: the sign flip is one XOR against a mask
|
||||
// that is uniform over the stage, so the per-element select disappears. Bit-identical -- IEEE
|
||||
// negation is exact and addition commutes.
|
||||
// `hi ? (o - v) : (v + o)` written as `o + (hi ? -v : v)`, with the sign flip one XOR against a
|
||||
// stage-uniform mask, so there is no per-element select. Bit-identical: negation is exact and
|
||||
// addition commutes.
|
||||
template <int VPL, int MASK>
|
||||
__device__ __forceinline__ void r4d_fwht_xstage(float* v, int lane) {
|
||||
const unsigned int sm = (lane & MASK) ? 0x80000000u : 0u;
|
||||
|
||||
@@ -1,33 +1,28 @@
|
||||
// r4d_gated_had_quant_i8.hip - r4d_gated_had_quant_i8: an elementwise GATED product, then the block
|
||||
// r4d_gated_had_quant_i8.hip - r4d_gated_had_quant_i8: an elementwise gated product, then the block
|
||||
// Hadamard, then the per-row int8 quantiser, in one pass.
|
||||
//
|
||||
// TWO OF THE FOUR ROTATED SITES HAVE THIS SHAPE, and they differ by one multiply:
|
||||
// Two of the four rotated sites have this shape and differ by one multiply:
|
||||
//
|
||||
// MODE 0, down_proj's input silu(a) * b = a * sigmoid(a) * b (vLLM's silu_and_mul)
|
||||
// MODE 1, o_proj's input sigmoid(a) * b (Qwen3_5Attention does
|
||||
// mode 0, down_proj's input silu(a) * b = a * sigmoid(a) * b (vLLM's silu_and_mul)
|
||||
// mode 1, o_proj's input sigmoid(a) * b (Qwen3_5Attention does
|
||||
// attn_output * sigmoid(gate))
|
||||
//
|
||||
// so one kernel serves the MLP of all 64 layers and the attention output of the 16 full-attention
|
||||
// ones. The 48 linear-attention layers reach out_proj through a gated RMSNorm instead and need
|
||||
// their own variant.
|
||||
// ones. The 48 linear-attention layers reach out_proj through a gated RMSNorm instead.
|
||||
//
|
||||
// Mode 0 is the WIDEST of the four and the one the rotation width is decided by. An intermediate of
|
||||
// 17408 at TP=2 leaves each rank 8704 = 2^9 * 17 -- so 512 is the largest power of two that tiles
|
||||
// it and 1024 is not available anywhere in the model, because a rotation block cannot straddle a
|
||||
// shard boundary. Between 128 and 512 the activation's quantisation error moves by far less than
|
||||
// the weight error that dominates both, so the width is chosen on cost.
|
||||
// Mode 0 is the widest site and sets the rotation width. An intermediate of 17408 at TP=2 leaves
|
||||
// 8704 = 2^9 * 17 per rank, so 512 is the largest power of two that tiles it (a rotation block
|
||||
// cannot straddle a shard boundary). Between 128 and 512 the activation's quantisation error moves
|
||||
// far less than the dominant weight error, so the width is chosen on cost.
|
||||
//
|
||||
// GATE AND UP ARRIVE AS SEPARATE TENSORS. vLLM fuses gate_proj and up_proj into one gate_up
|
||||
// projection and then splits it, so the two halves are either two tensors or two halves of one with
|
||||
// a row pitch of 2*K. `up` may alias `gate + K` for the fused layout; pass the pointers and the
|
||||
// stride and the kernel does not care which.
|
||||
// Gate and up arrive as two tensors, or as two halves of vLLM's fused gate_up with a row pitch of
|
||||
// 2*K (`up` aliasing `gate + K`); the kernel takes pointers and strides either way.
|
||||
//
|
||||
// The transform is in registers (r4d_fwht.h), so this is ONE pass: read gate and up, silu-multiply,
|
||||
// The transform is in registers (r4d_fwht.h), so this is one pass: read gate and up, multiply,
|
||||
// rotate inside the wave, stage once for the row absmax.
|
||||
//
|
||||
// silu(x) = x * sigmoid(x) is computed in fp32. Doing it in bf16 would cost more than the
|
||||
// quantiser that follows: the product feeds a rotation, which mixes 128 values, so a rounding error
|
||||
// in one lands on all 128.
|
||||
// silu is computed in fp32: the product feeds a rotation that mixes 128 values, so a bf16 rounding
|
||||
// error in one lands on all of them.
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -35,19 +30,12 @@
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
|
||||
// 0 = choose the workgroup width from M at launch (see r4d_act_threads in r4d_common.h); a
|
||||
// non-zero build-time value pins one width for every M.
|
||||
#ifndef R4D_GHQ_THREADS
|
||||
#define R4D_GHQ_THREADS 0
|
||||
#endif
|
||||
|
||||
template <int HAD, int MODE, int THR>
|
||||
__global__ __launch_bounds__(THR) void r4d_gated_had_quant_i8_kernel(
|
||||
const __hip_bfloat16* __restrict__ G, const __hip_bfloat16* __restrict__ U,
|
||||
signed char* __restrict__ Q, float* __restrict__ S,
|
||||
int K, long gstride, long ustride, float rnorm, float clip) {
|
||||
int K, long gstride, long ustride, float rnorm) {
|
||||
constexpr int VPL = HAD / 32, NW = THR / 32;
|
||||
extern __shared__ float lds[];
|
||||
float* red = lds + K;
|
||||
@@ -79,11 +67,7 @@ __global__ __launch_bounds__(THR) void r4d_gated_had_quant_i8_kernel(
|
||||
m = red[0];
|
||||
#pragma unroll
|
||||
for (int i = 1; i < NW; i++) m = fmaxf(m, red[i]);
|
||||
// CLIPPED ABSMAX. The row scale is set by the single largest rotated value in 8704 channels,
|
||||
// so one outlier costs every other channel a bit of resolution. clip < 1 trades a few saturated
|
||||
// channels for a finer grid on the rest; the saturate below is what makes it safe, and clip = 1
|
||||
// is the unclipped quantiser byte for byte.
|
||||
m = fmaxf(m, 1e-8f) * clip;
|
||||
m = fmaxf(m, 1e-8f);
|
||||
const float inv = 127.f / m;
|
||||
if (threadIdx.x == 0) S[row] = m * rnorm / 127.f;
|
||||
|
||||
@@ -96,25 +80,11 @@ __global__ __launch_bounds__(THR) void r4d_gated_had_quant_i8_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// R4D_CLIP_MLP_DOWN / R4D_CLIP_ATTN_OUT: one clip factor per site this kernel serves. They are
|
||||
// separate because the two distributions are -- a SwiGLU product and a sigmoid-gated attention
|
||||
// output. Read once and cached; unset or out of (0, 1] means the unclipped absmax.
|
||||
static float r4d_gated_act_clip(int mode) {
|
||||
static float cached[2] = {-1.f, -1.f};
|
||||
if (cached[mode] < 0.f) {
|
||||
const char* v = getenv(mode == 0 ? "R4D_CLIP_MLP_DOWN" : "R4D_CLIP_ATTN_OUT");
|
||||
const float f = v ? (float)atof(v) : 1.f;
|
||||
cached[mode] = (f > 0.f && f <= 1.f) ? f : 1.f;
|
||||
}
|
||||
return cached[mode];
|
||||
}
|
||||
|
||||
// The launch, as the plugin ABI's RadLaunchFn. See the note at the head of r4d_quant_act_i8.hip.
|
||||
//
|
||||
// THE SECOND OPERAND MAY BE ABSENT, and that is the packed gate_up form: `b` missing means the two
|
||||
// halves are one [M, 2n] tensor and `b` is `a + n`, which is vLLM's layout and the one the MLP
|
||||
// actually produces -- so both row pitches are 2n and the second pointer is computed rather than
|
||||
// passed. bf16 is two bytes an element, and the row's dtype constraint is what guarantees that.
|
||||
// A missing second operand is the packed gate_up form: one [M, 2n] tensor with `b` = `a + n`
|
||||
// (vLLM's layout and what the MLP produces), so both row pitches are 2n. The row's dtype
|
||||
// constraint guarantees bf16.
|
||||
enum { GH_A = 0, GH_B, GH_Q, GH_S };
|
||||
|
||||
extern "C" int r4d_rad_gated_had_quant_i8(const RadArgs* args, RadStream stream) {
|
||||
@@ -152,29 +122,25 @@ extern "C" int r4d_rad_gated_had_quant_i8(const RadArgs* args, RadStream stream)
|
||||
|
||||
const long long had = r4d_geti_or(args, "group", 0);
|
||||
if (had != 128 && had != 256 && had != 512) return R4D_NO(RAD_E_SHAPE);
|
||||
// A rotation block cannot straddle a tensor-parallel shard boundary; down_proj's input is 8704
|
||||
// per rank, so 512 is the widest available and 1024 is not.
|
||||
// A rotation block cannot straddle a tensor-parallel shard; down_proj's input is 8704 per rank,
|
||||
// so 512 is the widest available.
|
||||
if (K % had) return R4D_NO(RAD_E_SHAPE);
|
||||
if (K % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
// `act` is the vocabulary's name -- "silu" or "sigmoid" -- and `mode` is this kernel's integer
|
||||
// for the same choice. The mapping happens here and nowhere else; the caller names the
|
||||
// activation.
|
||||
// `act` names the activation ("silu" or "sigmoid"); `mode` is this kernel's integer for it.
|
||||
const int mode = r4d_act_code(args, "act", "mode", 0);
|
||||
if (mode != 0 && mode != 1) return R4D_NO(RAD_E_INVAL);
|
||||
if (r4d_numel(q) != M * K) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
const int thr = R4D_GHQ_THREADS ? R4D_GHQ_THREADS : r4d_act_threads((int)M, (int)K);
|
||||
const int thr = r4d_act_threads((int)M, (int)K);
|
||||
const size_t shmem = (size_t)K * sizeof(float) + (thr / 32) * sizeof(float);
|
||||
if (shmem > 65536) return R4D_NO(RAD_E_SCRATCH);
|
||||
const long gs = (long)(a_stride ? a_stride : K), us = (long)(b_stride ? b_stride : K);
|
||||
const float rn = 1.f / sqrtf((float)had);
|
||||
const float clip = r4d_gated_act_clip(mode);
|
||||
#define R4D_GHQ_LAUNCH(H, MD, T) hipLaunchKernelGGL((r4d_gated_had_quant_i8_kernel<H, MD, T>), \
|
||||
dim3((int)M), dim3(T), shmem, (hipStream_t)stream, pa, pb, (signed char*)r4d_wp(q), \
|
||||
(float*)r4d_wp(sc), (int)K, gs, us, rn, clip)
|
||||
(float*)r4d_wp(sc), (int)K, gs, us, rn)
|
||||
#define R4D_GHQ_T(H, MD) switch (thr) { \
|
||||
case 128: R4D_GHQ_LAUNCH(H, MD, 128); break; \
|
||||
case 256: R4D_GHQ_LAUNCH(H, MD, 256); break; \
|
||||
case 512: R4D_GHQ_LAUNCH(H, MD, 512); break; \
|
||||
case 1024: R4D_GHQ_LAUNCH(H, MD, 1024); break; \
|
||||
@@ -187,5 +153,5 @@ extern "C" int r4d_rad_gated_had_quant_i8(const RadArgs* args, RadStream stream)
|
||||
#undef R4D_GHQ_MODE
|
||||
#undef R4D_GHQ_T
|
||||
#undef R4D_GHQ_LAUNCH
|
||||
return RAD_OK;
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
|
||||
}
|
||||
+21
-27
@@ -1,9 +1,5 @@
|
||||
/* r4d_gdn_args.h -- what the gated-delta-net kernels share when they read their arguments.
|
||||
*
|
||||
* The GDN family is seven kernels across six translation units, and they share two things: a
|
||||
* dtype check that has to be by name, and `num_seqs` read off the cu_seqlens tensor. Both belong
|
||||
* to the family rather than to any one kernel, so they live here -- a header beside them, not an
|
||||
* adapter directory between them and the core. See libr4d/r4d_args.h.
|
||||
/* r4d_gdn_args.h -- argument helpers shared by the gated-delta-net kernels (and the DFlash ops):
|
||||
* dtype checks, num_seqs from cu_seqlens, the compiled-geometry check and a row-pitch reader.
|
||||
*/
|
||||
#ifndef R4D_GDN_ARGS_H
|
||||
#define R4D_GDN_ARGS_H
|
||||
@@ -12,29 +8,28 @@
|
||||
#include "r4d_args.h"
|
||||
|
||||
|
||||
/* EVERY POINTER libr4d TAKES AS `const void*` HAS ONE ELEMENT TYPE, AND THE CAST IS INSIDE THE
|
||||
* KERNEL. `r4d_gdn_conv_prep_w4_h128_bf16` casts `wgt` to `const unsigned short*` and `A_log` to
|
||||
* `const float*`; nothing in the signature says so.
|
||||
*
|
||||
* The hazard is concrete, not theoretical. A plugin that declares `ssm_conv1d.weight` f32 or the
|
||||
* `gdn_kkt` buffer f32 hands libr4d planes it reads as bf16: the convolution takes two bf16
|
||||
* elements out of every float, and the chunk scan's inverse is written as bf16 into a plane sized
|
||||
* and read as f32. Neither shows up on the host path, because libref reads every operand through
|
||||
* its OWN dtype and is therefore correct with either -- so the two implementations disagree and
|
||||
* only the device one is wrong.
|
||||
*
|
||||
* A shim exists to reject what the entry point would reject if it could see the argument (spec
|
||||
* §2.1, and the file header above says the same about pitches). A dtype the kernel silently
|
||||
* reinterprets is the strongest case of that there is, so it is checked here, by name. */
|
||||
/* Every `const void*` libr4d takes has one element type, cast inside the kernel (e.g.
|
||||
* r4d_gdn_conv_prep_w4_h128_bf16 reads `wgt` as bf16 and `A_log` as f32); the signature does not
|
||||
* say so. A plugin declaring `ssm_conv1d.weight` or the `gdn_kkt` buffer as f32 would be read as
|
||||
* bf16 on the device, while libref (which honours each operand's dtype) stays correct, so the bug
|
||||
* would show only on the device path. The shim therefore checks dtypes by name (spec §2.1). */
|
||||
static inline int r4d_dt(const RadTensor* t, uint32_t want) {
|
||||
if (!t) return RAD_OK; /* an absent optional operand has no dtype */
|
||||
return t->dtype == want ? RAD_OK : RAD_E_DTYPE;
|
||||
}
|
||||
#define R4D_DT(t, want) do { const int _d = r4d_dt((t), (want)); if (_d != RAD_OK) return _d; } while (0)
|
||||
#define R4D_DT(t, want) \
|
||||
do { const int _d = r4d_dt((t), (want)); if (_d != RAD_OK) return R4D_NO(_d); } while (0)
|
||||
|
||||
/* num_seqs from the cu_seqlens tensor: it is [N+1] and nothing else in the argument list carries
|
||||
* N. Refusing a cu of rank != 1 here is what stops an off-by-one N reaching a kernel that indexes
|
||||
* cu[N] unconditionally. */
|
||||
/* A raw r4d.h entry point's result as a RAD status. Those return 0, a negative code for a
|
||||
* geometry they were not compiled for, or the positive hipError_t of a failed launch. */
|
||||
static inline int r4d_raw_status(int rc, const char* file, int line) {
|
||||
if (rc == 0) return RAD_OK;
|
||||
return r4d_refused(rc < 0 ? RAD_E_SHAPE : RAD_E_DEVICE, file, line);
|
||||
}
|
||||
#define R4D_RAW(rc) r4d_raw_status((rc), __FILE__, __LINE__)
|
||||
|
||||
/* num_seqs from the [N+1] cu_seqlens tensor, the only operand that carries N. Requiring rank 1
|
||||
* keeps an off-by-one N from reaching kernels that index cu[N] unconditionally. */
|
||||
static inline int seqs_of(const RadTensor* cu, int* out) {
|
||||
if (!cu || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE);
|
||||
@@ -51,9 +46,8 @@ static inline int gdn_dims_ok(void) {
|
||||
}
|
||||
|
||||
|
||||
/* Elements between consecutive `width`-wide rows, for an operand that spells them either way: a
|
||||
* [.., heads, width] tensor steps a row with the stride of the axis above the last, and a flattened
|
||||
* [tokens, heads*width] one steps it with `width`. Negative when neither holds densely. */
|
||||
/* Elements between consecutive `width`-wide rows: the second-to-last stride of a [.., heads, width]
|
||||
* tensor, or `width` for a dense flattened [tokens, heads*width] one. Negative otherwise. */
|
||||
static inline long long gn_row_pitch(const RadTensor* t, long long width) {
|
||||
if (!t || t->rank < 1) return -1;
|
||||
if (t->shape[t->rank - 1] == width) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,26 +1,16 @@
|
||||
// r4d_gdn_conv_tap.h -- the arithmetic of one gated-delta-net convolution output, shared by the
|
||||
// standalone conv kernels (r4d_gdn_conv_w4_h128_bf16.hip) and the recurrent update that folds the
|
||||
// decode convolution into its prologue (r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip).
|
||||
// One definition is what makes the fold byte-identical to the standalone pair: the activation's
|
||||
// reciprocal form below changes the last bit of a bf16 output, so two copies that drift apart
|
||||
// would disagree on a real fraction of channels.
|
||||
// A single definition keeps the fold byte-identical to the standalone path: the reciprocal form
|
||||
// below changes the last bit of some bf16 outputs.
|
||||
#pragma once
|
||||
|
||||
#define R4D_GDN_CONV_W 4 // conv width; the state holds R4D_GDN_CONV_W - 1 taps of history
|
||||
|
||||
#ifndef CU_RCP
|
||||
#define CU_RCP 1
|
||||
#endif
|
||||
|
||||
// The divide here is IEEE-exact and the result is rounded to bf16 on the very next instruction, so
|
||||
// the exactness buys nothing: v_rcp_f32 is 1 ULP (~1e-7 relative) against bf16 s 2^-8 quantum. The
|
||||
// exact form costs a v_div_scale pair, a v_rcp, a Newton chain, v_div_fmas and v_div_fixup -- about
|
||||
// ten instructions and a long dependent chain -- where this costs two. The conv update runs four
|
||||
// waves on five workgroups, so its instruction count IS its time.
|
||||
// The result is rounded to bf16 immediately, so an IEEE-exact divide buys nothing: v_rcp_f32 is
|
||||
// 1 ULP (~1e-7 relative) against bf16's 2^-8 quantum. The exact form is ~10 dependent instructions
|
||||
// (v_div_scale, v_rcp, Newton, v_div_fmas, v_div_fixup); this is two. The conv update runs four
|
||||
// waves on five workgroups, so its time is its instruction count.
|
||||
__device__ __forceinline__ float cp_silu(float z) {
|
||||
#if CU_RCP
|
||||
return z * __builtin_amdgcn_rcpf(1.0f + __expf(-z));
|
||||
#else
|
||||
return z / (1.0f + __expf(-z));
|
||||
#endif
|
||||
}
|
||||
@@ -11,28 +11,20 @@
|
||||
// gate g = -exp(A_log) . softplus(a + dt_bias), beta = sigmoid(b)
|
||||
// cumsum g summed along the chunk, which is what the scan actually consumes
|
||||
//
|
||||
// It replaces causal_conv1d_fn + fused_post_conv_prep + chunk_local_cumsum. The pair it replaces
|
||||
// spends most of its time moving the conv output: causal_conv1d_fn writes all conv_dim channels of
|
||||
// every token to HBM and fused_post_conv_prep reads every one of them straight back, which at this
|
||||
// model's shape is 34 MB out and 34 MB in per layer per rank for a tensor that is dead two
|
||||
// microseconds later. Here the conv output only ever exists in registers.
|
||||
// Replaces causal_conv1d_fn + fused_post_conv_prep + chunk_local_cumsum. The unfused pair writes
|
||||
// the whole conv output to HBM and reads it straight back (34 MB each way per layer per rank at
|
||||
// this model's shape); here it stays in registers.
|
||||
//
|
||||
// The layout falls out of the l2norm. A workgroup is HPB waves, one wave per 128-dim head, one
|
||||
// lane per four dims -- so the norm of a head is a wave reduction with no LDS and no barrier, and
|
||||
// four contiguous bf16 per lane is one 8-byte access on both sides. Channel groups are counted in
|
||||
// heads rather than in channels so that a group never straddles the q/k/v boundaries (they fall on
|
||||
// head multiples at every tensor-parallel size).
|
||||
// Layout: a workgroup is HPB waves, one wave per 128-dim head, four dims per lane, so a head's
|
||||
// norm is a barrier-free wave reduction and each lane does one 8-byte access. Channel groups are
|
||||
// counted in heads so a group never straddles the q/k/v boundaries (head multiples at every TP).
|
||||
//
|
||||
// Tokens are blocked by the chunk, 64, because the cumsum is per chunk: the whole scan is then a
|
||||
// wave-level prefix over 32 lanes holding two tokens each, and no workgroup needs another's
|
||||
// partial sums. The conv reads three tokens of halo per block, 4.7% of the traffic, which is
|
||||
// cheaper than the barrier a shared staging buffer would need.
|
||||
// Tokens are blocked by the 64-token chunk because the cumsum is per chunk: it becomes a wave
|
||||
// prefix over 32 lanes of two tokens each. Each block reads three tokens of halo (4.7% of the
|
||||
// traffic), cheaper than a barrier around a shared staging buffer.
|
||||
//
|
||||
// The conv output is rounded to bf16 BEFORE the norm and the store, which is what the two kernels
|
||||
// it replaces do (the conv writes a bf16 tensor and the prep reads it back). Keeping the fp32
|
||||
// accumulator through the norm would be slightly finer and slightly different; matching is worth
|
||||
// more than the last half ULP here, because it makes this kernel a bit-for-bit drop-in for the
|
||||
// pair it replaces.
|
||||
// The conv output is rounded to bf16 before the norm and the store, as in the unfused pair, so
|
||||
// this kernel is a bit-exact drop-in for it.
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "r4d.h"
|
||||
#include "r4d_gdn_args.h"
|
||||
@@ -44,66 +36,37 @@
|
||||
#define CP_BT 64 // token block = the scan's chunk, so the cumsum stays wave-local
|
||||
#define CP_W R4D_GDN_CONV_W // conv width
|
||||
#define CP_ST (CP_W - 1) // conv state depth
|
||||
// CU_MAXT: tokens the DECODE update pre-loads into registers. 16 is about 13% slower than 8: the
|
||||
// sixteen ushort4 cost more in register pressure and predicated-load exec-mask work than the round
|
||||
// trips they hide, and the compiler already batches the loop's loads.
|
||||
// 1 disables it (slen is num_spec+1 > 1 on every speculative step).
|
||||
// CU_STATIC=1: index the xb[] preload with a COMPILE-TIME t. The preload exists so a token tap is
|
||||
// not an HBM round trip, but a register array under a RUNTIME index is not a register read: the
|
||||
// compiler builds a select tree for it. With both readers -- the token loop and the cache rewrite
|
||||
// -- indexing at runtime, the HPB=1 ISA census is 2033 instructions for 41 loads and 29 stores,
|
||||
// 193 s_cselect_b32 + 138 s_cmp_eq_u32 + 132 v_cndmask_b16 of it: about a third of the kernel
|
||||
// choosing which register to read. That is also why a larger CU_MAXT loses -- twice the array is
|
||||
// twice the tree, not twice the reuse. Unrolling both readers over CU_MAXT with a wave-uniform
|
||||
// `t < slen` guard turns every access into a static index; `slen` is uniform, so the guard is a
|
||||
// scalar branch, not a per-lane select.
|
||||
#ifndef CU_STATIC
|
||||
#define CU_STATIC 1
|
||||
#endif
|
||||
// CU_ISSUE=1: put the input preload AHEAD of the history load. `xrow` depends only on the token
|
||||
// range and this lane's channels, while `hp` depends on `slot`, which has to come back from
|
||||
// cache_idx first -- and the history block consumes its loads immediately (bf2f), so the compiler
|
||||
// waits on them before it issues a single input load and the two HBM round trips run back to back.
|
||||
// One wave per SIMD means nothing else hides either of them.
|
||||
#ifndef CU_ISSUE
|
||||
#define CU_ISSUE 1
|
||||
#endif
|
||||
#ifndef CU_MAXT
|
||||
// Tokens the decode update preloads into registers. 16 is ~13% slower than 8 (register pressure
|
||||
// and predicated-load overhead outweigh the hidden round trips).
|
||||
//
|
||||
// The xb[] preload is indexed with a compile-time t: a register array under a runtime index
|
||||
// compiles to a select tree (about a third of the kernel's instructions at HPB=1). Both readers
|
||||
// unroll over CU_MAXT with a wave-uniform `t < slen` guard, so every index is static and the guard
|
||||
// is a scalar branch. The preload is issued before the history load: the history address depends
|
||||
// on `slot` (a cache_idx load) and its values are consumed immediately, so otherwise the two
|
||||
// memory round trips serialise, with no other wave on the SIMD to hide them.
|
||||
#define CU_MAXT 8
|
||||
#endif
|
||||
// WVEC: read a channel's CP_W conv weights as one vector load instead of CP_W scalar ones.
|
||||
#ifndef WVEC
|
||||
#define WVEC 1
|
||||
#endif
|
||||
#define CP_DPL 4 // dims per lane (CP_HD / 32)
|
||||
|
||||
// cp_silu, and the reason it is a reciprocal and not a divide, is r4d_gdn_conv_tap.h: the
|
||||
// recurrent update folds the decode convolution in and has to compute the same bits.
|
||||
// cp_silu is in r4d_gdn_conv_tap.h, shared with the recurrent update's folded convolution.
|
||||
|
||||
// softplus, in the two-sided form FLA uses, with the same large-x cutoff
|
||||
// softplus, in FLA's two-sided form with the same large-x cutoff
|
||||
__device__ __forceinline__ float cp_softplus(float x, float thr) {
|
||||
if (x > thr) return x;
|
||||
return (x > 0.0f) ? (x + __logf(1.0f + __expf(-x)))
|
||||
: __logf(1.0f + __expf(x));
|
||||
}
|
||||
|
||||
// a and b arrive as the layer holds them: a chunk() of the ba projection, so bf16 and strided by
|
||||
// 2*H, not the fp32 contiguous pair FLA's own kernels are usually handed. Reading them where they
|
||||
// lie is what keeps this a single kernel -- a .float().contiguous() per tensor per layer would put
|
||||
// two more launches and 0.6 MB back on the path this exists to shorten.
|
||||
// a and b are read where they lie: a chunk() of the ba projection, bf16 with row stride 2*H (or
|
||||
// fp32), avoiding a .float().contiguous() copy and two launches per layer.
|
||||
template <int ABF16>
|
||||
__device__ __forceinline__ float cp_ab(const void* p, size_t i) {
|
||||
return ABF16 ? bf2f(((const unsigned short*)p)[i]) : ((const float*)p)[i];
|
||||
}
|
||||
|
||||
// `has_init` SAYS WHETHER THE SLOT HOLDS A HISTORY, and its width is the caller's -- the flag is
|
||||
// the caller's answer, like ab_is_bf16 above. Guessing the width is not safe. The engine hands
|
||||
// over RadBatch::ctx_lens, which is int32 like every derived buffer the core computes; reading
|
||||
// that as `unsigned char` takes byte n of an int32 array. At n = 0 with a cold sequence that is 0
|
||||
// by luck and correct; at the SECOND chunk of a long prompt, ctx_len 512 has a zero low byte, so
|
||||
// the conv window would silently start from zeros and the sequence would lose its history. libref
|
||||
// reads the operand through its own dtype and is right either way, so a width mismatch shows up
|
||||
// only as the two implementations disagreeing, with the fast path wrong.
|
||||
// `has_init` says whether the slot holds a history; its element width (int32 or byte) is given by
|
||||
// the caller. The engine passes RadBatch::ctx_lens (int32); read as bytes, a ctx_len of 512 would
|
||||
// look like 0 and the conv window would silently start from zeros.
|
||||
__device__ __forceinline__ bool r4d_has_init(const void* p, int i32, int n) {
|
||||
if (!p) return false;
|
||||
return i32 ? ((const int*)p)[n] != 0 : ((const unsigned char*)p)[n] != 0;
|
||||
@@ -128,8 +91,8 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch,
|
||||
{
|
||||
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
|
||||
// flat chunk id -> (sequence, chunk); see r4d_gdn_kkt_solve_k128_c64_bf16.hip for why the grid is an upper
|
||||
// bound rather than the exact count
|
||||
// flat chunk id -> (sequence, chunk); the grid is an upper bound (see
|
||||
// r4d_gdn_kkt_solve_k128_c64_bf16.hip)
|
||||
int n = -1, t0 = 0, bos = 0, rows = 0, slen = 0;
|
||||
{
|
||||
int acc = 0, want = blockIdx.x;
|
||||
@@ -145,8 +108,7 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch,
|
||||
const bool first = (t0 == 0);
|
||||
|
||||
// ---- the gating half, on one workgroup per chunk ----------------------------------------
|
||||
// g and beta come from a and b alone, so this is independent of the convolution; it rides on
|
||||
// the y == 0 workgroup rather than costing a launch of its own.
|
||||
// g and beta depend only on a and b; computed by the y == 0 workgroups instead of a launch.
|
||||
if (blockIdx.y == 0) {
|
||||
for (int hv = warp; hv < H; hv += HPB) {
|
||||
const float alog = __expf(A_log[hv]), dtb = dt_bias[hv];
|
||||
@@ -192,8 +154,8 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch,
|
||||
bs[c] = bias ? bf2f(bias[d0 + c]) : 0.0f;
|
||||
}
|
||||
|
||||
// window[i] holds x[t - (W-1) + i]; seed it from the previous tokens, or from the conv state
|
||||
// cache when this is the first chunk of the sequence
|
||||
// win[i] holds x[t - (W-1) + i]; seeded from the previous tokens, or from the conv state cache
|
||||
// at the sequence's first chunk
|
||||
float win[CP_W][CP_DPL];
|
||||
{
|
||||
const bool init = first && r4d_has_init(has_init, hi_i32, n);
|
||||
@@ -213,17 +175,15 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch,
|
||||
}
|
||||
|
||||
// ---- write the new conv state, from x, at the sequence's first chunk ---------------------
|
||||
// Ordering: the cache line is updated in place, so the read above and this write must be in the
|
||||
// same workgroup for the same channels -- which they are, and this is why the FIRST chunk owns
|
||||
// the write even though the tokens it stores belong to the last one.
|
||||
// The cache is updated in place, so the read above and this write must be in the same workgroup
|
||||
// for the same channels. That is why the first chunk writes the state even though its tokens
|
||||
// come from the last chunk.
|
||||
if (first && cache_idx) {
|
||||
unsigned short* sp = cstate + (size_t)cache_idx[(size_t)n * ci_stride] * cs_seq
|
||||
+ (size_t)d0 * cs_dim;
|
||||
const bool init = r4d_has_init(has_init, hi_i32, n);
|
||||
// Channel-major, because the cache is [dim][slot] with the slot contiguous: this lane owns
|
||||
// CP_DPL consecutive channels, so its CP_DPL*CP_ST shorts are one contiguous run and the wave
|
||||
// covers 32 of those back to back. A slot-major order would make every store a strided 2-byte
|
||||
// scalar.
|
||||
// Channel-major: the cache is [dim][slot] with slot contiguous, so a lane's CP_DPL*CP_ST
|
||||
// shorts are one contiguous run. Slot-major order would make every store a strided scalar.
|
||||
#pragma unroll
|
||||
for (int c = 0; c < CP_DPL; ++c) {
|
||||
#pragma unroll
|
||||
@@ -253,7 +213,7 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch,
|
||||
float acc = bs[c];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < CP_W; ++i) acc += wt[i][c] * win[i][c];
|
||||
// the pair this replaces rounds here, on the way to HBM; keep that
|
||||
// round as the unfused pair does on the way to HBM
|
||||
o[c] = bf2f(f2bf(cp_silu(acc)));
|
||||
}
|
||||
|
||||
@@ -318,15 +278,10 @@ extern "C" int r4d_gdn_conv_prep_w4_h128_bf16(
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The decode-time convolution. Same depthwise causal filter, but the tokens of a step are a
|
||||
// speculative window rather than a chunk, and the state cache is a rolling buffer of
|
||||
// width-1 + num_spec entries rather than width-1: a step reads its window starting at the slot
|
||||
// the last ACCEPTED token left behind, and rewrites the buffer shifted by one so the next step
|
||||
// can do the same. That offset is the only thing the caller has to get right, and it is why this
|
||||
// is a separate entry point rather than a flag on the one above.
|
||||
//
|
||||
// It writes q, k and v in their own layouts, which also removes the torch.cat the reference layer
|
||||
// needs to make the three views contiguous for the recurrent kernel.
|
||||
// Decode-time convolution. Same filter, but a step's tokens are a speculative window and the
|
||||
// state cache is a rolling buffer of width-1 + num_spec entries: a step reads its window starting
|
||||
// at the slot the last accepted token left, and rewrites the buffer shifted by one. Writes q, k
|
||||
// and v in their own layouts (no torch.cat for the recurrent kernel).
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
template <int HPB>
|
||||
__global__ __launch_bounds__(HPB * 32)
|
||||
@@ -346,55 +301,42 @@ void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitc
|
||||
const int bos = cu[n], slen = cu[n + 1] - bos;
|
||||
if (slen <= 0) return;
|
||||
const int slot = cache_idx[(size_t)n * ci_stride];
|
||||
// A NEGATIVE slot is the pad and ZERO IS A REAL SLOT. `slot <= 0` would be vLLM's NULL_BLOCK_ID
|
||||
// convention, where 0 is reserved; radiance's block manager hands out 0-based state slots, so
|
||||
// that test would skip the FIRST sequence on the card entirely -- no convolution at all, on
|
||||
// every decode step and every linear-attention layer, silently. libref skips only a negative
|
||||
// slot (libref/ref_gdn.cpp) and so does every index in libr4d.
|
||||
// A negative slot is padding; 0 is a real slot. (vLLM reserves 0 as NULL_BLOCK_ID, but this
|
||||
// engine's state slots are 0-based, as in libref/ref_gdn.cpp.)
|
||||
if (slot < 0) return;
|
||||
|
||||
const int off = naccept ? (naccept[n] - 1) : 0;
|
||||
// the cache depth this step actually uses; FLA shrinks the caller's max_query_len bound by the
|
||||
// tokens this sequence did not bring
|
||||
// cache depth this step uses: as in FLA, the bound shrinks by the tokens this sequence lacks
|
||||
const int slen_eff = state_len_max - (maxq - slen);
|
||||
|
||||
const int unit = blockIdx.y * HPB + warp;
|
||||
const int d0 = unit * CP_HD + lane * CP_DPL;
|
||||
|
||||
// The weight of one channel is CP_W contiguous shorts, so a lane's four channels are four
|
||||
// vector loads, not sixteen scalar ones.
|
||||
// A channel's weights are CP_W contiguous shorts: one vector load per channel.
|
||||
static_assert(CP_W == 4, "the weight load reads a channel's taps as one ushort4");
|
||||
float wt[CP_W][CP_DPL], bs[CP_DPL];
|
||||
#pragma unroll
|
||||
for (int c = 0; c < CP_DPL; ++c) {
|
||||
if (WVEC && CP_W == 4) {
|
||||
const ushort4 w4 = *(const ushort4*)(wgt + (size_t)(d0 + c) * CP_W);
|
||||
const unsigned short* ws = (const unsigned short*)&w4;
|
||||
const ushort4 w4 = *(const ushort4*)(wgt + (size_t)(d0 + c) * CP_W);
|
||||
const unsigned short* ws = (const unsigned short*)&w4;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < CP_W; ++i) wt[i][c] = bf2f(ws[i]);
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < CP_W; ++i) wt[i][c] = bf2f(wgt[(size_t)(d0 + c) * CP_W + i]);
|
||||
}
|
||||
for (int i = 0; i < CP_W; ++i) wt[i][c] = bf2f(ws[i]);
|
||||
bs[c] = bias ? bf2f(bias[d0 + c]) : 0.0f;
|
||||
}
|
||||
|
||||
// ADDRESS ARITHMETIC IS WHAT THIS KERNEL SPENDS ITS TIME ON. Indexing with (size_t)i * cs_tok
|
||||
// and (size_t)(bos + ti) * xpitch gives every one of the ~40 cache stores and every input tap a
|
||||
// 64-bit multiply: that form costs 1297 instructions -- 252 of them s_wait_alu and about 330
|
||||
// scalar address ALU -- to move 290 KB. The strides are small (cs_dim is the per-channel row, a
|
||||
// handful of tokens; xpitch is conv_dim), so every offset below is an int taken from a base
|
||||
// pointer that already carries the 64-bit part, and the loops walk their pointers rather than
|
||||
// re-deriving them.
|
||||
// This kernel's time is address arithmetic. size_t indexing gives each of the ~40 cache stores
|
||||
// and every input tap a 64-bit multiply. The strides are small, so offsets are 32-bit ints off
|
||||
// base pointers that carry the 64-bit part, and loops walk their pointers.
|
||||
const int csd = (int)cs_dim, cst = (int)cs_tok, xpi = (int)xpitch;
|
||||
unsigned short* const sp = cstate + (size_t)slot * cs_seq + (size_t)d0 * cs_dim;
|
||||
const unsigned short* const xrow = x + (size_t)bos * xpitch + d0;
|
||||
#if CU_ISSUE
|
||||
// Every input load of the step is issued before any is waited on; the cache rewrite below
|
||||
// reuses the same values.
|
||||
ushort4 xb[CU_MAXT];
|
||||
const bool xpre = (slen <= CU_MAXT);
|
||||
#pragma unroll
|
||||
for (int t = 0; t < CU_MAXT; ++t)
|
||||
if (xpre && t < slen) xb[t] = *(const ushort4*)(xrow + t * xpi);
|
||||
#endif
|
||||
float win[CP_W][CP_DPL];
|
||||
unsigned short hist[CP_ST][CP_DPL]; // the raw history, for the shifted rewrite
|
||||
{
|
||||
@@ -412,21 +354,7 @@ void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitc
|
||||
const int hq = unit, hk = unit - Hg, hv = unit - 2 * Hg;
|
||||
const int region = (unit < Hg) ? 0 : ((unit < 2 * Hg) ? 1 : 2);
|
||||
|
||||
// This step's inputs, all issued before the first is waited on. With the load inside the loop
|
||||
// each of the (num_spec + 1) four-tap taps pays an HBM round trip that nothing hides: a decode
|
||||
// step launches one wave per channel group, so there is no other wave on the SIMD to run
|
||||
// meanwhile. They are also exactly the values the cache rewrite at the bottom re-reads.
|
||||
#if !CU_ISSUE
|
||||
ushort4 xb[CU_MAXT];
|
||||
const bool xpre = (slen <= CU_MAXT);
|
||||
#pragma unroll
|
||||
for (int t = 0; t < CU_MAXT; ++t)
|
||||
if (xpre && t < slen) xb[t] = *(const ushort4*)(xrow + t * xpi);
|
||||
#endif
|
||||
|
||||
// The destination of a token is the previous one plus a fixed stride, so it is walked rather
|
||||
// than rebuilt: recomputing ((bos + t) * H + hv) * CP_HD per token is a 64-bit multiply each
|
||||
// time.
|
||||
// Output pointer walked by a fixed stride per token, avoiding a 64-bit multiply each.
|
||||
unsigned short* op = (region == 2)
|
||||
? (v + ((size_t)bos * H + hv) * CP_HD + lane * CP_DPL)
|
||||
: ((region ? k : q) + ((size_t)bos * Hg + (region ? hk : hq)) * CP_HD + lane * CP_DPL);
|
||||
@@ -452,10 +380,9 @@ void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitc
|
||||
_Pragma("unroll") \
|
||||
for (int c = 0; c < CP_DPL; ++c) win[i][c] = win[i + 1][c]; \
|
||||
}
|
||||
#if CU_STATIC
|
||||
if (xpre) {
|
||||
// A GUARD, NOT A BREAK. `#pragma unroll` needs a constant trip count; a data-dependent exit
|
||||
// leaves the loop rolled and `t` a runtime variable again, which is the whole thing being fixed.
|
||||
// A guard, not a break: a data-dependent exit would leave the loop rolled and t a runtime
|
||||
// index again.
|
||||
#pragma unroll
|
||||
for (int t = 0; t < CU_MAXT; ++t) {
|
||||
if (t < slen) CU_TOKEN_BODY(xb[t]) // static index: a register read, not a tree
|
||||
@@ -463,66 +390,40 @@ void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitc
|
||||
} else {
|
||||
for (int t = 0; t < slen; ++t) CU_TOKEN_BODY(*(const ushort4*)(xrow + t * xpi))
|
||||
}
|
||||
#else
|
||||
for (int t = 0; t < slen; ++t)
|
||||
CU_TOKEN_BODY(xpre ? xb[t] : *(const ushort4*)(xrow + t * xpi))
|
||||
#endif
|
||||
|
||||
// Rewrite the cache shifted by one: the tail of the old history, then this step's tokens. The
|
||||
// first CP_ST-1 entries are exactly the history already in registers, so the rewrite costs no
|
||||
// extra reads -- and reading before writing is what makes the in-place update safe.
|
||||
// Channel-major for the same reason as the prefill path, and it matters more here: this is
|
||||
// width-1 + num_spec slots per channel, so the slot-major order made it 44 strided 2-byte
|
||||
// stores per lane where channel-major is one 88-byte run.
|
||||
// The two halves of this run have different sources -- the tail of the old history, then this
|
||||
// step's tokens -- and testing for it per store put a branch and a select in front of every one
|
||||
// of the ~40. The split point is a loop bound instead. `nh` is CP_W-2 by construction
|
||||
// (state_len_max is (CP_W-1)+(maxq-1) and slen_eff takes off the tokens this sequence did not
|
||||
// bring), but it is computed rather than assumed so a caller that shrinks the window differently
|
||||
// still gets the shipped answer.
|
||||
// Rewrite the cache shifted by one: the tail of the old history (already in registers, read
|
||||
// before any write, so the in-place update is safe), then this step's tokens. Channel-major, as
|
||||
// in prefill: one contiguous run per lane instead of strided 2-byte stores.
|
||||
// The split between the two sources is a loop bound, not a per-store test. `nh` is CP_W-2 on the
|
||||
// shipped path but computed, so a caller that shrinks the window differently stays correct.
|
||||
const int VAL = CP_W - 2;
|
||||
const int nh = slen_eff - slen < 0 ? 0 : (slen_eff - slen);
|
||||
#pragma unroll
|
||||
for (int c = 0; c < CP_DPL; ++c) {
|
||||
unsigned short* dst = sp + c * csd;
|
||||
#if CU_STATIC
|
||||
// The history half is bounded by the array it reads: `hist[i + 1]` with i < nh already required
|
||||
// nh <= CP_ST - 1, so unrolling to that bound reads exactly what the runtime loop did.
|
||||
// History half, unrolled to hist's bound (i + 1 < CP_ST).
|
||||
#pragma unroll
|
||||
for (int i = 0; i + 1 < CP_ST; ++i)
|
||||
if (i < nh && i < slen_eff) dst[i * cst] = hist[i + 1][c];
|
||||
// The token half, walked by TOKEN rather than by slot, so the index into xb is the loop counter.
|
||||
// Token half, walked by token so the xb index is the loop counter.
|
||||
if (xpre) {
|
||||
#pragma unroll
|
||||
for (int t = 0; t < CU_MAXT; ++t) {
|
||||
const int i = t + VAL;
|
||||
if (i >= nh && i < slen_eff && t < slen) {
|
||||
// NOT `((const unsigned short*)&xb[t])[c]`. Taking the address of an element makes the
|
||||
// whole array address-taken, and an address-taken array does not become registers however
|
||||
// static the index is -- that one `&` costs 80 bytes a thread of SCRATCH under the
|
||||
// preload. With t and c both compile-time this ternary folds to a register read.
|
||||
// Not `((const unsigned short*)&xb[t])[c]`: taking an element's address forces the
|
||||
// whole array to scratch. With t and c compile-time, this ternary is a register read.
|
||||
const ushort4 vv = xb[t];
|
||||
dst[i * cst] = (c == 0) ? vv.x : (c == 1) ? vv.y : (c == 2) ? vv.z : vv.w;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Whatever the two loops above did not cover: a slot whose token is outside [0, slen), and the
|
||||
// whole range when the caller brought more tokens than the preload holds. Both are empty on the
|
||||
// shipped path (slen_eff is slen + CP_ST - 1 and nh is CP_W - 2), so this stores nothing.
|
||||
// Remainder: slots whose token is outside [0, slen), or the whole range when slen exceeds the
|
||||
// preload. Empty on the shipped path.
|
||||
for (int i = nh; i < slen_eff; ++i) {
|
||||
const int ti = i - VAL;
|
||||
if (!xpre || ti < 0 || ti >= slen) dst[i * cst] = xrow[ti * xpi + c];
|
||||
}
|
||||
#else
|
||||
int i = 0;
|
||||
for (; i < nh && i < slen_eff; ++i) dst[i * cst] = hist[i + 1][c];
|
||||
for (; i < slen_eff; ++i) {
|
||||
const int ti = i - VAL;
|
||||
dst[i * cst] = (xpre && ti >= 0 && ti < slen)
|
||||
? ((const unsigned short*)&xb[ti])[c]
|
||||
: xrow[ti * xpi + c];
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#undef CU_TOKEN_BODY
|
||||
}
|
||||
@@ -537,9 +438,8 @@ extern "C" int r4d_gdn_conv_update_w4_h128_bf16(
|
||||
const int units = 2 * Hg + H;
|
||||
int hpb = 8;
|
||||
while (hpb > 1 && (Hg % hpb || H % hpb)) hpb >>= 1;
|
||||
// A decode step is a handful of sequences, so the channel grouping is what decides whether the
|
||||
// grid covers the device: at 8 sequences and 8 heads per block this launches 40 workgroups for
|
||||
// 64 CUs. Narrow the block until there are enough of them.
|
||||
// A decode step has few sequences, so narrow the channel group until the grid covers the
|
||||
// device (8 sequences at 8 heads per block would be 40 workgroups for 64 CUs).
|
||||
while (hpb > 1 && (long)N * (units / hpb) < 256) hpb >>= 1;
|
||||
dim3 grid(N, units / hpb), blk(hpb * 32);
|
||||
#define CU_LAUNCH(P) \
|
||||
@@ -559,14 +459,9 @@ extern "C" int r4d_gdn_conv_update_w4_h128_bf16(
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
|
||||
// THE OPERAND ENUMS CARRY AN `OPD_` PREFIX: this kernel's own tile constants are already called
|
||||
// CP_W and CP_ST, and an unprefixed operand index named CP_W in the same translation unit is a
|
||||
// redefinition -- caught by the compiler, but only because the spellings happen to collide. The
|
||||
// prefix says which namespace a name is in.
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The shared operand helpers are r4d_gdn_args.h. See libr4d/r4d_args.h for why there is no
|
||||
// adapter directory between the core and these launches.
|
||||
// Shared operand helpers: r4d_gdn_args.h. Operand enums use an OPD_ prefix because CP_W and CP_ST
|
||||
// are already kernel constants in this unit.
|
||||
/* ------------------------------------------------------------------ conv prep */
|
||||
|
||||
|
||||
@@ -596,8 +491,8 @@ extern "C" int r4d_rad_gdn_conv_prep(const RadArgs* a, RadStream s) {
|
||||
|
||||
if (!x || !w || !alog || !dtb || !cst || !cu || !q || !k || !v || !g || !beta)
|
||||
return R4D_NO(RAD_E_INVAL);
|
||||
/* Optional in the SCHEMA so docs/OPS.md's shorter list stays a positional prefix, required by
|
||||
* the KERNEL: it dereferences all three unconditionally. Named rather than crashed. */
|
||||
/* Optional in the schema (so docs/OPS.md's shorter list stays a positional prefix) but
|
||||
* required here: the kernel dereferences all three. */
|
||||
if (!ta || !tb || !cidx) return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
if (x->rank < 2 || q->rank != 3 || k->rank != 3 || v->rank != 3) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -607,8 +502,8 @@ extern "C" int r4d_rad_gdn_conv_prep(const RadArgs* a, RadStream s) {
|
||||
int rc = seqs_of(cu, &N);
|
||||
if (rc != RAD_OK) return rc;
|
||||
|
||||
/* x may be a padded VIEW -- the qkvz split the layer hands it -- so its row pitch is an
|
||||
* argument. Its inner axes still have to be tight. */
|
||||
/* x may be a padded view (the layer's qkvz split), so its row pitch is an argument; inner
|
||||
* axes must be dense. */
|
||||
const long long xpitch = r4d_row_pitch(x);
|
||||
if (xpitch < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
const long long ab_stride = r4d_row_pitch(ta);
|
||||
@@ -633,32 +528,27 @@ extern "C" int r4d_rad_gdn_conv_prep(const RadArgs* a, RadStream s) {
|
||||
|
||||
const int width = (int)r4d_geti_or(a, "conv_width", 4);
|
||||
const float thr = (float)r4d_getf(a, "softplus_thr", 20.0);
|
||||
/* libr4d's l2 norm is rsqrt(ss + 1e-6f) with the epsilon COMPILED IN, not an argument. A
|
||||
* caller that names a different one is asking for arithmetic this kernel does not do, and
|
||||
* running it anyway would be a silently different normalisation. Refused by name instead. */
|
||||
/* The l2 norm epsilon is compiled in (1e-6f); refuse any other value. */
|
||||
if ((float)r4d_getf(a, "l2_eps", 1e-6) != 1e-6f) return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
/* `a` and `b` may be bf16 or f32; libr4d takes a flag rather than two entry points. */
|
||||
/* a and b may be bf16 or f32 (a flag, not two entry points). */
|
||||
const int ab_is_bf16 = (ta->dtype == RAD_BF16) ? 1 : 0;
|
||||
if (tb->dtype != ta->dtype) return R4D_NO(RAD_E_DTYPE);
|
||||
if (!ab_is_bf16 && ta->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
|
||||
|
||||
/* "bf16 x / weights / conv state / q,k,v out, fp32 a,b and gate/beta out". The CONV WEIGHT is
|
||||
* bf16: the kernel takes it as `const unsigned short*` and reads it through bf2f. */
|
||||
/* bf16 x, weights, conv state and q/k/v; fp32 A_log, dt_bias, g and beta. */
|
||||
R4D_DT(x, RAD_BF16); R4D_DT(w, RAD_BF16); R4D_DT(cst, RAD_BF16);
|
||||
R4D_DT(q, RAD_BF16); R4D_DT(k, RAD_BF16); R4D_DT(v, RAD_BF16);
|
||||
R4D_DT(alog, RAD_F32); R4D_DT(dtb, RAD_F32); R4D_DT(g, RAD_F32); R4D_DT(beta, RAD_F32);
|
||||
|
||||
return r4d_gdn_conv_prep_w4_h128_bf16(
|
||||
return R4D_RAW(r4d_gdn_conv_prep_w4_h128_bf16(
|
||||
x->data, (long)xpitch, w->data, b ? b->data : nullptr, cst->data,
|
||||
(long)cst->stride[0], (long)cst->stride[1], (long)cst->stride[2],
|
||||
cidx->data, (long)cidx->stride[0], hin ? hin->data : nullptr,
|
||||
/* The WIDTH of has_init, not a guess: the engine hands over RadBatch::ctx_lens, which is
|
||||
* int32 like every derived buffer. Reading it as bytes is silent for a cold first chunk
|
||||
* and wrong for every one after it. */
|
||||
/* has_init element width (see r4d_has_init) */
|
||||
hin && (hin->dtype == RAD_I32 || hin->dtype == RAD_U32),
|
||||
ta->data, tb->data, (long)ab_stride, ab_is_bf16,
|
||||
alog->data, dtb->data, q->data, k->data, v->data, g->data, beta->data,
|
||||
cu->data, N, (int)T, (int)H, (int)Hg, (int)K, (int)V, width, thr, s);
|
||||
cu->data, N, (int)T, (int)H, (int)Hg, (int)K, (int)V, width, thr, s));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ conv update */
|
||||
@@ -698,35 +588,29 @@ extern "C" int r4d_rad_gdn_conv_update(const RadArgs* a, RadStream s) {
|
||||
if (H == 0 || Hg == 0 || H % Hg) return R4D_NO(RAD_E_SHAPE);
|
||||
if (v->shape[0] != T || k->shape[0] != T) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* "bf16 x / weights / conv state / q,k,v out" -- same casts as the prefill conv. */
|
||||
/* bf16 x, weights, conv state and q/k/v, as in the prefill conv. */
|
||||
R4D_DT(x, RAD_BF16); R4D_DT(w, RAD_BF16); R4D_DT(cst, RAD_BF16);
|
||||
R4D_DT(q, RAD_BF16); R4D_DT(k, RAD_BF16); R4D_DT(v, RAD_BF16);
|
||||
|
||||
const int width = (int)r4d_geti_or(a, "conv_width", 4);
|
||||
/* THE TWO WINDOW ARGUMENTS DESCRIBE ONE WINDOW, SO ONLY ONE OF THEM IS FREE. The state cache
|
||||
* is a rolling window read at the slot the last ACCEPTED token left, which is how a
|
||||
* speculative rejection becomes a change of read offset rather than a recompute (spec 10).
|
||||
* The kernel lays it out as `width - 2` history entries followed by the step's tokens, and it
|
||||
* finds the split as `state_len_max - max_query_len` -- so that difference MUST be width - 2,
|
||||
* whatever the two of them are individually. The cache depth fixes one; the other follows.
|
||||
/* state_len_max and max_query_len describe one window, so only one is free. The state cache
|
||||
* is a rolling window read at the slot the last accepted token left, so a speculative
|
||||
* rejection is a change of read offset, not a recompute (spec 10). The kernel splits it into
|
||||
* `width - 2` history entries and the step's tokens at state_len_max - max_query_len, so that
|
||||
* difference must be width - 2; max_query_len follows from the cache depth.
|
||||
*
|
||||
* DO NOT DERIVE max_query_len FROM THE STEP. The mean tokens per sequence is wrong twice over:
|
||||
* it is not the max when one request in the step drafts and another does not, and even the max
|
||||
* is not what this kernel wants, because the pool is sized for the deepest draft the
|
||||
* DEPLOYMENT allows. A decode step that drafts nothing would then put the split at
|
||||
* width - 2 + n_spec instead of width - 2. The history half runs past what the kernel has in
|
||||
* registers, this step's tokens land outside the range the next step reads, and the
|
||||
* convolution advances over a window that never changes: the model stops hearing its own last
|
||||
* three tokens and repeats one phrase forever. */
|
||||
* Do not derive max_query_len from the step: the pool is sized for the deployment's deepest
|
||||
* draft, and a non-drafting step would misplace the split, so the convolution would stop
|
||||
* seeing the latest tokens and the model would loop on one phrase. */
|
||||
const long long state_len_max = cst->shape[2];
|
||||
const long long mql = state_len_max - (width - 2);
|
||||
if (width < 2 || mql < 1) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
return r4d_gdn_conv_update_w4_h128_bf16(
|
||||
return R4D_RAW(r4d_gdn_conv_update_w4_h128_bf16(
|
||||
x->data, (long)xpitch, w->data, b ? b->data : nullptr, cst->data,
|
||||
(long)cst->stride[0], (long)cst->stride[1], (long)cst->stride[2],
|
||||
(int)state_len_max, sidx->data, (long)sidx->stride[0],
|
||||
nacc ? nacc->data : nullptr, q->data, k->data, v->data, cu->data,
|
||||
N, (int)H, (int)Hg, (int)K, (int)V, width, (int)mql, s);
|
||||
N, (int)H, (int)Hg, (int)K, (int)V, width, (int)mql, s));
|
||||
}
|
||||
|
||||
@@ -1,22 +1,20 @@
|
||||
// r4d_gdn_gated_norm_had_quant_i8.hip - r4d_gdn_gated_norm_had_quant_i8: the GDN block's gated
|
||||
// RMS norm, the block Hadamard and the per-row int8 quantiser in one pass. This is out_proj's
|
||||
// input on the 48 linear-attention layers -- the fourth and last rotated site in a W4A8 layer.
|
||||
// r4d_gdn_gated_norm_had_quant_i8.hip -- the GDN block's gated RMS norm, block Hadamard and
|
||||
// per-row int8 quantiser in one pass: out_proj's input on the 48 linear-attention layers (the
|
||||
// fourth rotated site in a W4A8 layer).
|
||||
//
|
||||
// out = x * rsqrt(mean_head(x^2) + eps) * w * silu(z)
|
||||
//
|
||||
// TWO DIFFERENT EXTENTS IN ONE KERNEL, which is the whole reason it cannot reuse
|
||||
// r4d_gdn_gated_rmsnorm_h128_bf16. The RMS is per HEAD (head_v_dim = 128), while the rotation and
|
||||
// the int8 scale are per TOKEN, over the flattened H*128 that out_proj consumes. So the reduction
|
||||
// is segmented: a head is 128/VPL consecutive lanes, and an xor exchange with masks below that stays
|
||||
// inside one head by construction.
|
||||
// Two extents, which is why r4d_gdn_gated_rmsnorm_h128_bf16 cannot be reused: the RMS is per head
|
||||
// (head_v_dim = 128), while the rotation and int8 scale are per token over the flattened H*128.
|
||||
// The reduction is segmented: a head is 128/VPL consecutive lanes, and xor masks below that stay
|
||||
// inside one head.
|
||||
//
|
||||
// HAD=128 VPL=4 32 lanes/head one head per rotation block
|
||||
// HAD=256 VPL=8 16 lanes/head two heads per block
|
||||
// HAD=512 VPL=16 8 lanes/head four heads per block
|
||||
//
|
||||
// At width 128 the rotation lines up exactly with head boundaries and mixes only within a head;
|
||||
// wider widths mix across heads. That is not in itself a reason to prefer one: on this layout the
|
||||
// activation error is 0.00679 at width 128 against 0.00521 at 512, so the trade is already priced.
|
||||
// At width 128 the rotation mixes only within a head; wider widths mix across heads. Activation
|
||||
// error is 0.00679 at width 128 vs 0.00521 at 512.
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -25,11 +23,6 @@
|
||||
#include <cstdint>
|
||||
#include <cmath>
|
||||
|
||||
// 0 = choose the workgroup width from M at launch (see r4d_act_threads in r4d_common.h); a
|
||||
// non-zero build-time value pins one width instead.
|
||||
#ifndef R4D_GNHQ_THREADS
|
||||
#define R4D_GNHQ_THREADS 0
|
||||
#endif
|
||||
#define R4D_GNHQ_HEAD 128
|
||||
|
||||
template <int HAD, int THR>
|
||||
@@ -44,12 +37,9 @@ __global__ __launch_bounds__(THR) void r4d_gdn_gated_norm_had_quant_i8_kernel(
|
||||
const int row = blockIdx.x;
|
||||
const __hip_bfloat16* x = X + (size_t)row * xrow;
|
||||
const __hip_bfloat16* z = Z + (size_t)row * zrow;
|
||||
// zgrp != 0: Z is the INTERLEAVED qkvz projection rather than a compacted copy of the gate, so
|
||||
// element i of the flattened row lives at (i / zblk) * zgrp + (i % zblk). vLLM materialises that
|
||||
// copy with `z_out[:] = z` inside _forward_core_rocm; a single-sequence decode step pays it 48
|
||||
// times -- 94.5 us of kernel and as much again in launch gap -- for 65 KiB a layer this kernel
|
||||
// can read where it already is. `zblk` is a multiple of the rotation width, so a HAD-block never straddles
|
||||
// a group boundary and the offset is constant across the block.
|
||||
// zgrp != 0: Z is read in place from the interleaved qkvz projection (avoiding vLLM's
|
||||
// `z_out[:] = z` copy per layer): element i is at (i / zblk) * zgrp + (i % zblk). zblk is a
|
||||
// multiple of HAD, so a rotation block never straddles a group.
|
||||
const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
|
||||
|
||||
float m = 0.f;
|
||||
@@ -98,7 +88,7 @@ __global__ __launch_bounds__(THR) void r4d_gdn_gated_norm_had_quant_i8_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// The launch, as the plugin ABI's RadLaunchFn. See the note at the head of r4d_quant_act_i8.hip.
|
||||
// The plugin ABI launch (RadLaunchFn); see the note at the head of r4d_quant_act_i8.hip.
|
||||
enum { GG_X = 0, GG_Z, GG_W, GG_Q, GG_S };
|
||||
|
||||
extern "C" int r4d_rad_gdn_gated_norm_hq_i8(const RadArgs* args, RadStream stream) {
|
||||
@@ -127,14 +117,13 @@ extern "C" int r4d_rad_gdn_gated_norm_hq_i8(const RadArgs* args, RadStream strea
|
||||
const long long zrow = r4d_row_pitch(z);
|
||||
if (xrow < 0 || zrow < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
|
||||
// Z may be the INTERLEAVED qkvz projection rather than a compacted gate: element i of the
|
||||
// flattened row lives at (i / zblk) * zgrp + (i % zblk). 0 means contiguous.
|
||||
// Interleaved-gate layout (see the kernel); zgrp 0 means contiguous.
|
||||
const long long zgrp = r4d_geti_or(args, "zgrp", 0);
|
||||
const long long zblk = r4d_geti_or(args, "zblk", 0);
|
||||
if (zgrp && (zblk % had || zblk < had || zgrp < zblk)) return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
const float eps = (float)r4d_getf(args, "eps", 1e-6);
|
||||
const int thr = R4D_GNHQ_THREADS ? R4D_GNHQ_THREADS : r4d_act_threads((int)M, (int)K);
|
||||
const int thr = r4d_act_threads((int)M, (int)K);
|
||||
const size_t shmem = (size_t)K * sizeof(float) + (thr / 32) * sizeof(float);
|
||||
if (shmem > 65536) return R4D_NO(RAD_E_SCRATCH);
|
||||
const float rn = 1.f / sqrtf((float)had);
|
||||
@@ -144,7 +133,6 @@ extern "C" int r4d_rad_gdn_gated_norm_hq_i8(const RadArgs* args, RadStream strea
|
||||
(const __hip_bfloat16*)r4d_p(z), (const float*)r4d_p(w), (signed char*)r4d_wp(q), \
|
||||
(float*)r4d_wp(sc), (int)K, xr, zr, (int)zgrp, (int)zblk, eps, rn)
|
||||
#define R4D_GNHQ_T(H) switch (thr) { \
|
||||
case 128: R4D_GNHQ_LAUNCH(H, 128); break; \
|
||||
case 256: R4D_GNHQ_LAUNCH(H, 256); break; \
|
||||
case 512: R4D_GNHQ_LAUNCH(H, 512); break; \
|
||||
case 1024: R4D_GNHQ_LAUNCH(H, 1024); break; \
|
||||
@@ -156,5 +144,5 @@ extern "C" int r4d_rad_gdn_gated_norm_hq_i8(const RadArgs* args, RadStream strea
|
||||
}
|
||||
#undef R4D_GNHQ_T
|
||||
#undef R4D_GNHQ_LAUNCH
|
||||
return RAD_OK;
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
|
||||
}
|
||||
@@ -3,17 +3,14 @@
|
||||
//
|
||||
// out[r][d] = x[r][d] . rsqrt(mean_d(x[r][:]^2) + eps) . w[d] . act(z[r][d])
|
||||
//
|
||||
// one row per (token, head), 128 wide. It replaces FLA's `rmsnorm_fn` (mamba/ops/layernorm_gated),
|
||||
// which is the last Triton kernel in the layer.
|
||||
// one row per (token, head), 128 wide. Replaces FLA's `rmsnorm_fn` (mamba/ops/layernorm_gated).
|
||||
//
|
||||
// It exists as its own kernel only because the chunked scan cannot host it: that kernel's
|
||||
// workgroup owns 64 of the 128 v channels of a row (BV=64, and widening it to 128 leaves 24
|
||||
// workgroups on 64 CUs), while an RMS needs the whole row. The DECODE kernel does own the whole
|
||||
// row, so there the same arithmetic is fused into the epilogue and this kernel is not launched at
|
||||
// all -- see r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip.
|
||||
// A separate kernel because the chunked scan's workgroup owns only 64 of a row's 128 v channels
|
||||
// (BV=64; 128 would leave 24 workgroups on 64 CUs). The decode recurrent update owns whole rows and
|
||||
// fuses this into its epilogue (r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip).
|
||||
//
|
||||
// One wave per row, four channels per lane: the reduction is five shuffles with no LDS and no
|
||||
// barrier, and both loads and the store are one 8-byte access per lane.
|
||||
// One wave per row, four channels per lane: a barrier-free five-shuffle reduction, and one 8-byte
|
||||
// access per lane for each load and the store.
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "r4d.h"
|
||||
#include "r4d_gdn_args.h"
|
||||
@@ -42,10 +39,8 @@ void r4d_gdn_gated_rmsnorm_kernel(const unsigned short* __restrict__ x,
|
||||
const long r = (long)blockIdx.x * GN_NW + warp;
|
||||
if (r >= rows) return;
|
||||
const int d0 = lane * GN_DPL;
|
||||
// THE GATE CAN BE A COLUMN VIEW, and then its rows are not evenly spaced: the fp8 delta net
|
||||
// projects [q|k|v|z] in one GEMM, so within a token the `zheads` gate rows are `zrow` apart and
|
||||
// the next token is `ztok` away, which is wider. zheads <= 0 is the flat case and the one every
|
||||
// other caller passes.
|
||||
// The gate may be a column view of a fused [q|k|v|z] projection: within a token the `zheads`
|
||||
// gate rows are `zrow` apart and the next token is `ztok` away. zheads <= 0 is the flat case.
|
||||
const long zoff = zheads > 0 ? (r / zheads) * ztok + (r % zheads) * zrow : r * zrow;
|
||||
|
||||
const ushort4 xv = *(const ushort4*)(x + r * xrow + d0);
|
||||
@@ -88,9 +83,7 @@ extern "C" int r4d_gdn_gated_rmsnorm_h128_bf16(const void* x, const void* z, con
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The shared operand helpers are r4d_gdn_args.h. See libr4d/r4d_args.h for why there is no
|
||||
// adapter directory between the core and these launches.
|
||||
// Shared operand helpers: r4d_gdn_args.h.
|
||||
/* ------------------------------------------------------------------ gated rms norm */
|
||||
|
||||
enum { GN_X = 0, GN_Z, GN_W, GN_O };
|
||||
@@ -100,22 +93,17 @@ extern "C" int r4d_rad_gdn_gated_rmsnorm(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* z = r4d_opt(a, GN_Z);
|
||||
const RadTensor* w = r4d_opt(a, GN_W);
|
||||
const RadTensor* o = r4d_opt(a, GN_O);
|
||||
/* "bf16 x / z / out, fp32 weight". */
|
||||
/* bf16 x, z, out; fp32 weight. */
|
||||
R4D_DT(x, RAD_BF16); R4D_DT(z, RAD_BF16); R4D_DT(o, RAD_BF16); R4D_DT(w, RAD_F32);
|
||||
if (!x || !z || !w || !o) return R4D_NO(RAD_E_INVAL);
|
||||
if (x->rank < 2 || z->rank < 2 || o->rank < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE);
|
||||
|
||||
/* ONE ROW IS ONE (token, head), and the three operands do not agree on how that is spelled.
|
||||
* The norm's input and output are [tokens, heads, channels] -- rank 3, because the chunk scan
|
||||
* before them requires it -- while the gate arrives as the [tokens, heads*channels] projection
|
||||
* it was produced by. Both are the same rows in the same order; only the rank differs, and
|
||||
* taking the last axis as the width would refuse the gate for having 6144 columns instead of
|
||||
* 128. So the WIDTH comes from the op's `channels` (or x's last axis, which agrees), the row
|
||||
* COUNT comes from x's extent, and each operand's pitch is read according to which of the two
|
||||
* shapes it has. libr4d wants a pitch between consecutive (token, head) rows, which for a
|
||||
* flattened projection is the width itself and not the token stride. */
|
||||
/* One row is one (token, head). x and out are [tokens, heads, channels] (rank 3, as the chunk
|
||||
* scan requires) while the gate may be the flat [tokens, heads*channels] projection. So the
|
||||
* width comes from `channels` (or x's last axis), the row count from x, and each operand's
|
||||
* pitch between consecutive (token, head) rows is read per its shape. */
|
||||
const long long width = r4d_geti_or(a, "channels", x->shape[x->rank - 1]);
|
||||
if (width <= 0 || r4d_numel(x) % width) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long rows = r4d_numel(x) / width;
|
||||
@@ -125,31 +113,29 @@ extern "C" int r4d_rad_gdn_gated_rmsnorm(const RadArgs* a, RadStream s) {
|
||||
const long long orow = gn_row_pitch(o, width);
|
||||
if (xrow < 0 || orow < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
|
||||
/* AND THE GATE HAS A THIRD SPELLING: a COLUMN SLICE of a wider projection row, which the fp8
|
||||
* delta net hands it because [q|k|v|z] is one GEMM there. Its (token, head) rows are then not
|
||||
* evenly spaced -- heads are `width` apart inside a token and tokens are the slice's own
|
||||
* stride apart -- so one pitch cannot describe it and the kernel takes the head count too.
|
||||
* `zheads` is 0 for the two flat spellings, which is every other caller. */
|
||||
/* The gate may also be a column slice of a wider [q|k|v|z] row (fp8 delta net): heads are
|
||||
* `width` apart within a token and tokens are the slice's stride apart, so the kernel also
|
||||
* takes the head count. zheads stays 0 for the flat layouts. */
|
||||
long long zrow = gn_row_pitch(z, width), zheads = 0, ztok = 0;
|
||||
if (zrow < 0 && z->rank == 2 && z->stride[1] == 1 && z->shape[1] % width == 0) {
|
||||
zheads = z->shape[1] / width;
|
||||
ztok = z->stride[0];
|
||||
zrow = width;
|
||||
/* The gate's head count has to divide the row count, and where x spells its own it has to
|
||||
* agree: two operands disagreeing about how many heads a token carries would interleave
|
||||
* silently rather than run off the end. */
|
||||
/* The gate's head count must divide the row count and match x's head axis if it has one;
|
||||
* a mismatch would silently interleave rows. */
|
||||
if (zheads <= 0 || rows % zheads) return R4D_NO(RAD_E_SHAPE);
|
||||
if (x->rank >= 3 && x->shape[x->rank - 2] != zheads) return R4D_NO(RAD_E_SHAPE);
|
||||
}
|
||||
if (zrow < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
|
||||
const float eps = (float)r4d_getf(a, "eps", 1e-6);
|
||||
/* "silu" or "sigmoid". The integer libr4d wants is produced here and nowhere else. */
|
||||
/* "silu" (0) or "sigmoid" (1). */
|
||||
const int act = r4d_act_code(a, "act", nullptr, -1);
|
||||
if (act != 0 && act != 1) return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
return r4d_gdn_gated_rmsnorm_h128_bf16(x->data, z->data, w->data, o->data,
|
||||
(long)rows, (long)xrow, (long)zrow, (long)orow,
|
||||
(long)zheads, (long)ztok, (int)width, eps, act, s);
|
||||
return R4D_RAW(r4d_gdn_gated_rmsnorm_h128_bf16(x->data, z->data, w->data, o->data,
|
||||
(long)rows, (long)xrow, (long)zrow,
|
||||
(long)orow, (long)zheads, (long)ztok,
|
||||
(int)width, eps, act, s));
|
||||
}
|
||||
|
||||
@@ -2,117 +2,74 @@
|
||||
//
|
||||
// A = (I + strict_lower(diag(beta) . K K^T . e^{g_i - g_j}))^{-1} per chunk of 64
|
||||
//
|
||||
// It replaces FLA's chunk_scaled_dot_kkt_fwd + solve_tril, whose intermediate is a 64x64 fp32
|
||||
// matrix per (chunk, head) written to HBM and read straight back -- 16 KB in and 16 KB out per
|
||||
// chunk-head, for a matrix that is dead the moment the inverse is formed. Here the gram never
|
||||
// leaves LDS, and only the bf16 inverse is stored.
|
||||
// Replaces FLA's chunk_scaled_dot_kkt_fwd + solve_tril, whose 64x64 fp32 intermediate per
|
||||
// (chunk, head) round-trips through HBM. Here the gram stays in LDS and only the bf16 inverse is
|
||||
// stored. Also:
|
||||
//
|
||||
// Two structural wins over the pair it replaces, both from doing the whole thing at once:
|
||||
// * The gram is computed once per k head, not per v head: K K^T does not depend on beta or g,
|
||||
// so one workgroup owns a (chunk, k head) and applies each v head's scales to it.
|
||||
// * The gram is computed as its upper-triangle tiles. K K^T is symmetric, and read transposed
|
||||
// into A's strictly lower half each accumulator holds eight consecutive columns of one row:
|
||||
// one 16-byte LDS store instead of eight 2-byte ones.
|
||||
//
|
||||
// * THE GRAM IS COMPUTED ONCE PER K HEAD, NOT ONCE PER V HEAD. K K^T does not depend on beta or
|
||||
// g, and this model has three v heads per k head, so FLA computes the same 64x64x128 matmul
|
||||
// three times. One workgroup owns a (chunk, k head) and applies each v head's scales to the
|
||||
// gram it already holds in registers.
|
||||
// * THE GRAM IS COMPUTED IN ITS UPPER TRIANGLE. K K^T is symmetric, so the strictly LOWER half
|
||||
// of A can be read out of the upper tiles -- and that orientation is the one where a WMMA
|
||||
// accumulator's eight elements are eight CONSECUTIVE columns of one row of A, i.e. one
|
||||
// 16-byte LDS store instead of eight 2-byte ones.
|
||||
// The decay is applied per element as e^{g_i-g_j}, not split about a per-chunk reference c: each
|
||||
// half of e^{g_i-c} * e^{c-g_j} can overflow fp32 on its own. Here the exponent is always <= 0
|
||||
// (g decreases along the chunk and only i > j is kept), and the eight exps per tile are cheap in
|
||||
// a memory-bound kernel.
|
||||
//
|
||||
// The decay is applied as e^{g_i-g_j} PER ELEMENT, not split across a per-chunk reference. The
|
||||
// split form (e^{g_i-c} . e^{c-g_j}) is one exp per token instead of eight per tile, and it is what
|
||||
// the chunked scan uses -- but it only holds while the chunk's gate span stays inside fp32's
|
||||
// exponent range, and each half can overflow on its own even where the product cannot. Here the
|
||||
// difference is always <= 0 (g decreases along the chunk and only i > j is kept), so the direct
|
||||
// form cannot overflow at any span, and the exps it costs are eight per tile against a kernel
|
||||
// whose cost is memory.
|
||||
//
|
||||
// The inverse is blocked 16 -> 32 -> 64. The four diagonal blocks are inverted by fp32 forward
|
||||
// substitution (one wave each, one lane per column), which is both cheaper than a WMMA Neumann
|
||||
// series at this size and exact in fp32 -- FLA does the same thing for the same reason. The two
|
||||
// 32-merges and the 64-merge are WMMA, using the identity
|
||||
// The inverse is blocked 16 -> 32 -> 64. The four diagonal blocks use fp32 forward substitution
|
||||
// (one wave each, one lane per column), cheaper than a WMMA Neumann series at this size and exact
|
||||
// in fp32, as in FLA. The 32-merges and the 64-merge are WMMA, using
|
||||
//
|
||||
// [[P, 0], [R, Q]]^-1 = [[P^-1, 0], [-Q^-1 R P^-1, Q^-1]]
|
||||
//
|
||||
// Every buffer is named for the layout it holds because the WMMA contract fixes it:
|
||||
// mma(X, Y) computes X . Y^T from two row-major, k-contiguous operands, so a product's left
|
||||
// operand must be row-major and its right operand must be stored transposed. An accumulator
|
||||
// writes its transpose contiguously and its row-major form scattered, which is why the
|
||||
// intermediates below are staged transposed and the final M is assembled row-major (it is stored
|
||||
// to HBM by rows).
|
||||
// mma(X, Y) computes X . Y^T from two k-contiguous operands, so a left operand is row-major and a
|
||||
// right operand is stored transposed. An accumulator writes its transpose contiguously, so the
|
||||
// intermediates are staged transposed; the final inverse is assembled row-major for the HBM store.
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "r4d.h"
|
||||
#include "r4d_common.h" // lds_barrier
|
||||
#include "r4d_gdn_args.h"
|
||||
#include "r4d_gdn_wmma.h"
|
||||
|
||||
#define BT 64 // chunk
|
||||
#define KD 128 // head_k
|
||||
#define NBK 4 // 16x16 blocks per chunk edge
|
||||
#ifndef AP
|
||||
#define AP 68 // row pitch of the [BT][BT] buffers, in shorts. 136 B: 8-byte
|
||||
#endif // aligned for the paired stores, and 136 mod 128 has gcd 8 with
|
||||
// 128, so 16 rows still cover every bank
|
||||
#ifndef NW
|
||||
#define AP 68 // row pitch of the [BT][BT] buffers, in shorts (136 B): 8-byte
|
||||
// aligned for the paired stores, and 16 rows still cover every
|
||||
// bank
|
||||
#define NW 4
|
||||
#endif
|
||||
#define NTHR (NW * 32)
|
||||
#define NTILE 10 // upper-triangular tiles of a 4x4 tiling
|
||||
#define MAXT ((NTILE + NW - 1) / NW)
|
||||
|
||||
#ifndef LDSBAR
|
||||
#define LDSBAR 1
|
||||
#endif
|
||||
#if LDSBAR
|
||||
#define BAR() do { \
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); \
|
||||
__builtin_amdgcn_s_barrier(); \
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); \
|
||||
} while (0)
|
||||
#else
|
||||
#define BAR() __syncthreads()
|
||||
#endif
|
||||
|
||||
// LDS is what limits how many of these run per CU, and this kernel spends most of its time waiting
|
||||
// on memory -- so a buffer is worth keeping only if it buys more than the occupancy it costs. The
|
||||
// inverse's transposed form does not: it is needed as the right operand of three fragments per
|
||||
// head, and fragT rebuilds those from the row-major copy for eight scalar reads each.
|
||||
// ... and by the same argument the inverse does not need a buffer of its own either. Each stage
|
||||
// reads the block of A it is about to overwrite BEFORE writing it, and the stages are separated by
|
||||
// workgroup barriers, so the inverse can be formed in place:
|
||||
// LDS limits occupancy, and this kernel is memory-bound, so buffers are minimised. No transposed
|
||||
// inverse is kept (fragT rebuilds the three right operands that need it). The inverse is formed
|
||||
// in place in A, since each stage reads the block it overwrites before writing it, with barriers
|
||||
// between stages:
|
||||
// diagonal p reads A[p][p], writes it after the substitution has finished reading
|
||||
// 32-merge reads A10 and the two diagonal inverses, writes A10
|
||||
// 64-merge reads R = A[32:,:32] into registers everywhere, barriers, then writes it
|
||||
// That leaves one 64x64 buffer plus a 32x32 scratch: 11 KB, against 31 KB for a form that gives
|
||||
// every stage a buffer of its own.
|
||||
// 64-merge reads R = A[32:,:32] into TMP everywhere, barrier, then writes it
|
||||
// One 64x64 buffer plus a 32x32 scratch: 11 KB instead of 31 KB.
|
||||
struct KkSmem {
|
||||
unsigned short A[BT][AP]; // A on the way in, its inverse on the way out
|
||||
unsigned short TMP[32][36]; // one 32x32 intermediate, transposed
|
||||
float gb[BT], bt[BT]; // the chunk's gate cumsum and beta, per token
|
||||
};
|
||||
|
||||
// The (mt, nt) of the NTILE upper-triangular tiles, walked out arithmetically rather than read
|
||||
// from a __constant__ table: the table form is one byte load per tile from a segment this kernel
|
||||
// is otherwise never touching, and it is wave-uniform arithmetic either way.
|
||||
// (mt, nt) of upper-triangular tile ti, computed with wave-uniform arithmetic instead of a
|
||||
// __constant__ table load.
|
||||
__device__ __forceinline__ void kkt_tile(int ti, int* mt, int* nt) {
|
||||
int m = 0, n = ti;
|
||||
while (n >= NBK - m) { n -= (NBK - m); ++m; }
|
||||
*mt = m; *nt = n + m;
|
||||
}
|
||||
|
||||
// OCC: minimum waves per SIMD to compile for. This kernel is memory wait, not arithmetic
|
||||
// (~2000 instructions per wave against its wall clock), so occupancy is its lever -- and at
|
||||
// HG_RATIO=3 it lands on 190 VGPRs, which caps it at 8 waves/SIMD where its 11.5 KB of LDS
|
||||
// would allow 10. The trade does not pay: OCC=10 reaches 10 waves (144 VGPRs) but spills 148
|
||||
// bytes per lane and runs about 57% slower. Left at 0.
|
||||
#ifndef OCC
|
||||
#define OCC 0
|
||||
#endif
|
||||
// No occupancy hint: at HG_RATIO=3 the kernel uses 190 VGPRs (8 waves per SIMD; LDS would allow
|
||||
// 10), and forcing 10 waves spills 148 bytes per lane and is ~57% slower.
|
||||
template <int HG_RATIO>
|
||||
__global__
|
||||
#if OCC
|
||||
__launch_bounds__(NTHR, OCC)
|
||||
#else
|
||||
__launch_bounds__(NTHR)
|
||||
#endif
|
||||
void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
const float* __restrict__ beta,
|
||||
const float* __restrict__ g,
|
||||
@@ -125,10 +82,9 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
const int lo = lane & 15, hi = lane >> 4;
|
||||
const int hg = blockIdx.y;
|
||||
|
||||
// Resolve the flat chunk id to (sequence, chunk). The grid is launched with an upper bound on
|
||||
// the total chunk count, so this also decides which workgroups have nothing to do -- it costs
|
||||
// N+1 scalar loads and saves the host a device-to-host sync it would otherwise need to size the
|
||||
// grid exactly.
|
||||
// Resolve the flat chunk id to (sequence, chunk). The grid is an upper bound on the chunk
|
||||
// count, so surplus workgroups exit here; this saves the host a device-to-host sync to size
|
||||
// the grid exactly.
|
||||
int n = -1, t0 = 0, bos = 0, rows = 0;
|
||||
{
|
||||
int acc = 0, want = blockIdx.x;
|
||||
@@ -142,11 +98,8 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
if (n < 0) return;
|
||||
}
|
||||
|
||||
// ---- zero the parts no store ever reaches: the upper tiles of A, and everything in M / MT
|
||||
// outside the blocks the inverse writes. Done once; the write pattern is the same for every
|
||||
// head, so it cannot be dirtied between heads.
|
||||
// 16 bytes per thread per step, not 2: as shorts this is 34 ds_store_b16 per thread for a
|
||||
// buffer that is 8704 bytes and 16-byte aligned.
|
||||
// ---- zero A once: the parts no store reaches (the upper tiles) are the same for every head.
|
||||
// 16-byte stores (the buffer is 8704 bytes, 16-byte aligned).
|
||||
for (int i = tid; i < BT * AP / 8; i += NTHR) ((uint4*)&s.A[0][0])[i] = make_uint4(0, 0, 0, 0);
|
||||
|
||||
// ---- the gram, once for all HG_RATIO v heads of this k head -----------------------------
|
||||
@@ -160,10 +113,7 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
const int ti = warp + t * NW;
|
||||
if (ti < NTILE) {
|
||||
int mt, nt; kkt_tile(ti, &mt, &nt);
|
||||
// One 32-bit element offset per operand row, hoisted out of the k loop. The pointer form
|
||||
// (fragG) rebuilds v_mad_co_i64_i32 + v_lshlrev_b64 + a 64-bit add for EVERY one of the
|
||||
// sixteen fragments, because the size_t row stride forces 64-bit arithmetic and LLVM will
|
||||
// not keep the address live across the loop.
|
||||
// One 32-bit offset per operand row, hoisted out of the k loop (see rowGo/fragGo).
|
||||
const unsigned om = rowGo(krow, mt * 16, rows - 1, lane);
|
||||
const unsigned on = rowGo(krow, nt * 16, rows - 1, lane);
|
||||
#pragma unroll
|
||||
@@ -181,12 +131,12 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
s.gb[tid] = g[(size_t)(bos + t0 + t) * H + hv];
|
||||
s.bt[tid] = beta[(size_t)(bos + t0 + t) * H + hv];
|
||||
}
|
||||
BAR();
|
||||
lds_barrier();
|
||||
|
||||
// ---- scale, mask and place the gram as the strictly lower half of A ---------------------
|
||||
// Tile (mt, nt) holds P[m][n]; the element written is A[n][m] = rs[n] gv[m] P[m][n], which is
|
||||
// in the lower triangle exactly when n > m. n is fixed per lane and m runs over the eight
|
||||
// accumulator elements, so this is one row of A and one 16-byte store.
|
||||
// Tile (mt, nt) holds P[m][n]; the element written is A[n][m], in the lower triangle when
|
||||
// n > m. n is fixed per lane and m runs over the eight accumulator elements: one row of A,
|
||||
// one 16-byte store.
|
||||
#pragma unroll
|
||||
for (int t = 0; t < MAXT; ++t) {
|
||||
const int ti = warp + t * NW;
|
||||
@@ -201,14 +151,10 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int j = j0 + e;
|
||||
// i > j means g_i <= g_j, so this exponent is never positive whatever the span is --
|
||||
// but ONLY for a live row. On a padding row (i >= rows) gi is forced to 0 above while
|
||||
// gb[j] keeps its real, negative cumsum, so gi - gb[j] = -gb[j] is large POSITIVE,
|
||||
// __expf overflows to +INF, and bi * INF = 0 * INF = NaN. Those NaNs sit in padding
|
||||
// rows of the 64x64 tile, and the blocked inverse below merges the whole tile with
|
||||
// WMMA, so they reach live rows and poison the chunk's output for the head. On real
|
||||
// Qwen3.8-27B inputs that is a handful of non-finite values in A, which chunk_scan then
|
||||
// spreads across an entire head_v-wide head of the layer output.
|
||||
// For a live row, i > j gives g_i <= g_j, so the exponent is never positive. Padding
|
||||
// rows and columns must be masked to -inf: with gi = 0 the exponent -gb[j] is large and
|
||||
// positive, 0 * inf = NaN, and the WMMA merges in the blocked inverse would spread it
|
||||
// into live rows.
|
||||
const float d = (live && i > j && j < rows) ? (gi - s.gb[j]) : -INFINITY;
|
||||
vv[e] = bi * __expf(d) * P[t][e];
|
||||
}
|
||||
@@ -216,11 +162,11 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
*(uint2*)(&s.A[i][j0 + 4]) = f2bf4(vv[4], vv[5], vv[6], vv[7]);
|
||||
}
|
||||
}
|
||||
BAR();
|
||||
lds_barrier();
|
||||
|
||||
// ---- 1. the four diagonal blocks, by fp32 forward substitution --------------------------
|
||||
// D = (I + N)^-1 solves D = I - N D one row at a time. Lane l owns column l of D, so the
|
||||
// dot product over j < i is 16 registers deep and N[i][j] is a broadcast LDS read.
|
||||
// D = (I + N)^-1 solves D = I - N D row by row. Lane l owns column l of D, so the dot product
|
||||
// over j < i is in 16 registers and N[i][j] is a broadcast LDS read.
|
||||
for (int p = warp; p < NBK; p += NW) {
|
||||
const int b0 = p * 16;
|
||||
float d[16];
|
||||
@@ -237,7 +183,7 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
for (int i = 0; i < 16; ++i) s.A[b0 + i][b0 + lo] = f2bf(d[i]);
|
||||
}
|
||||
}
|
||||
BAR();
|
||||
lds_barrier();
|
||||
|
||||
// ---- 2. the two 32-merges: M10 = -D1 A10 D0 --------------------------------------------
|
||||
for (int blk = warp; blk < 2; blk += NW) {
|
||||
@@ -246,11 +192,10 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
v8f X = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
X = mma(frag(&s.A[0][0], AP, r0 + 16, r0, lane),
|
||||
fragT(&s.A[0][0], AP, r0, r0, lane), X);
|
||||
// stage X transposed for the next product. The two merges run on two waves against the
|
||||
// same scratch, so each owns 16 rows of it.
|
||||
// Stage X transposed for the next product; each of the two merges owns 16 rows of TMP.
|
||||
*(uint2*)(&s.TMP[blk * 16 + lo][8 * hi]) = f2bf4(X[0], X[1], X[2], X[3]);
|
||||
*(uint2*)(&s.TMP[blk * 16 + lo][8 * hi + 4]) = f2bf4(X[4], X[5], X[6], X[7]);
|
||||
// fragT reads A column-wise below, so the merge result only needs the row-major copy
|
||||
// fragT reads A column-wise below, so the merge result needs only the row-major copy
|
||||
__builtin_amdgcn_wave_barrier();
|
||||
// M10 = -D1 . X (left D1 row-major, in place in A; right X transposed, in TMP)
|
||||
v8f Y = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
@@ -261,7 +206,7 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) s.A[i + e][j] = f2bf(-Y[e]);
|
||||
}
|
||||
BAR();
|
||||
lds_barrier();
|
||||
|
||||
// ---- 3. the 64-merge: M[32:,:32] = -Q^-1 (R P^-1) --------------------------------------
|
||||
// Y = R . P^-1, R = A[32:,:32] row-major, P^-1 read transposed out of A[:32,:32] by fragT
|
||||
@@ -275,7 +220,7 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
*(uint2*)(&s.TMP[nt * 16 + lo][mt * 16 + 8 * hi]) = f2bf4(Y[0], Y[1], Y[2], Y[3]);
|
||||
*(uint2*)(&s.TMP[nt * 16 + lo][mt * 16 + 8 * hi + 4]) = f2bf4(Y[4], Y[5], Y[6], Y[7]);
|
||||
}
|
||||
BAR(); // every wave has read R into TMP; now it may be overwritten
|
||||
lds_barrier(); // every wave has read R into TMP; now it may be overwritten
|
||||
// Z = -Q^-1 . Y, Q^-1 = A[32:,32:] row-major, Y transposed = TMP
|
||||
for (int t = warp; t < 4; t += NW) {
|
||||
const int mt = t >> 1, nt = t & 1;
|
||||
@@ -289,7 +234,7 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) s.A[i + e][j] = f2bf(-Z[e]);
|
||||
}
|
||||
BAR();
|
||||
lds_barrier();
|
||||
|
||||
// ---- store: one row of the inverse is 64 bf16, contiguous in HBM -----------------------
|
||||
{
|
||||
@@ -300,7 +245,7 @@ void r4d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
*(uint4*)(op + (size_t)r * orow + c8) = *(const uint4*)(&s.A[r][c8]);
|
||||
}
|
||||
}
|
||||
if (hh + 1 < HG_RATIO) BAR();
|
||||
if (hh + 1 < HG_RATIO) lds_barrier();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -330,9 +275,7 @@ extern "C" int r4d_gdn_kkt_solve_k128_c64_bf16(const void* k, const void* beta,
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The shared operand helpers are r4d_gdn_args.h. See libr4d/r4d_args.h for why there is no
|
||||
// adapter directory between the core and these launches.
|
||||
// Shared operand helpers: r4d_gdn_args.h.
|
||||
/* ------------------------------------------------------------------ kkt solve */
|
||||
|
||||
enum { KS_K = 0, KS_BETA, KS_G, KS_CU, KS_A };
|
||||
@@ -348,8 +291,7 @@ extern "C" int r4d_rad_gdn_kkt_solve(const RadArgs* a, RadStream s) {
|
||||
if (k->rank != 3 || bt->rank != 2 || g->rank != 2 || A->rank != 3) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!r4d_contig(k) || !r4d_contig(bt) || !r4d_contig(g) || !r4d_contig(A))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
/* "bf16 k and A out, fp32 beta / gate / gram / inverse" -- and `A` is the OUT, written as
|
||||
* unsigned short by r4d_gdn_kkt_solve_kernel. */
|
||||
/* bf16 k and A (the output, written as bf16); fp32 beta and gate. */
|
||||
R4D_DT(k, RAD_BF16); R4D_DT(A, RAD_BF16); R4D_DT(bt, RAD_F32); R4D_DT(g, RAD_F32);
|
||||
|
||||
int N = 0;
|
||||
@@ -365,7 +307,8 @@ extern "C" int r4d_rad_gdn_kkt_solve(const RadArgs* a, RadStream s) {
|
||||
if (A->shape[0] != T || A->shape[1] != H) return R4D_NO(RAD_E_SHAPE);
|
||||
if (H == 0 || Hg == 0 || H % Hg) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
return r4d_gdn_kkt_solve_k128_c64_bf16(k->data, bt->data, g->data, A->data, cu->data,
|
||||
N, (int)T, (int)H, (int)Hg, (int)K, (int)chunk, s);
|
||||
return R4D_RAW(r4d_gdn_kkt_solve_k128_c64_bf16(k->data, bt->data, g->data, A->data,
|
||||
cu->data, N, (int)T, (int)H, (int)Hg, (int)K,
|
||||
(int)chunk, s));
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+20
-60
@@ -2,17 +2,16 @@
|
||||
// Layout (probed on this hardware, not documented by AMD):
|
||||
// 16-bit A/B : idx = lane%16 , k = 8*(e>>2) + 4*(lane>>4) + (e&3) ("two runs of four")
|
||||
// f32 C/D : n = lane%16 , m = 8*(lane>>4) + e
|
||||
// So A wants [M][K] and B wants [N][K] -- both K-contiguous -- and a D written to an
|
||||
// [N][M] buffer is one contiguous 8-element store while [M][N] costs eight scalar ones.
|
||||
// So A wants [M][K] and B wants [N][K] (both K-contiguous), and D stored to an [N][M] buffer is
|
||||
// one contiguous 8-element store, while [M][N] costs eight scalar ones.
|
||||
#pragma once
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
typedef __bf16 v8bf __attribute__((ext_vector_type(8)));
|
||||
typedef float v8f __attribute__((ext_vector_type(8)));
|
||||
|
||||
// gfx1201 has no bf16 convert instruction, so this is software. Round-half-away
|
||||
// (u + 0x8000) is one add where RTNE needs bfe + add3 + shift; the two differ only
|
||||
// when the discarded mantissa is exactly 0x8000, i.e. ~2^-16 of values.
|
||||
// Software f32 -> bf16 (gfx1201 has no convert). Round-half-away (u + 0x8000) is one add where
|
||||
// RTNE needs bfe + add3 + shift; they differ only when the discarded bits are exactly 0x8000.
|
||||
__device__ __forceinline__ unsigned short f2bf(float f) {
|
||||
return (unsigned short)((__builtin_bit_cast(unsigned, f) + 0x8000u) >> 16);
|
||||
}
|
||||
@@ -26,29 +25,16 @@ __device__ __forceinline__ unsigned f2bf2(float a, float b) {
|
||||
__device__ __forceinline__ uint2 f2bf4(float a, float b, float c, float d) {
|
||||
return make_uint2(f2bf2(a, b), f2bf2(c, d));
|
||||
}
|
||||
// Truncating pack: ONE v_perm_b32 per pair. The +0x8000 rounding adds cannot be
|
||||
// dual-issued (VOPD rejects the literal), so each is a full VALU slot -- 96 per chunk.
|
||||
// Truncation costs up to 1 ULP of bf16 instead of 0.5.
|
||||
__device__ __forceinline__ unsigned f2bf2t(float a, float b) {
|
||||
return __builtin_amdgcn_perm(__builtin_bit_cast(unsigned, b),
|
||||
__builtin_bit_cast(unsigned, a), 0x07060302u);
|
||||
}
|
||||
__device__ __forceinline__ uint2 f2bf4t(float a, float b, float c, float d) {
|
||||
return make_uint2(f2bf2t(a, b), f2bf2t(c, d));
|
||||
}
|
||||
__device__ __forceinline__ float bf2f(unsigned short h) {
|
||||
return __builtin_bit_cast(float, (unsigned)h << 16);
|
||||
}
|
||||
|
||||
// K-contiguous fragment from a row pointer already advanced to this lane's row and
|
||||
// half-K. The four dwords are indexed off ONE base so the assembler folds them into
|
||||
// two ds_read2_b32 with immediate offsets; writing `p + 8` instead makes LLVM
|
||||
// materialise a second address register per fragment (262 v_add_nc_u32 in the loop).
|
||||
// The four dwords are two 8-BYTE groups 16 bytes apart, so reading them as uint2 gets
|
||||
// one ds_load_2addr_b64 where reading them as four unsigned gets two ds_load_2addr_b32:
|
||||
// LLVM will only pair dwords into a b64 access if the pointer proves 8-byte alignment,
|
||||
// which every fragment address has (all row pitches are multiples of 4 shorts and the
|
||||
// lane's k offset is 4*(lane>>4)). Halves the fragment-load instruction count.
|
||||
// K-contiguous fragment from a row pointer already advanced to this lane's row and half-K.
|
||||
// Indexed off one base so the loads take immediate offsets (`p + 8` makes LLVM materialise a
|
||||
// second address register per fragment). The data is two 8-byte groups 16 bytes apart; reading
|
||||
// them as uint2 gives one ds_load_2addr_b64 instead of two ds_load_2addr_b32. LLVM pairs into b64
|
||||
// only with provable 8-byte alignment, which holds: row pitches are multiples of 4 shorts and the
|
||||
// lane's k offset is 4*(lane>>4).
|
||||
__device__ __forceinline__ v8bf fragP(const unsigned short* p) {
|
||||
const uint2* pw = (const uint2*)p;
|
||||
union { uint2 w[2]; v8bf f; } u;
|
||||
@@ -60,22 +46,12 @@ __device__ __forceinline__ const unsigned short* rowP(const unsigned short* src,
|
||||
int pitch, int base, int lane) {
|
||||
return src + (base + (lane & 15)) * pitch + 4 * (lane >> 4);
|
||||
}
|
||||
// Row pointer for a global source; `lim` clamps so a partial last chunk cannot read
|
||||
// past the tensor (those rows are discarded downstream).
|
||||
__device__ __forceinline__ const unsigned short* rowG(const unsigned short* base,
|
||||
size_t rowstride, int row0,
|
||||
int lim, int lane) {
|
||||
int r = row0 + (lane & 15); r = r < lim ? r : lim;
|
||||
return base + (size_t)r * rowstride + 4 * (lane >> 4);
|
||||
}
|
||||
// 32-BIT element offset for a global fragment source, split from a UNIFORM base.
|
||||
// The pointer form above compiles to ~13 instructions per fragment at this kernel's
|
||||
// register pressure: the `size_t` row stride forces v_mad_co_i64_i32 + v_lshlrev_b64 +
|
||||
// a 64-bit add, the ternary becomes exec-mask manipulation, LLVM will not keep the
|
||||
// address live across the k loop so it remats all of it per load, and a generic
|
||||
// pointer emits flat_load (which bumps BOTH loadcnt and dscnt on gfx12, so an LDS
|
||||
// drain also waits on HBM). Keeping the offset in one 32-bit register instead lets
|
||||
// the whole k loop be global_load_b64 vdst, voff, s[base] with a 13-bit immediate.
|
||||
// 32-bit element offset for a global fragment, split from a uniform base. `lim` clamps the row so a
|
||||
// partial last chunk cannot read past the tensor (those rows are discarded downstream). A per-lane
|
||||
// 64-bit row pointer costs ~13 instructions per fragment under register pressure (64-bit stride
|
||||
// math, exec-mask ternary, rematerialised per load) and can emit flat_load, which on gfx12 bumps
|
||||
// both loadcnt and dscnt so LDS drains also wait on memory. A 32-bit offset makes the k loop
|
||||
// global_load_b64 vdst, voff, s[base] with a 13-bit immediate.
|
||||
__device__ __forceinline__ unsigned rowGo(unsigned rowstride, int row0, int lim,
|
||||
int lane) {
|
||||
int r = row0 + (lane & 15); r = r < lim ? r : lim;
|
||||
@@ -87,14 +63,10 @@ __device__ __forceinline__ v8bf fragGo(const unsigned short* base, unsigned off)
|
||||
u.w[0] = pw[0]; u.w[1] = pw[2];
|
||||
return u.f;
|
||||
}
|
||||
// Fragment from a 32-BIT LDS BYTE OFFSET off the shared-block base. LDS row pointers
|
||||
// into different buffers of a large __shared__ block are further apart than
|
||||
// ds_read2_b32's immediate reach (8-bit fields in dwords = 1020 B), so LLVM will not
|
||||
// keep one base register per buffer live -- it rematerialises
|
||||
// `v_add_nc_u32 vaddr, <buffer_const>, vbase` in front of EVERY fragment, and then
|
||||
// splits the fragment's two dword pairs across two address registers as well.
|
||||
// Holding the offset in one opaque register instead makes all 8 k steps immediates
|
||||
// (8 dwords apart, 61 max -- well inside the field).
|
||||
// Fragment from a 32-bit LDS byte offset off the shared-block base. Buffers in a large __shared__
|
||||
// block are further apart than ds_read2_b32's immediate reach (1020 B), so LLVM rematerialises
|
||||
// `v_add_nc_u32 vaddr, <buffer_const>, vbase` before every fragment. An opaque offset register
|
||||
// (LDSOPAQUE) keeps all 8 k steps as immediates (8 dwords apart, 61 max).
|
||||
__device__ __forceinline__ v8bf fragO(const char* sb, unsigned off) {
|
||||
const uint2* pw = (const uint2*)(sb + off);
|
||||
union { uint2 w[2]; v8bf f; } u;
|
||||
@@ -137,15 +109,3 @@ __device__ __forceinline__ v8f gemm(const unsigned short* A, int Ap, int mt,
|
||||
acc = mma(frag(A, Ap, mt * 16, s * 16, lane), frag(B, Bp, nt * 16, s * 16, lane), acc);
|
||||
return acc;
|
||||
}
|
||||
|
||||
// Fragment straight from global memory (no LDS staging). `lim` clamps the row so a
|
||||
// partial last chunk cannot read past the tensor; those rows are discarded downstream.
|
||||
__device__ __forceinline__ v8bf fragG(const unsigned short* base, size_t rowstride,
|
||||
int row0, int lim, int kbase, int lane) {
|
||||
int r = row0 + (lane & 15); r = r < lim ? r : lim;
|
||||
const unsigned short* p = base + (size_t)r * rowstride + kbase + 4 * (lane >> 4);
|
||||
union { unsigned w[4]; v8bf f; } u;
|
||||
u.w[0] = ((const unsigned*)p)[0]; u.w[1] = ((const unsigned*)p)[1];
|
||||
u.w[2] = ((const unsigned*)(p + 8))[0]; u.w[3] = ((const unsigned*)(p + 8))[1];
|
||||
return u.f;
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
// r4d_gelu_mul_quant_i8.hip - r4d_gelu_mul_quant_i8: gelu(gate) * up and the per-row int8 quantiser
|
||||
// r4d_gemm_w4a8_nt_m64 reads, in one pass over the row.
|
||||
//
|
||||
// The down projection's input of a GELU-gated feed-forward (Gemma) on a w4a8 grid: unfused it is
|
||||
// gelu_mul and quant_act_i8, two single-row dispatches at a decode batch. This is the pair as one,
|
||||
// BYTE-IDENTICAL to it: the product is formed exactly as gelu_mul_kernel forms it (the tanh form,
|
||||
// the same constants, rounded to bf16), and the absmax, scale and codes are quant_act_i8's over
|
||||
// those bf16 values -- the absmax is a max and so takes no partition, and every code is a function
|
||||
// of its own value and the row scale.
|
||||
// The down projection's input of a GELU-gated feed-forward (Gemma) on a w4a8 grid, replacing the
|
||||
// gelu_mul + quant_act_i8 pair and byte-identical to it: the product is formed as gelu_mul_kernel
|
||||
// forms it (tanh form, same constants, rounded to bf16), and the absmax, scale and codes are
|
||||
// quant_act_i8's over those bf16 values. The absmax is a max, so partitioning does not change it.
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
@@ -15,8 +13,6 @@
|
||||
|
||||
namespace {
|
||||
|
||||
__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); }
|
||||
|
||||
template <uint32_t THR>
|
||||
__global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel(
|
||||
const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S,
|
||||
@@ -29,13 +25,13 @@ __global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel(
|
||||
|
||||
float m = 0.0f;
|
||||
for (uint32_t i = threadIdx.x; i < n; i += THR) {
|
||||
const float g = bf2f(gr[i]);
|
||||
const float g = bf16_to_f32(gr[i]);
|
||||
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
|
||||
const float gelu = 0.5f * g * (1.0f + tanhf(k0 * (g + k1 * g * g * g)));
|
||||
const uint16_t y = f32_to_bf16(gelu * bf2f(gr[n + i]));
|
||||
const uint16_t y = f32_to_bf16(gelu * bf16_to_f32(gr[n + i]));
|
||||
ybuf[i] = y;
|
||||
if (yo) yo[(size_t)row * y_ld + i] = y;
|
||||
m = fmaxf(m, fabsf(bf2f(y)));
|
||||
m = fmaxf(m, fabsf(bf16_to_f32(y)));
|
||||
}
|
||||
m = r4d_wave_max(m);
|
||||
if ((threadIdx.x & 31) == 0) lm[threadIdx.x >> 5] = m;
|
||||
@@ -50,7 +46,7 @@ __global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel(
|
||||
for (uint32_t i = threadIdx.x; i < n; i += THR) {
|
||||
const uint32_t s = i >> 4, j = i & 15;
|
||||
const uint32_t src = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3);
|
||||
const int t = __float2int_rn(bf2f(ybuf[src]) * inv);
|
||||
const int t = __float2int_rn(bf16_to_f32(ybuf[src]) * inv);
|
||||
qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
|
||||
}
|
||||
}
|
||||
@@ -61,7 +57,7 @@ __global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel(
|
||||
// fragment order, scale [M][1] f32, out_bf16 [M][n] bf16 optional.
|
||||
enum { GM_GU = 0, GM_Q, GM_S, GM_Y };
|
||||
|
||||
static int rad_gelu_mul_quant_i8_body(const RadArgs* a, const R4dSink& sk) {
|
||||
extern "C" int r4d_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream stream) {
|
||||
int emit_rc = RAD_OK;
|
||||
const RadTensor* gu = r4d_opt(a, GM_GU);
|
||||
const RadTensor* q = r4d_opt(a, GM_Q);
|
||||
@@ -83,7 +79,7 @@ static int rad_gelu_mul_quant_i8_body(const RadArgs* a, const R4dSink& sk) {
|
||||
const size_t lds = (size_t)n * sizeof(uint16_t);
|
||||
if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE);
|
||||
const int thr = r4d_act_threads((int)M, (int)n);
|
||||
#define R4D_GMQ_T(T) emit_rc = R4D_EMIT(sk, (gelu_mul_quant_i8_kernel<T>), dim3((uint32_t)M), dim3(T), lds, \
|
||||
#define R4D_GMQ_T(T) emit_rc = R4D_EMIT(stream, (gelu_mul_quant_i8_kernel<T>), dim3((uint32_t)M), dim3(T), lds, \
|
||||
(const uint16_t*)r4d_p(gu), (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), \
|
||||
(uint32_t)n, (uint32_t)gp, (uint32_t)yp)
|
||||
if (thr == 1024) R4D_GMQ_T(1024);
|
||||
@@ -93,4 +89,3 @@ static int rad_gelu_mul_quant_i8_body(const RadArgs* a, const R4dSink& sk) {
|
||||
#undef R4D_GMQ_T
|
||||
return emit_rc;
|
||||
}
|
||||
R4D_ENTRY(r4d_rad_gelu_mul_quant_i8, rad_gelu_mul_quant_i8_body)
|
||||
+138
-279
@@ -1,13 +1,11 @@
|
||||
/* r4d_gemm_args.h -- the skinny GEMMs' operand list and their split law.
|
||||
/* r4d_gemm_args.h -- the skinny GEMMs' operand lists and their split law.
|
||||
*
|
||||
* The launch law -- ladders, caps, `pick_sk`, a bound rule per weight grid -- lives beside the
|
||||
* kernels it decides for, so a kernel library built out of tree carries its own rule instead of
|
||||
* depending on one held in the engine. The declared tunable axes (r4d_rows.cpp) are the half of
|
||||
* that a tuner walks; this is the half that answers when a shape is left on the axis defaults.
|
||||
* The launch law (ladders, caps, `pick_sk`, a bound rule per weight grid) lives beside the kernels
|
||||
* so an out-of-tree kernel library carries its own rule. The tunable axes (r4d_rows.cpp) are what
|
||||
* a tuner walks; this resolves a shape left on the axis defaults.
|
||||
*
|
||||
* The operand plumbing is here for the ordinary reason: eleven kernels across eleven translation
|
||||
* units read the same two operand lists -- [A, B, Y] for the bf16 grid and [A, a_scale, B,
|
||||
* b_scale, Y, a_sum, B_ref] for every quantised one -- because they implement two ops.
|
||||
* Eleven kernels read one of two operand lists: [A, B, Y] for bf16 and
|
||||
* [A, a_scale, B, b_scale, Y, a_sum, B_ref] for every quantised grid.
|
||||
*/
|
||||
#ifndef R4D_GEMM_ARGS_H
|
||||
#define R4D_GEMM_ARGS_H
|
||||
@@ -21,29 +19,18 @@
|
||||
#include <exception>
|
||||
|
||||
|
||||
/* The build passes the same -DR4D_GEMM_*_GROUP to libr4d's translation units and to this one, so
|
||||
* these cannot drift apart silently -- a weight file written for one group and read by a kernel
|
||||
* compiled for another is wrong by a factor of nothing visible. */
|
||||
#ifndef R4D_GEMM_W4_GROUP
|
||||
#define R4D_GEMM_W4_GROUP 128
|
||||
#endif
|
||||
#ifndef R4D_GEMM_W8_GROUP
|
||||
#define R4D_GEMM_W8_GROUP 128
|
||||
#endif
|
||||
#ifndef R4D_GEMM_W4A8_GROUP
|
||||
/* K per scale group of each quantised weight layout. A mismatch between weight file and kernel
|
||||
* would be silently wrong, so each is checked against r4d_args.h's layout constant. */
|
||||
#define R4D_GEMM_W4_GROUP 128
|
||||
#define R4D_GEMM_W8_GROUP 128
|
||||
#define R4D_GEMM_W4A8_GROUP 128
|
||||
#endif
|
||||
#ifndef R4D_GEMM_W8A8_GROUP
|
||||
#define R4D_GEMM_W8A8_GROUP 128
|
||||
#endif
|
||||
#ifndef R4D_GEMM_W2A8_GROUP
|
||||
#define R4D_GEMM_W2A8_GROUP 128
|
||||
#endif
|
||||
static_assert(R4D_W4_GROUP == R4D_GEMM_W4_GROUP, "w4 group differs from libr4d's build");
|
||||
static_assert(R4D_W8_GROUP == R4D_GEMM_W8_GROUP, "w8 group differs from libr4d's build");
|
||||
static_assert(R4D_W4_GROUP == R4D_GEMM_W4A8_GROUP, "w4a8 group differs from libr4d's build");
|
||||
static_assert(R4D_W8_GROUP == R4D_GEMM_W8A8_GROUP, "w8a8 group differs from libr4d's build");
|
||||
static_assert(R4D_W2_GROUP == R4D_GEMM_W2A8_GROUP, "w2a8 group differs from libr4d's build");
|
||||
static_assert(R4D_W4_GROUP == R4D_GEMM_W4_GROUP, "w4 group differs from the layout constant");
|
||||
static_assert(R4D_W8_GROUP == R4D_GEMM_W8_GROUP, "w8 group differs from the layout constant");
|
||||
static_assert(R4D_W4_GROUP == R4D_GEMM_W4A8_GROUP, "w4a8 group differs from the layout constant");
|
||||
static_assert(R4D_W8_GROUP == R4D_GEMM_W8A8_GROUP, "w8a8 group differs from the layout constant");
|
||||
static_assert(R4D_W2_GROUP == R4D_GEMM_W2A8_GROUP, "w2a8 group differs from the layout constant");
|
||||
|
||||
|
||||
static inline int gemm_caught(const char* who, const char* what) {
|
||||
@@ -64,41 +51,23 @@ static inline int gemm_caught(const char* who, const char* what) {
|
||||
|
||||
/* ------------------------------------------------------------------ the split count
|
||||
*
|
||||
* libr4d's skinny GEMMs put split-K IN THE WORKGROUP: SK k-splits per column tile, reduced in LDS,
|
||||
* which is what fills a 64-CU part at M=1. The legality rule is K % (SK * unit) == 0, so no single
|
||||
* SK is legal at every K -- and a DEFAULT that is illegal at a shape would make an untuned install
|
||||
* FAIL rather than be slow, which is the wrong way round (spec §15).
|
||||
*
|
||||
* So the `sk` axis carries 0 as its DEFAULT and 0 means "the largest legal split from this K",
|
||||
* resolved here. The candidate ladder is the set of split counts that tuned configurations use, in
|
||||
* descending order, so an untuned install lands on a split count some shape was tuned to rather
|
||||
* than on 1. The cost of the sentinel is that two shapes with different K both running
|
||||
* `sk = 0` get different split counts; --debug-graph prints the chosen point, so a 0 there has to
|
||||
* be read as "the law decided" and not as a number.
|
||||
* The skinny GEMMs split K inside the workgroup: SK k-splits per column tile, reduced in LDS, to
|
||||
* fill a 64-CU part at M=1. Legality is K % (SK * unit) == 0, so no single SK is legal at every K,
|
||||
* and an illegal default would make an untuned install fail instead of run slowly (spec §15).
|
||||
* The `sk` axis therefore defaults to 0, meaning "the largest legal split for this K" from a
|
||||
* descending ladder of split counts tuned configurations use. A 0 in --debug-graph means the law
|
||||
* decided, not a literal split.
|
||||
*/
|
||||
/* THE LAUNCH BOUND IS PART OF A SPLIT'S LEGALITY.
|
||||
/* The launch bound is part of a split's legality. The skinny kernels' __launch_bounds__ tighten as
|
||||
* MB and NPW grow (w2a8: (MB >= 4) ? 256 : ((MB >= 2 || NPW >= 4) ? 512 : 1024)), and a block of
|
||||
* WV*SK*32 threads over its bound fails to launch, surfacing later as a device error at the next
|
||||
* sync. MB comes from M, so this only bites under concurrency: on the DFlash2 2-bit draft head
|
||||
* (N = 248320), M >= 49 gives a bound of 256 where sk = 10 needs 320 threads.
|
||||
*
|
||||
* libr4d's skinny kernels carry __launch_bounds__ that TIGHTEN as MB and NPW grow -- w2a8's is
|
||||
* (MB >= 4) ? 256 : ((MB >= 2 || NPW >= 4) ? 512 : 1024) -- and a block of WV*SK*32 threads wider
|
||||
* than its own bound is a launch failure, which surfaces later as a device error from whatever
|
||||
* happens to synchronise next. A split count picked against a flat 1024 is therefore not
|
||||
* necessarily legal.
|
||||
*
|
||||
* MB comes from M (`ceil(M/16)`, capped at 4), so this is an M-dependent trap that only springs
|
||||
* under CONCURRENCY. On the DFlash2 2-bit draft head, N = 248320: M >= 49 gives MB = 4 and a bound
|
||||
* of 256, where sk = 10 asks for 320 threads a block; M in [17, 48] gives MB = 2 and a bound of
|
||||
* 512, where sk = 20 asks for 640. Any bench that runs M <= 16 sees none of it. The engine refuses
|
||||
* the op at issue and fails the step, exactly as spec 17 says it must, so the symptom is
|
||||
* concurrent requests coming back empty rather than a wrong number.
|
||||
*
|
||||
* EACH CALLER NAMES ITS OWN RULE, because they genuinely differ and one conservative rule costs
|
||||
* real throughput: the bf16, w4a16, w8a16 and mxfp4 kernels declare a flat 1024 (or no
|
||||
* __launch_bounds__ at all, which is the same 1024), and capping them as if they were w2a8 costs
|
||||
* prefill throughput for nothing. w4a8 tightens on NPW alone and w8a8 on MT*NPW, both because the
|
||||
* bound is a REGISTER budget, which their own headers say at length. Where a kernel's macro is
|
||||
* switched off by a build flag the TIGHT branch is named here anyway: over-constraining a build
|
||||
* that relaxed its bound loses a little parallelism, and under-constraining one that did not is the
|
||||
* launch failure above.
|
||||
* Each caller names its own rule because one conservative rule costs throughput: bf16, w4a16,
|
||||
* w8a16 and mxfp4 are a flat 1024; w4a8 tightens on NPW and w8a8 on MB*NPW (a register budget).
|
||||
* Where a build flag can disable a kernel's bound, the tight rule is named anyway: over-constraining
|
||||
* loses a little parallelism, under-constraining fails to launch.
|
||||
*/
|
||||
enum BoundRule { BR_FLAT = 0, BR_W2A8, BR_NPW, BR_MBNPW };
|
||||
|
||||
@@ -111,154 +80,75 @@ static inline int block_bound(BoundRule r, int mb, int npw) {
|
||||
}
|
||||
}
|
||||
|
||||
static inline int pick_sk(long long K, long long unit, int wv, int bound) {
|
||||
/* The ladder enumerates the candidate splits the law above can reach, so its top entry is the
|
||||
* largest split any untuned shape will be given. 20 is on it because K = 5120 -- every
|
||||
* projection in this model -- divides by it, and 20 is the fastest legal split at that K on the
|
||||
* GDN a|b projection, which runs forty-eight times a step. `cap` still bounds the block at 1024
|
||||
* threads, which is what keeps wv = 2 from reaching 20 at all.
|
||||
*
|
||||
* 32 IS LEFT OUT ON PURPOSE. It is legal at K = 5120 and it is slower there than 20, so
|
||||
* including it would move the default AWAY from the fastest split purely to reach a bigger
|
||||
* number. The ladder tops out where the fastest split is, not where legality ends. */
|
||||
static const int ladder[] = { 20, 16, 10, 8, 5, 4, 2, 1 };
|
||||
const int cap = (wv > 0) ? (bound / (wv * 32)) : 1; /* threads/block <= this MB/NPW's bound */
|
||||
for (int s : ladder) {
|
||||
if (s > cap) continue;
|
||||
if (unit > 0 && (K % ((long long)s * unit)) == 0) return s;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* "THE LARGEST LEGAL SPLIT" IS THE WRONG LAW WHERE N ALREADY SUPPLIES THE PARALLELISM, and the
|
||||
* bf16 skinny GEMM is where that shows. The split exists to fill a 64-CU part at M = 1; a shape
|
||||
* with eighty N tiles is already full, and splitting it twenty ways is 1600 workgroups whose only
|
||||
* extra effect is the reduction. At K = 5120 the fastest split falls as N grows: at N = 48 (three
|
||||
* N tiles) the split IS the parallelism and the largest legal one wins; at N = 256 (sixteen tiles)
|
||||
* a split of 4 wins; at N = 1280 (eighty tiles) 1 or 2 does.
|
||||
*
|
||||
* So the law is the SMALLEST split whose `n_tiles * sk` reaches a target workgroup count, falling
|
||||
* back to the largest legal split at small N because nothing smaller reaches it. kFlatTileTarget
|
||||
* is that count; it is the same quantity `narrow_ksplit` targets in the fp8 kernel, where it is
|
||||
* called kSplitTarget.
|
||||
*
|
||||
* N = 48 IS THE ONLY TRUNK CALLER (the GDN a|b projection, forty-eight times a step); N = 1280 and
|
||||
* N = 256 are the DFlash2 drafter's. So at the trunk shape this law reduces to the largest legal
|
||||
* split, and the shapes it actually moves are the ones the drafter PROPOSES. */
|
||||
/* Where N already supplies the parallelism, the largest legal split is wrong: it only adds
|
||||
* reduction work. At K = 5120 the fastest split falls as N grows: largest legal at N = 48 (3 N
|
||||
* tiles), 4 at N = 256 (16 tiles), 1 or 2 at N = 1280 (80 tiles). So with `n_tiles` (the shape's
|
||||
* 16-row N tiles) this picks the smallest split whose `n_tiles * sk` reaches kFlatTileTarget
|
||||
* workgroups. Without it, or when none reaches, it picks the largest legal split. kFlatTileTarget
|
||||
* is the same quantity as kSplitTarget in the fp8 kernel's `narrow_ksplit`. */
|
||||
enum { kFlatTileTarget = 128 };
|
||||
|
||||
static inline int pick_sk_for(long long n_tiles, long long K, long long unit, int wv, int bound) {
|
||||
static const int ladder[] = { 1, 2, 4, 5, 8, 10, 16, 20 }; /* ascending: the SMALLEST that fits */
|
||||
const int cap = (wv > 0) ? (bound / (wv * 32)) : 1;
|
||||
int best = 0;
|
||||
static inline int pick_sk(long long n_tiles, long long K, long long unit, int wv, int bound) {
|
||||
/* The top entry is the largest split an untuned shape gets. 20 divides K = 5120 and is the
|
||||
* fastest legal split there on the GDN a|b projection; 32 is left out on purpose (legal at
|
||||
* K = 5120 but slower). `cap` keeps the block within its bound (wv = 2 cannot reach 20). */
|
||||
static const int ladder[] = { 1, 2, 4, 5, 8, 10, 16, 20 };
|
||||
const int cap = (wv > 0) ? (bound / (wv * 32)) : 1; /* threads/block <= this MB/NPW's bound */
|
||||
int best = 1;
|
||||
for (int s : ladder) {
|
||||
if (s > cap) continue;
|
||||
if (unit > 0 && (K % ((long long)s * unit))) continue;
|
||||
best = s; /* legal; remember it in case none reaches */
|
||||
if (n_tiles * s >= (long long)kFlatTileTarget) return s;
|
||||
if (s > cap || unit <= 0 || (K % ((long long)s * unit))) continue;
|
||||
best = s;
|
||||
if (n_tiles > 0 && n_tiles * s >= (long long)kFlatTileTarget) return s;
|
||||
}
|
||||
return best > 0 ? best : 1; /* nothing reaches the target: the largest legal */
|
||||
return best;
|
||||
}
|
||||
|
||||
/* Resolve the tuned point into (WV, SK, MB, NPW, NT) for a shape whose split unit is `unit`. */
|
||||
struct Cfg { int wv, sk, mb, npw, nt; };
|
||||
|
||||
/* `n_tiles` is how many 16-row N tiles the shape has, and it is what turns "the largest legal
|
||||
* split" into "enough split to fill the machine". Zero keeps the largest legal split, which is
|
||||
* right wherever the split is the only source of parallelism. See the note at pick_sk_for. */
|
||||
/* `n_tiles` is the shape's number of 16-row N tiles, for pick_sk. Zero keeps the largest legal
|
||||
* split, right wherever the split is the only source of parallelism. */
|
||||
static inline int cfg_for(const RadArgs* a, long long K, long long M, long long unit, BoundRule br,
|
||||
Cfg* out, long long n_tiles = 0);
|
||||
|
||||
static inline int cfg_for(const RadArgs* a, long long K, long long M, long long unit, BoundRule br,
|
||||
Cfg* out, long long n_tiles) {
|
||||
Cfg* out, long long n_tiles = 0) {
|
||||
R4dGemmCfg cv;
|
||||
r4d_cfg_gemm(a, &cv);
|
||||
const R4dGemmCfg* c = &cv;
|
||||
out->wv = c->wv > 0 ? c->wv : 1;
|
||||
/* MB IS HOW MANY ROW TILES ONE BLOCK COVERS, and mb <= 0 means "all of them", the same way
|
||||
* sk <= 0 means "the largest legal split". It matters far more than it looks: grid.y is
|
||||
* ceil(ceil(M/16)/MB), and every block in a grid.y column reads THE WHOLE WEIGHT for its N
|
||||
* tile. At these shapes the weight is the entire cost, so MB = 1 at M = 64 reads it four times
|
||||
* -- on the DFlash2 drafter's fc, [5120, 25600] and 250 MiB, that is a gibibyte moved at peak
|
||||
* bandwidth to compute a 64-row slice. Covering every row tile in one block is right whenever
|
||||
* the weight is bigger than the activation, which is every caller here. */
|
||||
/* MB is the number of row tiles one block covers; mb <= 0 means all of them. grid.y is
|
||||
* ceil(ceil(M/16)/MB) and each grid.y row of blocks reads the whole weight, so MB = 1 at M = 64
|
||||
* reads it four times. Covering every row tile is right when the weight outweighs the
|
||||
* activation. */
|
||||
out->mb = c->mb > 0 ? c->mb : (int)((M + 15) / 16);
|
||||
if (out->mb < 1) out->mb = 1;
|
||||
if (out->mb > 4) out->mb = 4;
|
||||
/* ...AND IN THE DECODE BAND IT IS THE OPPOSITE RULE, because there the weight is not the cost:
|
||||
* the GRID is. `grid.y` is ceil(ceil(M/16)/MB), so MB = ceil(M/16) makes it ONE -- and at the
|
||||
* GDN a|b projection, N = 48, that is a THREE-BLOCK grid on a 32-WGP part for the whole kernel.
|
||||
* MB = 1 makes it twelve at M = 64 and reads a 0.5 MiB weight four times, and those extra
|
||||
* reads cost far less than the idle machine does. Across the decode band MB = 1 is the fastest
|
||||
* choice at every (N, M) these callers run; MB = 2 edges it only at the widest N and the top of
|
||||
* the band, by less than a second threshold would be worth.
|
||||
/* In the decode band (M <= 64, four row tiles) the grid is the cost, not the weight: at
|
||||
* N = 48, MB = ceil(M/16) gives a three-block grid on a 32-WGP part. MB = 1 is fastest at
|
||||
* every decode (N, M) these callers run despite re-reading the weight. Prefill (hundreds of
|
||||
* row tiles) is excluded by the bound.
|
||||
*
|
||||
* FOUR ROW TILES IS THE BAND, and the bound is what makes it safe rather than a guess: a
|
||||
* PREFILL chunk is hundreds of row tiles, where grid.y is already large and MB = 1 would read
|
||||
* the weight a hundred and seventy times. `mtiles <= 4` is exactly M <= 64, which is exactly
|
||||
* the decode band this kernel's callers run (C * (1 + n_spec) at n_spec 7 tops out at 64), and
|
||||
* prefill is untouched by construction.
|
||||
*
|
||||
* BR_FLAT ONLY, and that is what leaves the output bits unchanged. `block_bound` ignores MB
|
||||
* for BR_FLAT, so the split `pick_sk_for` answers below does not move -- and with the same
|
||||
* split every output element is still one wave's accumulation over the same K slices in the
|
||||
* same ascending order. MB moves which block owns the element, not what it adds. On a rule
|
||||
* whose bound DOES read MB (BR_W2A8, BR_MBNPW) this would change the split and therefore the
|
||||
* bits, which is why it is gated rather than applied to every auto.
|
||||
*
|
||||
* `R4D_GEMM_MB1=0` disables this branch and leaves MB on the shape-derived default. */
|
||||
static const bool mb1 = [] { const char* e = std::getenv("R4D_GEMM_MB1");
|
||||
return !(e && e[0] == '0'); }();
|
||||
if (mb1 && c->mb <= 0 && br == BR_FLAT && ((M + 15) / 16) <= 4) out->mb = 1;
|
||||
/* ...AND PAST THE DECODE BAND WHEN N IS NARROW. Above 64 rows an N of 128 or more belongs to
|
||||
* the tiled row (r4d_gemm_bf16_nt_tiled.hip), and what stays here is the narrow projections --
|
||||
* the GDN a|b at 48, a shared-expert gate at 1 -- whose weight is a few hundred KiB against an
|
||||
* activation of megabytes, so the "weight is the cost" reading above is backwards for them.
|
||||
* Measured at K = 2560 over M 80..2048 and N 16/48/112, MB = 1 is 2-5x faster than covering
|
||||
* every row tile at every point (M 2048, N 48: 27.8 -> 14.9 us; N 16: 27.9 -> 8.8). The same
|
||||
* BR_FLAT argument as above keeps the bits. */
|
||||
* BR_FLAT only: its bound ignores MB, so the split is unchanged and every output element keeps
|
||||
* the same accumulation order, hence the same bits. Under BR_W2A8 or BR_MBNPW, MB would move
|
||||
* the split. */
|
||||
if (c->mb <= 0 && br == BR_FLAT && ((M + 15) / 16) <= 4) out->mb = 1;
|
||||
/* Also past the decode band when N is narrow. Above 64 rows, N >= 128 goes to the tiled row
|
||||
* (r4d_gemm_bf16_nt_tiled.hip); what stays here are narrow projections (GDN a|b at 48, a
|
||||
* shared-expert gate at 1) whose weight is small against the activation. At K = 2560,
|
||||
* M 80..2048, N 16..112, MB = 1 is 2-5x faster. BR_FLAT keeps the bits as above. */
|
||||
if (c->mb <= 0 && br == BR_FLAT && n_tiles > 0 && n_tiles < 8) out->mb = 1;
|
||||
out->npw = c->npw > 0 ? c->npw : 1;
|
||||
out->nt = c->nt;
|
||||
/* W2A8 PAST ONE ROW TILE NEEDS A WIDER BLOCK, not a taller one, and the shape-derived default
|
||||
* gives it a taller one. The DFlash2 draft head is the only w2a8 caller and it runs
|
||||
* M = n_seq * steps, so M crosses 16 at the SECOND concurrent sequence: a single-stream bench
|
||||
* never reaches this branch at all.
|
||||
/* W2A8 past one row tile needs a wider block, not a taller one. Its only caller (the DFlash2
|
||||
* draft head, N = 124160, K = 5120) runs M = n_seq * steps, so M > 16 from the second
|
||||
* concurrent sequence on. At NPW = 1 the kernel then drops to about a third of memory
|
||||
* bandwidth; NPW = 4 gives each block four N tiles to hide the dequantise behind. MB is pinned
|
||||
* at 2: MB = 4 with NPW = 4 spills (MT * NPW accumulators), and MB = 3 (12 accumulators vs 8)
|
||||
* is slower even where it moves the same bytes. Reading the weight twice is cheaper than any
|
||||
* shape that reads it once; see rad_block_dflash2.h for the vocabulary shard.
|
||||
*
|
||||
* At one row tile the kernel runs at memory bandwidth on its 170.5 MiB weight, N = 124160 and
|
||||
* K = 5120. Past one row tile, at NPW = 1, it falls to roughly a third of the bus even though
|
||||
* the weight read has not changed -- MB covers every row tile in one block throughout -- so the
|
||||
* collapse is entirely the block shape. Widening the block over N recovers most of it: NPW = 4
|
||||
* gives each block four N tiles to hide the dequantise behind, where NPW = 1 has only its own.
|
||||
* MB is pinned at 2 rather than left to grow because MB = 4 with NPW = 4 spills -- accumulators
|
||||
* are MT * NPW -- and reading the weight twice is cheaper than spilling, which is the same
|
||||
* conclusion the kernel's own header reaches from its sweep.
|
||||
*
|
||||
* Only mb = 0 is touched: a tuned mb is the tuner's decision and must survive. */
|
||||
/* AND THE SPLIT IS PINNED WITH THEM, because `pick_sk` takes the LARGEST split the bound
|
||||
* allows and the largest is not the fastest here. At K = 5120 the unit is 128, so the legal
|
||||
* counts are the divisors of 40 up to bound/(wv*32) = 16, and pick_sk answers 10. Eight is
|
||||
* uniformly faster than ten across the whole M band this branch covers. The one cost step
|
||||
* inside that band is where grid.y grows and the weight is read again; it sits in the same
|
||||
* place at either split count.
|
||||
*
|
||||
* MB = 4 WOULD REMOVE THE SECOND WEIGHT READ AND IS STILL WRONG: at NPW = 4 it spills, and
|
||||
* below NPW = 4 the block is too narrow to hide the dequantise. Reading the weight twice
|
||||
* really is cheaper than any block shape that reads it once, which is the same conclusion the
|
||||
* kernel's own header reaches. The lever that IS left is a vocabulary shard -- see
|
||||
* rad_block_dflash2.h.
|
||||
*
|
||||
* MB = 3 IS THE COUNT BETWEEN THEM AND IT IS ALSO WRONG, which is worth stating because the
|
||||
* analogous hole at three in the fp8 GEMM's NT ladder is a real loss there (r4d_gemm_fp8a8.hip,
|
||||
* "...AND THE TOKEN-TILE COUNT HAD A HOLE IN IT AT THREE"). At three row tiles -- M = 33..48 --
|
||||
* MB = 2 makes grid.y two and reads the whole weight twice while MB = 3 makes it one, and
|
||||
* MB = 3 is still slower: MT * NPW accumulators is twelve against eight, which costs more than
|
||||
* the read it saves. It is slower even at an M where grid.y and the bytes moved are identical
|
||||
* between them, so the accumulator count is the whole of it. The second weight read past 32
|
||||
* rows stands.
|
||||
*
|
||||
* A pin that this K cannot divide, or that overruns the bound, falls back to pick_sk rather
|
||||
* than becoming a refusal: this branch is the AUTO path and auto must serve every shape. */
|
||||
* The split is pinned to 8: pick_sk would answer 10 (divisors of 40 up to 16), and 8 is faster
|
||||
* across this M band. Only mb = 0 is touched, so a tuned mb survives. A pin this K cannot
|
||||
* divide or that overruns the bound falls back to pick_sk, since the auto path must serve
|
||||
* every shape. */
|
||||
int sk_pin = 0;
|
||||
if (br == BR_W2A8 && c->mb <= 0 && out->mb >= 2) {
|
||||
out->mb = 2;
|
||||
@@ -269,26 +159,18 @@ static inline int cfg_for(const RadArgs* a, long long K, long long M, long long
|
||||
if (sk_pin && (out->wv * sk_pin * 32 > bound ||
|
||||
(unit > 0 && (K % ((long long)sk_pin * unit)))))
|
||||
sk_pin = 0;
|
||||
out->sk = c->sk > 0 ? c->sk
|
||||
: (sk_pin ? sk_pin
|
||||
: (n_tiles > 0 ? pick_sk_for(n_tiles, K, unit, out->wv, bound)
|
||||
: pick_sk(K, unit, out->wv, bound)));
|
||||
/* A NAMED split that overruns the bound is a REFUSAL, not a device error. The tuner has to see
|
||||
* "does not serve this shape" so it never records the candidate, and the selector must not be
|
||||
* able to hand a cached name to a shape whose MB has since grown. */
|
||||
out->sk = c->sk > 0 ? c->sk : (sk_pin ? sk_pin : pick_sk(n_tiles, K, unit, out->wv, bound));
|
||||
/* A named split that overruns the bound is refused, so the tuner never records the candidate
|
||||
* and the selector cannot hand a cached name to a shape whose MB has grown. */
|
||||
if (out->wv * out->sk * 32 > bound) return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
/* A NAMED split count that this K cannot divide is a refusal, not a silent clamp: the tuner
|
||||
* has to see that this candidate does not serve this shape, or it will record a measurement
|
||||
* for a configuration that never ran. */
|
||||
/* A named split this K cannot divide is refused rather than clamped, so the tuner never
|
||||
* records a configuration that did not run. */
|
||||
if (unit > 0 && (K % ((long long)out->sk * unit))) return R4D_NO(RAD_E_SHAPE);
|
||||
if (out->wv * out->sk * 32 > 1024) return R4D_NO(RAD_E_SHAPE);
|
||||
/* R4D_GEMMCFG=1 prints each DISTINCT (tuned point, K, M, n_tiles) this resolved, once. The rule
|
||||
* above is shape-dependent and the harness cannot see which branch it took. */
|
||||
/* R4D_GEMMCFG=1 prints each distinct (tuned point, K, M, n_tiles) resolution once. */
|
||||
static const bool dbg = [] { const char* e = std::getenv("R4D_GEMMCFG");
|
||||
return e && e[0] && e[0] != '0'; }();
|
||||
if (dbg) {
|
||||
/* Once per DISTINCT key, to at most 64 of them: the engine resolves this on every issue
|
||||
* of every GEMM row and a line each would be the log. */
|
||||
/* At most 64 keys: this runs on every issue of every GEMM row. */
|
||||
static uint64_t seen[64];
|
||||
static int nseen = 0;
|
||||
const uint64_t key = ((uint64_t)(unsigned)(c->wv * 41 + c->sk * 7 + c->mb * 3 + c->npw) << 56)
|
||||
@@ -314,18 +196,17 @@ enum { G_A = 0, G_B, G_Y }; /* gemm_nt
|
||||
enum { Q_A = 0, Q_ASCALE, Q_B, Q_BSCALE, Q_Y, Q_ASUM, Q_BREF }; /* gemm_nt_q */
|
||||
|
||||
struct GemmOps {
|
||||
/* A flattened view of `a`, when the caller declared it rank 3; see gemm_ops. Held by value
|
||||
* because the operand array it was folded from belongs to the core. */
|
||||
/* Flattened views of a rank-3 `a` / `y`; see gemm_ops. Held by value because the operand
|
||||
* array belongs to the core. */
|
||||
RadTensor a_flat, y_flat;
|
||||
const RadTensor *a, *ascale, *b, *bscale, *y, *asum, *bref;
|
||||
long long M, N, K;
|
||||
};
|
||||
|
||||
/* THE MXFP4 GEMMS' ACTIVATION SCALE GRID, read off the operand rather than assumed. One f32 a row
|
||||
* (`[M]` or `[M][1]`: a per-token quantiser) is group 0; one per (row, 128 of K) (`[M][ceil(K/128)]`:
|
||||
* the block-scaled fp8 family's quantisers, which every fused producer in arch/common writes) is
|
||||
* group 128, read at the operand's own row stride. Anything else is refused by shape: a grid read
|
||||
* at the wrong width is an answer that is merely wrong. */
|
||||
/* The MXFP4 GEMMs' activation scale grid, read off the operand. One f32 per row (`[M]` or
|
||||
* `[M][1]`, a per-token quantiser) is group 0; one per (row, 128 of K) (`[M][ceil(K/128)]`, the
|
||||
* block-scaled fp8 quantisers every fused producer in arch/common writes) is group 128, read at the
|
||||
* operand's row stride. Anything else is refused. */
|
||||
static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs, int parts = 1) {
|
||||
const RadTensor* s = g.ascale;
|
||||
if (!s || g.M <= 0) return R4D_NO(RAD_E_INVAL);
|
||||
@@ -340,28 +221,26 @@ static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs, int part
|
||||
rstride = cols;
|
||||
}
|
||||
const long long kb = (g.K + 127) / 128;
|
||||
/* PARTS: the activation's copies sit side by side in a row, so its scale row is `parts` times
|
||||
* as long; each part reads its own kb of them at the row stride. */
|
||||
/* With parts, the activation's copies sit side by side in a row, so its scale row is `parts`
|
||||
* times as long; each part reads its own kb entries. */
|
||||
if (parts == 1 && cols == 1 && (s->rank < 2 || rstride == 1)) { *group = 0; *rs = 1; return RAD_OK; }
|
||||
if (cols == kb * parts && rstride >= kb * parts) { *group = 128; *rs = (int)rstride; return RAD_OK; }
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* THE PARTS OF A PARTITIONED MXFP4 WEIGHT (gemm_nt_q's `pb1`/`pb2`), as launches.
|
||||
/* The parts of a partitioned MXFP4 weight (gemm_nt_q's `pb1`/`pb2`), as launches.
|
||||
*
|
||||
* A fused projection whose pieces were rotated apart (ParoQuant: gate|up, q|k|v) has one copy of
|
||||
* the activation a piece, written side by side in a row of `a` -- [M, parts * K] -- and its scales
|
||||
* the same, so the weight's rows [0, pb1), [pb1, pb2), [pb2, N) each meet THEIR copy. A part is
|
||||
* then the ordinary product over a window of the planes: the activation from byte p * K of each row
|
||||
* and its scales from p * ceil(K/128), the fragment-order weight from tile n0 / 16 (its bytes are
|
||||
* n0 * K / 2 in), the exponents and reference from column n0, the output from column n0, the last
|
||||
* three with the full planes' row pitch. So the kernels learn only row pitches (`lda`, `ldws`,
|
||||
* `ldc`) and a part is one launch of the kernel the shape would have picked anyway.
|
||||
* the activation per piece, side by side in a row of `a` ([M, parts * K]), and its scales likewise;
|
||||
* weight rows [0, pb1), [pb1, pb2), [pb2, N) each meet their own copy. A part is the ordinary
|
||||
* product over a window of the planes: activation from byte p * K of each row, scales from
|
||||
* p * ceil(K/128), fragment-order weight from tile n0 / 16 (byte n0 * K / 2), exponents, reference
|
||||
* and output from column n0 at the full planes' row pitch. The kernels learn only row pitches
|
||||
* (`lda`, `ldws`, `ldc`), and each part is one launch of the kernel the shape would pick anyway.
|
||||
*
|
||||
* `pb1` = 0 is one part and `pb2` = 0 ends the second part at N, as libref reads them. Bounds are
|
||||
* whole 16-row tiles (the weight's fragment unit). Returns the parts in `p`, K corrected to the
|
||||
* op's own (gemm_ops read the row's width, which is parts * K), and the activation's row pitch in
|
||||
* `lda`. */
|
||||
* whole 16-row tiles. Fills `p`, corrects K to the op's own (gemm_ops read parts * K) and sets the
|
||||
* activation's row pitch in `lda`. */
|
||||
struct MxParts {
|
||||
int n = 1;
|
||||
long long n0[3] = { 0, 0, 0 }, n1[3] = { 0, 0, 0 };
|
||||
@@ -405,14 +284,28 @@ static inline int mx_parts(const RadArgs* a, GemmOps* g, MxParts* p) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Common shape and layout checks. A is [M,K] row-major, C is [M,N] row-major and the weight is
|
||||
* an opaque packed blob whose element count the layout hook owns -- so the weight's SHAPE is not
|
||||
* checked here beyond being present, which is deliberate: the byte count that matters is the one
|
||||
* rad-convert wrote from RadLayout.bytes, and re-deriving it from N and K would be a second
|
||||
* source for one number. */
|
||||
/* `parts`: the caller reads a partitioned weight's `pb1`/`pb2` (mx_parts). Any other row REFUSES them
|
||||
* rather than ignore them -- a part bound it does not apply would multiply every row of the weight by
|
||||
* the first copy of the activation. */
|
||||
/* Folds a contiguous rank-3+ operand to rank 2 (rows x the product of the rest), held by value in
|
||||
* `flat` because the operand array is the core's; a rank-2 operand is left as it is. */
|
||||
static inline int fold_rows(const RadTensor** t, RadTensor* flat) {
|
||||
if ((*t)->rank < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
if ((*t)->rank == 2) return RAD_OK;
|
||||
if (!r4d_contig(*t)) return R4D_NO(RAD_E_STRIDE);
|
||||
*flat = **t;
|
||||
int64_t k = 1;
|
||||
for (uint32_t d = 1; d < (*t)->rank; ++d) k *= (*t)->shape[d];
|
||||
flat->rank = 2;
|
||||
flat->shape[1] = k; flat->stride[1] = 1;
|
||||
flat->stride[0] = k;
|
||||
*t = flat;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Common shape and layout checks. A is [M,K] row-major, C is [M,N] row-major. The weight is an
|
||||
* opaque packed blob whose size the layout hook owns (RadLayout.bytes), so only its presence is
|
||||
* checked here.
|
||||
*
|
||||
* `parts`: the caller applies a partitioned weight's `pb1`/`pb2` (mx_parts). Any other caller
|
||||
* refuses them; ignoring them would multiply every weight row by the first activation copy. */
|
||||
static inline int gemm_ops(const RadArgs* a, GemmOps* g, int quantised, int parts = 0) {
|
||||
std::memset(g, 0, sizeof(*g));
|
||||
if (quantised && !parts && (r4d_geti_or(a, "pb1", 0) > 0 || r4d_geti_or(a, "pb2", 0) > 0))
|
||||
@@ -432,46 +325,14 @@ static inline int gemm_ops(const RadArgs* a, GemmOps* g, int quantised, int part
|
||||
g->y = r4d_opt(a, G_Y);
|
||||
if (!g->a || !g->b || !g->y) return R4D_NO(RAD_E_INVAL);
|
||||
}
|
||||
/* A CONTIGUOUS RANK-3 ACTIVATION IS A RANK-2 ACTIVATION, and refusing it would refuse a real
|
||||
* model: the bf16 plugin's gated delta net writes its output into a [tokens, heads,
|
||||
* head_v] buffer -- rank 3 because `gdn_chunk_scan` declares its `o` operand that way -- and
|
||||
* hands the same bytes to `gemm_nt` for the out projection. libref computes that correctly,
|
||||
* because it takes K from the op's K PARAMETER and reads A as M x K whatever the declared rank;
|
||||
* this shim derived K from shape[1] instead, which is the HEAD COUNT, so it refused the rank
|
||||
* rather than computing with 48 where K is 3072. The fp8 plugin never reached it only because
|
||||
* its quantiser writes a separate rank-2 codes buffer.
|
||||
*
|
||||
* The fold is exact for a CONTIGUOUS tensor and gives the same M x K the parameter names. It is
|
||||
* held by value here rather than written back through g->a: those tensors are the core's
|
||||
* operand array, which every other kernel in the step also reads.
|
||||
*
|
||||
* A STRIDED rank-3 tensor is still refused, and must be: it is not a rank-2 one. */
|
||||
if (g->a->rank < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
if (g->a->rank > 2) {
|
||||
if (!r4d_contig(g->a)) return R4D_NO(RAD_E_STRIDE);
|
||||
g->a_flat = *g->a;
|
||||
int64_t k = 1;
|
||||
for (uint32_t d = 1; d < g->a->rank; ++d) k *= g->a->shape[d];
|
||||
g->a_flat.rank = 2;
|
||||
g->a_flat.shape[1] = k; g->a_flat.stride[1] = 1;
|
||||
g->a_flat.stride[0] = k;
|
||||
g->a = &g->a_flat;
|
||||
}
|
||||
if (g->y->rank < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
/* ...AND THE SAME ON THE OUTPUT SIDE, for the same reason and from the same plugin. The gated
|
||||
* attention writes its query-and-gate projection into a [tokens, heads, 2*head_dim] buffer --
|
||||
* rank 3 so that q and gate are ordinary column slices of the last dimension, which is what
|
||||
* makes the interleaving addressable at all -- and N is the product of the trailing two. */
|
||||
if (g->y->rank > 2) {
|
||||
if (!r4d_contig(g->y)) return R4D_NO(RAD_E_STRIDE);
|
||||
g->y_flat = *g->y;
|
||||
int64_t n = 1;
|
||||
for (uint32_t d = 1; d < g->y->rank; ++d) n *= g->y->shape[d];
|
||||
g->y_flat.rank = 2;
|
||||
g->y_flat.shape[1] = n; g->y_flat.stride[1] = 1;
|
||||
g->y_flat.stride[0] = n;
|
||||
g->y = &g->y_flat;
|
||||
}
|
||||
/* The gated delta net hands its [tokens, heads, head_v] output (as `gdn_chunk_scan` declares
|
||||
* `o`) to `gemm_nt`, so K is the product of the trailing dims, not shape[1]. Gated attention
|
||||
* writes q|gate into [tokens, heads, 2*head_dim], so q and gate are column slices of the last
|
||||
* dim and N is the product of the trailing two. A strided rank-3 tensor is refused. */
|
||||
int rc = fold_rows(&g->a, &g->a_flat);
|
||||
if (rc != RAD_OK) return rc;
|
||||
rc = fold_rows(&g->y, &g->y_flat);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (!r4d_contig(g->a) || !r4d_contig(g->y)) return R4D_NO(RAD_E_STRIDE);
|
||||
if (!r4d_aligned(g->a->data, 16) || !r4d_aligned(g->b->data, 16)) return R4D_NO(RAD_E_ALIGN);
|
||||
|
||||
@@ -485,20 +346,18 @@ static inline int gemm_ops(const RadArgs* a, GemmOps* g, int quantised, int part
|
||||
|
||||
|
||||
|
||||
/* The asymmetric grid is a different WEIGHT FORMAT, not a different call: the nibble is read
|
||||
* UNSIGNED and the stored per-group zero is corrected out with the activation's per-group row
|
||||
* sums. So it is selected by `dtype`, which is what the weight file was written for, and never by
|
||||
* whether a_sum happens to be present -- guessing from an operand would make a caller that forgot
|
||||
* to pass the sums silently compute the symmetric answer against asymmetric bytes. */
|
||||
/* The asymmetric grid is a different weight format: the nibble is read unsigned and the per-group
|
||||
* zero is corrected with the activation's per-group row sums. It is selected by `dtype`, never by
|
||||
* whether a_sum is present: inferring it would silently give the symmetric answer to a caller
|
||||
* that forgot the sums. */
|
||||
static inline int is_asym(const RadArgs* a) {
|
||||
const char* dt = r4d_gets(a, "dtype");
|
||||
return dt && std::strstr(dt, "_asym") != nullptr;
|
||||
}
|
||||
|
||||
/* The tiled and prefill kernels take a single opaque tile VARIANT into libr4d's own tile switch.
|
||||
* The block width BN is a property of the variant, and N must be a multiple of it -- which the ROW
|
||||
* cannot express, because BN varies by variant. So the row constrains N % 256 (the default
|
||||
* variant's BN) and this is where a variant whose BN does not divide N is refused. */
|
||||
/* The tiled and prefill kernels take an opaque tile variant into libr4d's tile switch. N must be a
|
||||
* multiple of the variant's BN, which the row cannot express since BN varies; the row constrains
|
||||
* N % 256 (the default BN) and this refuses a variant whose BN does not divide N. */
|
||||
static inline int tile_ok(const R4dTileCfg* t, long long N) {
|
||||
if (!t) return R4D_NO(RAD_E_INVAL);
|
||||
if (t->bn > 0 && (N % t->bn)) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
// r4d_gemm_bf16_nt_m16.hip -- THE ROW THAT FORWARDS. There is no kernel in this file.
|
||||
// r4d_gemm_bf16_nt_m16.hip -- forwarding entry, no kernel.
|
||||
//
|
||||
// This row owns the M <= 16 band -- the MoE router gate's band -- and serves it with the WMMA
|
||||
// kernel behind the M <= 64 row, which is faster than a scalar split-K kernel at every point of it.
|
||||
// This row owns the M <= 16 band (the MoE router gate) and serves it with the M <= 64 WMMA kernel,
|
||||
// which is faster than a scalar split-K kernel across the band. The result is not bit-identical to
|
||||
// a scalar kernel: the reduction tree differs, which moves emitted text at N = 48 (GDN a|b
|
||||
// projection). A reduction order is not a quality bar, so that is accepted.
|
||||
//
|
||||
// THE FORWARD IS NOT BIT-NEUTRAL against a scalar kernel of the same band. Both formulations are
|
||||
// deterministic fp32 reductions over the same split, but they are different reduction TREES, so the
|
||||
// last bit differs. At N = 1280 and N = 256, which are the DFlash2 drafter's shapes, a bit change
|
||||
// is not a text change; at N = 48, the trunk's GDN a|b projection and 48 calls a step, the emitted
|
||||
// text does move where M <= 16. A reduction order is not a quality bar, so that is accepted.
|
||||
//
|
||||
// THE ROW STAYS EVEN THOUGH THERE IS NO KERNEL. Deleting the registry row would leave the M <= 16
|
||||
// band to whatever else claims it, and a band that resolves to a kernel which cannot serve it is
|
||||
// invisible until a request lands in it. One forwarding entry is cheap and the band stays
|
||||
// explicitly owned.
|
||||
// The row is kept so the band stays explicitly owned rather than falling to whatever else claims it.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
|
||||
|
||||
@@ -1,33 +1,21 @@
|
||||
// r4d_gemm_bf16_nt_m64.hip - r4d_gemm_bf16_nt_m64: skinny bf16 GEMM at any M, gfx1201.
|
||||
//
|
||||
// THE NAME SAYS 64 AND THE KERNEL IS GENERAL IN M. MT row tiles live in a block and `grid.y`
|
||||
// covers the rest -- `mt0 = blockIdx.y * MT`, fragment rows clamped to M-1, the store guarded by
|
||||
// `m < M` -- so any M up to R4D_GEMM64_MAX_M is served. The 64 is the registry band this row is
|
||||
// listed under, not a limit of the kernel; the M <= 16 row forwards here as well.
|
||||
//
|
||||
// C[M,N] = A[M,K] @ W[N,K]^T, bf16 in and out, fp32 accumulate.
|
||||
//
|
||||
// THE SCALAR ALTERNATIVE is a wave per output COLUMN holding M accumulators for it, so every
|
||||
// 16-wide step of K costs one weight load and M activation loads. That ratio is the whole cost at
|
||||
// these shapes: at M=16, N=48, K=5120 the activation is re-read sixteen times per weight element,
|
||||
// 7.9 MB against a 480 KiB weight, so the kernel is bound by traffic it did not need to move.
|
||||
// Above M=16 that form cannot run at all -- 64 accumulators per column leaves nothing to prefetch
|
||||
// with.
|
||||
// General in M up to R4D_GEMM64_MAX_M: MT row tiles per block, grid.y covers the rest. The 64 is
|
||||
// the registry band, not a kernel limit; the M <= 16 row forwards here too.
|
||||
//
|
||||
// WMMA fixes the ratio by construction. One wmma_f32_16x16x16 consumes a 16x16 activation fragment
|
||||
// and a 16x16 weight fragment and produces a whole 16(M) x 16(N) tile, so a step of 16 K costs
|
||||
// ceil(M/16) activation fragments and ONE weight fragment however large M is, and the accumulator
|
||||
// for a tile is 8 VGPRs per lane instead of 16 scalars per output element. At M=64 that is four
|
||||
// fragments and four wmma per weight fragment, against sixty-four loads before.
|
||||
// A scalar kernel (one wave per output column, M accumulators) costs one weight load and M
|
||||
// activation loads per 16 K, and cannot run above M=16. One wmma_f32_16x16x16 produces a whole
|
||||
// 16x16 tile, so a 16-K step costs ceil(M/16) activation fragments and one weight fragment, with
|
||||
// 8 VGPRs per lane of accumulator per tile.
|
||||
//
|
||||
// Parallel decomposition: a block is WV column-tiles x SK k-splits
|
||||
// waves, each wave owning one 16-wide N tile over one contiguous slice of K, and the k-splits are
|
||||
// reduced through LDS in wave order so the result does not depend on how the waves are scheduled.
|
||||
// N=48 (a TP=2 shard of the gated-delta-net b/a projection) is three tiles; three waves would leave
|
||||
// the machine idle, so SK is what fills it.
|
||||
// A block is WV column tiles x SK k-splits waves; each wave owns one 16-wide N tile over one
|
||||
// contiguous K slice. Splits are reduced through LDS in wave order, so the result does not depend
|
||||
// on scheduling. SK fills the machine when N is small (N=48 is three tiles).
|
||||
//
|
||||
// Fragment rows are CLAMPED, not masked: a tile whose rows run past M or N re-reads the last valid
|
||||
// row, computes a result nobody stores, and never touches memory it does not own.
|
||||
// Fragment rows are clamped, not masked: rows past M or N re-read the last valid row and their
|
||||
// results are never stored.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_gdn_wmma.h"
|
||||
@@ -38,19 +26,15 @@
|
||||
#define R4D_GEMM64_MAX_M 65536
|
||||
#define WAVE32 32
|
||||
|
||||
// A fragment from a base pointer plus a COMPILE-TIME k step. The header's fragGo takes a 32-bit
|
||||
// element offset, which is correct but leaves LLVM re-deriving a 64-bit address per fragment per
|
||||
// step -- a b64 shift and a carry-in add pair, three instructions each, twenty per step around four
|
||||
// WMMA. Holding one pointer per fragment and stepping it with a constant turns those into the
|
||||
// 13-bit immediate field of global_load_b64: a k step is 32 bytes, so eight of them fit.
|
||||
// A fragment from a base pointer plus a compile-time k step. With fragGo's 32-bit element offset,
|
||||
// LLVM re-derives a 64-bit address per fragment per step (a b64 shift and a carry-in add pair); a
|
||||
// constant step instead folds into the 13-bit immediate of global_load_b64 (32 bytes per k step,
|
||||
// so eight fit).
|
||||
//
|
||||
// The pointer is explicitly in the global address space. Held as a plain `const uint2*` it is a
|
||||
// GENERIC pointer once it lives in an array across loop iterations -- LLVM's address-space
|
||||
// inference does not see through that -- and every load becomes flat_load_b64, which on gfx12
|
||||
// increments dscnt as well as loadcnt, so any later LDS wait also waits on HBM.
|
||||
// The element type is a scalar rather than uint2: HIP's vector types are structs whose assignment
|
||||
// operator does not accept an address-space-qualified source, and an 8-byte scalar carries the same
|
||||
// alignment the paired load needs.
|
||||
// The pointer is explicitly global: a plain pointer held in an array across iterations becomes
|
||||
// generic, so loads become flat_load_b64, which on gfx12 also increments dscnt and makes later LDS
|
||||
// waits wait on HBM. The element is a scalar because HIP's vector structs cannot be assigned from
|
||||
// an address-space-qualified source.
|
||||
typedef __attribute__((address_space(1))) const unsigned long long* r4d_gu2;
|
||||
|
||||
__device__ __forceinline__ v8bf fragU(r4d_gu2 p, int u) {
|
||||
@@ -60,13 +44,10 @@ __device__ __forceinline__ v8bf fragU(r4d_gu2 p, int u) {
|
||||
return x.f;
|
||||
}
|
||||
|
||||
// MT = row tiles per BLOCK, held as MT v8f accumulators (8 VGPRs each); grid.y covers the rest.
|
||||
// More row tiles per block amortises the weight fragment over more WMMA, fewer of them put more
|
||||
// blocks on the machine -- which one wins is a per-shape question, so MT is tunable, not assumed.
|
||||
// KU is how many k steps the loop unrolls; see the loop for why it exists.
|
||||
#ifndef KU
|
||||
#define KU 8
|
||||
#endif
|
||||
// MT = row tiles per block, held as MT v8f accumulators (8 VGPRs each); grid.y covers the rest.
|
||||
// More amortises each weight fragment, fewer puts more blocks on the machine, so MT is tunable.
|
||||
// KU is the k-step unroll; see the loop.
|
||||
constexpr int KU = 8;
|
||||
template <int MT>
|
||||
__global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel(
|
||||
const unsigned short* __restrict__ A, const unsigned short* __restrict__ W,
|
||||
@@ -83,20 +64,16 @@ __global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel(
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[i] = (v8f)(0.f);
|
||||
|
||||
// Row offsets as 32-bit ELEMENT offsets: computing them as pointers instead makes the size_t row
|
||||
// stride a 64-bit multiply-add and the row clamp exec-mask work, none of which LLVM keeps live
|
||||
// across the loop. They are turned into pointers ONCE, below.
|
||||
// Row offsets as 32-bit element offsets, turned into pointers once below; as pointers, LLVM
|
||||
// would not keep the 64-bit stride math and the row clamp out of the loop.
|
||||
unsigned woff = rowGo((unsigned)K, n0, N - 1, lane) + (unsigned)kbase;
|
||||
unsigned aoff[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
aoff[i] = rowGo((unsigned)K, (mt0 + i) * 16, M - 1, lane) + (unsigned)kbase;
|
||||
|
||||
// Unrolled so the k step is a load IMMEDIATE rather than an address update. Rolled, LLVM widens
|
||||
// each offset to a 64-bit induction variable and rebuilds the address every step: a b64 shift and
|
||||
// a carry-in add pair per fragment, twenty instructions per step around four WMMA. Unrolled, the
|
||||
// sub-step offset is a constant that folds into the 13-bit field of global_load_b64, and the base
|
||||
// offsets advance once per block of KU.
|
||||
// Unrolled so the k step is a load immediate (the 13-bit field of global_load_b64) and the base
|
||||
// pointers advance once per KU steps; rolled, LLVM rebuilds a 64-bit address every step.
|
||||
if (n0 < N) {
|
||||
r4d_gu2 pw = (r4d_gu2)(const unsigned long long*)(W + woff);
|
||||
r4d_gu2 pa[MT];
|
||||
@@ -125,11 +102,8 @@ __global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// Reduce one row tile at a time: SK partial tiles is WV*SK KiB of LDS whatever MT is, where
|
||||
// holding all MT at once would be four times that at M=64. The sum is spread over every thread
|
||||
// in the block rather than left to the k-split-0 waves, which at SK=8 is one output element per
|
||||
// thread instead of sixty-four; the order over splits is fixed, so the result does not depend on
|
||||
// how the waves were scheduled.
|
||||
// Reduce one row tile at a time, so LDS is WV*SK KiB regardless of MT. Every thread in the block
|
||||
// shares the sum (one element per thread at SK=8); the order over splits is fixed.
|
||||
const int slot = (col_local * SK + ksplit) * 256;
|
||||
const int nthreads = WV * SK * WAVE32;
|
||||
#pragma unroll
|
||||
@@ -145,15 +119,15 @@ __global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel(
|
||||
const int l = off & 31;
|
||||
const int n = (blockIdx.x * WV + col) * 16 + (l & 15);
|
||||
const int m = (mt0 + i) * 16 + 8 * (l >> 4) + (off >> 5);
|
||||
// The language's own float-to-bf16 conversion, deliberately and not the header's f2bf,
|
||||
// which rounds half away from zero.
|
||||
// The language's float-to-bf16 conversion on purpose; the header's f2bf rounds half away
|
||||
// from zero.
|
||||
if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// grid = ceil(ceil(N/16)/WV) blocks; block = WV*SK waves. MT is compile-time so the accumulators
|
||||
// and the fragment loop are exactly the size M needs.
|
||||
// grid = ceil(ceil(N/16)/WV) x ceil(ceil(M/16)/MB) blocks; block = WV*SK waves. MT = MB is
|
||||
// compile-time so the accumulators are sized exactly.
|
||||
void r4d_gemm_bf16_nt_m64(long a, long w, long c, int M, int K, int N, int WV, int SK, int MB,
|
||||
long stream) {
|
||||
if (M < 1 || M > R4D_GEMM64_MAX_M) throw std::runtime_error("r4d gemm_bf16_nt_m64: M out of range");
|
||||
@@ -182,8 +156,7 @@ int r4d_gemm_bf16_nt_m64_max_m(void) { return R4D_GEMM64_MAX_M; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there
|
||||
// is no adapter directory between the core and these launches.
|
||||
// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h.
|
||||
extern "C" int r4d_rad_gemm_bf16_m64(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 0);
|
||||
|
||||
@@ -3,30 +3,21 @@
|
||||
// C[M,N] = A[M,K] @ W[N,K]^T, bf16 in and out, fp32 accumulate: gemm_bf16_nt_m64's arithmetic in a
|
||||
// block shape that reuses what it loads.
|
||||
//
|
||||
// WHY THE SKINNY KERNEL IS THE WRONG SHAPE ABOVE 64 ROWS. It gives a wave one 16-wide N tile and
|
||||
// reads every fragment straight from global memory, so each WMMA costs an activation fragment
|
||||
// load, and every N tile re-reads the whole activation. That is the right trade at decode, where
|
||||
// the weight is the cost; at a 2048-row prefill chunk the activation is the larger operand and it
|
||||
// is read N/16 times. Measured at M = 2048, K = 2560: the MoE router (N 512) 224 us, ~24 TF/s, and
|
||||
// the PLE key projection (N 10240) 3.5 ms, ~31 TF/s, at the kernel's untuned point -- and no point
|
||||
// of its space reaches 50.
|
||||
// The skinny kernel reads every fragment from global memory and re-reads the whole activation per
|
||||
// N tile: right at decode, where the weight is the cost, but at a 2048-row prefill chunk the
|
||||
// activation is read N/16 times and no configuration reaches 50 TF/s.
|
||||
//
|
||||
// HERE a block of eight waves stages a BM x 64 activation tile and a BN x 64 weight tile through
|
||||
// LDS, and each wave computes a (BM/2) x (BN/4) patch from them: every staged fragment feeds
|
||||
// TM or TN WMMA instead of one. The next K tile is loaded into registers while the current one is
|
||||
// computed, so the global latency sits behind four k steps of WMMA.
|
||||
// Here a block of eight waves stages a BM x 64 activation tile and a BN x 64 weight tile through
|
||||
// LDS, and each wave computes a (BM/2) x (BN/4) patch, so each staged fragment feeds TM or TN WMMA.
|
||||
// The next K tile is loaded into registers while the current one is computed.
|
||||
//
|
||||
// BYTE-IDENTICAL TO gemm_bf16_nt_m64, and that is a contract rather than a coincidence. That
|
||||
// kernel splits K into SK slices, accumulates each slice from zero with one WMMA per 16 K in
|
||||
// ascending order, and sums the slices in ascending order starting from 0.f. This one issues the
|
||||
// same WMMA sequence for every output tile, with the same fragment layout, and at the end of each
|
||||
// slice adds the slice into a running fp32 sum that started at 0.f -- the same additions in the
|
||||
// same order. SK comes from the same automatic rule (cfg_for), so an op whose band moves from one
|
||||
// row to the other changes no bit of its output. What differs is only where the operands sit
|
||||
// between global memory and the matrix unit.
|
||||
// Contract: byte-identical to gemm_bf16_nt_m64. Both accumulate each of SK slices from zero with
|
||||
// one WMMA per 16 K in ascending order, using the same fragment layout, and sum the slices in
|
||||
// ascending order from 0.f. SK comes from the same rule (cfg_for), so an op moving between the two
|
||||
// rows changes no output bit.
|
||||
//
|
||||
// Fragment rows are CLAMPED, as in the skinny kernel: a tile that runs past M or N re-reads the
|
||||
// last valid row, computes a result nobody stores, and never touches memory it does not own.
|
||||
// Fragment rows are clamped as in the skinny kernel: rows past M or N re-read the last valid row
|
||||
// and their results are never stored.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -35,10 +26,9 @@
|
||||
#include <cstdint>
|
||||
|
||||
#define BT_BK 64 // K per staged tile: four WMMA k steps
|
||||
// THE LDS ROW PITCH, in elements: 144 bytes. A fragment read has sixteen lanes on sixteen rows at
|
||||
// one k, each reading 8 bytes; at 36 dwords a row the sixteen land on distinct bank pairs, and the
|
||||
// upper half-wave's +2 dwords lands between them. 144 is also a multiple of 16, so a staged
|
||||
// 16-byte chunk is one aligned ds_store_b128.
|
||||
// LDS row pitch in elements (144 bytes). A fragment read is sixteen lanes on sixteen rows, 8 bytes
|
||||
// each; at 36 dwords per row they land on distinct bank pairs, and the upper half-wave's +2 dwords
|
||||
// fall between them. 144 is a multiple of 16, so a staged chunk is one aligned ds_store_b128.
|
||||
#define BT_PITCH (BT_BK + 8)
|
||||
#define BT_WM 2 // waves over M
|
||||
#define BT_WN 4 // waves over N
|
||||
@@ -58,21 +48,19 @@ __global__ __launch_bounds__(256) void r4d_gemm_bf16_nt_tiled_kernel(
|
||||
|
||||
const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31;
|
||||
const int wm = wave / BT_WN, wn = wave % BT_WN;
|
||||
// THE GRID RUNS IN GROUPS OF 8 ACTIVATION BANDS, M fastest inside a group. Blocks are
|
||||
// dispatched in flattened-id order, and the launch's x-fastest grid swept every weight band for
|
||||
// each activation band, reading the whole weight once per 128 rows: free while it sits in the
|
||||
// 64 MB MALL, and half the rate once it does not (N 12288 x K 4096, 96 MB, ran at 68 TFLOP/s
|
||||
// where N 8192 ran at 118). A group keeps its bands' weight tiles shared by the blocks in
|
||||
// flight and reads the weight once a group. Small grids take it too: with fewer bands than a
|
||||
// group the order is plain M-fastest, which is what reads the weight once.
|
||||
// Blocks are remapped into groups of 8 activation bands, M fastest within a group. Blocks
|
||||
// dispatch in flattened-id order; x-fastest order would read the whole weight once per 128 rows,
|
||||
// which halves the rate once the weight exceeds the 64 MB MALL. A group shares weight tiles among
|
||||
// blocks in flight and reads the weight once per group; with fewer bands than a group the order
|
||||
// is plain M-fastest.
|
||||
constexpr unsigned kGroupM = 8;
|
||||
const unsigned per = kGroupM * gridDim.x, lin = blockIdx.y * gridDim.x + blockIdx.x;
|
||||
const unsigned first = lin / per * kGroupM, r = lin % per;
|
||||
const unsigned gm = min(gridDim.y - first, kGroupM);
|
||||
const int m0 = (int)(first + r % gm) * BM, n0 = (int)(r / gm) * BN;
|
||||
|
||||
// Staging: chunk c = tid + 256 i is row c / CPR, elements (c % CPR) * 8 of it. Eight threads
|
||||
// cover a row's 128 bytes, so a warp's loads are four whole lines.
|
||||
// Staging: chunk c = tid + 256 i is row c / CPR, elements (c % CPR) * 8. Eight threads cover a
|
||||
// row's 128 bytes, so a wave's loads are four whole lines.
|
||||
unsigned aoff[AL], woff[WL];
|
||||
unsigned short* adst[AL];
|
||||
unsigned short* wdst[WL];
|
||||
@@ -140,10 +128,9 @@ __global__ __launch_bounds__(256) void r4d_gemm_bf16_nt_tiled_kernel(
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) acc[i][j] = mma(af[i], bf[j], acc[i][j]);
|
||||
/* A K STEP'S FRAGMENT READS, THEN ITS PRODUCTS, as the scheduler's groups. Left to itself,
|
||||
* gfx12's compiler spreads each step's LDS reads among the previous step's WMMAs and waits on
|
||||
* them early; grouped, the 128 x 128 tile measured 6 to 9% faster than LLVM 22's schedule at
|
||||
* Flash-Next's shapes (M 384 to 2048, K 2560, N 2560 and 10240). */
|
||||
/* Schedule each k step's fragment reads, then its products. Otherwise the compiler spreads
|
||||
* LDS reads among the previous step's WMMAs and waits on them early; grouping is 6-9% faster
|
||||
* on the 128 x 128 tile at M 384..2048, K 2560. */
|
||||
__builtin_amdgcn_sched_group_barrier(0x100, TM + TN, 0); /* DS reads */
|
||||
__builtin_amdgcn_sched_group_barrier(0x008, TM * TN, 0); /* WMMA */
|
||||
if constexpr (SPLIT) {
|
||||
@@ -179,13 +166,10 @@ __global__ __launch_bounds__(256) void r4d_gemm_bf16_nt_tiled_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// THE TWO TILES, and the rule between them. A block walks the whole of K alone, so its time is a
|
||||
// floor -- ~40 us at K = 2560 -- and a grid too small to fill the part pays it with idle CUs:
|
||||
// at M = 200, N = 512 the 128 x 128 tile is an eight-block grid. Measured at K = 2560 (us, 128 x
|
||||
// 128 / 64 x 64): M 2048 N 512 66 / 114, N 2560 341 / 644, N 10240 1627 / 2661; M 500 N 512 41 / 31,
|
||||
// N 2560 92 / 163; M 200 N 512 39 / 26, N 2560 66 / 72; M 80 N 2560 50 / 45. The large tile wins
|
||||
// once its grid is 32 blocks, half the part's CUs, and loses by less than the small one does
|
||||
// below that. (64 x 128 and 128 x 64 gain no more than a few percent over these.)
|
||||
// Tile choice. A block walks all of K alone, so its time is a floor (~40 us at K = 2560), and a
|
||||
// grid too small to fill the part leaves CUs idle (M = 200, N = 512 is eight 128 x 128 blocks).
|
||||
// At K = 2560 the 128 x 128 tile wins once its grid reaches 32 blocks (half the CUs) and loses by
|
||||
// less than the 64 x 64 tile does below that. 64 x 128 and 128 x 64 gain only a few percent.
|
||||
enum { kBtLargeGrid = 32 };
|
||||
|
||||
int r4d_gemm_bf16_nt_tiled_arm(int M, int N) {
|
||||
@@ -221,8 +205,7 @@ extern "C" int r4d_rad_gemm_bf16_tiled(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 0);
|
||||
if (rc != RAD_OK) return rc;
|
||||
// THE SPLIT IS THE SKINNY ROW'S, resolved by the same rule from the same arguments, which is
|
||||
// what keeps the two rows' outputs identical.
|
||||
// The skinny row's split rule with the same arguments keeps the two rows' outputs identical.
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, g.M, 16, BR_FLAT, &c, (g.N + 15) / 16);
|
||||
if (rc != RAD_OK) return rc;
|
||||
|
||||
+181
-534
File diff suppressed because it is too large.
Load diff
+384
-938
File diff suppressed because it is too large.
Load diff
@@ -1,57 +1,45 @@
|
||||
// r4d_gemm_mxfp4a8_decode.hip - r4d_gemm_mxfp4a8_decode: the OCP-MXFP4 x fp8 GEMM for the DECODE
|
||||
// band, M <= 128, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T over the same operands, weight
|
||||
// layout and fold as r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_tiled.
|
||||
// r4d_gemm_mxfp4a8_decode.hip - r4d_gemm_mxfp4a8_decode: the OCP-MXFP4 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 and
|
||||
// fold of r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_tiled.
|
||||
//
|
||||
// WHY A THIRD MXFP4 KERNEL. At decode the GEMM is a weight stream: a speculative verify step is
|
||||
// a handful of rows against the whole 4-bit trunk, and the only number that matters is how close
|
||||
// the stream runs to the card's DRAM bandwidth. The skinny kernel splits K inside one workgroup
|
||||
// and reads the weight straight into registers, which leaves the narrow projections well short of
|
||||
// it. This one splits K ACROSS workgroups with a fused last-arriver reduction, unpacks the weight
|
||||
// through LDS, gives each block one 16-row A fragment per M tile, and streams the weight with
|
||||
// non-temporal loads.
|
||||
// At decode the GEMM is a weight stream and the goal is DRAM bandwidth. The skinny kernel (split-K
|
||||
// within a workgroup, weight straight to registers) falls short on narrow projections. This one
|
||||
// splits K across workgroups with a fused last-arriver reduction, unpacks the weight through LDS,
|
||||
// and streams it with non-temporal loads.
|
||||
//
|
||||
// THE TILE. A block is DWN = 8 waves over BND = 128 output columns, one 16-column fragment a wave,
|
||||
// and DTM 16-row M fragments -- the SMALLEST that covers M, because a wider tile computes rows
|
||||
// nobody asked for. A K slab of DBK bytes is staged: A (16*DTM rows) and the weight's 128 rows,
|
||||
// unpacked to e4m3 with the block exponent folded in through r4d_mxfp4.h, as the other two MXFP4
|
||||
// kernels fold it.
|
||||
// Tile: DWN = 8 waves over BND = 128 output columns (one 16-column fragment per wave) and DTM
|
||||
// 16-row M fragments, the fewest that cover M. Each K slab of DBK bytes stages A (16*DTM rows) and
|
||||
// 128 weight rows, unpacked to e4m3 through r4d_mxfp4.h.
|
||||
//
|
||||
// SPLIT-K IS NOT OPTIONAL. With one 16-row M fragment the independent N fragments number N/16, so
|
||||
// N=5120 is 320 waves -- 2.5 a SIMD however the N tile is chosen. DKS blocks split the K slabs;
|
||||
// each writes an fp32 partial [DKS][M][N] and the LAST to arrive (an agent-scope counter per column
|
||||
// block) sums them in place, so there is no second launch.
|
||||
// Split-K is required: N/16 fragments alone (320 waves at N=5120) do not fill the part. DKS blocks
|
||||
// split the K slabs; each writes an fp32 partial [DKS][M][N], and the last to arrive (an
|
||||
// agent-scope counter per column block) sums them, with no second launch.
|
||||
//
|
||||
// THE SPLIT, SLAB AND LOAD HINT are a rule measured cell by cell on this kernel -- every split x
|
||||
// slab x hint against the 27B's per-rank shapes at M = 8..128, DRAM-fed -- because no single
|
||||
// fill target fits: the split is the smallest power of two whose grid reaches 48 blocks at M <= 16,
|
||||
// 56 at M <= 96 and 40 above (an unsplit 40-block grid already streams a short-K weight at the
|
||||
// card's rate there, and a split's partial traffic grows with M); a deep K (8192 or more, down at
|
||||
// K=8704) keeps doubling while a split still has 24 or more 128-wide slabs, since 40-odd blocks
|
||||
// do not keep its long slab loop fed; and no split goes past ks*M = 512, where the partials
|
||||
// outweigh what the split buys. The slab is 128 except where LDS per block, (16*DTM + 128) *
|
||||
// (DBK+8) bytes, would cost a wide or deeply split grid its resident blocks (see mxd_plan); a K
|
||||
// that is not a multiple of 128 takes 64 (and a 2-way split widens to 4). Weight loads are non-temporal for weights of 4 MiB or more,
|
||||
// plain below, where the weight is too small to evict anything the split partials need. All three
|
||||
// are tunables (`ks`, `bk`, `nt`) whose 0 is this rule.
|
||||
// Split, slab and load hint follow a rule tuned per cell on the 27B's per-rank shapes at
|
||||
// M = 8..128 (tunables `ks`, `bk`, `nt`; 0 selects the rule):
|
||||
// - split: the smallest power of two whose grid reaches 48 blocks at M <= 16, 56 at M <= 96 and
|
||||
// 40 above; for K >= 8192 keep doubling while a split has >= 24 128-wide slabs; never past
|
||||
// ks*M = 512, where partial traffic outweighs the gain.
|
||||
// - slab: 128, or 64 where LDS per block, (16*DTM + 128) * (DBK+8) bytes, would cost a wide or
|
||||
// deeply split grid its resident blocks (see mxd_plan). A K not a multiple of 128 takes 64 (and
|
||||
// a 2-way split widens to 4).
|
||||
// - non-temporal weight loads for weights of 4 MiB or more.
|
||||
//
|
||||
// NO STATE IS KEYED ON THE STREAM. The split partial is the op's own scratch -- the core sizes it
|
||||
// from the scratch hook and treats it as read+write, so two ops that could overlap get disjoint
|
||||
// slices -- and the arrival counters are a small block keyed on the OUTPUT buffer (mxd_out_ctr),
|
||||
// zero at entry and left zero by the reducer. A recorded pass is replayed with its recorded
|
||||
// arguments, possibly on another stream than it was recorded on, so a pointer that depended on the
|
||||
// stream would make the replay differ from its recording. Two launches writing the same output are
|
||||
// ordered by that dependency; two that can overlap write different outputs. The row is therefore
|
||||
// concurrent (rad_kernel_concurrent), as gemm_fp8a8_nt_m16 is. A scratch shorter than the split
|
||||
// needs is refused: the hook sizes it for every M of the band, so a short one is a caller's error.
|
||||
// No state is keyed on the stream, since a recorded pass may replay on another stream. The split
|
||||
// partial is the op's scratch (sized by the scratch hook, read+write, so overlapping ops get
|
||||
// disjoint slices); the arrival counters are keyed on the output buffer (mxd_out_ctr), zero at
|
||||
// entry and reset by the reducer. Launches writing the same output are ordered; overlapping ones
|
||||
// write different outputs. The row is therefore concurrent (rad_kernel_concurrent), like
|
||||
// gemm_fp8a8_nt_m16. A scratch shorter than the split needs is refused.
|
||||
//
|
||||
// Every thread fences its partial stores before the counter: a fence on thread 0 alone orders
|
||||
// only thread 0's stores, and the reducer would then read whatever happened to drain.
|
||||
// Every thread fences its partial stores before the counter; a fence on thread 0 alone would order
|
||||
// only its own stores.
|
||||
//
|
||||
// TWO ACTIVATION SCALE GRIDS, as in the tiled kernel: one f32 a row, or one a (row, 128 of K). The
|
||||
// per-block form carries each row's accumulator in the current block's scale and rescales it by
|
||||
// s_prev / s_next at each 128 boundary, the ratio computed once a row into LDS from scales loaded a
|
||||
// boundary early; with the accumulator transposed a lane reads one ratio for each of its rows. A split's partial is brought back
|
||||
// to absolute units before it is written, because the splits end in different blocks.
|
||||
// Two activation scale grids as in the tiled kernel: one f32 per row, or one per (row, 128 of K).
|
||||
// The block form carries each row's accumulator in the current block's scale, rescaling by
|
||||
// s_prev / s_next at each boundary (ratio computed once per row into LDS from scales loaded a
|
||||
// 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_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -81,22 +69,17 @@ static __device__ __forceinline__ T mxd_ld(const T* p) {
|
||||
else return *p;
|
||||
}
|
||||
|
||||
// ---- what both kernels share: the scale grid at a 128 boundary, and the epilogue.
|
||||
// ---- 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 its A operand and the
|
||||
// activation fragment as its B operand -- the two fragments have the same register layout, so
|
||||
// this is only an argument order -- and computes C^T: a lane's accumulator for M fragment i holds
|
||||
// ONE row, m = 16i + col, and the eight consecutive columns n0 + 16*wave + kb8 + e. So a row's
|
||||
// activation scale is one value a lane, not eight: the (row, 128) grid's boundary rescale reads
|
||||
// DTM scales instead of 8*DTM, and the epilogue writes each lane's eight outputs as one 16-byte
|
||||
// store (one 32-byte store of partials) instead of eight 2-byte ones.
|
||||
// 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, computed once a row: thread t < ROWS owns row t. It loads the next
|
||||
// 128 boundary's two scales -- the block that starts there and the one before it -- a boundary
|
||||
// early, writes the row's ratio s_prev / s_next to LDS at the boundary (published by the staging
|
||||
// barrier), and a lane then reads ONE ratio for each of its rows. A zero block keeps the carried
|
||||
// scale; a zero block before this one sends the carried scale back to the grid, which only an
|
||||
// all-zero activation block ever does.
|
||||
// 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 mxd_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;
|
||||
@@ -112,9 +95,9 @@ static __device__ __forceinline__ void mxd_rescale(v8f (&acc)[DTM], const float*
|
||||
}
|
||||
}
|
||||
|
||||
// The split's result: written straight to C when the accumulator holds the whole K range, 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).
|
||||
// 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 mxd_epilogue(
|
||||
const v8f (&acc)[DTM], const float* __restrict__ As, int as_rs,
|
||||
@@ -125,8 +108,8 @@ static __device__ __forceinline__ void mxd_epilogue(
|
||||
constexpr int ROWS = R4D_MXD_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, once a row: the scale the split's accumulators end in (ABLK), or the
|
||||
// row's own. The K loop's closing barrier retired the last ratio reads.
|
||||
// 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];
|
||||
@@ -178,7 +161,7 @@ static __device__ __forceinline__ void mxd_epilogue(
|
||||
}
|
||||
}
|
||||
}
|
||||
// EVERY thread's partial stores are ordered before the counter, then the last arriver reduces.
|
||||
// Every thread's partial stores are ordered before the counter; then the last arriver reduces.
|
||||
__threadfence();
|
||||
__syncthreads();
|
||||
if (tid == 0)
|
||||
@@ -186,7 +169,7 @@ static __device__ __forceinline__ void mxd_epilogue(
|
||||
__HIP_MEMORY_SCOPE_AGENT);
|
||||
__syncthreads();
|
||||
if (*s_last != (unsigned)(DKS - 1)) return;
|
||||
if (tid == 0) cnt[blockIdx.x] = 0u; // left clean for the next launch on this stream
|
||||
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) {
|
||||
@@ -200,12 +183,10 @@ static __device__ __forceinline__ void mxd_epilogue(
|
||||
}
|
||||
}
|
||||
|
||||
/* THE WAVES A SIMD EACH TILE SHAPE RUNS AT (R4D_WAVES): the register budget the decode tile was
|
||||
* tuned at, by K block, M fragments and activation-scale form, so a compiler release cannot move
|
||||
* it -- LLVM 24 adds two VGPRs to the DBK 64, three-fragment form and drops it from sixteen waves to
|
||||
* twelve. Where LLVM 22 itself ran out of registers (DBK 128 at seven and eight fragments without
|
||||
* block activation scales, 256 VGPRs and a spill) the budget is the one the tile reaches without
|
||||
* spilling. */
|
||||
/* 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. */
|
||||
constexpr int mxd_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)
|
||||
@@ -281,8 +262,8 @@ void r4d_gemm_mxfp4a8_decode_kernel(
|
||||
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 gn = n0 + r;
|
||||
// gn is even and N % 16 == 0: clamping to the last even row keeps the 8 B read aligned and
|
||||
// gc + 1 in bounds; the slot address is recomputed from the clamped row.
|
||||
// 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 mxd_u2 wv =
|
||||
@@ -328,13 +309,10 @@ void r4d_gemm_mxfp4a8_decode_kernel(
|
||||
kb_end, &s_last, sR);
|
||||
}
|
||||
|
||||
// THE ONE-FRAGMENT FORM (M <= 16), which is every single-sequence verify step. The same tile, fold
|
||||
// and split as above, with two changes that pay only when one M fragment leaves the block waiting
|
||||
// on memory: the NEXT slab's A, codes and exponents are loaded into registers while this slab
|
||||
// computes, so a block keeps its loads in flight across the WMMA phase instead of draining at every
|
||||
// barrier; and a thread takes four adjacent slots, one 16 B load instead of two 8 B ones. Each
|
||||
// row's reference exponent is read once, not once a slab. Bit-identical to the kernel above at
|
||||
// every split: the K order, the fold and the reduction are unchanged.
|
||||
// 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 and exponents 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_MXD_DWN * 32) R4D_WAVES(DBK == 64 ? 16 : 12)
|
||||
void r4d_gemm_mxfp4a8_decode1_kernel(
|
||||
@@ -479,10 +457,10 @@ void r4d_gemm_mxfp4a8_decode1_kernel(
|
||||
}
|
||||
|
||||
namespace {
|
||||
// THE ARRIVAL COUNTERS, one block an output buffer -- see the header. The counters cannot live in
|
||||
// the scratch: other ops write the arena between two of ours, and the counters must be zero at
|
||||
// entry. So they are a small device allocation of their own, taken once per (device, output) and
|
||||
// kept zero by the reducer, as gemm_fp8a8_nt_m16 keys its split_ctr.
|
||||
// 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.
|
||||
unsigned* mxd_out_ctr(const void* out) {
|
||||
static std::mutex mu;
|
||||
static std::map<std::pair<int, const void*>, unsigned*> blocks;
|
||||
@@ -499,9 +477,8 @@ unsigned* mxd_out_ctr(const void* out) {
|
||||
return p;
|
||||
}
|
||||
|
||||
// THE SPLIT, SLAB AND LOAD HINT A LAUNCH RUNS, from M, the shape and the tunables (0 = the rule).
|
||||
// One function for the launch and the scratch hook, so the partial the hook sizes is the one
|
||||
// written. See the header for the rule and what it was measured on.
|
||||
// The split, slab and load hint for a launch, from M, the shape and the tunables (0 = the rule; see
|
||||
// the header). Shared by the launch and the scratch hook so the sized partial is the one written.
|
||||
struct MxdPlan { int ks, bk; bool nt; };
|
||||
MxdPlan mxd_plan(int M, int K, int N, int KS, int BK, int NT) {
|
||||
const int nblk = (N + R4D_MXD_DWN * 16 - 1) / (R4D_MXD_DWN * 16);
|
||||
@@ -513,9 +490,8 @@ MxdPlan mxd_plan(int M, int K, int N, int KS, int BK, int NT) {
|
||||
if (K >= 8192) // a deep K: a split of 24 or more slabs still waits on them
|
||||
while (ks < R4D_MXD_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, (16*DTM + 128)*(DBK+8) bytes, costs a wide or deeply split
|
||||
// grid its resident blocks: DTM 4 unsplit on 110+ column blocks, and DTM 8 on those or at a 4-way
|
||||
// split.
|
||||
// 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));
|
||||
@@ -632,11 +608,10 @@ extern "C" int r4d_rad_gemm_mxfp4a8_decode(const RadArgs* a, RadStream s) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The core sizes the op's scratch from this. `M` is the band's widest, and a narrower M can split
|
||||
* wider (the fill rule asks for more blocks at M <= 24), so the size is the widest split over the
|
||||
* band times its widest M -- an upper bound on every launch the band can make. A partitioned
|
||||
* weight launches each part at ITS rows, which splits wider than the whole would, so the bound is
|
||||
* the largest of the parts' (they run one after another and share the scratch). */
|
||||
/* 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_mxfp4a8_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);
|
||||
|
||||
@@ -3,87 +3,51 @@
|
||||
// e4m3 and W stored as OCP micro-scaling fp4: an e2m1 element per nibble and one E8M0 exponent
|
||||
// per 32 elements along K.
|
||||
//
|
||||
// WHY THIS EXISTS ALONGSIDE r4d_gemm_w4a8_nt_m64. That kernel's 4-bit code is an int4 the library
|
||||
// derives at load; this one's is a checkpoint format it does not get to choose. An MXFP4
|
||||
// checkpoint arrives with its own per-32 E8M0 exponents, and a serving stack that re-derives them
|
||||
// as int4 has quantised twice. The two also want different matrix instructions -- iu8 there, fp8
|
||||
// here -- and on this part both run at the same rate, so the format is the whole decision:
|
||||
// Unlike r4d_gemm_w4a8_nt_m64, whose int4 code the library derives, this reads a checkpoint
|
||||
// format: MXFP4 ships its own per-32 E8M0 exponents, and re-deriving int4 would quantise twice. The
|
||||
// fp8 WMMA runs at the iu8 rate on this part (f16 207 TF/s; fp8 412; iu8 407).
|
||||
//
|
||||
// v_wmma_f32_16x16x16_f16 207 TF/s 5.95 cyc/instr
|
||||
// v_wmma_f32_16x16x16_fp8_fp8 412 2.99
|
||||
// v_wmma_i32_16x16x16_iu8 407 3.03
|
||||
// The per-32 exponent is folded into the element. With a per-row reference Wref[n] =
|
||||
// max_k E8M0[n][k] (computed offline), d = Wref[n] - E8M0[n][blk] is folded into the e4m3 value:
|
||||
// the e2m1 magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} scaled by 2^-d are e4m3 numbers, so a 16-entry
|
||||
// table indexed by d replaces the per-element multiply with a v_perm_b32. One factor per row,
|
||||
// 2^(Wref[n]-127), is applied in the epilogue with the activation scale.
|
||||
//
|
||||
// THE PER-32 EXPONENT IS FOLDED INTO THE ELEMENT, WHICH IS WHY THE UNPACK IS CHEAP. The naive
|
||||
// MXFP4 dequant multiplies each element by 2^(E8M0-127), which is a per-32-block rescale inside
|
||||
// the inner loop and puts a multiply on every weight. Instead, take a per-ROW reference exponent
|
||||
// Wref[n] = max_k E8M0[n][k] once, offline, and fold the difference d = Wref[n] - E8M0[n][blk]
|
||||
// into the e4m3 VALUE: the eight e2m1 magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} scaled by 2^-d are
|
||||
// themselves e4m3 numbers, so a 16-entry table of packed e4m3 bytes indexed by d replaces the
|
||||
// multiply with a v_perm_b32. What is left is one factor per row, 2^(Wref[n]-127), applied once
|
||||
// in the epilogue next to the activation's own per-row scale.
|
||||
// The table extends into e4m3 subnormals: stopping at 2^-6 would flush 6.7% of one checkpoint's
|
||||
// weights (per-channel errors up to 18.7%). Down to 2^-9 every d <= 8 is exact, which relies on the
|
||||
// gfx12 fp8 WMMA honouring e4m3 subnormals (exact for every m*2^-9, m = 1..7). d >= 13 is zero.
|
||||
//
|
||||
// The table runs into e4m3 SUBNORMALS on purpose. Stopping at the smallest normal (2^-6) flushes
|
||||
// every element whose block exponent is more than 5 binades below its row reference; on this
|
||||
// checkpoint that is 6.7% of the weights on 36 output channels, for per-channel errors up to
|
||||
// 18.7%. Extending to 2^-9 makes every d <= 8 exact. That is only sound because the gfx12 fp8
|
||||
// WMMA HONOURS e4m3 subnormals rather than flushing them: the product is exact for every m*2^-9,
|
||||
// m = 1..7. d >= 13 rounds to zero, which is correct: those elements are below the
|
||||
// representable range of the row.
|
||||
// Unpack (r4d_mxfp4.h): four v_perm_b32 per eight weights, no multiply. The scale lookup is once
|
||||
// per fragment: eight consecutive k at an offset that is a multiple of 8 lie in one 32-block.
|
||||
//
|
||||
// UNPACK IS FOUR v_perm_b32 PER EIGHT WEIGHTS. A lane's fragment is eight consecutive k, which is
|
||||
// four packed bytes. Splitting the low and high nibbles gives the even and odd elements; each is
|
||||
// mapped through the folded-magnitude table by a v_perm_b32 that indexes it with the 3-bit
|
||||
// magnitude, the sign rides along as bit 3 shifted into the e4m3 sign position, and two more
|
||||
// v_perm_b32 interleave the halves back into k order. No multiply, no exponent arithmetic in the
|
||||
// loop, and the scale lookup is once per fragment rather than once per element: eight consecutive
|
||||
// k always lie inside one 32-element block, because the fragment's k offset is a multiple of 8.
|
||||
// Split-K is within the workgroup, reduced in LDS: N/16 tiles alone do not fill the part (320
|
||||
// waves at N=5120), and a cross-workgroup split would need an HBM partial buffer and a counter.
|
||||
// The kernel needs no scratch, so it is graph-replay safe.
|
||||
//
|
||||
// SPLIT-K IS IN THE WORKGROUP, AS EVERYWHERE ELSE IN THIS LIBRARY. With one 16-row M fragment the
|
||||
// independent N fragments number N/16 -- 320 waves at N=5120 -- which does not fill the part, so
|
||||
// the K range has to be split. Doing it across workgroups needs an fp32 partial buffer in HBM and
|
||||
// a counter to decide who reduces; doing it across waves of one workgroup reduces in LDS and needs
|
||||
// neither. The LDS form is also what keeps this kernel cudagraph-safe with no scratch to register:
|
||||
// a caller can replay it without having handed the library any memory.
|
||||
//
|
||||
// THE WEIGHT IS PRE-PERMUTED INTO FRAGMENT ORDER, AS IT IS FOR w4a16/w4a8. A B fragment maps lane
|
||||
// l onto N row l&15, so in checkpoint order the sixteen lanes of a half-wave read sixteen rows K/2
|
||||
// bytes apart -- a fully strided read on the operand that dominates traffic. Reordering the weight
|
||||
// once at load fixes it and is what lets this kernel skip LDS entirely.
|
||||
//
|
||||
// The layout is one 32-lane slot per (n-tile, k-step):
|
||||
// The weight is pre-permuted into fragment order (as for w4a16/w4a8). In checkpoint order the
|
||||
// sixteen lanes of a half-wave would read rows K/2 bytes apart. The layout is one 32-lane slot per
|
||||
// (n-tile, k-step):
|
||||
//
|
||||
// Wp[((n/16) * (K/16) + (k/16)) * 32 + lane] one uint32 = 4 packed bytes = 8 elements
|
||||
//
|
||||
// where lane's row is 16*(n/16) + (lane&15) and its eight elements start at k + 8*(lane>>4). A
|
||||
// wave then reads 128 contiguous bytes per step. In checkpoint terms, taking W as
|
||||
// [N/16][16][K/16][8] bytes, slot l of tile (nt, ks) is W[nt][l&15][ks][4*(l>>4) .. +4].
|
||||
// permute_w() in mxfp4_layout.py is the reference implementation.
|
||||
// where lane's row is 16*(n/16) + (lane&15) and its eight elements start at k + 8*(lane>>4); a wave
|
||||
// reads 128 contiguous bytes per step. Taking W as [N/16][16][K/16][8] bytes, slot l of tile
|
||||
// (nt, ks) is W[nt][l&15][ks][4*(l>>4) .. +4]. permute_w() in mxfp4_layout.py is the reference.
|
||||
// With the permute this LDS-free kernel beats an LDS-staged one on every shape; without it, it
|
||||
// loses on every shape. The E8M0 scales stay in [K/32][N] order (a half-wave reads sixteen
|
||||
// consecutive bytes).
|
||||
//
|
||||
// The permute is what makes the LDS-free form worth having. Reading checkpoint order directly,
|
||||
// this kernel is slower than an LDS-staged one on every shape; with the permute it is faster than
|
||||
// the LDS-staged form on every shape, at both ends of the M range. It also moves the tuning: the
|
||||
// fastest configs are the ones with deeper split-K (SK 4-8) and NPW 2, which only pay once the
|
||||
// weight read coalesces.
|
||||
// Two activation scale grids, as in r4d_gemm_mxfp4a8_tiled.hip: one f32 per row (ABLK=false) or
|
||||
// one per (row, 128 of K) (ABLK=true). With ABLK each wave carries its partial sums in units of the
|
||||
// current block's scale, rescaling by s_prev / s_next at each boundary. Split-K segments end in
|
||||
// different blocks, so each partial is multiplied by its last scale before the LDS reduction, and
|
||||
// the epilogue applies only the weight's reference factor.
|
||||
//
|
||||
// The E8M0 scales are left in [K/32][N] order -- a half-wave reads sixteen consecutive bytes of
|
||||
// those already.
|
||||
// Benchmarking note: a weight of tens of MB streamed in a loop stays Infinity-Cache resident, so
|
||||
// such a bandwidth figure can exceed the DRAM roofline.
|
||||
//
|
||||
// TWO ACTIVATION SCALE GRIDS, as in r4d_gemm_mxfp4a8_tiled.hip: one f32 per row (ABLK=false), or
|
||||
// one per (row, 128 of K) (ABLK=true, the block-scaled fp8 family's grid). With ABLK each wave
|
||||
// carries its partial sums in units of the current 128-block's scale and rescales them by
|
||||
// s_prev / s_next at each block boundary inside its split-K segment. The segments end in
|
||||
// DIFFERENT blocks, so each partial is brought back to absolute units -- multiplied by its own
|
||||
// last scale -- before the LDS reduction adds them, and the epilogue applies only the weight's
|
||||
// reference factor.
|
||||
//
|
||||
// TRAP FOR ANYONE MEASURING THIS KERNEL: a weight of tens of megabytes streamed in a loop is
|
||||
// Infinity-Cache resident on this part, so a bandwidth figure taken that way can read above the
|
||||
// DRAM roofline. It ranks kernels reading the same bytes; it is not achieved DRAM bandwidth.
|
||||
//
|
||||
// A IS NOT STAGED IN LDS. A lane's A fragment is eight consecutive bytes of one row, so the
|
||||
// global load already has the shape the fragment wants; staging it would cost LDS, a barrier and a
|
||||
// second read for nothing. Rows past M are CLAMPED rather than masked -- a tile past M recomputes
|
||||
// the last valid row and the store discards it -- which keeps the inner loop branch-free.
|
||||
// A is not staged in LDS: a lane's A fragment is eight consecutive bytes of one row. Rows past M are
|
||||
// clamped, not masked, keeping the inner loop branch-free.
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_mxfp4.h"
|
||||
@@ -99,8 +63,8 @@
|
||||
typedef int v2i __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned uint2v __attribute__((ext_vector_type(2)));
|
||||
|
||||
// Eight e2m1 codes (four packed bytes) -> the B fragment, eight e4m3 bytes in k order with the
|
||||
// block's exponent difference folded in (r4d_mxfp4.h, shared with the other two MXFP4 kernels).
|
||||
// Eight e2m1 codes (four packed bytes) -> the B fragment: eight e4m3 bytes in k order with the
|
||||
// block's exponent difference folded in (r4d_mxfp4.h).
|
||||
__device__ __forceinline__ v2i r4d_mxfp4_frag8(unsigned int wv, int d) {
|
||||
unsigned int lo, hi;
|
||||
r4d_mxfp4_unpack8(wv, d, &lo, &hi);
|
||||
@@ -130,11 +94,9 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
// Column tiles this wave owns, CLAMPED to the last real tile. grid.x rounds N/16 up to a
|
||||
// multiple of ncols = WV*NPW, so the tail block addresses tiles that do not exist -- at N=48
|
||||
// with ncols=4 it reaches tile 3 of 3. Clamping the TILE (not just the row) matters because the
|
||||
// weight is indexed by tile: an unclamped tile index walks off the end of the buffer, which is a
|
||||
// GPU memory fault rather than a wrong answer. The epilogue still drops these columns.
|
||||
// Column tiles this wave owns, clamped to the last real tile: grid.x rounds N/16 up to a multiple
|
||||
// of WV*NPW, and the weight is indexed by tile, so an unclamped index would fault. The epilogue
|
||||
// drops these columns.
|
||||
const int ntmax = N / 16 - 1;
|
||||
int wtile[NPW], wrow[NPW];
|
||||
unsigned char wref[NPW];
|
||||
@@ -149,7 +111,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
|
||||
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
|
||||
const int ksteps = K / 16;
|
||||
|
||||
// ABLK: the scale each accumulator row of this lane is carried in -- row (mt0+i)*16 + mhalf + e.
|
||||
// ABLK: the scale each accumulator row of this lane is carried in (row (mt0+i)*16 + mhalf + e).
|
||||
float scur[ABLK ? MT : 1][8];
|
||||
if constexpr (ABLK) {
|
||||
#pragma unroll
|
||||
@@ -196,9 +158,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int n = wrow[j];
|
||||
// Fragment-order weight: lane l's four bytes for this (n-tile, k-step) sit at slot l, so the
|
||||
// wave reads 128 contiguous bytes. In checkpoint order these would be sixteen rows K/2 bytes
|
||||
// apart -- a fully strided read on the operand that dominates traffic.
|
||||
// Fragment-order weight: lane l's four bytes for this (n-tile, k-step) are at slot l.
|
||||
const unsigned int wv = Wp[((size_t)wtile[j] * ksteps + kstep) * WAVE32 + lane];
|
||||
const v2i wf = r4d_mxfp4_frag8(wv, r4d_mxfp4_fold_d(wref[j], Ws[(size_t)blk * ldws + n]));
|
||||
#pragma unroll
|
||||
@@ -223,10 +183,9 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
|
||||
// One pass over the block's 256-element tiles; every thread takes a stride.
|
||||
for (int t = tid; t < ncols * 256; t += blockDim.x) {
|
||||
const int col = t >> 8, off = t & 255;
|
||||
// off = lane*8 + e, so the lane is off>>3 -- but a lane's N index is lane&15, and its
|
||||
// eight accumulator elements are the M values 8*(lane>>4)+e. Using the whole lane id for N
|
||||
// writes the upper half-wave into the NEXT column tile; it is invisible for M <= 8 because
|
||||
// those rows are then out of range and dropped by the guard below.
|
||||
// off = lane*8 + e. A lane's N index is lane&15 and its eight elements are M rows
|
||||
// 8*(lane>>4)+e; using the whole lane id for N would write the upper half-wave into the
|
||||
// next column tile.
|
||||
const int n = (blockIdx.x * ncols + col) * 16 + ((off >> 3) & 15);
|
||||
const int m = (mt0 + i) * 16 + ((off >> 7) << 3) + (off & 7);
|
||||
if (n >= N || m >= M) continue;
|
||||
@@ -245,9 +204,8 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l
|
||||
int M, int K, int N, int WV, int SK, int MB, int NPW,
|
||||
int as_group, int as_rs, long stream,
|
||||
int lda, int ldws, int ldc) {
|
||||
// The operands of one PART of a partitioned weight (ParoQuant) are windows of larger planes:
|
||||
// the activation a row of lda bytes, the exponents a row of ldws, the output a row of ldc.
|
||||
// 0 is the plane's own width, which is every other caller.
|
||||
// A part of a partitioned weight (ParoQuant) reads windows of larger planes: activation rows of
|
||||
// lda bytes, exponent rows of ldws, output rows of ldc. 0 means the plane's own width.
|
||||
if (!lda) lda = K;
|
||||
if (!ldws) ldws = N;
|
||||
if (!ldc) ldc = N;
|
||||
@@ -304,8 +262,7 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there
|
||||
// is no adapter directory between the core and these launches.
|
||||
// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h.
|
||||
extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
|
||||
@@ -313,9 +270,8 @@ extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) {
|
||||
if (g.N % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
if (g.M > r4d_gemm_mxfp4a8_nt_m64_max_m()) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale) return R4D_NO(RAD_E_INVAL);
|
||||
/* The per-row reference exponent is a weight aux stream and RadArgs has no way to deliver one,
|
||||
* so gemm_nt_q carries it as a trailing optional weight operand. Without it the fold has no
|
||||
* reference and every element would be scaled against zero. */
|
||||
/* The per-row reference exponent arrives as gemm_nt_q's trailing optional operand (RadArgs
|
||||
* cannot carry a weight aux stream); the fold needs it. */
|
||||
if (!g.bref) return R4D_NO(RAD_E_INVAL);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
|
||||
@@ -1,74 +1,52 @@
|
||||
// r4d_gemm_mxfp4a8_tiled.hip - r4d_gemm_mxfp4a8_tiled: the OCP-MXFP4 x fp8 GEMM for PREFILL row
|
||||
// counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the same operands, the same weight
|
||||
// layout and the same fold as r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_decode -- the band
|
||||
// above theirs.
|
||||
// r4d_gemm_mxfp4a8_tiled.hip - r4d_gemm_mxfp4a8_tiled: the OCP-MXFP4 x fp8 GEMM for prefill row
|
||||
// counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the operands, weight layout and fold
|
||||
// of r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_decode, for the band above theirs.
|
||||
//
|
||||
// WHY A SEPARATE KERNEL. The decode kernels give a block at most 128 rows, so at prefill they
|
||||
// would re-read the whole weight ceil(M/128) times. Here a block is a 256 x (32*TN) tile and each
|
||||
// weight byte is unpacked once per K slab into LDS, where all four row-waves of the block read it.
|
||||
// The decode kernels cover at most 128 rows per block, so at prefill they would re-read the weight
|
||||
// ceil(M/128) times. Here a block is a 256 x (32*TN) tile and each weight byte is unpacked once per
|
||||
// K slab into LDS, shared by the block's four row-waves.
|
||||
//
|
||||
// A COMES STRAIGHT FROM GLOBAL INTO REGISTERS, NOT THROUGH LDS. Staging A through LDS costs a
|
||||
// write, a barrier and a second read of the operand the block uses most, and a WMMA A fragment --
|
||||
// lane l holds row l%16, k-bytes 8*(l/16)..+8 of a 16 x 16 tile -- is 16 rows apart in a row-major
|
||||
// plane, so it cannot be loaded straight from one either. So A is re-tiled first, into the op's
|
||||
// scratch, in FRAGMENT ORDER:
|
||||
// A goes from global straight into registers. A WMMA A fragment (lane l holds row l%16, k-bytes
|
||||
// 8*(l/16)..+8) spans 16 rows of a row-major plane, and staging it through LDS would cost a write,
|
||||
// a barrier and a second read. So A is first re-tiled into the op's scratch in fragment order:
|
||||
//
|
||||
// AT[((m/16) * (K/16) + k/16) * 256 + ((m%16) + 16 * ((k/8)%2)) * 8 + k%8] = A[m][k]
|
||||
//
|
||||
// One 16 x 16 fragment is 256 contiguous bytes and a lane's eight are one aligned 8-byte load, so
|
||||
// every A fragment a wave needs for a slab issues as one clause of global loads off a wave-uniform
|
||||
// base (SGPR, the SADDR form) and is consumed at the WMMAs. The re-tile is one read and one write
|
||||
// of A -- tens of microseconds at a 2048-row chunk against the hundreds the A-direct loop saves on
|
||||
// every large projection -- and it is the op's own, so no producer has to know about the layout.
|
||||
// Rows past M in the last fragment are written as zeros; they only reach accumulators the
|
||||
// epilogue drops.
|
||||
// A fragment is 256 contiguous bytes and a lane's eight are one aligned 8-byte load, so a slab's A
|
||||
// fragments issue as one clause of global loads off a wave-uniform SGPR base (SADDR form). The
|
||||
// re-tile costs one read and write of A, far less than it saves on large projections, and is
|
||||
// internal to the op. Rows past M in the last fragment are written as zeros.
|
||||
//
|
||||
// THE WEIGHT AND THE FOLD ARE THE SKINNY KERNEL'S. It reads the fragment-order weight that
|
||||
// r4d_rad_layout_mxfp4 stores and folds each block's exponent into the e4m3 value through the
|
||||
// table in r4d_mxfp4.h, so all three MXFP4 kernels produce the same e4m3 byte for every element.
|
||||
// The table is copied to LDS once per block: read from global it would be a dependent load issued
|
||||
// behind the A fragments, and the in-order load counter would make the fold wait for all of them.
|
||||
// 2^(Wref[n]-127) is applied once in the epilogue next to the activation's scale; see
|
||||
// r4d_gemm_mxfp4a8_nt_m64.hip for the fold and its error analysis.
|
||||
// Weight and fold as in the skinny kernel: the fragment-order weight from r4d_rad_layout_mxfp4,
|
||||
// folded through r4d_mxfp4.h's table, so all three MXFP4 kernels produce identical e4m3 bytes. The
|
||||
// table is copied to LDS per block; from global it would be a dependent load behind the A
|
||||
// fragments, and the in-order load counter would make the fold wait for all of them.
|
||||
// 2^(Wref[n]-127) is applied in the epilogue (see r4d_gemm_mxfp4a8_nt_m64.hip).
|
||||
//
|
||||
// THE TILE. 8 waves as 4 (M) x 2 (N); a wave owns TM=4 x TN accumulator fragments, so the block
|
||||
// covers BMF = 4*4*16 = 256 rows and BNF = 2*TN*16 columns. The tall tile is for reuse: every
|
||||
// weight byte staged is multiplied against 256 rows. TN is the axis that depends on M. Widening
|
||||
// N halves the column-block count while BMF still masks most of a short M, so TN=4 wins only on
|
||||
// long prompts; on a 17408x5120 weight the two cross near M=2048. Hence tn=0, the default, picks
|
||||
// TN=4 from M >= 2048 and TN=2 below. The K slab is 128 at TN=2 and 64 at TN=4 (and 64 at TN=2
|
||||
// when K is not a multiple of 128): TN=4 holds twice the accumulators, and a 128 slab's A
|
||||
// fragments on top of them would cost occupancy.
|
||||
// Tile: 8 waves as 4 (M) x 2 (N), each owning TM=4 x TN fragments, so a block covers BMF = 256
|
||||
// rows and BNF = 2*TN*16 columns. TN=4 halves the column-block count and only wins on long prompts
|
||||
// (crossover near M=2048 on a 17408x5120 weight), so tn=0 picks TN=4 from M >= 2048. The K slab is
|
||||
// 128 at TN=2 (64 if K % 128 != 0) and 64 at TN=4, which holds twice the accumulators.
|
||||
//
|
||||
// BARRIERS FENCE LDS ONLY. __syncthreads() is a workgroup acquire/release over every address
|
||||
// space, which drains the global load counter at each barrier. Nothing in global memory is
|
||||
// shared between the block's waves, so the barrier is scoped to LDS and the next slab's A loads
|
||||
// stay in flight across it.
|
||||
// Barriers fence LDS only: __syncthreads() also drains the global load counter, and nothing in
|
||||
// global memory is shared between the waves, so the next slab's A loads stay in flight.
|
||||
//
|
||||
// STAGING IS CLAMPED, NEVER PREDICATED. A bounds-predicated load lands in its own exec-mask
|
||||
// region and the compiler then cannot carry a counted s_wait_loadcnt across the merge. Clamped
|
||||
// (a tile past M reads the last real tile, a weight row past N the last aligned group), a slab's
|
||||
// loads issue back to back; the epilogue drops what they computed.
|
||||
// Staging is clamped, never predicated: a predicated load gets its own exec-mask region and the
|
||||
// compiler cannot carry a counted s_wait_loadcnt across the merge. Clamped loads (tile past M ->
|
||||
// last real tile, row past N -> last aligned group) issue back to back; the epilogue drops them.
|
||||
//
|
||||
// THE ACCUMULATOR IS C TRANSPOSED. The WMMA takes the weight fragment as its A operand and the
|
||||
// activation fragment as its B operand -- the two have the same register layout, so this is only
|
||||
// an argument order -- and computes C^T: a lane's accumulator for (M fragment i, N fragment j)
|
||||
// holds ONE row and eight consecutive columns. So a row's activation scale is one value a lane
|
||||
// for each of its TM rows, and the epilogue writes each (i, j) as one 16-byte store.
|
||||
// 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 (i, j) holds one row and eight consecutive
|
||||
// columns. A lane needs one activation scale per row, and each (i, j) is one 16-byte store.
|
||||
//
|
||||
// TWO ACTIVATION SCALE GRIDS. `a_scale` is either one f32 per row (ABLK=false) or one per (row,
|
||||
// 128 of K) (ABLK=true: the block-scaled fp8 family's grid, which every fused producer in
|
||||
// arch/common writes). Per-block scales vary along K and so cannot wait for the epilogue. The
|
||||
// accumulator is carried IN UNITS OF THE CURRENT BLOCK'S SCALE: at each 128 boundary every row's
|
||||
// partial sum is multiplied by s_prev / s_next, and the epilogue applies the last block's scale --
|
||||
// one multiply per accumulator element per 128 of K, ~K/128 fp32 ulps of extra rounding. The
|
||||
// ratio is computed once a row: thread t owns row t of the block, loads the next boundary's two
|
||||
// scales a boundary early (no slab waits on a scale load) and writes the ratio to LDS, and a lane
|
||||
// reads one ratio for each of its TM rows.
|
||||
// Two activation scale grids: one f32 per row (ABLK=false) or one per (row, 128 of K) (ABLK=true,
|
||||
// as every fused producer in arch/common writes). With ABLK the accumulator is carried in units of
|
||||
// the current block's scale: at each 128 boundary every row is multiplied by s_prev / s_next
|
||||
// (~K/128 fp32 ulps of extra rounding), and the epilogue applies the last scale. Thread t owns row
|
||||
// t of the block, loads the next boundary's two scales a boundary early and writes the ratio to
|
||||
// LDS; a lane reads one ratio per row.
|
||||
//
|
||||
// TRAP FOR ANYONE MEASURING THIS KERNEL: the same as the skinny kernel's. A weight of tens of
|
||||
// megabytes streamed in a loop is Infinity-Cache resident on this part, so a bandwidth figure
|
||||
// taken that way reads above the DRAM roofline.
|
||||
// Benchmarking note: as for the skinny kernel, a looped weight stays Infinity-Cache resident.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -91,14 +69,7 @@ typedef int mxt_v2i __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned mxt_u2 __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned mxt_u4 __attribute__((ext_vector_type(4)));
|
||||
|
||||
static __device__ __forceinline__ void mxt_lds_barrier() {
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local");
|
||||
__builtin_amdgcn_s_barrier();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local");
|
||||
}
|
||||
|
||||
// The re-tile: one thread per 8-byte slot of the fragment-ordered plane, so the writes are
|
||||
// contiguous and each lane reads one 8-byte group of one row.
|
||||
// The re-tile: one thread per 8-byte slot of the fragment-ordered plane; writes are contiguous.
|
||||
__global__ __launch_bounds__(256) void r4d_mxfp4a8_tile_a_kernel(
|
||||
const unsigned char* __restrict__ A, unsigned char* __restrict__ AT, int M, int K,
|
||||
long long slots, int lda) {
|
||||
@@ -139,8 +110,8 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
|
||||
if (tid < 32) sMag[tid] = (&kMxfp4Mag[0][0])[tid];
|
||||
|
||||
// One A base per M fragment: wave-uniform, so readfirstlane keeps it in an SGPR and every load
|
||||
// takes the SADDR form with a 32-bit lane offset. A tile past M reads the last real one.
|
||||
// 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) {
|
||||
@@ -176,19 +147,18 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) acc[i][j] = (v8f)(0.f);
|
||||
|
||||
// ABLK, once a row: thread t owns row m0 + t (BMF == NTHR) and loads the next 128 boundary's two
|
||||
// scales -- the block that starts there and the one before it -- a boundary early.
|
||||
// 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;
|
||||
mxt_lds_barrier(); // sMag
|
||||
lds_barrier(); // sMag
|
||||
|
||||
for (int k0 = 0; k0 < K; k0 += LBK) {
|
||||
// ABLK: a new 128-wide activation block starts with this slab; each row's ratio goes to LDS,
|
||||
// published by the staging barrier below (sR's previous readers were behind the last slab's
|
||||
// closing barrier). A zero block keeps the carried scale; a zero block before this one sends
|
||||
// the carried scale back to the grid, which only an all-zero activation block ever does.
|
||||
// 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)
|
||||
@@ -231,7 +201,7 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
*(mxt_u2*)(&sW[(wrow[it] + q) * STR + wkloc[it]]) = mxt_u2{lo, hi};
|
||||
}
|
||||
}
|
||||
mxt_lds_barrier();
|
||||
lds_barrier();
|
||||
|
||||
if constexpr (ABLK) {
|
||||
// Re-express each row's partial sum in the new block's scale: one ratio a lane a row.
|
||||
@@ -261,8 +231,8 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
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);
|
||||
}
|
||||
// One step's W fragments live at a time: without the fence the compiler hoists every
|
||||
// step's loads above the first WMMA and holds them all.
|
||||
// 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)
|
||||
@@ -271,17 +241,17 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf[j], af[i][step],
|
||||
acc[i][j]);
|
||||
}
|
||||
mxt_lds_barrier();
|
||||
lds_barrier();
|
||||
}
|
||||
|
||||
// Epilogue. A lane holds row m0 + 64*wm + 16i + col of M fragment i and eight consecutive columns of N fragment
|
||||
// j, so each (i, j) is one 16-byte store. 2^(Wref[n]-127) is exactly the float whose exponent
|
||||
// field is Wref[n]; N % 16 == 0 keeps a lane's eight columns all inside N or all outside it.
|
||||
// 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);
|
||||
mxt_lds_barrier();
|
||||
lds_barrier();
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) sc[i] = sR[wm * TM * 16 + i * 16 + col];
|
||||
} else {
|
||||
@@ -341,8 +311,8 @@ extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, l
|
||||
if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: N must be a multiple of 16");
|
||||
if (K < R4D_MXT_KUNIT || K % R4D_MXT_KUNIT)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_tiled: K must be a multiple of 64");
|
||||
// tn=0: TN=4 from the M crossover on, unless its 128-wide tile leaves the grid short of 128
|
||||
// blocks (a narrow N): there the TN=2 grid's extra blocks win.
|
||||
// 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_MXT_TN4_MIN_M && (long)((N + 127) / 128) * ((M + R4D_MXT_BMF - 1) / R4D_MXT_BMF) >= 128
|
||||
? 4 : 2;
|
||||
@@ -372,17 +342,15 @@ extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, l
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
// The row-major activation is re-tiled into the op's scratch, then the GEMM reads it from there.
|
||||
// A partitioned weight re-tiles each part's copy of the activation into the scratch in turn and
|
||||
// runs the GEMM over that part's rows (mx_parts).
|
||||
// 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_mxfp4a8_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, as in r4d_rad_gemm_mxfp4a8_m64: without it the fold has no
|
||||
* reference and every element would be scaled against zero. */
|
||||
/* 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);
|
||||
@@ -410,9 +378,9 @@ extern "C" int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs* a, RadStream s) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The core sizes the op's scratch from this, at the band's widest M: the fragment-tiled copy of
|
||||
* the activation, whole 16-row fragments. One copy for every part: the parts run one after another
|
||||
* on the op's stream, so a part's re-tile cannot overtake the previous part's GEMM. */
|
||||
/* 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_mxfp4a8_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_mxfp4a8_tile_a_bytes((int)M, (int)K);
|
||||
|
||||
+33
-59
@@ -1,39 +1,31 @@
|
||||
// r4d_gemm_w2a8_nt.hip - r4d_gemm_w2a8_nt: 2-bit-weight, 8-bit-activation skinny GEMM, gfx1201.
|
||||
// C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with A quantised per row and W asymmetric per (row, group).
|
||||
//
|
||||
// WHAT IT IS FOR. The DFlash2 draft head is `x[M,5120] @ W[124160,5120]^T` at two bits, run once
|
||||
// per decode step. Its 178.8 MB weight puts a one-pass memory floor near 280 us; at M = 64 its
|
||||
// 64 x 124160 x 5120 MACs cost around 815 us on the f16 WMMA at 207 TF/s, which is the rate a bf16
|
||||
// dequant form (`0x3F80 | v<<5`) runs at. So a bf16 form is COMPUTE bound once several sequences
|
||||
// are in flight, not memory bound. The same codes on v_wmma_i32_16x16x16_iu8 at 407 TF/s put the
|
||||
// compute floor near 200 us, under the memory floor, so this kernel is a stream at both ends of
|
||||
// the M range.
|
||||
// Used for the DFlash2 draft head, `x[M,5120] @ W[124160,5120]^T` at two bits, once per decode
|
||||
// step. Its 178.8 MB weight gives a memory floor near 280 us. A bf16 dequant form runs on the f16
|
||||
// WMMA (207 TF/s) and is compute bound at M = 64 (~815 us); v_wmma_i32_16x16x16_iu8 at 407 TF/s
|
||||
// puts the compute floor near 200 us, under the memory floor, across the M range.
|
||||
//
|
||||
// STRUCTURE AND ACTIVATION ARE r4d_gemm_w4a8_nt_m64's: same 512-byte
|
||||
// packed block (32 lanes x 16 bytes), same permuted int8 activation from r4d_quant_act_i8_asum,
|
||||
// same [K/group][Mpad] group-major activation sums, same split-K reduction, same per-row scale
|
||||
// applied once at the store. A packed block covers 128 K here instead of 64, because the code is
|
||||
// half as wide.
|
||||
// Structure and activation as r4d_gemm_w4a8_nt_m64: 512-byte packed block (32 lanes x 16 bytes),
|
||||
// permuted int8 activation from r4d_quant_act_i8_asum, [K/group][Mpad] group-major activation sums,
|
||||
// split-K reduction, per-row scale at the store. A packed block covers 128 K (64 for 4-bit).
|
||||
//
|
||||
// THE UNPACK PUTS THE CODE IN THE BYTE'S HIGH TWO BITS. For q in 0..3 the byte 64*q is exactly
|
||||
// the UNSIGNED int8 of 64*q, so
|
||||
// The unpack puts the code in the byte's high two bits; for q in 0..3 the byte 64*q is the
|
||||
// unsigned int8 of 64*q:
|
||||
//
|
||||
// t0 = (w << 6) & 0xC0C0C0C0 bytes <- fields 0, 4, 8, 12
|
||||
// t1 = (w << 4) & 0xC0C0C0C0 bytes <- fields 1, 5, 9, 13
|
||||
// t2 = (w << 2) & 0xC0C0C0C0 bytes <- fields 2, 6, 10, 14
|
||||
// t3 = w & 0xC0C0C0C0 bytes <- fields 3, 7, 11, 15
|
||||
//
|
||||
// is the whole dequant: seven instructions per dword, which is two 16x16x16 fragments, and the
|
||||
// factor of 64 folds into the group scale at the store. Fragment 2d+0 is (t0, t1) and 2d+1 is
|
||||
// (t2, t3), so element e of fragment h reads field 4*(e&3) + (e>>2) + 2h of dword d -- which is
|
||||
// what the packer writes and nothing else has to know.
|
||||
// Seven instructions per dword (two 16x16x16 fragments); the factor 64 is removed at the store.
|
||||
// Fragment 2d+0 is (t0, t1) and 2d+1 is (t2, t3), so element e of fragment h reads field
|
||||
// 4*(e&3) + (e>>2) + 2h of dword d, as the packer writes it.
|
||||
//
|
||||
// WHY UNSIGNED, AND WHAT IT COSTS. Four levels are not enough for a symmetric grid: the draft
|
||||
// head's quantiser is asymmetric per (row, group of 128), w ~= sc*(q - zp), and 16*nibble-style
|
||||
// offset binary is affine in the code where two's complement is affine only on each half of the
|
||||
// range. So the WMMA reads B unsigned and the zero point comes out afterwards as
|
||||
// sc*(<a,q> - zp*sum a), with the group's activation sum loaded from Asum. That is the same
|
||||
// arrangement r4d_gemm_w4a8_asym_nt_m64 uses, and the same quantiser produces both.
|
||||
// Unsigned because four levels are too few for a symmetric grid: the quantiser is asymmetric per
|
||||
// (row, group of 128), w ~= sc*(q - zp). The WMMA reads B unsigned and the zero point is removed
|
||||
// as sc*(<a,q> - zp*sum a) with the group's activation sum from Asum, as in
|
||||
// r4d_gemm_w4a8_asym_nt_m64.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -43,9 +35,6 @@
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#ifndef R4D_GEMM_W2A8_GROUP
|
||||
#define R4D_GEMM_W2A8_GROUP 128 // K per (scale, zero) pair
|
||||
#endif
|
||||
#define R4D_GEMM_W2A8_KPB 128 // K per packed block: 8 k steps, 16 bytes per lane
|
||||
#define WAVE32 32
|
||||
|
||||
@@ -81,13 +70,10 @@ __device__ __forceinline__ v8i w2_mmai(v2i a, v2i b, v8i c) {
|
||||
return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a, false, b, c, false);
|
||||
}
|
||||
|
||||
// __launch_bounds__ HAS TO SEE MT, NOT JUST NPW. A block cannot exceed 1024 threads, but this
|
||||
// kernel's accumulators scale with MT * NPW: at MT=4 the two arrays alone are 8*MT*NPW VGPRs and
|
||||
// the group's activation sums are another 8*MT. Telling the compiler 1024 makes it budget for 32
|
||||
// waves on ONE workgroup, which on this part is 1536/32 = 48 VGPRs per wave, so every MT=4 config
|
||||
// spills hard enough that MB=2 -- which reads the WHOLE WEIGHT TWICE at M=64 -- is faster than any
|
||||
// of them. The bound has to be what the config can actually run, and an MT=4 config can never run
|
||||
// 32 waves. The same rule, on NPW alone, is in r4d_gemm_w4a8_nt_m64.
|
||||
// __launch_bounds__ depends on MT as well as NPW. Accumulators are 8*MT*NPW VGPRs per array plus
|
||||
// 8*MT for the activation sums; a bound of 1024 budgets 1536/32 = 48 VGPRs per wave, and every MT=4
|
||||
// config then spills badly. The bound must be what the config can run. r4d_gemm_w4a8_nt_m64 has
|
||||
// the same rule on NPW alone.
|
||||
#define R4D_W2A8_BOUNDS(MT, NPW) \
|
||||
((MT) >= 4 ? 256 : (((MT) >= 2 || (NPW) >= 4) ? 512 : 1024))
|
||||
|
||||
@@ -137,18 +123,12 @@ __global__ __launch_bounds__(R4D_W2A8_BOUNDS(MT, NPW)) void r4d_gemm_w2a8_nt_ker
|
||||
(size_t)(t * nsz + kbase / R4D_GEMM_W2A8_GROUP) * 16 + (lane & 15);
|
||||
}
|
||||
|
||||
// PREFETCHING THE NEXT GROUP'S WEIGHT IS A LOSS, and the MB=4 configs it would most help --
|
||||
// they read the weight once where MB=2 reads it twice -- lose the most by it. One more uint4v
|
||||
// a column tile is four more VGPRs on a kernel already at 214, and a wave fewer per SIMD costs
|
||||
// more latency cover than the prefetch buys. The same holds in r4d_gemm_w4a8_nt_m64.
|
||||
// No next-group weight prefetch: four more VGPRs per column tile on a kernel at 214 costs a wave
|
||||
// per SIMD, which loses more latency cover than the prefetch gains (likewise in w4a8_nt_m64).
|
||||
for (int g = 0; g < groups; g++) {
|
||||
// TWO FMAs, NOT A MUL-SUB-FMA. Written as fmaf(g_acc - z64*asum, sc, acc) the compiler emits
|
||||
// v_mul + v_sub + v_fma_mix per accumulator element -- three instructions on top of the
|
||||
// v_cvt, 238 VALU a group against 512 cycles of WMMA. Splitting the group's contribution
|
||||
// into sc*g_acc and (-sc*z64)*asum makes both halves plain f32 FMAs into the same
|
||||
// accumulator, which is one instruction less and a VOPD pair rather than a mixed-precision
|
||||
// op. The scale is converted to f32 once a group here instead of riding into every
|
||||
// v_fma_mix as an f16.
|
||||
// Two f32 FMAs, sc*g_acc and (-sc*z64)*asum, rather than fmaf(g_acc - z64*asum, sc, acc),
|
||||
// which compiles to v_mul + v_sub + v_fma_mix per element. This saves an instruction and
|
||||
// pairs as VOPD; the scale is converted to f32 once per group.
|
||||
float sc[NPW], scz[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
@@ -157,15 +137,14 @@ __global__ __launch_bounds__(R4D_W2A8_BOUNDS(MT, NPW)) void r4d_gemm_w2a8_nt_ker
|
||||
const float nz = __half2float(__ushort_as_half((unsigned short)(sz >> 16)));
|
||||
scz[j] = -sc[j] * (64.f * (-nz - 1024.f));
|
||||
}
|
||||
// Element e of tile i at this lane is output row (mt0+i)*16 + 8*(lane>>4) + e, so the eight
|
||||
// rows a lane needs are contiguous at a fixed group -- which is why Asum is [G][Mpad].
|
||||
// Element e of tile i at this lane is output row (mt0+i)*16 + 8*(lane>>4) + e, so a lane's
|
||||
// eight rows are contiguous at a fixed group; hence Asum is [G][Mpad].
|
||||
float asum[MT][8];
|
||||
{
|
||||
const size_t gi = (size_t)(kbase / R4D_GEMM_W2A8_GROUP + g) * Mpad;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
// Clamped: MB past the number of row tiles is a legal config, and rows past M produce
|
||||
// results the store discards -- but an unclamped read here is a page fault, not garbage.
|
||||
// Clamped: MB may exceed the row tiles, and an unclamped read could fault.
|
||||
int rb = (mt0 + i) * 16 + 8 * (lane >> 4);
|
||||
rb = rb < Mpad - 8 ? rb : Mpad - 8;
|
||||
const v4f* pv = (const v4f*)(Asum + gi + rb);
|
||||
@@ -251,13 +230,9 @@ void r4d_gemm_w2a8_nt(long a, long ascale, long wq, long ws, long asum, long c,
|
||||
if (K % (SK * R4D_GEMM_W2A8_GROUP))
|
||||
throw std::runtime_error("r4d gemm_w2a8_nt: K must be divisible by SK*group");
|
||||
if (!asum) throw std::runtime_error("r4d gemm_w2a8_nt: asum is required");
|
||||
if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_w2a8_nt: threads/block > 1024");
|
||||
// __launch_bounds__ is a MAXIMUM BLOCK SIZE, not a hint: a block wider than the bound the
|
||||
// instantiation was compiled with does not run slowly, it fails to launch -- and on this runtime
|
||||
// that surfaces as `hipErrorLaunchFailure` from whatever unrelated call happens to synchronise
|
||||
// next. So the launcher has to know the same rule the macro does.
|
||||
const int bound = (MB >= 4) ? 256 : (((MB >= 2) || (NPW >= 4)) ? 512 : 1024);
|
||||
if (WV * SK * WAVE32 > bound)
|
||||
// __launch_bounds__ is a hard maximum: a wider block fails to launch, surfacing as
|
||||
// hipErrorLaunchFailure at the next sync.
|
||||
if (WV * SK * WAVE32 > R4D_W2A8_BOUNDS(MB, NPW))
|
||||
throw std::runtime_error("r4d gemm_w2a8_nt: block wider than this MB/NPW's launch bound");
|
||||
if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w2a8_nt: MB must be 1..4");
|
||||
if (NPW != 1 && NPW != 2 && NPW != 4)
|
||||
@@ -297,15 +272,14 @@ int r4d_gemm_w2a8_nt_group(void) { return R4D_GEMM_W2A8_GROUP; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there
|
||||
// is no adapter directory between the core and these launches.
|
||||
// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h.
|
||||
extern "C" int r4d_rad_gemm_w2a8(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale) return R4D_NO(RAD_E_INVAL);
|
||||
/* The 2-bit grid is asymmetric by construction, so the group sums are not optional. */
|
||||
/* The 2-bit grid is always asymmetric, so the group sums are required. */
|
||||
if (!g.asum) return R4D_NO(RAD_E_INVAL);
|
||||
const int group = r4d_gemm_w2a8_nt_group();
|
||||
Cfg c;
|
||||
|
||||
@@ -1,60 +1,41 @@
|
||||
// r4d_gemm_w4a16_nt_m64.hip - r4d_gemm_w4a16_nt_m64: 4-bit-weight skinny GEMM for M up to 64,
|
||||
// gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C, fp32 accumulate.
|
||||
//
|
||||
// Same problem and the same decomposition as r4d_gemm_bf16_nt_m64 -- a weight-streaming GEMM whose
|
||||
// M is a speculative decode batch, so every output element is read once and the whole cost is the
|
||||
// weight -- with the weight at 4 bits instead of 16. That is the entire point: at M=8 a projection
|
||||
// moves M*K*2 bytes of activation against N*K bytes of weight, 82 KiB against 44 MiB on the
|
||||
// drafter's MLP, so the format of the WEIGHT is the only thing in the cost model.
|
||||
// The decomposition of r4d_gemm_bf16_nt_m64 with the weight at 4 bits. M is a speculative decode
|
||||
// batch, so the weight dominates the cost (at M=8 on the drafter's MLP: 82 KiB of activation
|
||||
// against 44 MiB of weight).
|
||||
//
|
||||
// WHY f16 AND NOT bf16. A 4-bit weight has to be widened to a WMMA input type, and the cheapest
|
||||
// widening is a byte permute into a fixed exponent: `0x6400 | n` is the f16 for 1024 + n, exactly,
|
||||
// for every n in 0..15, so four v_perm_b32 turn one dword of eight nibbles into a whole 16x16x16
|
||||
// fragment. The quantizer's zero point then has to be subtracted, and gfx1201 has NO packed bf16
|
||||
// arithmetic (v_pk_add_bf16 is not an instruction on this part) while v_pk_add_f16 is -- so the
|
||||
// subtract is four instructions in f16 and would be sixteen in bf16, through f32 and back. Ten
|
||||
// VALU per fragment against one WMMA leaves the kernel memory-bound over the whole M band; the
|
||||
// bf16 route does not. Everything the WMMA sees is exact: the activation is an f16 value, the
|
||||
// weight is a small integer, and the group scale is applied to the f32 accumulator afterwards.
|
||||
// f16, not bf16: `0x6400 | n` is exactly the f16 for 1024 + n, so four v_perm_b32 turn a dword of
|
||||
// eight nibbles into a 16x16x16 fragment, and the zero point is subtracted with v_pk_add_f16.
|
||||
// gfx1201 has no packed bf16 arithmetic, so in bf16 that subtract would be sixteen instructions
|
||||
// instead of four. The WMMA inputs are exact; the group scale is applied to the f32 accumulator.
|
||||
//
|
||||
// AND WHY THAT CAPS IT. Widening to f16 reaches the SLOWEST matrix instruction on this part:
|
||||
// v_wmma_f32_16x16x16_f16 issues at 207 TF/s where v_wmma_i32_16x16x16_iu8 and
|
||||
// v_wmma_f32_16x16x16_fp8_fp8 both issue at 407-412 and v_wmma_i32_16x16x32_iu4 at 830. Below
|
||||
// M=32 that costs nothing, because this kernel is at the DRAM roofline there -- 620-648 GB/s on
|
||||
// this part -- and the arithmetic hides under the weight stream. At M=64 the matrix instruction
|
||||
// is the whole cost, and r4d_gemm_w4a8_nt_m64 runs the SAME packed weight through the int8 form
|
||||
// instead. So this kernel owns the small-M band and the int8 one owns the rest.
|
||||
// The cost is the slowest matrix instruction on this part: v_wmma_f32_16x16x16_f16 at 207 TF/s
|
||||
// (iu8 and fp8 at 407-412, iu4 at 830). Below M=32 the kernel is at the DRAM roofline (620-648 GB/s)
|
||||
// and the arithmetic hides; at M=64 r4d_gemm_w4a8_nt_m64 runs the same packed weight through the
|
||||
// int8 form. This kernel owns the small-M band.
|
||||
//
|
||||
// WHY THE SCALE IS NOT FOLDED INTO THE FRAGMENT. It is tempting to fold both quantizer parameters
|
||||
// into one v_pk_fma_f16 -- fma(1024 + n, s, -(1024 + z) * s) -- and drop the per-group epilogue.
|
||||
// That is wrong by 12%: -(1024 + z) * s is not representable in f16, and the term it cancels is
|
||||
// ~1024*s against a result of ~4*s, so half an f16 ULP of the addend is an eighth of the answer.
|
||||
// The subtraction has to happen where 1024 + z is exact, which is the integer grid, and the scale
|
||||
// has to be applied where the cancellation has already happened, which is the f32 accumulator.
|
||||
// The scale is not folded into the fragment as fma(1024 + n, s, -(1024 + z) * s): the addend is
|
||||
// not representable in f16 and cancels ~1024*s against a result of ~4*s, an error of ~12%. The
|
||||
// subtraction must happen on the integer grid and the scale after the cancellation.
|
||||
//
|
||||
// THE ACTIVATION IS NOT FREE, EVEN AT M=8. A 16x16x16 fragment covers sixteen ROWS whether M is 8
|
||||
// or 64, and every column tile re-reads the whole of A, so a wave that owns one column tile moves
|
||||
// 16*K*2 bytes of activation against 16*K/2 bytes of weight -- four times as much, out of cache
|
||||
// rather than DRAM, but four times as many load instructions. NPW (column tiles per WAVE) is the
|
||||
// answer and it costs no LDS and no barrier: the wave loads one activation fragment and spends it
|
||||
// on NPW weight fragments, so the ratio falls to 4*MT/NPW. WV still exists and still sets how many
|
||||
// column tiles a BLOCK covers, but WV alone does nothing for this -- the waves of a block issue
|
||||
// their own loads and only share through the cache.
|
||||
// A fragment covers sixteen rows whatever M is, and every column tile re-reads A: one column tile
|
||||
// per wave moves four times as many activation bytes (from cache) as weight bytes. NPW (column
|
||||
// tiles per wave) reuses one activation fragment on NPW weight fragments, with no LDS or barrier,
|
||||
// dropping the ratio to 4*MT/NPW. WV alone does not help: a block's waves share only through cache.
|
||||
//
|
||||
// LAYOUT. Wq is pre-permuted offline into exactly the order the fragment wants, so a lane's 16
|
||||
// bytes are contiguous and a wave's weight load for four k steps is one 512-byte global_load_b128.
|
||||
// Nothing is staged through LDS on the weight path and nothing is masked: with
|
||||
// Layout: Wq is pre-permuted offline into fragment order, so a lane's 16 bytes are contiguous and a
|
||||
// wave's weight load for four k steps is one 512-byte global_load_b128, with no LDS and no mask:
|
||||
//
|
||||
// idx = lane%16 , k = 8*(e>>2) + 4*(lane>>4) + (e&3) (r4d_gdn_wmma.h)
|
||||
//
|
||||
// fragment element e of lane l is W[n0 + (l&15)][16s + 8*(e>>2) + 4*(l>>4) + (e&3)], and the dword
|
||||
// holding it stores that value in nibble 2e for e<4 and nibble 2(e-4)+1 for e>=4 -- the order the
|
||||
// two-mask, four-permute unpack below produces. The packer in radiance_w4.py builds this layout.
|
||||
// fragment element e of lane l is W[n0 + (l&15)][16s + 8*(e>>2) + 4*(l>>4) + (e&3)], stored in
|
||||
// nibble 2e for e<4 and nibble 2(e-4)+1 for e>=4, the order the unpack below produces. The packer
|
||||
// in radiance_w4.py builds this layout.
|
||||
//
|
||||
// QUANTIZER. Asymmetric, per output channel, per group of R4D_GEMM_W4_GROUP contiguous K:
|
||||
// w ~= scale * (q - zero) with q in 0..15 and an INTEGER zero, which is what makes the subtract
|
||||
// exact. Both parameters live in one dword per (row, group): the f16 scale in the low half and the
|
||||
// f16 of -(1024 + zero) in the high half, ready to be broadcast into a v_pk_add_f16.
|
||||
// Quantiser: per output channel, per group of R4D_GEMM_W4_GROUP contiguous K: w ~= scale * (q - zero)
|
||||
// with q in 0..15 and an integer zero, which keeps the subtract exact. One dword per (row, group):
|
||||
// the f16 scale low and the f16 of -(1024 + zero) high, broadcast into a v_pk_add_f16.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_gdn_wmma.h"
|
||||
@@ -64,34 +45,23 @@
|
||||
#include <stdexcept>
|
||||
|
||||
#define R4D_GEMM_W4_MAX_M 64
|
||||
#ifndef R4D_GEMM_W4_GROUP
|
||||
#define R4D_GEMM_W4_GROUP 128 // K per (scale, zero) pair
|
||||
#endif
|
||||
#define R4D_GEMM_W4_KPB 64 // K per packed block: 4 k steps, 16 bytes per lane
|
||||
#define WAVE32 32
|
||||
|
||||
typedef _Float16 v8h __attribute__((ext_vector_type(8)));
|
||||
typedef unsigned uint4v __attribute__((ext_vector_type(4)));
|
||||
|
||||
// NT reads the weight non-temporally. The weight is streamed once per step and never reused, while
|
||||
// the activation is re-read once per column tile and wants to stay resident, so telling the cache
|
||||
// not to keep the weight decides which of the two occupies the last level. It is a gain at M=8 and
|
||||
// M=16 and a LOSS from M=24 up on the shapes with the longest K, so it is per-call, like every
|
||||
// other geometry parameter, and the table in radiance_w4.py carries the value per M band.
|
||||
//
|
||||
// One copy of any of these weights fits this part's 64 MiB last level, so a bench that streams a
|
||||
// SINGLE buffer in a loop measures a cache-resident machine and cannot see this effect at all; a
|
||||
// pooled working set is what makes the difference visible.
|
||||
// NT reads the weight non-temporally so the re-read activation keeps the last level. It wins at
|
||||
// M=8 and M=16 and loses from M=24 up on the longest-K shapes, so it is per call; radiance_w4.py
|
||||
// carries the value per M band. A benchmark must use a pooled working set: one weight fits the
|
||||
// 64 MiB last level, so looping over a single buffer hides the effect.
|
||||
|
||||
// NPW (column tiles per WAVE) is a template parameter because it sizes the accumulator array, and a
|
||||
// launch argument because the right value is a property of M: at M=8 the kernel is at the DRAM
|
||||
// roofline and NPW>1 only costs blocks, while at M=64 the activation re-read is four times the
|
||||
// weight and NPW=4 is what claws it back. Instantiated only for the two values that win in
|
||||
// practice; anything else is rejected rather than silently rounded.
|
||||
// NPW is a template parameter (it sizes the accumulators) chosen per M: at M=8 NPW>1 only costs
|
||||
// blocks; at M=64 NPW=4 recovers the activation re-read. Only 1 and 4 are instantiated; anything
|
||||
// else is rejected.
|
||||
|
||||
// Address-space-qualified so the loads stay global_load rather than flat_load: on gfx12 a flat
|
||||
// load increments dscnt as well as loadcnt, so a later LDS wait would also wait on HBM. See the
|
||||
// same declaration in r4d_gemm_bf16_nt_m64.hip for why the element type is a scalar there.
|
||||
// Address-space-qualified so loads stay global_load, not flat_load (on gfx12 a flat load also
|
||||
// increments dscnt). See r4d_gemm_bf16_nt_m64.hip for why the element type is a scalar.
|
||||
typedef __attribute__((address_space(1))) const uint4v* r4d_gw4;
|
||||
typedef __attribute__((address_space(1))) const unsigned long long* r4d_gu2;
|
||||
typedef __attribute__((address_space(1))) const unsigned* r4d_gu1;
|
||||
@@ -103,41 +73,22 @@ __device__ __forceinline__ v8h fragA(r4d_gu2 p, int u) {
|
||||
return x.f;
|
||||
}
|
||||
|
||||
// One dword of eight nibbles -> one 16x16x16 f16 B fragment, minus the zero point.
|
||||
// t0/t1 split the even and odd nibbles into bytes; each v_perm_b32 pairs two of those bytes with
|
||||
// the constant high byte 0x64, which is the f16 exponent field for 1024. nz carries
|
||||
// -(1024 + zero) in BOTH halves so one v_pk_add_f16 corrects a pair.
|
||||
// The unpack is under a percent of this kernel at M=8, where it is at the DRAM roofline and the
|
||||
// arithmetic hides in the load latency. It is a real fraction at M=64, but that band belongs to
|
||||
// r4d_gemm_w4a8_nt_m64 -- and with no dequant at all the f16 form still trails the int8 one there,
|
||||
// because the gap is the matrix instruction and not the dequant. Nothing here is worth a knob.
|
||||
#ifndef R4D_GEMM_W4_TWOS
|
||||
#define R4D_GEMM_W4_TWOS 1
|
||||
#endif
|
||||
// One dword of eight nibbles -> one 16x16x16 f16 B fragment, minus the zero point. t0/t1 split the
|
||||
// even and odd nibbles into bytes; each v_perm_b32 pairs two of them with the high byte 0x64 (the
|
||||
// f16 exponent for 1024). nz holds -(1024 + zero) in both halves.
|
||||
|
||||
// DO NOT FOLD THE GROUP SCALE INTO THE B FRAGMENT. One v_pk_mul_f16 per pair on the finished
|
||||
// integer q is exact in f16, removes the second accumulator array entirely and takes the M=64 shape
|
||||
// from 192 VGPRs to 135 -- and it is SLOWER on most of the drafter's shapes. The multiply lands
|
||||
// inside the per-fragment dependent chain between the unpack and the WMMA, where the per-group
|
||||
// epilogue it replaces sits outside it; this kernel is stall-bound, not register-bound.
|
||||
// Do not fold the group scale into the B fragment. A v_pk_mul_f16 on the integer q is exact and
|
||||
// saves registers (192 -> 135 VGPRs at M=64), but it is slower on most shapes: it lengthens the
|
||||
// dependent chain between unpack and WMMA, and this kernel is stall-bound, not register-bound.
|
||||
|
||||
__device__ __forceinline__ v8h dequant(unsigned w, __half2 nz) {
|
||||
const unsigned K64 = 0x64646464u;
|
||||
#if R4D_GEMM_W4_TWOS
|
||||
// The stored nibble is a 4-bit TWO'S COMPLEMENT code, because that is what
|
||||
// r4d_gemm_w4a8_nt_m64 needs -- it shifts the nibble into the byte's high half and reads the
|
||||
// byte signed. This kernel wants OFFSET BINARY, so that 1024 + n minus the constant 1024 + 8
|
||||
// is the value. The two differ by bit 3 of the nibble, so one XOR per spread dword converts,
|
||||
// and the zero point is then pinned to 8 for every group. Two instructions per fragment, on
|
||||
// the kernel whose whole unpack is a fraction of a percent of its time at M=8 -- which is why
|
||||
// the conversion lives here and not in the int8 kernel, where the unpack is three instructions
|
||||
// and does matter. One quantised weight, two kernels, dispatched on M.
|
||||
// The stored nibble is two's complement, which r4d_gemm_w4a8_nt_m64 reads as a signed high
|
||||
// nibble. This kernel needs offset binary (1024 + n minus 1024 + 8); the two differ in bit 3, so
|
||||
// one XOR per dword converts and the zero point is 8 for every group. The conversion lives here,
|
||||
// where the unpack is negligible, rather than in the int8 kernel.
|
||||
const unsigned t0 = (w & 0x0F0F0F0Fu) ^ 0x08080808u;
|
||||
const unsigned t1 = ((w >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
|
||||
#else
|
||||
const unsigned t0 = w & 0x0F0F0F0Fu;
|
||||
const unsigned t1 = (w >> 4) & 0x0F0F0F0Fu;
|
||||
#endif
|
||||
union { unsigned u[4]; __half2 h2[4]; v8h f; } x;
|
||||
x.u[0] = __builtin_amdgcn_perm(K64, t0, 0x05010400u); // nibbles 0, 2
|
||||
x.u[1] = __builtin_amdgcn_perm(K64, t0, 0x05030402u); // nibbles 4, 6
|
||||
@@ -152,8 +103,7 @@ __device__ __forceinline__ v8f mmah(v8h a, v8h b, v8f c) {
|
||||
return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c);
|
||||
}
|
||||
|
||||
// MT = row tiles per BLOCK, as in the bf16 kernel: more of them amortise the weight fragment and
|
||||
// its unpack over more WMMA, fewer put more blocks on the machine.
|
||||
// MT = row tiles per block, as in the bf16 kernel.
|
||||
template <int MT, int NPW, bool NT>
|
||||
__global__ __launch_bounds__(1024) void r4d_gemm_w4a16_nt_m64_kernel(
|
||||
const unsigned short* __restrict__ A, const unsigned* __restrict__ Wq,
|
||||
@@ -176,8 +126,7 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w4a16_nt_m64_kernel(
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
if (n0 < N) {
|
||||
// Activation: rows clamped, never masked -- a tile past M re-reads the last valid row and
|
||||
// computes a result nobody stores.
|
||||
// Activation rows are clamped, not masked; results past M are never stored.
|
||||
unsigned aoff[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
@@ -186,8 +135,8 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w4a16_nt_m64_kernel(
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] = (r4d_gu2)(const unsigned long long*)(A + aoff[i]);
|
||||
|
||||
// Weight: one uint4 per lane per four k steps, tiles already permuted, so the whole k loop is
|
||||
// global_load_b128 with a constant stride and no address arithmetic per step.
|
||||
// Weight: one uint4 per lane per four k steps, already permuted, so the k loop is
|
||||
// global_load_b128 at a constant stride.
|
||||
const int kpb = K / R4D_GEMM_W4_KPB; // packed blocks in a full row of tiles
|
||||
const int nsz = K / R4D_GEMM_W4_GROUP; // (scale, zero) dwords per row of tiles
|
||||
r4d_gw4 pw[NPW];
|
||||
@@ -195,9 +144,7 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w4a16_nt_m64_kernel(
|
||||
const int ntlast = N / 16 - 1;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
// Clamped, like the row tiles: a wave whose last column tiles run past N re-reads the last
|
||||
// real tile and computes a result the store discards, rather than reading memory it does not
|
||||
// own or diverging the whole k loop on a mask.
|
||||
// Column tiles past N are clamped to the last real tile; the store discards them.
|
||||
const int t = (nt0 + j) < ntlast ? (nt0 + j) : ntlast;
|
||||
pw[j] = (r4d_gw4)(const uint4v*)(Wq) +
|
||||
(size_t)(t * kpb + kbase / R4D_GEMM_W4_KPB) * WAVE32 + lane;
|
||||
@@ -218,8 +165,7 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w4a16_nt_m64_kernel(
|
||||
nz[j] = __half2half2(__ushort_as_half((unsigned short)(sz >> 16)));
|
||||
}
|
||||
|
||||
// The first WMMA of a group takes an inline zero for C, so the group accumulator costs no
|
||||
// instruction to clear.
|
||||
// The first WMMA of a group takes an inline zero for C, so no clear is needed.
|
||||
v8f g_acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++) {
|
||||
@@ -256,9 +202,8 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w4a16_nt_m64_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// Split-K reduction and store: identical to r4d_gemm_bf16_nt_m64, one row tile at a time so the
|
||||
// LDS is WV*SK KiB whatever MT is, and in a fixed order over splits so the result does not depend
|
||||
// on how the waves were scheduled.
|
||||
// Split-K reduction and store as in r4d_gemm_bf16_nt_m64: one row tile at a time, fixed split
|
||||
// order.
|
||||
const int ncols = WV * NPW;
|
||||
const int nthreads = WV * SK * WAVE32;
|
||||
#pragma unroll
|
||||
@@ -325,8 +270,7 @@ int r4d_gemm_w4a16_nt_m64_group(void) { return R4D_GEMM_W4_GROUP; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there
|
||||
// is no adapter directory between the core and these launches.
|
||||
// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h.
|
||||
/* ------------------------------------------------------------------ f16-activation grids */
|
||||
|
||||
extern "C" int r4d_rad_gemm_w4a16_m64(const RadArgs* a, RadStream s) {
|
||||
@@ -334,6 +278,8 @@ extern "C" int r4d_rad_gemm_w4a16_m64(const RadArgs* a, RadStream s) {
|
||||
int rc = gemm_ops(a, &g, 1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
/* Any other activation dtype would read plausible but wrong numbers. */
|
||||
if (g.a->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE);
|
||||
if (g.M > r4d_gemm_w4a16_nt_m64_max_m()) return R4D_NO(RAD_E_SHAPE);
|
||||
const int group = r4d_gemm_w4a16_nt_m64_group();
|
||||
Cfg c;
|
||||
|
||||
+60
-317
@@ -1,70 +1,43 @@
|
||||
// r4d_gemm_w4a8_nt_m64.hip - r4d_gemm_w4a8_nt_m64: 4-bit-weight, 8-bit-activation skinny GEMM for
|
||||
// M up to 64, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with A quantised per row.
|
||||
//
|
||||
// WHY THIS EXISTS ALONGSIDE r4d_gemm_w4a16_nt_m64. The f16 kernel is at the DRAM roofline at M=8
|
||||
// (620-648 GB/s) and there is nothing left to win there. At M=64 -- the drafter's batch at eight
|
||||
// concurrent requests -- it is not near memory at all: 300-350 GB/s and 72-78 TF/s, against a
|
||||
// v_wmma_f32_16x16x16_f16 issue ceiling of 207 TF/s, and removing the unpack entirely barely
|
||||
// changes that. The wall is the f16 matrix instruction, and on this part it is the slow one:
|
||||
// Complements r4d_gemm_w4a16_nt_m64, which is at the DRAM roofline at M=8 but capped by the f16
|
||||
// matrix instruction at M=64 (72-78 TF/s against a 207 TF/s issue ceiling; removing the unpack
|
||||
// barely helps). Every 8-bit form runs at twice the f16 rate:
|
||||
//
|
||||
// v_wmma_f32_16x16x16_f16 207 TF/s 5.95 cyc/instr
|
||||
// v_wmma_f32_16x16x16_fp8_fp8 412 2.99
|
||||
// v_wmma_i32_16x16x16_iu8 407 3.03
|
||||
// v_wmma_i32_16x16x32_iu4 830 2.97
|
||||
//
|
||||
// So the widening that made the f16 kernel cheap is what caps it: every 8-bit form runs at twice
|
||||
// the rate. This kernel takes the int8 one, which needs no exponent games at all.
|
||||
//
|
||||
// THE UNPACK IS THREE INSTRUCTIONS AND NEEDS NO ZERO POINT. Store the weight as a 4-bit TWO'S
|
||||
// COMPLEMENT code and put the nibble in the HIGH half of its byte: for q in -8..7 the byte 16*q is
|
||||
// exactly the signed int8 of 16*q, so
|
||||
// The unpack is three instructions with no zero point. The weight is a 4-bit two's complement code
|
||||
// placed in the high half of its byte: for q in -8..7 the byte 16*q is the signed int8 of 16*q:
|
||||
//
|
||||
// lo = (w << 4) & 0xF0F0F0F0 bytes <- nibbles 0,2,4,6 (elements 0..3)
|
||||
// hi = w & 0xF0F0F0F0 bytes <- nibbles 1,3,5,7 (elements 4..7)
|
||||
//
|
||||
// is the whole dequant: two v_and_b32 and one v_lshlrev_b32 per eight weights, against eleven for
|
||||
// the f16 route, and the factor of 16 folds into the group scale offline. A symmetric grid also
|
||||
// deletes the zero point, which in an integer kernel would otherwise cost a per-group row-sum of A
|
||||
// and a second correction term. A symmetric 4-bit grid is the best of the 4-bit options on
|
||||
// quality anyway, so this costs nothing to pick.
|
||||
// Two v_and_b32 and one v_lshlrev_b32 per eight weights (eleven on the f16 route); the factor 16 is
|
||||
// removed at the store. A symmetric grid needs no per-group row sum of A for a zero point.
|
||||
//
|
||||
// The nibble ORDER is the one r4d_gemm_w4a16_nt_m64 already uses: its f16 unpack pairs nibble 2b
|
||||
// into element b and nibble 2b+1 into element 4+b, which is exactly what the two masks above
|
||||
// produce. One packed layout, two kernels.
|
||||
// The weight is shared byte for byte with r4d_gemm_w4a16_nt_m64. Its f16 unpack pairs nibble 2b
|
||||
// into element b and 2b+1 into element 4+b, the order the two masks above produce, and with a
|
||||
// constant zero point 8 it computes the same n-8. Only the low half (the scale) of the
|
||||
// (scale, -(1024+zero)) dword is read here. Small M stays on the f16 kernel, which needs no
|
||||
// activation-quantiser launch.
|
||||
//
|
||||
// IT SHARES ITS WEIGHT WITH r4d_gemm_w4a16_nt_m64, BYTE FOR BYTE. The two kernels want the same
|
||||
// nibbles in the same order, and a signed 4-bit code is what the f16 kernel computes anyway when
|
||||
// its integer zero point is the constant 8: it builds 1024+n and adds -(1024+8), leaving n-8. So
|
||||
// one quantised weight feeds both, and the scale array is the f16 kernel's (scale, -(1024+zero))
|
||||
// dword with only the low half read here. The stored scale multiplies q-8 while the WMMA here
|
||||
// sees 16*(q-8), so the factor of 1/16 rides along with the per-row activation scale at the store,
|
||||
// where it costs nothing. That matters because the dispatch is per call: below M=16 the f16
|
||||
// kernel is already at the DRAM roofline and there is nothing for an int8 one to win, while the
|
||||
// activation quantiser costs a launch -- so the small-M path stays on f16 and the same bytes serve
|
||||
// both.
|
||||
// The activation is shuffled within each k step. Fragment element e of lane l is
|
||||
// A[row][16s + 8*(e>>2) + 4*(l>>4) + (e&3)], two dwords eight bytes apart in a row-major A. The
|
||||
// quantiser writes each step's sixteen bytes as [half 0's eight][half 1's eight], so a fragment is
|
||||
// one global_load_b64 (32 loads per group instead of 64).
|
||||
//
|
||||
// THE ACTIVATION IS PRE-SHUFFLED TOO, BUT ONLY INSIDE A K STEP. A fragment element e of lane l is
|
||||
// A[row][16s + 8*(e>>2) + 4*(l>>4) + (e&3)], so read out of a row-major A a lane's eight bytes are
|
||||
// two dwords eight bytes apart: 64 global_load_b32 against 64 WMMA for one group, and 32
|
||||
// s_wait_loadcnt with them. The activation layout is this library's to choose -- the quantiser
|
||||
// writes it -- so it is written with the sixteen bytes of each k step reordered to
|
||||
// [half 0's eight][half 1's eight]. A lane's fragment is then one global_load_b64 and the group
|
||||
// costs 32 loads instead of 64.
|
||||
// Do not lay A out as two planes ([2][M][K/2]): it allows global_load_b128 but is slower, because
|
||||
// one instruction then spans two distant regions and touches twice the cache lines. The shuffle
|
||||
// keeps a wave within the same sixteen rows.
|
||||
//
|
||||
// DO NOT LAY A OUT AS TWO PLANES. [2][M][K/2] makes a lane's four k steps contiguous and the
|
||||
// group eight global_load_b128, and it is SLOWER than the shuffle below. Sixteen lanes of a wave
|
||||
// then address one plane and sixteen the other, Mp*K/2 bytes away, so a single instruction spans
|
||||
// two distant regions and doubles the cache lines it touches. The shuffle keeps every lane of a
|
||||
// wave inside the same sixteen rows the row-major version touches, and only makes each lane's own
|
||||
// eight bytes adjacent.
|
||||
//
|
||||
// THE ACTIVATION SCALE COMES OUT OF THE GROUP LOOP. Per-row symmetric quantisation makes the row
|
||||
// scale a constant in n and in the group index, so sum_g s_g * <a_row, w_g> * ar = ar * sum_g ...:
|
||||
// it is applied once at the store and never inside the k loop. What does stay in the loop is one
|
||||
// v_cvt_f32_i32 per accumulator element per group, because group scales differ -- eight of them
|
||||
// against eight WMMA. That argued for a WIDE group, and this kernel alone would take 256; the
|
||||
// group is 128 because the f16 kernel at M=8 needs the split-K that a wider group takes away
|
||||
// (`K % (SK*GROUP) == 0` halves the legal split count), and one artifact feeds every W4 kernel.
|
||||
// The per-row activation scale is constant over n and groups, so it is applied once at the store.
|
||||
// The loop keeps one v_cvt_f32_i32 per accumulator element per group. A wider group would suit this
|
||||
// kernel alone; 128 keeps enough legal split-K counts for the f16 kernel at M=8 (one artifact
|
||||
// feeds every W4 kernel).
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -74,13 +47,10 @@
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
// M is not structural here -- `mt0 = blockIdx.y * MT` tiles it and the row index is clamped into
|
||||
// 0..M-1 -- so this is a guard against a garbage shape, not the band the kernel is good at. It is
|
||||
// set wide enough to reach a prefill chunk as well as the decode band, where at eight concurrent
|
||||
// sequences with spec width 8 the target verifies 8 x 9 = 72 rows. Whether the tuned geometry
|
||||
// above M = 64 is still the right one is a separate question and is NOT answered by this bound.
|
||||
// M is not structural (grid.y tiles it, rows are clamped); this is a sanity bound wide enough for a
|
||||
// prefill chunk and the decode band (e.g. 8 sequences x 9 verify rows = 72), not a tuning band.
|
||||
#define R4D_GEMM_W4A8_MAX_M 8192
|
||||
// R4D_GEMM_W4A8_GROUP comes from r4d_common.h -- see the note there.
|
||||
// R4D_GEMM_W4A8_GROUP comes from r4d_common.h; see the note there.
|
||||
#define R4D_GEMM_W4A8_KPB 64 // K per packed block: 4 k steps, 16 bytes per lane
|
||||
#define WAVE32 32
|
||||
|
||||
@@ -90,91 +60,11 @@ typedef int v2i __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned uint4v __attribute__((ext_vector_type(4)));
|
||||
|
||||
typedef __attribute__((address_space(1))) const uint4v* r4d_gw4;
|
||||
typedef __attribute__((address_space(1))) const unsigned* r4d_gu1;
|
||||
typedef __attribute__((address_space(1))) const unsigned* r4d_gh1;
|
||||
typedef __attribute__((address_space(1))) const unsigned short* r4d_gh2;
|
||||
typedef unsigned uint2v __attribute__((ext_vector_type(2)));
|
||||
typedef __attribute__((address_space(1))) const uint2v* r4d_ga2;
|
||||
|
||||
// A fragment out of the pre-permuted plane: eight contiguous bytes per k step, so a uint4 is two
|
||||
// steps and the whole group is eight global_load_b128 per row tile.
|
||||
#ifndef R4D_W4A8_APERM
|
||||
#define R4D_W4A8_APERM 1 // 0 reads A row-major, for a harness with an unpermuted buffer
|
||||
#endif
|
||||
|
||||
// THE SCALE DWORD IS HALF DEAD ON A SYMMETRIC GRID, AND AT THE DECODE BATCH THAT IS PURE COST.
|
||||
// The shared (f16 scale, f16 of -(1024 + zero)) dword exists for r4d_gemm_w4a16_nt_m64, which
|
||||
// builds its value as 1024 + n and needs the second half to subtract. A symz grid only ever
|
||||
// writes the constant 8 there, and THIS kernel never reads it: the ISA shows one
|
||||
// `global_load_b32` per group whose high sixteen bits are dropped by the `op_sel_hi` on the
|
||||
// v_fma_mix that consumes it.
|
||||
//
|
||||
// At group 128 the scale array is 4 bytes per 16 columns per group against 1024 bytes of nibbles,
|
||||
// so the dead half is 32 of every 1088 bytes -- 2.94% of everything the kernel reads. That is not
|
||||
// an instruction count, it is DRAM traffic, and at M <= 16 this kernel runs at 97-98% of the part's
|
||||
// 639 GB/s read ceiling, where traffic is the ONLY thing that sets the time. WS16 reads
|
||||
// an f16-only scale plane instead. Sixteen lanes then take 32 contiguous bytes and consecutive
|
||||
// groups are adjacent, so the 64-byte line is still fully used -- the halving is real and not an
|
||||
// artefact of counting bytes the cache would have fetched anyway.
|
||||
//
|
||||
// The asymmetric form keeps the dword: its whole reason for existing is the zero point.
|
||||
#ifndef R4D_GEMM_W4A8_WS16
|
||||
#define R4D_GEMM_W4A8_WS16 0
|
||||
#endif
|
||||
|
||||
// COST ABLATIONS. Wrong answers by construction; they exist to say what the kernel's time is made
|
||||
// of. WS16 above deletes 2.94% of the bytes read and does not move the time, so byte counts alone
|
||||
// do not explain it.
|
||||
// 1 no scale load (sc = 1)
|
||||
// 2 no activation load (the A fragment is a constant)
|
||||
// 4 no weight load (the B fragment is a constant; leaves the A stream and the WMMA)
|
||||
#ifndef R4D_W4A8_ABL
|
||||
#define R4D_W4A8_ABL 0
|
||||
#endif
|
||||
|
||||
// SOFTWARE-PIPELINE THE WEIGHT. The ablations above say the weight stream IS the kernel at a
|
||||
// decode M: deleting the scale load or the activation loads barely moves the time, while deleting
|
||||
// the weight load removes most of it, and that stream runs at 587 GB/s against the part's
|
||||
// 639.6 GB/s ceiling. The loop as written issues its two `global_load_b128`, waits on them, then
|
||||
// spends ~80 cycles in VALU and WMMA during which the wave issues no memory at all. PF holds the
|
||||
// NEXT group's weight in registers so the load is issued a whole group ahead of the wait.
|
||||
// Costs bpg*NPW*4 more VGPRs (16 instead of 8 at NPW=1, against 58 used).
|
||||
#ifndef R4D_W4A8_PF
|
||||
#define R4D_W4A8_PF 0
|
||||
#endif
|
||||
|
||||
// STAGGER THE GROUP ORDER PER WAVE, so the block's waves stop marching in lockstep across the
|
||||
// memory channels.
|
||||
//
|
||||
// Wave (col_local, ksplit) reads n-tile plane `nt0+col_local` starting at byte offset
|
||||
// `ksplit * (Ks/KPB) * 512` and advances 512 bytes per k-block. Every plane pitch here is
|
||||
// kpb*512 -- 40960 at K=5120, 69632 at 8704, 24576 at 3072 -- and every one of those is an exact
|
||||
// multiple of 4096. A 256-bit GDDR6 part interleaves 16 channels at 256 B, so the address period
|
||||
// that sweeps every channel is 4096 B, which means at time t EVERY wave in the grid is at the same
|
||||
// address modulo 4096 and therefore aimed at the same channel. The block issues 20 concurrent
|
||||
// streams and they all camp one channel group at a time.
|
||||
//
|
||||
// The fix is hipBLASLt's `StaggerU`: start each wave at a different group inside its OWN k-slice
|
||||
// and wrap. The slice, the split-K partition and the bytes read are all unchanged -- only the
|
||||
// order is -- so the only cost is that `pa` must be computed from g instead of incremented.
|
||||
//
|
||||
// NOTE this reorders an fp32 accumulation, so results move by ~1 ULP against a non-staggered build.
|
||||
#ifndef R4D_W4A8_STAGGER
|
||||
#define R4D_W4A8_STAGGER 0
|
||||
#endif
|
||||
|
||||
// Under STAGGER the group loop no longer visits groups in order, so the activation pointer is
|
||||
// indexed rather than bumped; without it the bump stays and this is zero.
|
||||
#if R4D_W4A8_STAGGER
|
||||
#if R4D_W4A8_APERM
|
||||
#define AOFF(g) ((g) * (R4D_GEMM_W4A8_GROUP / 8))
|
||||
#else
|
||||
#define AOFF(g) ((g) * (R4D_GEMM_W4A8_GROUP / 4))
|
||||
#endif
|
||||
#else
|
||||
#define AOFF(g) 0
|
||||
#endif
|
||||
|
||||
// A fragments from the pre-permuted plane: eight contiguous bytes per k step.
|
||||
__device__ __forceinline__ v2i fragA8(r4d_ga2 p, int u) {
|
||||
const uint2v w = p[2 * u];
|
||||
v2i r;
|
||||
@@ -183,15 +73,7 @@ __device__ __forceinline__ v2i fragA8(r4d_ga2 p, int u) {
|
||||
return r;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v2i fragA8row(r4d_gu1 p, int u) {
|
||||
v2i r;
|
||||
r[0] = p[4 * u];
|
||||
r[1] = p[4 * u + 2];
|
||||
return r;
|
||||
}
|
||||
|
||||
// The whole dequant: two ands and a shift, no zero point. It is a few percent of the kernel at
|
||||
// M=64 and under a fifth of a percent at M=8, so there is nothing here worth a knob.
|
||||
// The whole dequant: two ands and a shift.
|
||||
__device__ __forceinline__ v2i dequant8(unsigned w) {
|
||||
v2i r;
|
||||
r[0] = (int)((w << 4) & 0xF0F0F0F0u);
|
||||
@@ -199,31 +81,19 @@ __device__ __forceinline__ v2i dequant8(unsigned w) {
|
||||
return r;
|
||||
}
|
||||
|
||||
// BSIGNED=false reads the unpacked byte as 16*nibble (0..240) rather than 16*twos(nibble)
|
||||
// (-128..112). That is what makes an ASYMMETRIC grid expressible: 16*nibble is affine in the
|
||||
// nibble, so sum_k a_k (nibble_k - z) = sum_k a_k nibble_k - z sum_k a_k, whereas twos() is affine
|
||||
// on each half of the range and not across it. The flag's meaning on gfx1201: a B byte of 0x81
|
||||
// gives -2032 signed against 2064 unsigned, a ratio of -127/129 exactly.
|
||||
// BSIGNED=false reads the unpacked byte as 16*nibble (0..240) instead of 16*twos(nibble)
|
||||
// (-128..112), which makes an asymmetric grid expressible: 16*nibble is affine in the nibble, so
|
||||
// sum_k a_k (nibble_k - z) = sum_k a_k nibble_k - z sum_k a_k.
|
||||
template <bool BSIGNED>
|
||||
__device__ __forceinline__ v8i mmai(v2i a, v2i b, v8i c) {
|
||||
return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a, BSIGNED, b, c, false);
|
||||
}
|
||||
|
||||
// __launch_bounds__ IS PER NPW, AND A FLAT 1024 COSTS THE WIDE ONES 192 REGISTERS.
|
||||
// A block cannot exceed 1024 threads, but it also cannot exceed 64 KB of LDS, and the split-K
|
||||
// buffer is WV*NPW*SK*1024 bytes -- so WV*NPW*SK <= 64 is structural and threads = 32*WV*SK is
|
||||
// therefore capped at 32*64/NPW. Telling the compiler 1024 for every NPW makes it budget for 32
|
||||
// waves on one workgroup, which on this part is 1536/8 = 192 VGPRs per wave, and NPW=4 and NPW=8
|
||||
// then SPILL against that cap (up to 1875 bytes at MT=4, NPW=8). Those configs can never run more
|
||||
// than 8 or 16 waves, so that cap is imaginary and the spill is not.
|
||||
#ifndef R4D_GEMM_W4A8_LB
|
||||
#define R4D_GEMM_W4A8_LB 1
|
||||
#endif
|
||||
#if R4D_GEMM_W4A8_LB
|
||||
// __launch_bounds__ depends on NPW. The split-K buffer (WV*NPW*SK KiB) must fit 64 KiB of LDS, so
|
||||
// threads = 32*WV*SK <= 32*64/NPW. A flat 1024 would budget 32 waves per workgroup and make NPW=4
|
||||
// and NPW=8 spill, though they can never run more than 16 or 8 waves. The bound is a hard launch
|
||||
// limit, so the host checks WV*SK against the same expression.
|
||||
#define R4D_W4A8_BOUNDS(NPW) ((NPW) >= 8 ? 256 : ((NPW) >= 4 ? 512 : 1024))
|
||||
#else
|
||||
#define R4D_W4A8_BOUNDS(NPW) 1024
|
||||
#endif
|
||||
|
||||
template <int MT, int NPW, bool NT, bool ASYM>
|
||||
__global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_kernel(
|
||||
@@ -247,138 +117,65 @@ __global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_ker
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
// TWO THINGS THAT DO NOT WORK ON THE ASYMMETRIC CORRECTION'S ACTIVATION SUMS.
|
||||
//
|
||||
// Loading the sums just before the epilogue instead of at the top of the group, to cut
|
||||
// asum[MT][8]'s 32-VGPR live range at MT=4, is SLOWER. At the top of the group the load is
|
||||
// already hidden behind the WMMA block, and the register pressure costs less than exposing that
|
||||
// latency does.
|
||||
//
|
||||
// Staging the sums in LDS is also SLOWER, at both ends of the M range. Every wave of the block
|
||||
// re-reads a group's sums, and the staging can alias the split-K buffer for free since `red` is
|
||||
// only touched in the store loop and that loop opens with a barrier -- but the staging prologue
|
||||
// is (K/GROUP)*(MT*16) loads plus a __syncthreads() on a kernel that runs a few microseconds at a
|
||||
// decode M, and the sums are not the latency problem.
|
||||
// The asymmetric activation sums are loaded at the top of each group, hidden behind the WMMA
|
||||
// block. Loading them later (shorter live range) or staging them in LDS were both slower.
|
||||
|
||||
if (n0 < N) {
|
||||
// Rows clamped, never masked, as in the f16 kernel: a tile past M recomputes the last valid
|
||||
// row and the store discards it. A is int8 so the row stride is K bytes, not 2K.
|
||||
// Plane (lane >> 4), row clamped into 0..M-1, and the group's byte offset is K/2 per row.
|
||||
#if R4D_W4A8_APERM
|
||||
// Rows clamped into 0..M-1, never masked; the store discards rows past M. A is int8, so the
|
||||
// row stride is K bytes.
|
||||
r4d_ga2 pa[MT];
|
||||
#else
|
||||
r4d_gu1 pa[MT];
|
||||
#endif
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
int r = (mt0 + i) * 16 + (lane & 15);
|
||||
r = r < M - 1 ? r : M - 1;
|
||||
#if R4D_W4A8_APERM
|
||||
const size_t off = (size_t)r * K + kbase + 8 * (lane >> 4);
|
||||
pa[i] = (r4d_ga2)(const uint2v*)(A + off);
|
||||
#else
|
||||
const size_t off = (size_t)r * K + kbase + 4 * (lane >> 4);
|
||||
pa[i] = (r4d_gu1)(const unsigned*)(A + off);
|
||||
#endif
|
||||
}
|
||||
|
||||
const int kpb = K / R4D_GEMM_W4A8_KPB;
|
||||
const int nsz = K / R4D_GEMM_W4A8_GROUP;
|
||||
r4d_gw4 pw[NPW];
|
||||
#if R4D_GEMM_W4A8_WS16
|
||||
r4d_gh2 ps[NPW];
|
||||
#else
|
||||
r4d_gh1 ps[NPW];
|
||||
#endif
|
||||
const int ntlast = N / 16 - 1;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int t = (nt0 + j) < ntlast ? (nt0 + j) : ntlast;
|
||||
pw[j] = (r4d_gw4)(const uint4v*)(Wq) +
|
||||
(size_t)(t * kpb + kbase / R4D_GEMM_W4A8_KPB) * WAVE32 + lane;
|
||||
#if R4D_GEMM_W4A8_WS16
|
||||
ps[j] = (r4d_gh2)(const unsigned short*)(Ws) +
|
||||
(size_t)(t * nsz + kbase / R4D_GEMM_W4A8_GROUP) * 16 + (lane & 15);
|
||||
#else
|
||||
ps[j] = (r4d_gh1)(const unsigned*)(Ws) +
|
||||
(size_t)(t * nsz + kbase / R4D_GEMM_W4A8_GROUP) * 16 + (lane & 15);
|
||||
#endif
|
||||
}
|
||||
|
||||
const int bpg = R4D_GEMM_W4A8_GROUP / R4D_GEMM_W4A8_KPB;
|
||||
|
||||
#if R4D_W4A8_PF
|
||||
uint4v nx[NPW][bpg];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++)
|
||||
nx[j][b] = NT ? __builtin_nontemporal_load(&pw[j][(size_t)b * WAVE32])
|
||||
: pw[j][(size_t)b * WAVE32];
|
||||
#endif
|
||||
|
||||
#if R4D_W4A8_STAGGER
|
||||
const int gstag = groups > 1 ? (wave * R4D_W4A8_STAGGER) % groups : 0;
|
||||
#endif
|
||||
for (int gi = 0; gi < groups; gi++) {
|
||||
#if R4D_W4A8_STAGGER
|
||||
const int g = gi + gstag < groups ? gi + gstag : gi + gstag - groups;
|
||||
#else
|
||||
const int g = gi;
|
||||
#endif
|
||||
for (int g = 0; g < groups; g++) {
|
||||
float sc[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#if R4D_W4A8_ABL & 1
|
||||
sc[j] = 1.f;
|
||||
#elif R4D_GEMM_W4A8_WS16
|
||||
sc[j] = __half2float(__ushort_as_half(ps[j][(size_t)g * 16]));
|
||||
#else
|
||||
sc[j] = __half2float(__ushort_as_half(
|
||||
(unsigned short)(ps[j][(size_t)g * 16] & 0xFFFFu)));
|
||||
#endif
|
||||
|
||||
// The zero point lives in the SAME dword's high half, as the f16 of -(1024 + zero) -- the
|
||||
// encoding the f16 kernel already needs, and exact because f16 has exactly 1024 steps between
|
||||
// 1024 and 2048. The symz grid only ever writes the constant 8 there.
|
||||
// The zero point is the dword's high half, the f16 of -(1024 + zero) (exact: f16 has unit
|
||||
// steps between 1024 and 2048). The symmetric grid always stores 8 there.
|
||||
float z16[NPW];
|
||||
float asum[MT][8];
|
||||
if (ASYM) {
|
||||
#if R4D_W4A8_ASUM_ABLATE
|
||||
// Cost ablation only -- same arithmetic, no global loads. Wrong answers by construction;
|
||||
// it exists to say whether the asymmetric path costs its FMAs or its memory.
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) z16[j] = 16.f;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) asum[i][e] = 1.f;
|
||||
#else
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const float nz = __half2float(__ushort_as_half(
|
||||
(unsigned short)(ps[j][(size_t)g * 16] >> 16)));
|
||||
z16[j] = 16.f * (-nz - 1024.f);
|
||||
}
|
||||
// Element e of tile i at this lane is output row (mt0+i)*16 + 8*(lane>>4) + e, so the eight
|
||||
// rows a lane needs are CONTIGUOUS at a fixed group -- which is why Asum is [G][Mpad] and
|
||||
// not [M][G].
|
||||
//
|
||||
// TWO v4f LOADS, NOT EIGHT SCALARS. These loads, and not the correction's arithmetic, are
|
||||
// most of what an asymmetric grid costs over a symmetric one.
|
||||
// They vectorise only if the base is 32-byte aligned, which is why the row stride is padded
|
||||
// to a multiple of 16 (also making the last tile's rb+7 in bounds, since rb reaches
|
||||
// (mtiles-1)*16 + 8).
|
||||
// Element e of tile i at this lane is output row (mt0+i)*16 + 8*(lane>>4) + e, so a lane's
|
||||
// eight rows are contiguous at a fixed group; hence Asum is [G][Mpad]. Two v4f loads need a
|
||||
// 32-byte aligned base, which Mpad (a multiple of 16) provides; it also keeps the last
|
||||
// tile's rb+7 in bounds. These loads are most of the asymmetric grid's extra cost.
|
||||
const int Mpad = ((M + 15) / 16) * 16;
|
||||
const size_t gi = (size_t)(kbase / R4D_GEMM_W4A8_GROUP + g) * Mpad;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
// CLAMPED, and it has to be. When MB exceeds the number of M tiles -- MB=4 with M=9 is a
|
||||
// legal config the tuner will pick -- this loop still runs MT tiles, and rb reaches
|
||||
// (MT-1)*16+8 = 56 against an Mpad of 16. The symz path survives that because its A
|
||||
// pointer clamps and the store discards rows past M; an unclamped Asum read is a page
|
||||
// fault. Rows past M produce garbage that is discarded, so clamping the base is enough,
|
||||
// and it stays a multiple of 8 so the v4f loads stay aligned.
|
||||
// Clamped: MB may exceed the number of M tiles (MB=4 with M=9 is legal), and an unclamped
|
||||
// Asum read could fault. The clamped base stays a multiple of 8, keeping v4f alignment.
|
||||
int rb = (mt0 + i) * 16 + 8 * (lane >> 4);
|
||||
rb = rb < Mpad - 8 ? rb : Mpad - 8;
|
||||
const v4f* pv = (const v4f*)(Asum + gi + rb);
|
||||
@@ -389,57 +186,23 @@ __global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_ker
|
||||
asum[i][e + 4] = v1[e];
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
v8i g_acc[NPW][MT];
|
||||
#if R4D_W4A8_PF
|
||||
// Take this group's weight out of the registers the last iteration filled, and issue the
|
||||
// next group's loads BEFORE any of it is consumed, so the wait sits a full group away.
|
||||
uint4v cw[NPW][bpg];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++) cw[j][b] = nx[j][b];
|
||||
if (g + 1 < groups) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++) {
|
||||
const size_t o = (size_t)((g + 1) * bpg + b) * WAVE32;
|
||||
nx[j][b] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o];
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++) {
|
||||
uint4v wv[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
#if R4D_W4A8_PF
|
||||
wv[j] = cw[j][b];
|
||||
#else
|
||||
const size_t o = (size_t)(g * bpg + b) * WAVE32;
|
||||
#if R4D_W4A8_ABL & 4
|
||||
(void)o;
|
||||
wv[j] = (uint4v)(0x21212121u);
|
||||
#else
|
||||
wv[j] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o];
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
#pragma unroll
|
||||
for (int s = 0; s < 4; s++) {
|
||||
const int u = b * 4 + s;
|
||||
v2i afrag[MT];
|
||||
#pragma unroll
|
||||
#if R4D_W4A8_ABL & 2
|
||||
for (int i = 0; i < MT; i++) { afrag[i][0] = 0x01010101; afrag[i][1] = 0x01010101; }
|
||||
#elif R4D_W4A8_APERM
|
||||
for (int i = 0; i < MT; i++) afrag[i] = fragA8(pa[i] + AOFF(g), u);
|
||||
#else
|
||||
for (int i = 0; i < MT; i++) afrag[i] = fragA8row(pa[i] + AOFF(g), u);
|
||||
#endif
|
||||
for (int i = 0; i < MT; i++) afrag[i] = fragA8(pa[i], u);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const v2i bfrag = dequant8(wv[j][s]);
|
||||
@@ -460,20 +223,12 @@ __global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_ker
|
||||
if (ASYM) t -= z16[j] * asum[i][e];
|
||||
acc[j][i][e] = fmaf(t, sc[j], acc[j][i][e]);
|
||||
}
|
||||
#if !R4D_W4A8_STAGGER
|
||||
#pragma unroll
|
||||
#if R4D_W4A8_APERM
|
||||
for (int i = 0; i < MT; i++) pa[i] += R4D_GEMM_W4A8_GROUP / 8;
|
||||
#else
|
||||
for (int i = 0; i < MT; i++) pa[i] += R4D_GEMM_W4A8_GROUP / 4;
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// Split-K reduction and store, one row tile at a time. The per-row activation scale is applied
|
||||
// here and only here: it is constant over n and over the group index, so it never entered the
|
||||
// k loop.
|
||||
// Split-K reduction and store, one row tile at a time, applying the per-row activation scale.
|
||||
const int ncols = WV * NPW;
|
||||
const int nthreads = WV * SK * WAVE32;
|
||||
#pragma unroll
|
||||
@@ -493,7 +248,7 @@ __global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_ker
|
||||
const int l = off & 31;
|
||||
const int n = (blockIdx.x * ncols + col) * 16 + (l & 15);
|
||||
const int m = (mt0 + i) * 16 + 8 * (l >> 4) + (off >> 5);
|
||||
// 0.0625 is the 1/16 the unpack introduced by putting the nibble in the byte's high half.
|
||||
// 0.0625 undoes the 16 from placing the nibble in the byte's high half.
|
||||
if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)(v * Ascale[m] * 0.0625f);
|
||||
}
|
||||
}
|
||||
@@ -507,7 +262,8 @@ static void r4d_gemm_w4a8_impl(long a, long ascale, long wq, long ws, long asum,
|
||||
if (N % 16) throw std::runtime_error("r4d gemm_w4a8_nt_m64: N must be a multiple of 16");
|
||||
if (K % (SK * R4D_GEMM_W4A8_GROUP))
|
||||
throw std::runtime_error("r4d gemm_w4a8_nt_m64: K must be divisible by SK*group");
|
||||
if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_w4a8_nt_m64: threads/block > 1024");
|
||||
if (WV * SK * WAVE32 > R4D_W4A8_BOUNDS(NPW))
|
||||
throw std::runtime_error("r4d gemm_w4a8_nt_m64: WV*SK*32 exceeds this tile's launch bound");
|
||||
if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w4a8_nt_m64: MB must be 1..4");
|
||||
if (NPW != 1 && NPW != 2 && NPW != 4 && NPW != 8)
|
||||
throw std::runtime_error("r4d gemm_w4a8_nt_m64: NPW must be 1, 2, 4 or 8");
|
||||
@@ -534,8 +290,9 @@ static void r4d_gemm_w4a8_impl(long a, long ascale, long wq, long ws, long asum,
|
||||
#define LAUNCH_NPW(TT, AS) switch (NPW) { \
|
||||
case 1: LAUNCH_MB(1, TT, AS); break; \
|
||||
case 2: LAUNCH_MB(2, TT, AS); break; \
|
||||
case 4: LAUNCH_MB(4, TT, AS); break; \
|
||||
case 8: LAUNCH_MB(8, TT, AS); break; \
|
||||
default: LAUNCH_MB(4, TT, AS); break; }
|
||||
default: throw std::runtime_error("r4d gemm_w4a8_nt_m64: NPW must be 1, 2, 4 or 8"); }
|
||||
if (asym) {
|
||||
if (NT) { LAUNCH_NPW(true, true); } else { LAUNCH_NPW(false, true); }
|
||||
} else {
|
||||
@@ -551,39 +308,25 @@ void r4d_gemm_w4a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M,
|
||||
r4d_gemm_w4a8_impl(a, ascale, wq, ws, 0, c, M, K, N, WV, SK, MB, NPW, NT, false, stream);
|
||||
}
|
||||
|
||||
// Asymmetric grid: the weight nibble is read UNSIGNED and the stored zero point is corrected out
|
||||
// with a per-row per-group sum of the activation, which r4d_quant_act_i8_asum emits. `asum` is
|
||||
// [K/group][Mpad] float with Mpad = ceil(M/16)*16 -- group-major, because a lane's eight
|
||||
// accumulator elements are eight CONTIGUOUS output rows at one group, and padded so that base is
|
||||
// 32-byte aligned for a v4f load and the last tile stays in bounds. Allocate it ZEROED.
|
||||
// Asymmetric grid: the nibble is read unsigned and the zero point is corrected with the per-row
|
||||
// per-group activation sums from r4d_quant_act_i8_asum. `asum` is [K/group][Mpad] float,
|
||||
// Mpad = ceil(M/16)*16 (see the kernel). Allocate it zeroed.
|
||||
void r4d_gemm_w4a8_asym_nt_m64(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) {
|
||||
if (!asum) throw std::runtime_error("r4d gemm_w4a8_asym_nt_m64: asum is required");
|
||||
#if R4D_GEMM_W4A8_WS16
|
||||
// The zero point is the only thing in the dword's high half, and WS16 is the build that does not
|
||||
// store it. The two are mutually exclusive by construction, so say so instead of reading zero.
|
||||
throw std::runtime_error("r4d gemm_w4a8_asym_nt_m64: built with WS16, which has no zero point");
|
||||
#endif
|
||||
r4d_gemm_w4a8_impl(a, ascale, wq, ws, asum, c, M, K, N, WV, SK, MB, NPW, NT, true, stream);
|
||||
}
|
||||
|
||||
int r4d_gemm_w4a8_nt_m64_max_m(void) { return R4D_GEMM_W4A8_MAX_M; }
|
||||
int r4d_gemm_w4a8_nt_m64_group(void) { return R4D_GEMM_W4A8_GROUP; }
|
||||
int r4d_gemm_w4a8_nt_m64_aperm(void) { return R4D_W4A8_APERM; }
|
||||
int r4d_gemm_w4a8_nt_m64_ws16(void) { return R4D_GEMM_W4A8_WS16; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there
|
||||
// is no adapter directory between the core and these launches.
|
||||
// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h.
|
||||
/* ------------------------------------------------------------------ int8-activation grids */
|
||||
|
||||
/* The asymmetric grid is a different WEIGHT FORMAT, not a different call: the nibble is read
|
||||
* UNSIGNED and the stored per-group zero is corrected out with the activation's per-group row
|
||||
* sums. So it is selected by `dtype`, which is what the weight file was written for, and never by
|
||||
* whether a_sum happens to be present -- guessing from an operand would make a caller that forgot
|
||||
* to pass the sums silently compute the symmetric answer against asymmetric bytes. */
|
||||
/* The asymmetric grid is selected by `dtype`, not by the presence of a_sum (see is_asym). */
|
||||
|
||||
extern "C" int r4d_rad_gemm_w4a8_m64(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
|
||||
@@ -1,41 +1,24 @@
|
||||
// W4A8 GEMM FOR PREFILL: the same packed weight and the same rotated int8 activation as
|
||||
// r4d_gemm_w4a8_tiled, laid out for the regime where the matrix pipe is the answer.
|
||||
// W4A8 GEMM for prefill: the packed weight and rotated int8 activation of r4d_gemm_w4a8_tiled, for
|
||||
// the compute-bound regime. At decode this GEMM is a weight stream at the DRAM ceiling; at M = 4096
|
||||
// (730 GFLOP against 44.6 MB) every non-matrix instruction is overhead.
|
||||
//
|
||||
// WHY A SECOND KERNEL. At a decode batch this GEMM is a weight stream and every question is
|
||||
// bandwidth: `gate_up_proj` at M = 9 moves 47 MB and runs at the DRAM ceiling, so the inner loop's
|
||||
// instruction mix does not matter because the loop is waiting on memory. At M = 4096
|
||||
// the same call is 730 GFLOP against 44.6 MB, so the loop is waiting on nothing and every
|
||||
// instruction that is not a matrix instruction is a tax. The two want different code.
|
||||
// Ceiling: v_wmma_i32_16x16x16_iu8 occupies its SIMD for 8 cycles on gfx1201 (f16/bf16: 16), an
|
||||
// int8 peak of ~375 TOPS. There is no wider iu8 form (v_wmma_i32_16x16x32_iu8 does not exist), and
|
||||
// iu4 needs both operands 4-bit. The budget is 8 cycles per matrix instruction plus one per other
|
||||
// VALU instruction. The group fold is the largest non-matrix item, and as v_fma_mix_f32 (VOP3P,
|
||||
// never dual-issued) it costs more than as v_fmac_f32, which pairs as v_dual_fmac_f32, the only
|
||||
// VOPD form this loop can use (no v_dual_and_b32 or v_dual_lshlrev_b32). So the f16 scale is
|
||||
// materialised and folded with plain FMACs.
|
||||
//
|
||||
// THE CEILING THIS AIMS AT. `v_wmma_i32_16x16x16_iu8` occupies its SIMD for EIGHT cycles on
|
||||
// gfx1201 -- half what f16/bf16 take, at 16.0-16.2 cycles -- so the int8 matrix peak is ~375 TOPS,
|
||||
// not the ~187 an f16 roofline would say. gfx1201 has no wider iu8 form: `llvm-mc` rejects
|
||||
// `v_wmma_i32_16x16x32_iu8`, and `v_wmma_i32_16x16x32_iu4` is exactly twice the rate but needs
|
||||
// BOTH operands 4-bit, which the activation is not. So the budget is 8 cycles of matrix work per
|
||||
// matrix instruction plus one cycle per other VALU instruction, and the job is to make the second
|
||||
// term small. In a register-only replica of this inner loop, the matrix instructions on their own
|
||||
// reach most of that peak and the weight unpack costs little on top; the GROUP FOLD is the largest
|
||||
// non-matrix item in the loop, and it costs materially more as a `v_fma_mix_f32` than as a plain
|
||||
// `v_fmac_f32`.
|
||||
// A fragment reads: the tiled kernel stores A k-major and issues one ds_load_b64 per (row tile,
|
||||
// k step). Here a row's 64 bytes are half-major, [row][lane half][k step][2], so one ds_load_b128
|
||||
// fetches a lane's two consecutive k steps (TM*2 reads per 64-k block instead of TM*4). Only the LDS
|
||||
// copy is permuted; a lane still consumes the k values the weight names.
|
||||
//
|
||||
// The reason is dual issue. `v_fma_mix_f32` is VOP3P, which can never dual-issue;
|
||||
// `v_dual_fmac_f32` is the ONLY VOPD form gfx1201 offers that this loop can use
|
||||
// (`v_dual_and_b32` and `v_dual_lshlrev_b32` do not exist here, so the unpack cannot be packed at
|
||||
// all). This kernel therefore forces the f16 scale to materialise and folds with plain FMACs.
|
||||
//
|
||||
// THE OTHER HALF IS THE ACTIVATION FRAGMENT READ. The tiled kernel stores A in LDS k-major and
|
||||
// reads one `ds_load_b64` per (row tile, k step): 32 reads and ~30 `s_wait_dscnt` per scale group.
|
||||
// Here the row's 64 bytes are stored HALF-MAJOR -- [row][lane half][k step][2] instead of
|
||||
// [row][k step][lane half][2] -- which puts a lane's two consecutive k steps side by side, so one
|
||||
// `ds_load_b128` fetches them both and a whole 64-k block of A is TM*2 reads instead of TM*4.
|
||||
// The permutation is inside the LDS copy only: the packed weight is untouched and the activation
|
||||
// in memory is untouched, because a lane still consumes exactly the k values the weight names.
|
||||
//
|
||||
// The 4-dword XOR swizzle keeps that conflict-free. A row is 16 dwords and LDS has 32 banks, so
|
||||
// the row index contributes only its low bit; the mask has to separate the rest and it has to
|
||||
// permute whole 4-dword BLOCKS or a `ds_load_b128` lands astride two of them. ((r >> 1) & 3) << 2
|
||||
// gives lanes 0..7 the start banks {0,16,4,20,8,24,12,28} -- eight distinct starts, four dwords
|
||||
// each, all 32 banks once.
|
||||
// A 4-dword XOR swizzle keeps it conflict-free. A row is 16 dwords across 32 banks, so the row
|
||||
// index contributes only its low bit; the mask must separate the rest and permute whole 4-dword
|
||||
// blocks so a ds_load_b128 never straddles two. ((r >> 1) & 3) << 2 gives lanes 0..7 start banks
|
||||
// {0,16,4,20,8,24,12,28}, all 32 banks once.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -52,9 +35,8 @@ typedef float v8f_t __attribute__((ext_vector_type(8)));
|
||||
typedef unsigned u4v_t __attribute__((ext_vector_type(4)));
|
||||
typedef float v4f_t __attribute__((ext_vector_type(4)));
|
||||
|
||||
// The unpacked byte is 16*nibble, read SIGNED, and the 16 comes back out in the store. Three
|
||||
// instructions for two dwords is the floor here: gfx1201 has no `v_lshl_and_b32` and no nibble
|
||||
// permute, so each output dword costs at least its own mask.
|
||||
// The unpacked byte is 16*nibble, read signed; the 16 is removed at the store. Three instructions
|
||||
// for two dwords is the floor: gfx1201 has no v_lshl_and_b32 and no nibble permute.
|
||||
__device__ __forceinline__ v2i_t pf_dq8(unsigned w) {
|
||||
v2i_t r;
|
||||
r[0] = (int)((w << 4) & 0xF0F0F0F0u);
|
||||
@@ -63,12 +45,14 @@ __device__ __forceinline__ v2i_t pf_dq8(unsigned w) {
|
||||
}
|
||||
|
||||
// OPT bits
|
||||
// 1 grid swizzle: walk GSW m-tiles per n-tile so the resident workgroups form a square and
|
||||
// both the A row block and the W column block are shared by several of them
|
||||
// 2 fold with plain `v_fmac_f32` (VOPD) instead of letting the f16 convert contract into a
|
||||
// `v_fma_mix_f32`
|
||||
// 4 split barrier: signal after the commit, do the k block's matrix work, wait at the top
|
||||
// 8 read the A fragments one `ds_load_b64` per k step (the tiled kernel's shape), for comparison
|
||||
// 1 grid swizzle: walk GSW m-tiles per n-tile so resident workgroups share A row blocks and
|
||||
// W column blocks
|
||||
// 2 fold with plain v_fmac_f32 (VOPD) rather than v_fma_mix_f32
|
||||
// 8 read A fragments with one ds_load_b64 per k step (the tiled kernel's shape)
|
||||
// 128 load a row tile's eight Ascale values as two b128: a lane's rows
|
||||
// (m0 + i*16 + 8*half + e, e = 0..7) are contiguous
|
||||
// 256 unpredicated stores for blocks wholly inside the matrix (all but the last row block)
|
||||
// 512 non-temporal stores for C
|
||||
template <int WM, int WN, int TM, int TN, int OPT, int GSW>
|
||||
__global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel(
|
||||
const signed char* __restrict__ A, const float* __restrict__ Ascale,
|
||||
@@ -83,31 +67,13 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel(
|
||||
constexpr int NT_ = WM * WN * 32;
|
||||
constexpr int UNR = GRP / BK; // k blocks per scale group
|
||||
constexpr bool VOPD = (OPT & 2) != 0;
|
||||
constexpr bool SPLITB = (OPT & 4) != 0;
|
||||
constexpr bool NARROWA = (OPT & 8) != 0;
|
||||
// ABLATIONS. Both compute wrong answers on purpose and both keep every instruction that is not
|
||||
// the thing being priced, so what they measure is one item and not a deleted pipeline.
|
||||
// 16 every fragment read comes from buffer 0 at k = 0: the same LDS reads, the same count,
|
||||
// the same banks, but no dependency on the staging that filled it
|
||||
// 32 the A fragment never leaves registers: prices the A LDS read itself
|
||||
constexpr bool ABSTALE = (OPT & 16) != 0;
|
||||
constexpr bool ABNOA = (OPT & 32) != 0;
|
||||
// 64 store one output element in eight, with the other seven folded into it so nothing in the
|
||||
// k loop goes dead: prices the store epilogue, which is 64 predicated bf16 stores, 64 f32
|
||||
// multiplies, 64 software bf16 roundings and 32 `Ascale` loads per lane
|
||||
constexpr bool ABSTORE = (OPT & 64) != 0;
|
||||
// 128 load the eight `Ascale` values of a row tile as two b128 instead of eight scalars: the
|
||||
// rows a lane owns (m0 + i*16 + 8*half + e, e = 0..7) are CONTIGUOUS
|
||||
constexpr bool ASCVEC = (OPT & 128) != 0;
|
||||
// 256 an unpredicated store path for the blocks that are wholly inside the matrix, which at a
|
||||
// prefill M is all but the last row block: 64 compares and 64 cndmasks per lane go away
|
||||
// 512 non-temporal stores for C, which is written once and never read by this kernel
|
||||
constexpr bool STFAST = (OPT & 256) != 0;
|
||||
constexpr bool STNT = (OPT & 512) != 0;
|
||||
|
||||
// Both stagings move 16 bytes per thread per pass, with a predicate on the last one so a block
|
||||
// shape does not have to divide the block width. AD/4 = BM*4 and WD/4 = (BN/16)*32, so at 512
|
||||
// threads that is exact only for BM = 128 and BN = 256; every other tile in the sweep is ragged.
|
||||
// Both stagings move 16 bytes per thread per pass, predicated on the last pass so the tile need
|
||||
// not divide the thread count (exact at 512 threads only for BM = 128, BN = 256).
|
||||
constexpr int AU = AD / 4, WU = WD / 4;
|
||||
constexpr int APT = (AU + NT_ - 1) / NT_, WPT = (WU + NT_ - 1) / NT_;
|
||||
constexpr bool APAD = (AU % NT_) != 0, WPAD = (WU % NT_) != 0;
|
||||
@@ -131,8 +97,7 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel(
|
||||
const int m0 = by * BM, n0 = bx * BN;
|
||||
const int kpb = K / BK, nsz = K / GRP;
|
||||
|
||||
// A LDS position of (row, lane half, k step). See the header: half-major inside the row, with a
|
||||
// 4-dword XOR that separates eight rows.
|
||||
// A LDS position of (row, lane half, k step): half-major within the row, 4-dword XOR swizzle.
|
||||
#define PF_APOS(r, h, u) ((r) * 16 + ((((h) * 8 + (u) * 2)) ^ ((((r) >> 1) & 3) << 2)))
|
||||
|
||||
v8f_t acc[TN][TM];
|
||||
@@ -182,13 +147,9 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel(
|
||||
}
|
||||
};
|
||||
auto bar = [&]() {
|
||||
// THE LDS STORES IN `commit` HAVE TO LAND BEFORE THE SIGNAL, which is what the
|
||||
// release fence is for. `s_barrier_signal` is not `__syncthreads()`: it emits
|
||||
// the barrier alone, with no wait on the outstanding `ds_store`s. Without the
|
||||
// fence a wave announces writes that are still in flight and its neighbours read
|
||||
// whatever LDS held from the previous k block -- the generated code carries
|
||||
// `s_wait_loadcnt` for the global loads feeding the stores and no `s_wait_dscnt`
|
||||
// at all, and the kernel returns a different answer on every call.
|
||||
// The release fence makes commit's LDS stores land before the signal. Unlike
|
||||
// __syncthreads(), s_barrier_signal emits no s_wait_dscnt, so without the fence other
|
||||
// waves would read the previous k block's LDS contents.
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup");
|
||||
__builtin_amdgcn_s_barrier_signal(-1);
|
||||
__builtin_amdgcn_s_barrier_wait(-1);
|
||||
@@ -204,29 +165,21 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel(
|
||||
const int k0 = kg + h * BK;
|
||||
const int buf = h & 1;
|
||||
if (k0 + BK < K) issue(k0 + BK);
|
||||
if ((k0 % GRP) == 0) { // the group scale, one whole k block early
|
||||
if ((k0 % GRP) == 0) { // the group scale, one k block early
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
scv[j] = Ws[(unsigned)(((n0 / 16 + wn * TN + j) * nsz + k0 / GRP) * 16 + (lane & 15))];
|
||||
}
|
||||
|
||||
// ---- fragments: the whole 64-k block, up front ----
|
||||
// ---- fragments for the whole 64-k block, up front ----
|
||||
v2i_t af[TM][BK / 16];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) {
|
||||
const int row = (wm * TM + i) * 16 + (lane & 15);
|
||||
if (ABNOA) {
|
||||
#pragma unroll
|
||||
for (int u = 0; u < BK / 16; u++) {
|
||||
af[i][u][0] = (int)(0x11111111u + i + u);
|
||||
af[i][u][1] = (int)(0x22222222u + i);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (NARROWA) {
|
||||
#pragma unroll
|
||||
for (int u = 0; u < BK / 16; u++) {
|
||||
const unsigned* p = lds_a[ABSTALE ? 0 : buf] + PF_APOS(row, half, u);
|
||||
const unsigned* p = lds_a[buf] + PF_APOS(row, half, u);
|
||||
af[i][u][0] = (int)p[0];
|
||||
af[i][u][1] = (int)p[1];
|
||||
}
|
||||
@@ -234,7 +187,7 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel(
|
||||
#pragma unroll
|
||||
for (int q = 0; q < BK / 32; q++) { // one b128 = two k steps
|
||||
const u4v_t v =
|
||||
*(const u4v_t*)(lds_a[ABSTALE ? 0 : buf] + PF_APOS(row, half, 2 * q));
|
||||
*(const u4v_t*)(lds_a[buf] + PF_APOS(row, half, 2 * q));
|
||||
af[i][2 * q][0] = (int)v[0];
|
||||
af[i][2 * q][1] = (int)v[1];
|
||||
af[i][2 * q + 1][0] = (int)v[2];
|
||||
@@ -245,15 +198,12 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel(
|
||||
u4v_t wv[TN];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
wv[j] = *(const u4v_t*)(lds_w[ABSTALE ? 0 : buf] + (size_t)(wn * TN + j) * 128 + lane * 4);
|
||||
wv[j] = *(const u4v_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 128 + lane * 4);
|
||||
|
||||
if (SPLITB) { // the next block's LDS write, then arrive
|
||||
if (k0 + BK < K) commit(buf ^ 1);
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup"); // see bar()
|
||||
__builtin_amdgcn_s_barrier_signal(-1);
|
||||
}
|
||||
|
||||
// ---- the matrix work ----
|
||||
// ---- matrix work ----
|
||||
// A group's first WMMA seeds C with 0x4B400000 (the float 1.5 * 2^23), so the int32 sum's
|
||||
// bits read as a float are 12582912 + sum while |sum| < 2^22. The fold below multiplies that
|
||||
// float by the scale, and the bias 12582912 * sum(scale) is removed after the K loop.
|
||||
#pragma unroll
|
||||
for (int u = 0; u < BK / 16; u++) {
|
||||
#pragma unroll
|
||||
@@ -274,9 +224,8 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel(
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++) {
|
||||
sc[j] = __half2float(__ushort_as_half((unsigned short)(scv[j] & 0xFFFFu)));
|
||||
// Materialise the convert. Left alone the compiler folds it into `v_fma_mix_f32`, which
|
||||
// reads the f16 for free and is VOP3P -- and VOP3P never dual-issues, so the fold stays
|
||||
// at one instruction per accumulator element instead of one per two.
|
||||
// Materialise the convert; otherwise it contracts into v_fma_mix_f32 (VOP3P, never
|
||||
// dual-issued).
|
||||
if (VOPD) asm("" : "+v"(sc[j]));
|
||||
csum[j] += sc[j];
|
||||
}
|
||||
@@ -289,12 +238,8 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel(
|
||||
acc[j][i][e] = fmaf(__uint_as_float((unsigned)g[j][i][e]), sc[j], acc[j][i][e]);
|
||||
}
|
||||
|
||||
if (SPLITB) {
|
||||
__builtin_amdgcn_s_barrier_wait(-1);
|
||||
} else {
|
||||
if (k0 + BK < K) commit(buf ^ 1);
|
||||
bar();
|
||||
}
|
||||
if (k0 + BK < K) commit(buf ^ 1);
|
||||
bar();
|
||||
}
|
||||
}
|
||||
#undef PF_APOS
|
||||
@@ -308,30 +253,14 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel(
|
||||
for (int e = 0; e < 8; e++) acc[j][i][e] += d;
|
||||
}
|
||||
|
||||
if (ABSTORE) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) {
|
||||
float v = 0.f;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) v += acc[j][i][e];
|
||||
const int n = n0 + (wn * TN + j) * 16 + (lane & 15);
|
||||
const int m = m0 + (wm * TM + i) * 16 + 8 * (lane >> 4);
|
||||
if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)(v * Ascale[m] * 0.0625f);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const bool inside = STFAST && (m0 + BM <= M);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) {
|
||||
float as[8];
|
||||
const int mb = m0 + (wm * TM + i) * 16 + 8 * (lane >> 4);
|
||||
if (ASCVEC) {
|
||||
// The vector reads Ascale[mc .. mc+7], which lies inside [0, M) only when M >= 8. Below that
|
||||
// it would read past the last row's scale -- past the operand, when the plane is exactly M
|
||||
// long -- so a short M takes the clamped scalar read for every lane instead. M is uniform
|
||||
// over the grid, so the branch costs one compare.
|
||||
// The vector read Ascale[mc .. mc+7] stays inside [0, M) only when M >= 8; a short M, or a
|
||||
// lane whose rows were clamped, takes the clamped scalar read instead.
|
||||
const int mc = mb < M - 8 ? mb : (M > 8 ? M - 8 : 0);
|
||||
if (M >= 8) {
|
||||
const v4f_t* pv = (const v4f_t*)(Ascale + mc);
|
||||
@@ -353,7 +282,7 @@ __global__ __launch_bounds__(WM * WN * 32, 8) void r4d_gemm_w4a8_prefill_kernel(
|
||||
const __hip_bfloat16 v =
|
||||
(__hip_bfloat16)(acc[j][i][e] * (ASCVEC ? as[e] : Ascale[m]) * 0.0625f);
|
||||
if (inside || (n < N && m < M)) {
|
||||
// the non-temporal builtin does not take a __hip_bfloat16*, so go through its bits
|
||||
// the non-temporal builtin does not take a __hip_bfloat16*, so store its bits
|
||||
if (STNT)
|
||||
__builtin_nontemporal_store(*(const unsigned short*)&v,
|
||||
(unsigned short*)(C + (size_t)m * N + n));
|
||||
@@ -380,36 +309,22 @@ static void pf_launch(long a, long ascale, long wq, long ws, long c, int M, int
|
||||
void r4d_gemm_w4a8_prefill(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
|
||||
long stream, int variant) {
|
||||
#define PF(...) pf_launch<__VA_ARGS__>(a, ascale, wq, ws, c, M, K, N, stream)
|
||||
// The arms tile_bmbn in r4d_rows.cpp lists; 8, 9, 10, 13 and 14 change the tile, the rest are
|
||||
// BM 128 x BN 256 with other OPT bits.
|
||||
switch (variant) {
|
||||
case 1: PF(2, 8, 4, 2, 0, 1); break; // no VOPD fold, b128 A
|
||||
case 2: PF(2, 8, 4, 2, 8, 1); break; // b64 A, no VOPD fold
|
||||
case 3: PF(2, 8, 4, 2, 10, 1); break; // b64 A, VOPD fold
|
||||
case 4: PF(2, 8, 4, 2, 6, 1); break; // + split barrier
|
||||
case 5: PF(2, 8, 4, 2, 3, 4); break; // + grid swizzle, GSW 4
|
||||
case 6: PF(2, 8, 4, 2, 3, 8); break; // + grid swizzle, GSW 8
|
||||
case 7: PF(2, 8, 4, 2, 7, 8); break; // swizzle + split barrier
|
||||
case 8: PF(2, 8, 2, 2, 2, 1); break; // BM 64, BN 256
|
||||
case 9: PF(2, 8, 3, 2, 2, 1); break; // BM 96, BN 256
|
||||
case 10: PF(2, 8, 4, 1, 2, 1); break; // BM 128, BN 128
|
||||
case 11: PF(4, 8, 4, 2, 2, 1); break; // BM 256, BN 256, 1024 threads
|
||||
case 12: PF(2, 16, 4, 2, 2, 1); break; // BM 128, BN 512, 1024 threads
|
||||
case 13: PF(1, 8, 4, 2, 2, 1); break; // BM 64, BN 256, 256 threads
|
||||
case 14: PF(2, 8, 8, 1, 2, 1); break; // BM 256, BN 128
|
||||
case 15: PF(4, 4, 4, 2, 2, 1); break; // BM 256, BN 128, 512 threads
|
||||
case 20: PF(2, 8, 4, 2, 2 | 16, 1); break; // abl: fragments from a stale buffer
|
||||
case 21: PF(2, 8, 4, 2, 2 | 32, 1); break; // abl: A fragment never touches LDS
|
||||
case 22: PF(2, 8, 4, 2, 2 | 16 | 32, 1); break; // abl: both
|
||||
case 23: PF(2, 8, 4, 2, 8 | 16, 1); break; // abl: stale, b64 A reads
|
||||
case 24: PF(2, 8, 4, 2, 0, 1); break; // b128 A, fma_mix fold
|
||||
case 25: PF(2, 8, 4, 2, 2 | 64, 1); break; // abl: one store in eight
|
||||
case 26: PF(2, 8, 4, 2, 8 | 64, 1); break; // abl: one store in eight, b64 A
|
||||
case 27: PF(2, 8, 4, 2, 2 | 128, 1); break; // vectorised Ascale
|
||||
case 28: PF(2, 8, 4, 2, 8 | 128, 1); break; // vectorised Ascale, b64 A
|
||||
case 29: PF(2, 8, 4, 2, 8 | 128 | 256, 1); break; // + unpredicated store
|
||||
case 30: PF(2, 8, 4, 2, 8 | 128 | 256 | 512, 1); break; // + non-temporal
|
||||
case 31: PF(2, 8, 4, 2, 2 | 128 | 256, 1); break; // b128 A + both
|
||||
case 32: PF(2, 8, 4, 2, 8 | 128 | 256 | 1, 4); break; // + grid swizzle 4
|
||||
case 33: PF(2, 8, 4, 2, 8 | 128 | 256 | 1, 8); break; // + grid swizzle 8
|
||||
default: PF(2, 8, 4, 2, 2, 1); break; // b128 A + VOPD fold
|
||||
}
|
||||
#undef PF
|
||||
@@ -417,8 +332,7 @@ void r4d_gemm_w4a8_prefill(long a, long ascale, long wq, long ws, long c, int M,
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there
|
||||
// is no adapter directory between the core and these launches.
|
||||
// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h.
|
||||
extern "C" int r4d_rad_gemm_w4a8_prefill(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1);
|
||||
|
||||
+152
-1264
File diff suppressed because it is too large.
Load diff
@@ -1,32 +1,28 @@
|
||||
// r4d_gemm_w5a16_nt_m64.hip - r4d_gemm_w5a16_nt_m64: 5-bit-weight skinny GEMM for M up to 64,
|
||||
// gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C, fp32 accumulate.
|
||||
//
|
||||
// r4d_gemm_w4a16_nt_m64 with a fifth bit per weight, for ParoQuant's int5 (asymmetric, an f16 scale
|
||||
// and a 5-bit integer zero per 128 of K, the rotation done on the activation in front of it). The
|
||||
// reading of that kernel's header holds word for word -- weight-streaming, memory-bound, f16
|
||||
// because 1024 + n is exact -- and this file only says what the fifth bit changes.
|
||||
// r4d_gemm_w4a16_nt_m64 with a fifth bit per weight, for ParoQuant's int5 (asymmetric: an f16 scale
|
||||
// and a 5-bit integer zero per 128 of K, with the rotation applied to the activation beforehand).
|
||||
// That kernel's header applies; this one covers only what the fifth bit changes.
|
||||
//
|
||||
// THE WEIGHT BLOB IS TWO PLANES. The low four bits of every code are w4's fragment order exactly
|
||||
// (offset binary here: the nibble is q & 15, no sign flip). The fifth bits follow as a second
|
||||
// plane of 32-bit words, ONE A (n-tile, 64-wide k block, lane):
|
||||
// The weight blob is two planes. The low four bits of each code are in w4's fragment order (offset
|
||||
// binary: the nibble is q & 15, no sign flip). The fifth bits follow as 32-bit words, one per
|
||||
// (n-tile, 64-wide k block, lane):
|
||||
//
|
||||
// hi[(t * (K/64) + kb) * 32 + lane] byte s = k step s of the block, bit e = element e
|
||||
//
|
||||
// element e of a lane's fragment being the same one nibble 2e / 2(e-4)+1 of dword s holds. So a
|
||||
// lane's 16 bytes of nibbles and its 4 bytes of fifth bits cover the same 32 weights, and the
|
||||
// second load is one dword a block.
|
||||
// where element e is the one nibble 2e / 2(e-4)+1 of dword s holds. A lane's 16 bytes of nibbles and
|
||||
// 4 bytes of fifth bits cover the same 32 weights; the second load is one dword per block.
|
||||
//
|
||||
// THE UNPACK ADDS TWO MULTIPLIES TO w4's. The even elements' fifth bits are the byte's low nibble,
|
||||
// the odd elements' its high one; a 4-bit mask n becomes one bit a byte by n * 0x00204081 (bit j
|
||||
// lands at 8j and nothing else lands on a multiple of eight below bit 32), masked with 0x01010101
|
||||
// and shifted to the 16s place of the nibble's byte. The 5-bit code is then 0..31, 1024 + q is
|
||||
// exact in f16, and the zero point -- an integer 0..31 in the scale dword's high half as
|
||||
// -(1024 + zero) -- subtracts exactly.
|
||||
// The unpack adds two multiplies to w4's. The even elements' fifth bits are the byte's low nibble,
|
||||
// the odd elements' its high one. n * 0x00204081 moves bit j of a 4-bit mask to bit 8j (no other
|
||||
// term lands on a multiple of eight below bit 32); masking with 0x01010101 and shifting by 4 puts
|
||||
// it at the 16s place. The code is then 0..31, 1024 + q is exact in f16, and the integer zero
|
||||
// (0..31, stored as -(1024 + zero)) subtracts exactly.
|
||||
//
|
||||
// The dispatcher takes M past 64 as chunks of 64 rows (the weight is re-read per chunk, which at a
|
||||
// 2048-row prefill chunk is near the compute bound of the f16 matrix instruction anyway), and
|
||||
// partitioned weights (ParoQuant's gate|up: `pb1`/`pb2`, see r4d_gemm_args.h) as one launch per
|
||||
// part over windows of the planes.
|
||||
// The dispatcher runs M past 64 as chunks of 64 rows, re-reading the weight per chunk (near the f16
|
||||
// compute bound at a 2048-row prefill chunk anyway), and partitioned weights (ParoQuant's gate|up:
|
||||
// `pb1`/`pb2`, see r4d_gemm_args.h) as one launch per part.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_gdn_wmma.h"
|
||||
@@ -37,34 +33,16 @@
|
||||
#include <stdexcept>
|
||||
|
||||
#define R4D_GEMM_W4_MAX_M 64
|
||||
#ifndef R4D_GEMM_W4_GROUP
|
||||
#define R4D_GEMM_W4_GROUP 128 // K per (scale, zero) pair
|
||||
#endif
|
||||
#define R4D_GEMM_W4_KPB 64 // K per packed block: 4 k steps, 16 bytes per lane
|
||||
#define WAVE32 32
|
||||
|
||||
typedef _Float16 v8h __attribute__((ext_vector_type(8)));
|
||||
typedef unsigned uint4v __attribute__((ext_vector_type(4)));
|
||||
|
||||
// NT reads the weight non-temporally. The weight is streamed once per step and never reused, while
|
||||
// the activation is re-read once per column tile and wants to stay resident, so telling the cache
|
||||
// not to keep the weight decides which of the two occupies the last level. It is a gain at M=8 and
|
||||
// M=16 and a LOSS from M=24 up on the shapes with the longest K, so it is per-call, like every
|
||||
// other geometry parameter, and the table in radiance_w4.py carries the value per M band.
|
||||
//
|
||||
// One copy of any of these weights fits this part's 64 MiB last level, so a bench that streams a
|
||||
// SINGLE buffer in a loop measures a cache-resident machine and cannot see this effect at all; a
|
||||
// pooled working set is what makes the difference visible.
|
||||
// NT and NPW: see r4d_gemm_w4a16_nt_m64.hip. Only NPW 1 and 4 are instantiated.
|
||||
|
||||
// NPW (column tiles per WAVE) is a template parameter because it sizes the accumulator array, and a
|
||||
// launch argument because the right value is a property of M: at M=8 the kernel is at the DRAM
|
||||
// roofline and NPW>1 only costs blocks, while at M=64 the activation re-read is four times the
|
||||
// weight and NPW=4 is what claws it back. Instantiated only for the two values that win in
|
||||
// practice; anything else is rejected rather than silently rounded.
|
||||
|
||||
// Address-space-qualified so the loads stay global_load rather than flat_load: on gfx12 a flat
|
||||
// load increments dscnt as well as loadcnt, so a later LDS wait would also wait on HBM. See the
|
||||
// same declaration in r4d_gemm_bf16_nt_m64.hip for why the element type is a scalar there.
|
||||
// Address-space-qualified so loads stay global_load, not flat_load (on gfx12 a flat load also
|
||||
// increments dscnt). See r4d_gemm_bf16_nt_m64.hip for why the element type is a scalar.
|
||||
typedef __attribute__((address_space(1))) const uint4v* r4d_gw4;
|
||||
typedef __attribute__((address_space(1))) const unsigned long long* r4d_gu2;
|
||||
typedef __attribute__((address_space(1))) const unsigned* r4d_gu1;
|
||||
@@ -76,18 +54,12 @@ __device__ __forceinline__ v8h fragA(r4d_gu2 p, int u) {
|
||||
return x.f;
|
||||
}
|
||||
|
||||
// DO NOT FOLD THE GROUP SCALE INTO THE B FRAGMENT. One v_pk_mul_f16 per pair on the finished
|
||||
// integer q is exact in f16, removes the second accumulator array entirely and takes the M=64 shape
|
||||
// from 192 VGPRs to 135 -- and it is SLOWER on most of the drafter's shapes. The multiply lands
|
||||
// inside the per-fragment dependent chain between the unpack and the WMMA, where the per-group
|
||||
// epilogue it replaces sits outside it; this kernel is stall-bound, not register-bound.
|
||||
// Do not fold the group scale into the B fragment; see r4d_gemm_w4a16_nt_m64.hip.
|
||||
|
||||
// One dword of eight nibbles plus the byte of their fifth bits -> one 16x16x16 f16 B fragment,
|
||||
// minus the zero point. Nibble 2e (e < 4) / 2(e-4)+1 is fragment element e, so bits 0..3 of `hb`
|
||||
// are the fifth bits of the even nibbles' elements and bits 4..7 the odd nibbles'. Each v_perm_b32
|
||||
// pairs two code bytes with the constant high byte 0x64, the f16 exponent field for 1024, so a half
|
||||
// is 1024 + code; nz carries -(1024 + zero) in BOTH halves, so one v_pk_add_f16 corrects a pair.
|
||||
// The codes are offset binary (0..31, or 0..15 without the fifth bit): no sign flip.
|
||||
// minus the zero point. Bits 0..3 of `hb` are the even nibbles' fifth bits, bits 4..7 the odd
|
||||
// nibbles'. Each v_perm_b32 pairs two code bytes with the high byte 0x64 (1024 + code); nz holds
|
||||
// -(1024 + zero) in both halves. Codes are offset binary (0..31, or 0..15 without the fifth bit).
|
||||
__device__ __forceinline__ unsigned spread16(unsigned n) { // 4 bits -> bit 4 of each byte
|
||||
return ((n * 0x00204081u) & 0x01010101u) << 4;
|
||||
}
|
||||
@@ -109,9 +81,8 @@ __device__ __forceinline__ v8f mmah(v8h a, v8h b, v8f c) {
|
||||
return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c);
|
||||
}
|
||||
|
||||
// MT = row tiles per BLOCK, as in the bf16 kernel: more of them amortise the weight fragment and
|
||||
// its unpack over more WMMA, fewer put more blocks on the machine.
|
||||
// HI false is the 4-bit asymmetric grid (z-lab's plain int4): the same kernel with no fifth-bit plane.
|
||||
// MT = row tiles per block, as in the bf16 kernel. HI false is the 4-bit asymmetric grid (z-lab's
|
||||
// plain int4), with no fifth-bit plane.
|
||||
template <int MT, int NPW, bool NT, bool HI>
|
||||
__global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel(
|
||||
const unsigned short* __restrict__ A, const unsigned* __restrict__ Wq,
|
||||
@@ -134,8 +105,7 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel(
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
if (n0 < N) {
|
||||
// Activation: rows clamped, never masked -- a tile past M re-reads the last valid row and
|
||||
// computes a result nobody stores.
|
||||
// Activation rows are clamped, not masked; results past M are never stored.
|
||||
unsigned aoff[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
@@ -144,8 +114,8 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel(
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] = (r4d_gu2)(const unsigned long long*)(A + aoff[i]);
|
||||
|
||||
// Weight: one uint4 per lane per four k steps, tiles already permuted, so the whole k loop is
|
||||
// global_load_b128 with a constant stride and no address arithmetic per step.
|
||||
// Weight: one uint4 per lane per four k steps, already permuted, so the k loop is
|
||||
// global_load_b128 at a constant stride.
|
||||
const int kpb = K / R4D_GEMM_W4_KPB; // packed blocks in a full row of tiles
|
||||
const int nsz = K / R4D_GEMM_W4_GROUP; // (scale, zero) dwords per row of tiles
|
||||
r4d_gw4 pw[NPW];
|
||||
@@ -154,15 +124,14 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel(
|
||||
const int ntlast = N / 16 - 1;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
// Clamped, like the row tiles: a wave whose last column tiles run past N re-reads the last
|
||||
// real tile and computes a result the store discards, rather than reading memory it does not
|
||||
// own or diverging the whole k loop on a mask.
|
||||
// Column tiles past N are clamped to the last real tile; the store discards them.
|
||||
const int t = (nt0 + j) < ntlast ? (nt0 + j) : ntlast;
|
||||
pw[j] = (r4d_gw4)(const uint4v*)(Wq) +
|
||||
(size_t)(t * kpb + kbase / R4D_GEMM_W4_KPB) * WAVE32 + lane;
|
||||
// Quantizer parameters: 16 distinct dwords per group, read by the 16 lanes that own the rows.
|
||||
// Fifth-bit plane: one dword per lane per packed block (unused when !HI).
|
||||
ph[j] = (r4d_gu1)(const unsigned*)(HI ? Whi : Wq) +
|
||||
(size_t)(t * kpb + kbase / R4D_GEMM_W4_KPB) * WAVE32 + lane;
|
||||
// Quantiser parameters: 16 dwords per group, read by the 16 lanes that own the rows.
|
||||
ps[j] = (r4d_gu1)(const unsigned*)(Wsz) +
|
||||
(size_t)(t * nsz + kbase / R4D_GEMM_W4_GROUP) * 16 + (lane & 15);
|
||||
}
|
||||
@@ -179,8 +148,7 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel(
|
||||
nz[j] = __half2half2(__ushort_as_half((unsigned short)(sz >> 16)));
|
||||
}
|
||||
|
||||
// The first WMMA of a group takes an inline zero for C, so the group accumulator costs no
|
||||
// instruction to clear.
|
||||
// The first WMMA of a group takes an inline zero for C, so no clear is needed.
|
||||
v8f g_acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++) {
|
||||
@@ -219,9 +187,8 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// Split-K reduction and store: identical to r4d_gemm_bf16_nt_m64, one row tile at a time so the
|
||||
// LDS is WV*SK KiB whatever MT is, and in a fixed order over splits so the result does not depend
|
||||
// on how the waves were scheduled.
|
||||
// Split-K reduction and store as in r4d_gemm_bf16_nt_m64: one row tile at a time, fixed split
|
||||
// order.
|
||||
const int ncols = WV * NPW;
|
||||
const int nthreads = WV * SK * WAVE32;
|
||||
#pragma unroll
|
||||
@@ -295,8 +262,7 @@ int r4d_gemm_w5a16_nt_m64_group(void) { return R4D_GEMM_W4_GROUP; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there
|
||||
// is no adapter directory between the core and these launches.
|
||||
// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h.
|
||||
/* ------------------------------------------------------------------ f16-activation grids */
|
||||
|
||||
static int w5_dispatch(const RadArgs* a, RadStream s, bool hi5) {
|
||||
@@ -304,21 +270,21 @@ static int w5_dispatch(const RadArgs* a, RadStream s, bool hi5) {
|
||||
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
/* Any other activation dtype would read plausible but wrong numbers. */
|
||||
if (g.a->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.K % R4D_GEMM_W4_GROUP) return R4D_NO(RAD_E_SHAPE);
|
||||
const int group = r4d_gemm_w5a16_nt_m64_group();
|
||||
// The row's M is the step's, not the kernel's: rows past 64 are chunks of 64, each its own pass
|
||||
// over the weight, so a prefill chunk costs the weight's bytes once a 64 rows.
|
||||
// Rows past 64 run as chunks of 64, each a pass over the weight.
|
||||
const long long mc = std::min<long long>(g.M, r4d_gemm_w5a16_nt_m64_max_m());
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, mc, group, BR_FLAT, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
/* cfg_for pins MB = 1 across the decode band (the grid, not the weight, is the cost for the bf16 and
|
||||
* mxfp4 skinny kernels). Here the dequantise is: one block per row tile unpacks each weight fragment
|
||||
* once PER TILE, so three streams (M = 24, two tiles) pay it twice. Cover every row tile in one block
|
||||
* unless the tuner pinned MB; same split, so the output bits are unchanged. */
|
||||
/* cfg_for pins MB = 1 in the decode band, but here the dequantise is the cost: with one block per
|
||||
* row tile, each weight fragment is unpacked once per tile. Cover every row tile in one block
|
||||
* unless the tuner pinned MB; the split is unchanged, so the output bits are too. */
|
||||
R4dGemmCfg tuned;
|
||||
r4d_cfg_gemm(a, &tuned);
|
||||
if (tuned.mb <= 0) c.mb = std::min<long long>(4, (mc + 15) / 16);
|
||||
|
||||
@@ -1,47 +1,30 @@
|
||||
// r4d_gemm_w8a16_nt_m64.hip - r4d_gemm_w8a16_nt_m64: 8-bit-weight skinny GEMM for M up to 64,
|
||||
// gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C, fp32 accumulate.
|
||||
//
|
||||
// WHY THIS EXISTS WHEN THE 4-BIT ONE ALREADY DOES. One site in the decode step is quantised to
|
||||
// eight bits and not four -- lm_head -- because it is the only layer whose error lands on the
|
||||
// SAMPLED TOKEN rather than on a residual a later layer can absorb.
|
||||
// Used for lm_head, quantised to eight bits rather than four because its error lands on the
|
||||
// sampled token rather than on a residual later layers can absorb.
|
||||
//
|
||||
// A general int8 library GEMM is the wrong shape for it. Those paths refuse M <= 16, so eight
|
||||
// speculative rows are padded to SEVENTEEN, which is two 16-row macro tiles, and a weight-streaming
|
||||
// GEMM with two row tiles READS THE WEIGHT TWICE -- well under the ~640 GB/s this part delivers,
|
||||
// and the cost only stops rising once M is large enough that the last level absorbs the re-reads.
|
||||
// A skinny kernel holds every row of M in registers, so the weight is read once whatever M is and
|
||||
// the time does not move with the batch.
|
||||
// A skinny kernel holds every row of M in registers, so the weight is read once regardless of M.
|
||||
// General int8 GEMMs pad M <= 16 to two 16-row macro tiles and read the weight twice. The scale is
|
||||
// applied to the in-register accumulator and stored as bf16, with no separate epilogue launch.
|
||||
//
|
||||
// It also folds the epilogue. A library path costs four launches -- quantise the activation, zero
|
||||
// a padded buffer, GEMM, then scale an M x N int32 buffer -- and the last of those moves tens of
|
||||
// megabytes at eight requests. Here the scale is applied to the accumulator that is already in
|
||||
// registers and the store is bf16.
|
||||
// Structure matches r4d_gemm_w4a16_nt_m64: fragment order, 512 B packed block (32 lanes x 16 B),
|
||||
// (scale, zero) dword per (row, group), split-K reduction and clamped tiles. Only the bits per
|
||||
// element differ, so a packed block covers 32 K instead of 64.
|
||||
//
|
||||
// STRUCTURE IS r4d_gemm_w4a16_nt_m64's, AND DELIBERATELY SO: same fragment order, same packed-block
|
||||
// size (32 lanes x 16 bytes = 512 B), same (scale, zero) dword per (row, group), same split-K
|
||||
// reduction, same clamped row and column tiles. Only the weight's bits per element change, and
|
||||
// with them how much K one packed block covers: 64 at four bits, 32 at eight.
|
||||
// Dequant: `0x6400 | b` is exactly the f16 for 1024 + b for b in 0..255, so four v_perm_b32 turn
|
||||
// two dwords into a 16x16x16 fragment, and one v_pk_add_f16 per pair adds -(1024 + zero). The
|
||||
// subtraction is exact (integers below 2048), so the group scale is applied to the f32 accumulator.
|
||||
//
|
||||
// THE DEQUANT IS THE SAME TRICK AT A WIDER RADIX. `0x6400 | b` is the f16 for 1024 + b, exactly,
|
||||
// for every b in 0..255 -- f16 carries eleven significant bits and 1279 needs eleven -- so four
|
||||
// v_perm_b32 turn two dwords of four bytes into a whole 16x16x16 fragment, and one v_pk_add_f16
|
||||
// per pair subtracts the constant -(1024 + zero). That subtraction is exact for the same reason
|
||||
// (both operands are integers below 2048 and the difference is small), which is what lets the group
|
||||
// scale wait for the f32 accumulator, where the cancellation has already happened.
|
||||
// A is f16, not bf16, because bf16's eight significant bits cannot hold 1024 + b. The alternative
|
||||
// (raw codes plus a per-group activation sum, as in r4d_gemm_w4a8_asym_nt_m64) gains nothing here:
|
||||
// the adds hide under the weight stream. The caller's bf16 -> f16 cast is exact for a post-norm
|
||||
// hidden state (O(10)).
|
||||
//
|
||||
// WHY f16 AND NOT bf16 A. Reaching 1024 + b is the whole reason the unpack is four instructions,
|
||||
// and bf16 has eight significant bits, so 1024 + b is not representable there at all. The
|
||||
// alternative -- keep the raw offset-binary code in the fragment and correct with a per-group
|
||||
// activation sum, which r4d_gemm_w4a8_asym_nt_m64 does -- needs that sum computed somewhere, and at
|
||||
// this M the four v_pk_add_f16 hide entirely under a weight stream that is 99% of the cost. The
|
||||
// caller casts bf16 to f16, which is exact: bf16's mantissa is a strict prefix of f16's and a
|
||||
// post-norm hidden state is O(10).
|
||||
//
|
||||
// QUANTIZER. Asymmetric, per output channel, per group of R4D_GEMM_W8_GROUP contiguous K:
|
||||
// w ~= scale * (q - zero) with q in 0..255 and an INTEGER zero, so the subtract stays on the
|
||||
// integer grid. Both parameters live in one dword per (row, group): the f16 scale in the low half
|
||||
// and the f16 of -(1024 + zero) in the high half. The group costs 3.1% more bytes than a
|
||||
// per-channel scale would and halves the KL divergence against the unquantised layer.
|
||||
// Quantiser: asymmetric, per output channel, per group of R4D_GEMM_W8_GROUP contiguous K:
|
||||
// w ~= scale * (q - zero), q in 0..255, integer zero. One dword per (row, group): the f16 scale low,
|
||||
// the f16 of -(1024 + zero) high. The group costs 3.1% more bytes than a per-channel scale and
|
||||
// halves the KL divergence against the unquantised layer.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_gdn_wmma.h"
|
||||
@@ -51,9 +34,6 @@
|
||||
#include <stdexcept>
|
||||
|
||||
#define R4D_GEMM_W8_MAX_M 64
|
||||
#ifndef R4D_GEMM_W8_GROUP
|
||||
#define R4D_GEMM_W8_GROUP 128 // K per (scale, zero) pair
|
||||
#endif
|
||||
#define R4D_GEMM_W8_KPB 32 // K per packed block: 2 k steps, 16 bytes per lane
|
||||
#define WAVE32 32
|
||||
|
||||
@@ -71,10 +51,9 @@ __device__ __forceinline__ v8h fragA8(r4d_gu2 p, int u) {
|
||||
return x.f;
|
||||
}
|
||||
|
||||
// Two dwords of four bytes -> one 16x16x16 f16 B fragment, minus the zero point. The packer put
|
||||
// fragment elements 0..3 in the first dword and 4..7 in the second, in order, so each v_perm_b32
|
||||
// pairs two consecutive bytes with the constant high byte 0x64 -- the f16 exponent field for 1024.
|
||||
// nz carries -(1024 + zero) in BOTH halves so one v_pk_add_f16 corrects a pair.
|
||||
// Two dwords of four bytes -> one 16x16x16 f16 B fragment, minus the zero point. The packer puts
|
||||
// fragment elements 0..3 in the first dword and 4..7 in the second, so each v_perm_b32 pairs two
|
||||
// bytes with the high byte 0x64 (the f16 exponent for 1024). nz holds -(1024 + zero) in both halves.
|
||||
__device__ __forceinline__ v8h dequant8(unsigned w0, unsigned w1, __half2 nz) {
|
||||
const unsigned K64 = 0x64646464u;
|
||||
union { unsigned u[4]; __half2 h2[4]; v8h f; } x;
|
||||
@@ -209,12 +188,9 @@ __global__ __launch_bounds__(1024) void r4d_gemm_w8a16_nt_m64_kernel(
|
||||
|
||||
void r4d_gemm_w8a16_nt_m64(long a, long wq, long wsz, long c, int M, int K, int N,
|
||||
int WV, int SK, int MB, int NPW, int NT, long stream) {
|
||||
// NO UPPER BOUND ON M. The row tiles a BLOCK covers are MT, and grid.y covers the rest, with
|
||||
// rows past M clamped on load and masked on the store -- so any M is CORRECT. What ends at 64
|
||||
// is the band this kernel is the right shape for: past it every extra row-tile group re-reads
|
||||
// the whole weight, and the caller should be on a staged kernel. max_m() reports that band;
|
||||
// this guard only rejects nonsense, because the alternative is a caller silently getting a
|
||||
// wrong answer from a fallback that was handed a PACKED weight.
|
||||
// Any M is correct (grid.y covers row tiles past MT; rows past M are clamped and masked). 64 is
|
||||
// the band this shape suits, since each extra row-tile group re-reads the weight; max_m()
|
||||
// reports it.
|
||||
if (M < 1) throw std::runtime_error("r4d gemm_w8a16_nt_m64: M must be >= 1");
|
||||
if (N % 16) throw std::runtime_error("r4d gemm_w8a16_nt_m64: N must be a multiple of 16");
|
||||
if (K % (SK * R4D_GEMM_W8_GROUP))
|
||||
@@ -257,14 +233,13 @@ int r4d_gemm_w8a16_nt_m64_group(void) { return R4D_GEMM_W8_GROUP; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there
|
||||
// is no adapter directory between the core and these launches.
|
||||
// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h.
|
||||
extern "C" int r4d_rad_gemm_w8a16_m64(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
/* An f16 kernel handed any other activation reads plausible numbers that are not the input. */
|
||||
/* Any other activation dtype would read plausible but wrong numbers. */
|
||||
if (g.a->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE);
|
||||
if (g.M > r4d_gemm_w8a16_nt_m64_max_m()) return R4D_NO(RAD_E_SHAPE);
|
||||
const int group = r4d_gemm_w8a16_nt_m64_group();
|
||||
|
||||
+45
-272
@@ -2,45 +2,28 @@
|
||||
// M up to a prefill chunk, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, A quantised per row and
|
||||
// W per (row, 128-wide group).
|
||||
//
|
||||
// WHY THIS EXISTS. The INT4 target promotes 80 of its 256 linears -- every down_proj and the
|
||||
// sixteen attention o_proj -- to eight bits, because those two groups are where the 4-bit grid
|
||||
// costs the most KL. Serving those through a library int8 matmul means a composite -- rotate the
|
||||
// activation with a bf16 matmul, quantise it, call the library, then scale an int32 [M,N] back to
|
||||
// bf16 -- which is eight launches and three materialised intermediates per site, 80 sites a step.
|
||||
// It also THROWS AWAY the fused rms+Hadamard+quantise producer the 4-bit sites read: the int8 the
|
||||
// norm has already written is ignored and the bf16 is re-rotated and re-quantised.
|
||||
// Serves the linears an INT4 model promotes to eight bits (every down_proj and the attention
|
||||
// o_proj, where the 4-bit grid costs the most KL) in one launch that reads exactly what the 4-bit
|
||||
// GEMM reads: the same permuted int8 activation from the fused rms+Hadamard+quantise producer, the
|
||||
// same per-row scale, and a weight in the same fragment order at twice the radix.
|
||||
//
|
||||
// This is one launch that reads exactly what the 4-bit GEMM reads: the SAME permuted int8
|
||||
// activation buffer, the SAME per-row scale, and a weight in the same fragment order at twice the
|
||||
// radix. Nothing about the producer changes; only the GEMM does.
|
||||
// It is r4d_gemm_w4a8_nt_m64 without the unpack: the eight weight bytes are the B fragment. The A
|
||||
// fragment read, split-K reduction, per-group scale fold and per-row activation scale at the store
|
||||
// are the same.
|
||||
//
|
||||
// IT IS r4d_gemm_w4a8_nt_m64 WITH THE UNPACK DELETED. That kernel spends two v_and_b32 and one
|
||||
// v_lshlrev_b32 turning a dword of nibbles into eight int8 lanes; here the eight bytes ARE the
|
||||
// fragment, so the B operand is two dwords straight out of the load and the dequant is nothing at
|
||||
// all. Everything else -- the A fragment read, the split-K reduction, the per-group scale folded
|
||||
// with one v_cvt_f32_i32 and one fma, the per-row activation scale applied once at the store -- is
|
||||
// the same code.
|
||||
// gemm_w8a16_nt_m64 uses the f16 WMMA (207 TF/s vs 407 for iu8), which is fine for lm_head at M=8
|
||||
// (DRAM bound) but caps these sites at M=72.
|
||||
//
|
||||
// WHY NOT gemm_w8a16_nt_m64, WHICH ALREADY EXISTS. It runs v_wmma_f32_16x16x16_f16 at 207 TF/s
|
||||
// where v_wmma_i32_16x16x16_iu8 runs at 407. For lm_head at M=8 that is invisible -- the kernel is
|
||||
// at the DRAM roofline and the matrix pipe is free -- but the promoted sites run at M=8 AND at
|
||||
// M=72, and the f16 form is where the M=64 cliff in that kernel comes from. An 8-bit weight has
|
||||
// no reason to widen to 16 bits to be multiplied by an 8-bit activation.
|
||||
//
|
||||
// THE WEIGHT LAYOUT. Per n-tile t (16 output rows) and k-block kb (KPB=32 columns), 32 lanes hold
|
||||
// 16 bytes each: 512 bytes covering 16 rows x 32 k, which is TWO WMMA k steps. Byte j of lane l is
|
||||
// Weight layout: per n-tile t (16 output rows) and k-block kb (KPB=32 columns), 32 lanes hold
|
||||
// 16 bytes each, 512 bytes covering 16 rows x 32 k (two WMMA k steps). Byte j of lane l is
|
||||
//
|
||||
// W[t*16 + (l & 15)][kb*32 + 16*(j >> 3) + 8*((j & 7) >> 2) + 4*(l >> 4) + (j & 3)]
|
||||
//
|
||||
// -- the iu8 16x16x16 fragment order the A side already uses, so one permutation serves both
|
||||
// operands and the packer is the same routine at a different radix. A group is GROUP/KPB blocks
|
||||
// and its f16 scale is read once per group per n-plane, as in the 4-bit kernel.
|
||||
// the iu8 16x16x16 fragment order the A side uses, so one permutation serves both operands. A
|
||||
// group is GROUP/KPB blocks; its f16 scale is read once per group per n-plane.
|
||||
//
|
||||
// THE SCALE PLANE IS f16-ONLY, NOT THE SHARED (scale, zero) DWORD. There is no zero point on a
|
||||
// symmetric grid and this kernel is DRAM-bound at the decode batch, so the dead half of that dword
|
||||
// would be pure traffic: at group 128 it is 32 bytes per 2048 of weight, 1.5% of everything read.
|
||||
// The 4-bit kernel keeps the dword because r4d_gemm_w4a16_nt_m64 shares its bytes; nothing shares
|
||||
// these.
|
||||
// The scale plane is f16 only: a symmetric grid has no zero point, and the unused half of a
|
||||
// (scale, zero) dword would be 1.5% extra traffic on a DRAM-bound kernel.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -50,12 +33,8 @@
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
// Not structural: mt0 = blockIdx.y * MT tiles M and the row index is clamped into 0..M-1, so any M
|
||||
// is correct. It is a guard against a caller handing over a garbage shape.
|
||||
// Not structural (grid.y tiles M, rows are clamped); a sanity bound only.
|
||||
#define R4D_GEMM_W8A8_MAX_M 32768
|
||||
#ifndef R4D_GEMM_W8A8_GROUP
|
||||
#define R4D_GEMM_W8A8_GROUP 128
|
||||
#endif
|
||||
#define R4D_GEMM_W8A8_KPB 32 // K per packed block: 2 k steps, 16 bytes per lane
|
||||
#define WAVE32 32
|
||||
|
||||
@@ -68,65 +47,8 @@ typedef unsigned uint2v __attribute__((ext_vector_type(2)));
|
||||
typedef __attribute__((address_space(1))) const uint4v* r4d_gw8;
|
||||
typedef __attribute__((address_space(1))) const unsigned short* r4d_gs2;
|
||||
typedef __attribute__((address_space(1))) const uint2v* r4d_ga2;
|
||||
typedef __attribute__((address_space(1))) const unsigned* r4d_gu1;
|
||||
|
||||
// 0 reads A row-major, which only a harness feeding an unpermuted buffer needs; the serving path
|
||||
// always feeds the permuted buffer the quantiser writes.
|
||||
#ifndef R4D_W8A8_APERM
|
||||
#define R4D_W8A8_APERM 1
|
||||
#endif
|
||||
|
||||
// COST ABLATIONS. Wrong answers by construction; they exist to say what the time is made of.
|
||||
// 1 no scale load (sc = 1)
|
||||
// 2 no activation load (the A fragment is a constant)
|
||||
// 4 no weight load (the B fragment is a constant; leaves the A stream and the WMMA)
|
||||
#ifndef R4D_W8A8_ABL
|
||||
#define R4D_W8A8_ABL 0
|
||||
#endif
|
||||
|
||||
// SOFTWARE-PIPELINE THE WEIGHT: hold the NEXT group's weight in registers so its load is issued a
|
||||
// whole group ahead of the wait, instead of issuing two loads, waiting, and then spending the WMMA
|
||||
// block with no memory in flight. Costs bpg*NPW*4 VGPRs.
|
||||
#ifndef R4D_W8A8_PF
|
||||
#define R4D_W8A8_PF 0
|
||||
#endif
|
||||
|
||||
// STAGGER THE GROUP ORDER PER WAVE. Every plane pitch here is a multiple of 4096 and a 256-bit
|
||||
// GDDR6 part sweeps all sixteen channels in exactly 4096 bytes, so without this every wave in the
|
||||
// grid is at the same address modulo 4096 and aimed at the same channel group. Starting each wave
|
||||
// at a different group inside its OWN k-slice and wrapping changes only the order.
|
||||
// NOTE this reorders an fp32 accumulation, so results move by ~1 ULP.
|
||||
#ifndef R4D_W8A8_STAGGER
|
||||
#define R4D_W8A8_STAGGER 0
|
||||
#endif
|
||||
|
||||
#if R4D_W8A8_STAGGER
|
||||
#if R4D_W8A8_APERM
|
||||
#define AOFF8(g) ((g) * (R4D_GEMM_W8A8_GROUP / 8))
|
||||
#else
|
||||
#define AOFF8(g) ((g) * (R4D_GEMM_W8A8_GROUP / 4))
|
||||
#endif
|
||||
#else
|
||||
#define AOFF8(g) 0
|
||||
#endif
|
||||
|
||||
// HOIST THE ACTIVATION LOADS OFF THEIR WMMA.
|
||||
// Read `afrag[i]` inside the k-step loop immediately before the WMMA that consumes it and the group
|
||||
// loop gets one wait per load: at MT=5, NPW=1 that is 40 `global_load_b64`, 40 WMMA and 37
|
||||
// `s_wait_loadcnt`. The wave issues one load, stalls on it, runs one matrix instruction and issues
|
||||
// the next, so there is no memory-level parallelism and the matrix pipe is fully exposed instead of
|
||||
// co-issued. The ablations below price that exposure at a significant fraction of the kernel.
|
||||
//
|
||||
// A lane's eight A bytes for consecutive k steps are SIXTEEN bytes apart -- the intervening eight
|
||||
// belong to the other lane half -- so they cannot be merged into one b128, and the layout is fixed:
|
||||
// the same buffer feeds r4d_gemm_w4a8_nt_m64. What can change is when they are
|
||||
// issued. 1 loads the two k steps of a weight block up front (2*MT loads, then 2*NPW*MT WMMA);
|
||||
// 2 loads the whole group (2*bpg*MT), which costs bpg times the registers.
|
||||
#ifndef R4D_W8A8_AHOIST
|
||||
#define R4D_W8A8_AHOIST 2
|
||||
#endif
|
||||
|
||||
// The A fragment, byte for byte what r4d_gemm_w4a8_nt_m64 reads -- same buffer, same producer.
|
||||
// The A fragment, as r4d_gemm_w4a8_nt_m64 reads it.
|
||||
__device__ __forceinline__ v2i fragA8w(r4d_ga2 p, int u) {
|
||||
const uint2v w = p[2 * u];
|
||||
v2i r;
|
||||
@@ -135,44 +57,16 @@ __device__ __forceinline__ v2i fragA8w(r4d_ga2 p, int u) {
|
||||
return r;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v2i fragA8row(r4d_gu1 p, int u) {
|
||||
v2i r;
|
||||
r[0] = p[4 * u];
|
||||
r[1] = p[4 * u + 2];
|
||||
return r;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v8i mmai8(v2i a, v2i b, v8i c) {
|
||||
return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a, true, b, c, false);
|
||||
}
|
||||
|
||||
// __launch_bounds__ IS A REGISTER BUDGET, AND IT HAS TO SEE MT.
|
||||
// A block of T threads is T/32 waves spread over four SIMDs, so the compiler budgets 1536/(T/128)
|
||||
// VGPRs per wave: 1024 threads leaves 192, 512 leaves 256 (the architectural cap), 256 the same.
|
||||
// The accumulator is what runs out -- `acc` is MT*NPW*8 VGPRs and `g_acc` another MT*NPW*8 while a
|
||||
// group is in flight -- so MT*NPW is the thing that decides, and a bound written in NPW alone is
|
||||
// blind to half of it. A flat bound of 1024 leaves 192 VGPRs, and under that bound
|
||||
// `-Rpass-analysis=kernel-resource-usage` reports every wide tile SPILLING:
|
||||
//
|
||||
// MT=5..8, NPW=2 192 VGPRs, 15 / 51 / 87 / 123 spilled
|
||||
// MT=3,4, NPW=4 256 VGPRs, 11 / 65 spilled
|
||||
// MT=2,3,4 NPW=8 256 VGPRs, 99 / 287 / 530 spilled
|
||||
//
|
||||
// and those are the configs M=72 wants, because MB=5 or 6 is what covers five row tiles in one
|
||||
// block. A wide tile has plenty of independent WMMA to hide latency with and does not need the
|
||||
// waves; it needs the registers. Bounding it at 256 threads gives it all 256 VGPRs.
|
||||
//
|
||||
// The bound is a REAL constraint on the launch, not a hint: a kernel built for 256 threads cannot
|
||||
// be launched with more, so the host checks WV*SK against the same expression and refuses instead
|
||||
// of failing at dispatch.
|
||||
#ifndef R4D_GEMM_W8A8_LB
|
||||
#define R4D_GEMM_W8A8_LB 1
|
||||
#endif
|
||||
#if R4D_GEMM_W8A8_LB
|
||||
// __launch_bounds__ is a register budget and depends on MT*NPW. A block of T threads gives
|
||||
// 1536/(T/128) VGPRs per wave (1024 threads: 192; 512 or fewer: the 256 cap). `acc` and `g_acc` are
|
||||
// MT*NPW*8 VGPRs each, so under a flat 1024 bound every wide tile spills. A wide tile has enough
|
||||
// independent WMMA to hide latency without more waves; bounding it at 256 threads gives it 256
|
||||
// VGPRs. The bound is a hard launch limit, so the host checks WV*SK against the same expression.
|
||||
#define R4D_W8A8_BOUNDS(MT, NPW) ((MT) * (NPW) >= 8 ? 256 : ((MT) * (NPW) >= 4 ? 512 : 1024))
|
||||
#else
|
||||
#define R4D_W8A8_BOUNDS(MT, NPW) 1024
|
||||
#endif
|
||||
|
||||
template <int MT, int NPW, bool NT>
|
||||
__global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64_kernel(
|
||||
@@ -196,24 +90,15 @@ __global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
if (n0 < N) {
|
||||
// Rows clamped, never masked: a tile past M recomputes the last valid row and the store
|
||||
// discards it. A is int8, so the row stride is K bytes.
|
||||
#if R4D_W8A8_APERM
|
||||
// Rows clamped into 0..M-1, never masked; the store discards rows past M. A is int8, so the
|
||||
// row stride is K bytes.
|
||||
r4d_ga2 pa[MT];
|
||||
#else
|
||||
r4d_gu1 pa[MT];
|
||||
#endif
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
int r = (mt0 + i) * 16 + (lane & 15);
|
||||
r = r < M - 1 ? r : M - 1;
|
||||
#if R4D_W8A8_APERM
|
||||
const size_t off = (size_t)r * K + kbase + 8 * (lane >> 4);
|
||||
pa[i] = (r4d_ga2)(const uint2v*)(A + off);
|
||||
#else
|
||||
const size_t off = (size_t)r * K + kbase + 4 * (lane >> 4);
|
||||
pa[i] = (r4d_gu1)(const unsigned*)(A + off);
|
||||
#endif
|
||||
}
|
||||
|
||||
const int kpb = K / R4D_GEMM_W8A8_KPB;
|
||||
@@ -232,118 +117,41 @@ __global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64
|
||||
|
||||
const int bpg = R4D_GEMM_W8A8_GROUP / R4D_GEMM_W8A8_KPB;
|
||||
|
||||
#if R4D_W8A8_PF
|
||||
uint4v nx[NPW][R4D_GEMM_W8A8_GROUP / R4D_GEMM_W8A8_KPB];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++)
|
||||
nx[j][b] = NT ? __builtin_nontemporal_load(&pw[j][(size_t)b * WAVE32])
|
||||
: pw[j][(size_t)b * WAVE32];
|
||||
#endif
|
||||
|
||||
#if R4D_W8A8_STAGGER
|
||||
const int gstag = groups > 1 ? (wave * R4D_W8A8_STAGGER) % groups : 0;
|
||||
#endif
|
||||
for (int gi = 0; gi < groups; gi++) {
|
||||
#if R4D_W8A8_STAGGER
|
||||
const int g = gi + gstag < groups ? gi + gstag : gi + gstag - groups;
|
||||
#else
|
||||
const int g = gi;
|
||||
#endif
|
||||
for (int g = 0; g < groups; g++) {
|
||||
float sc[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#if R4D_W8A8_ABL & 1
|
||||
sc[j] = 1.f;
|
||||
#else
|
||||
sc[j] = __half2float(__ushort_as_half(ps[j][(size_t)g * 16]));
|
||||
#endif
|
||||
|
||||
v8i g_acc[NPW][MT];
|
||||
#if R4D_W8A8_PF
|
||||
uint4v cw[NPW][R4D_GEMM_W8A8_GROUP / R4D_GEMM_W8A8_KPB];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++) cw[j][b] = nx[j][b];
|
||||
if (g + 1 < groups) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++) {
|
||||
const size_t o = (size_t)((g + 1) * bpg + b) * WAVE32;
|
||||
nx[j][b] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o];
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#if R4D_W8A8_AHOIST == 2
|
||||
// The whole group's activation, issued before any of it is consumed.
|
||||
// The whole group's activation, issued before any of it is consumed. Loading each fragment
|
||||
// just before its WMMA gives one s_wait_loadcnt per load and no memory-level parallelism; a
|
||||
// lane's A bytes for consecutive k steps are 16 bytes apart, so they cannot merge into one
|
||||
// b128 and only the issue order can change.
|
||||
v2i afg[2 * (R4D_GEMM_W8A8_GROUP / R4D_GEMM_W8A8_KPB)][MT];
|
||||
#pragma unroll
|
||||
for (int u = 0; u < 2 * bpg; u++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#if R4D_W8A8_ABL & 2
|
||||
{ afg[u][i][0] = 0x01010101; afg[u][i][1] = 0x01010101; }
|
||||
#elif R4D_W8A8_APERM
|
||||
afg[u][i] = fragA8w(pa[i] + AOFF8(g), u);
|
||||
#else
|
||||
afg[u][i] = fragA8row(pa[i] + AOFF8(g), u);
|
||||
#endif
|
||||
#endif
|
||||
afg[u][i] = fragA8w(pa[i], u);
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++) {
|
||||
uint4v wv[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
#if R4D_W8A8_PF
|
||||
wv[j] = cw[j][b];
|
||||
#else
|
||||
const size_t o = (size_t)(g * bpg + b) * WAVE32;
|
||||
#if R4D_W8A8_ABL & 4
|
||||
(void)o;
|
||||
wv[j] = (uint4v)(0x01010101u);
|
||||
#else
|
||||
wv[j] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o];
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
#if R4D_W8A8_AHOIST == 1
|
||||
// Both k steps of this weight block, issued before either is consumed.
|
||||
v2i afb[2][MT];
|
||||
#pragma unroll
|
||||
for (int s = 0; s < 2; s++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#if R4D_W8A8_ABL & 2
|
||||
{ afb[s][i][0] = 0x01010101; afb[s][i][1] = 0x01010101; }
|
||||
#elif R4D_W8A8_APERM
|
||||
afb[s][i] = fragA8w(pa[i] + AOFF8(g), b * 2 + s);
|
||||
#else
|
||||
afb[s][i] = fragA8row(pa[i] + AOFF8(g), b * 2 + s);
|
||||
#endif
|
||||
#endif
|
||||
// Two WMMA k steps per 16-byte weight load: dwords (0,1) then (2,3).
|
||||
#pragma unroll
|
||||
for (int s = 0; s < 2; s++) {
|
||||
const int u = b * 2 + s;
|
||||
v2i afrag[MT];
|
||||
#pragma unroll
|
||||
#if R4D_W8A8_AHOIST == 2
|
||||
for (int i = 0; i < MT; i++) afrag[i] = afg[u][i];
|
||||
#elif R4D_W8A8_AHOIST == 1
|
||||
for (int i = 0; i < MT; i++) afrag[i] = afb[s][i];
|
||||
#elif R4D_W8A8_ABL & 2
|
||||
for (int i = 0; i < MT; i++) { afrag[i][0] = 0x01010101; afrag[i][1] = 0x01010101; }
|
||||
#elif R4D_W8A8_APERM
|
||||
for (int i = 0; i < MT; i++) afrag[i] = fragA8w(pa[i] + AOFF8(g), u);
|
||||
#else
|
||||
for (int i = 0; i < MT; i++) afrag[i] = fragA8row(pa[i] + AOFF8(g), u);
|
||||
#endif
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
// The eight bytes ARE the fragment: no mask, no shift, no zero point.
|
||||
// The eight weight bytes are the fragment.
|
||||
v2i bfrag;
|
||||
bfrag[0] = (int)wv[j][2 * s];
|
||||
bfrag[1] = (int)wv[j][2 * s + 1];
|
||||
@@ -361,28 +169,17 @@ __global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++)
|
||||
acc[j][i][e] = fmaf((float)g_acc[j][i][e], sc[j], acc[j][i][e]);
|
||||
#if !R4D_W8A8_STAGGER
|
||||
#pragma unroll
|
||||
#if R4D_W8A8_APERM
|
||||
for (int i = 0; i < MT; i++) pa[i] += R4D_GEMM_W8A8_GROUP / 8;
|
||||
#else
|
||||
for (int i = 0; i < MT; i++) pa[i] += R4D_GEMM_W8A8_GROUP / 4;
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// Split-K reduction and store, one row tile at a time. The per-row activation scale is applied
|
||||
// here and only here: it is constant over n and over the group index, so it never entered the
|
||||
// k loop.
|
||||
// Split-K reduction and store, one row tile at a time, applying the per-row activation scale.
|
||||
const int ncols = WV * NPW;
|
||||
const int nthreads = WV * SK * WAVE32;
|
||||
|
||||
// AT SK == 1 THERE IS NOTHING TO REDUCE. The general path below writes eight floats per
|
||||
// accumulator to LDS and reads them straight back, and pays two __syncthreads() per row tile to
|
||||
// do it -- MB row tiles is MB barrier pairs on a kernel whose whole job is to keep a load in
|
||||
// flight. With one k-slice a lane already holds the finished value, and the same (m, n) it
|
||||
// would have landed on is just the LDS index arithmetic with off = e*32 + lane substituted in.
|
||||
// At SK == 1 there is nothing to reduce: store directly and skip the two barriers per row tile.
|
||||
// (m, n) is the LDS path's index arithmetic with off = e*32 + lane.
|
||||
if (SK == 1) {
|
||||
if (n0 >= N) return;
|
||||
#pragma unroll
|
||||
@@ -432,14 +229,8 @@ void r4d_gemm_w8a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M,
|
||||
throw std::runtime_error("r4d gemm_w8a8_nt_m64: K must be divisible by SK*group");
|
||||
if (WV * SK * WAVE32 > R4D_W8A8_BOUNDS(MB, NPW))
|
||||
throw std::runtime_error("r4d gemm_w8a8_nt_m64: WV*SK*32 exceeds this tile's launch bound");
|
||||
// MB RUNS TO EIGHT, AND THAT IS THE WHOLE POINT AT M = 72. A block covers MB row tiles and
|
||||
// grid.y takes the rest, so every extra grid.y walks the WHOLE weight again -- the same
|
||||
// "seventeen rows is two macro tiles" that makes a library GEMM read a 636 MB lm_head twice. At
|
||||
// eight concurrent sequences the target verifies 8 x 9 = 72 rows, which is mtiles = 5, so a cap
|
||||
// of 4 would force grid.y = 2 and read the whole weight twice to do LESS work than M = 64 does
|
||||
// in one pass. Five is the shape the model actually runs.
|
||||
if (MB < 1 || MB > 8) throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB must be 1..8");
|
||||
if (MB * NPW > 10) throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB*NPW > 10 would spill");
|
||||
// cfg_for (r4d_gemm_args.h) caps MB at 4.
|
||||
if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB must be 1..4");
|
||||
if (NPW != 1 && NPW != 2 && NPW != 4 && NPW != 8)
|
||||
throw std::runtime_error("r4d gemm_w8a8_nt_m64: NPW must be 1, 2, 4 or 8");
|
||||
const int ntiles = N / 16, mtiles = (M + 15) / 16;
|
||||
@@ -455,39 +246,24 @@ void r4d_gemm_w8a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M,
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH8(MT, NP, TT) hipLaunchKernelGGL((r4d_gemm_w8a8_nt_m64_kernel<MT, NP, TT>), \
|
||||
grid, block, smem, st, Ap, Sp, Wp, Zp, Cp, M, K, N, WV, SK)
|
||||
// WHICH (MT, NPW) EXIST AT ALL. `acc` is MT*NPW*8 VGPRs and `g_acc` another MT*NPW*8 while a
|
||||
// group is in flight, so a tile costs 16*MT*NPW registers plus about forty of addressing against
|
||||
// an architectural cap of 256 -- and `-Rpass-analysis=kernel-resource-usage` puts the boundary
|
||||
// exactly where that predicts: MT*NPW = 10 lands at 207 VGPRs and does not spill, 12 spills 33,
|
||||
// and 16 spills 119 to 530. A spilling tile can never win, so it is not built: it would only cost
|
||||
// compile time and give the tuner configs to reject.
|
||||
#define LAUNCH8_MB8(NP, TT) switch (MB) { \
|
||||
// Only tiles with MT*NPW <= 8 are built: a tile costs about 16*MT*NPW + 40 VGPRs against the 256
|
||||
// cap.
|
||||
#define LAUNCH8_MB4(NP, TT) switch (MB) { \
|
||||
case 1: LAUNCH8(1, NP, TT); break; \
|
||||
case 2: LAUNCH8(2, NP, TT); break; \
|
||||
case 3: LAUNCH8(3, NP, TT); break; \
|
||||
case 4: LAUNCH8(4, NP, TT); break; \
|
||||
case 5: LAUNCH8(5, NP, TT); break; \
|
||||
case 6: LAUNCH8(6, NP, TT); break; \
|
||||
case 7: LAUNCH8(7, NP, TT); break; \
|
||||
case 8: LAUNCH8(8, NP, TT); break; \
|
||||
default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB unsupported"); }
|
||||
#define LAUNCH8_MB5(NP, TT) switch (MB) { \
|
||||
case 1: LAUNCH8(1, NP, TT); break; \
|
||||
case 2: LAUNCH8(2, NP, TT); break; \
|
||||
case 3: LAUNCH8(3, NP, TT); break; \
|
||||
case 4: LAUNCH8(4, NP, TT); break; \
|
||||
case 5: LAUNCH8(5, NP, TT); break; \
|
||||
default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB*NPW > 10 would spill"); }
|
||||
#define LAUNCH8_MB2(NP, TT) switch (MB) { \
|
||||
case 1: LAUNCH8(1, NP, TT); break; \
|
||||
case 2: LAUNCH8(2, NP, TT); break; \
|
||||
default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB*NPW > 10 would spill"); }
|
||||
default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB*NPW > 8 would spill"); }
|
||||
#define LAUNCH8_MB1(NP, TT) switch (MB) { \
|
||||
case 1: LAUNCH8(1, NP, TT); break; \
|
||||
default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB*NPW > 10 would spill"); }
|
||||
default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB*NPW > 8 would spill"); }
|
||||
#define LAUNCH8_NPW(TT) switch (NPW) { \
|
||||
case 1: LAUNCH8_MB8(1, TT); break; \
|
||||
case 2: LAUNCH8_MB5(2, TT); break; \
|
||||
case 1: LAUNCH8_MB4(1, TT); break; \
|
||||
case 2: LAUNCH8_MB4(2, TT); break; \
|
||||
case 4: LAUNCH8_MB2(4, TT); break; \
|
||||
case 8: LAUNCH8_MB1(8, TT); break; \
|
||||
default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: NPW must be 1, 2, 4 or 8"); }
|
||||
@@ -495,20 +271,17 @@ void r4d_gemm_w8a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M,
|
||||
#undef LAUNCH8_NPW
|
||||
#undef LAUNCH8_MB1
|
||||
#undef LAUNCH8_MB2
|
||||
#undef LAUNCH8_MB5
|
||||
#undef LAUNCH8_MB8
|
||||
#undef LAUNCH8_MB4
|
||||
#undef LAUNCH8
|
||||
}
|
||||
|
||||
int r4d_gemm_w8a8_nt_m64_max_m(void) { return R4D_GEMM_W8A8_MAX_M; }
|
||||
int r4d_gemm_w8a8_nt_m64_group(void) { return R4D_GEMM_W8A8_GROUP; }
|
||||
int r4d_gemm_w8a8_nt_m64_kpb(void) { return R4D_GEMM_W8A8_KPB; }
|
||||
int r4d_gemm_w8a8_nt_m64_aperm(void) { return R4D_W8A8_APERM; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there
|
||||
// is no adapter directory between the core and these launches.
|
||||
// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h.
|
||||
extern "C" int r4d_rad_gemm_w8a8_m64(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1);
|
||||
|
||||
+139
-1351
File diff suppressed because it is too large.
Load diff
@@ -1,37 +1,35 @@
|
||||
// r4d_gemm_wpa8i8_tiled.hip - r4d_gemm_w4a8i8_tiled / r4d_gemm_w5a8i8_tiled: the 4- and 5-bit ASYMMETRIC
|
||||
// weight x int8 activation GEMM for PREFILL row counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with
|
||||
// r4d_gemm_wpa8i8_tiled.hip - r4d_gemm_w4a8i8_tiled / r4d_gemm_w5a8i8_tiled: the 4- and 5-bit asymmetric
|
||||
// weight x int8 activation GEMM for prefill row counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with
|
||||
//
|
||||
// dequant(Wq)[n][k] = scale[n][k/128] * (code[n][k] - zero[n][k/128]), code in 0..15 or 0..31
|
||||
//
|
||||
// -- ParoQuant's int4 (z-lab) and int5 once the activation has been rotated (givens_dense_quant) -- in
|
||||
// 16x16x16 int8 WMMA, which issues at the fp8 instruction's rate. The f16 skinny kernel these weights
|
||||
// also serve (r4d_gemm_w5a16_nt_m64) is capped by the f16 matrix instruction at about 75 TF/s; this is the
|
||||
// tall-tile form with no such ceiling, built on r4d_gemm_mxfp4a8_tiled.hip's arrangement:
|
||||
// (ParoQuant's int4 (z-lab) and int5, after the activation is rotated by givens_dense_quant) in
|
||||
// 16x16x16 int8 WMMA, which issues at the fp8 rate. The f16 skinny kernel for these weights
|
||||
// (r4d_gemm_w5a16_nt_m64) is capped by the f16 matrix instruction at about 75 TF/s. Arrangement as in
|
||||
// r4d_gemm_mxfp4a8_tiled.hip:
|
||||
//
|
||||
// * a 256 x 64 tile (4 x 2 waves, 4 x 2 fragments each); the activation is re-tiled by
|
||||
// r4d_mxfp4a8_tile_a into fragment order (one 16 x 16 fragment = 256 bytes) in the op's scratch and
|
||||
// read straight into registers; the weight slab is staged through LDS;
|
||||
// * a slab is one scale group (128 of K = 8 WMMA steps): the int32 accumulators start at zero each slab and
|
||||
// are folded into the running float total as slab * (a_scale[row][g] * w_scale[col][g]), because the
|
||||
// weight's f16 scale varies by column and so cannot ride inside the matrix instruction;
|
||||
// * a slab is one scale group (128 of K = 8 WMMA steps): the int32 accumulators restart each slab and
|
||||
// are folded into the float total as slab * (a_scale[row][g] * w_scale[col][g]), since the weight
|
||||
// scale varies by column;
|
||||
// * a partitioned weight (pb1/pb2) is one launch per part over windows of the planes.
|
||||
//
|
||||
// WHY INT8 AND NOT FP8. (code - zero) is -15..15 (int4) or -31..31 (int5); both are exact in an int8,
|
||||
// so the weight needs no conversion at all -- the staging is a byte-wise subtract -- whereas e4m3's three
|
||||
// mantissa bits stop at 16 and int5 would need two matrix issues a step. The activation is quantised to
|
||||
// int8 with one scale a (row, 128 of K): after the rotation a group is flat, so 127 uniform levels of its
|
||||
// maximum are finer than e4m3's relative 2^-4 for nearly every element (measured: ppl equal to the f16
|
||||
// path's, slightly better than the fp8 band's). The accumulators are int32 and exact: a slab is 128
|
||||
// Why int8, not fp8: (code - zero) is -15..15 (int4) or -31..31 (int5), exact in int8, so staging is a
|
||||
// byte-wise subtract; e4m3's three mantissa bits stop at 16. The activation is int8 with one scale per
|
||||
// (row, 128 of K): after rotation a group is flat, so 127 uniform levels beat e4m3's relative 2^-4 for
|
||||
// nearly every element (perplexity equals the f16 path's). Accumulators are exact int32: a slab is 128
|
||||
// products of at most 31 * 127.
|
||||
//
|
||||
// STAGING. A code byte c (0..31) minus the zero z (0..31): (c | 0x80) - z is 128 + (c - z), never below
|
||||
// 97 and never carrying into the next byte, and XOR 0x80 turns it into the two's complement byte of
|
||||
// (c - z). Three ALU ops a dword of four weights.
|
||||
// Staging: for a code byte c (0..31) and zero z (0..31), (c | 0x80) - z = 128 + (c - z) never drops
|
||||
// below 97 or borrows across bytes, and XOR 0x80 gives the two's complement byte of (c - z). Three ALU
|
||||
// ops per dword of four weights.
|
||||
//
|
||||
// THE WEIGHT BLOB is r4d_gemm_w5a16_nt_m64's (BITS 5): the nibble plane (w4's fragment order), then the
|
||||
// fifth bits, one dword a (n-tile, 64 of K, lane): byte s = k step s of the block, bit e = element e. For
|
||||
// BITS 4 it is the nibble plane alone. The scale operand is the f16 kernel's dword plane
|
||||
// [N/16][K/128][16]: the f16 scale in the low half, -(1024 + zero) in the high.
|
||||
// Weight blob as r4d_gemm_w5a16_nt_m64's (BITS 5): the nibble plane (w4's fragment order), then the
|
||||
// fifth bits, one dword per (n-tile, 64 of K, lane): byte s = k step s, bit e = element e. BITS 4 is the
|
||||
// nibble plane alone. The scale operand is the f16 kernel's dword plane [N/16][K/128][16]: f16 scale
|
||||
// low, -(1024 + zero) high.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -73,9 +71,8 @@ __global__ __launch_bounds__(R4D_WPT_NTHR) void r4d_gemm_wpa8i8_tiled_kernel(
|
||||
constexpr int TM = R4D_WPT_TM, TN = R4D_WPT_TN, WN = R4D_WPT_WN, NTHR = R4D_WPT_NTHR, BMF = R4D_WPT_BMF;
|
||||
constexpr int LBK = R4D_WPT_LBK, NS = LBK / 16, STR = LBK + R4D_WPT_PAD, BNF = WN * TN * 16;
|
||||
constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32;
|
||||
// A thread stages one lane's 16 bytes of a 64-wide k block -- four k steps of one weight row, which
|
||||
// is how the fragment-order plane is laid out (dword (t, kb, lane, s)) -- so a slab of two blocks
|
||||
// over the block's tiles is TOT_SLOTS / 4 reads.
|
||||
// A thread stages one lane's 16 bytes of a 64-wide k block (four k steps of one weight row, as the
|
||||
// plane is laid out: dword (t, kb, lane, s)), so a slab of two blocks is TOT_SLOTS / 4 reads.
|
||||
constexpr int NW = TOT_SLOTS / 4 / NTHR;
|
||||
static_assert(NW * NTHR * 4 == TOT_SLOTS, "the W tile must split evenly over the block");
|
||||
__shared__ unsigned char sW[BNF * STR];
|
||||
@@ -239,9 +236,8 @@ static void wpa8i8_launch(long at, long ascale, long wq, long whi, long wsz, lon
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
// The row-major int8 activation is re-tiled into the op's scratch (one slab, the parts in turn), then the GEMM
|
||||
// reads it from there -- mxfp4a8_tiled's arrangement exactly, including a partitioned weight as
|
||||
// one launch per part over windows of the planes.
|
||||
// The row-major int8 activation is re-tiled into the op's scratch (one part at a time) and the GEMM
|
||||
// reads it there, as in mxfp4a8_tiled, including one launch per part of a partitioned weight.
|
||||
template <int BITS>
|
||||
static int wpa8i8_dispatch(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
|
||||
+48
-41
@@ -3,13 +3,13 @@
|
||||
// flow-matching sampler over them, and the image decoder's convolution, channel norm, resampling
|
||||
// shortcuts and pixel output.
|
||||
//
|
||||
// EACH KERNEL ROUNDS WHERE ITS libref FUNCTION DOES (libref/ref_gen.cpp), and libref rounds where
|
||||
// the reference model materialises a bf16 tensor. A reduction's order differs -- a block sum here,
|
||||
// a sequential one there -- so a sum can land one bf16 step apart; nothing else does.
|
||||
// Each kernel rounds where its libref function does (libref/ref_gen.cpp), and libref rounds where
|
||||
// the reference model materialises a bf16 tensor. Only reduction order differs (a block sum here,
|
||||
// a sequential one there), so a sum can land one bf16 step apart.
|
||||
//
|
||||
// IMAGE GEOMETRY IS IN THE OPERANDS. An image operand is [height, width * channels], dense, and
|
||||
// the shims read both off its shape: a parameter is fixed at declare and an image's size is a
|
||||
// request's.
|
||||
// Image geometry comes from the operands: an image operand is a dense [height, width * channels],
|
||||
// and the shims read both off its shape, because parameters are fixed at declare and image size
|
||||
// is per request.
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -18,6 +18,7 @@
|
||||
#include "rad_philox.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <initializer_list>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
@@ -116,17 +117,15 @@ __global__ __launch_bounds__(kT) void gate_add_kernel(
|
||||
|
||||
// ---------------------------------------------------------------------------- ln_mod_quant_fp8
|
||||
// gate_add, ln_mod and quant_act_fp8 in one pass over the row: the DiT block's norm in front of
|
||||
// every quantised linear, with the gated residual of the branch before it folded in. Three passes
|
||||
// over a 16384 x 4096 activation were ~0.9 GB of traffic a norm; this one reads the delta and the
|
||||
// residual and writes the residual and the E4M3 pair. The bf16 norm output is written only when
|
||||
// bound -- the fp8 linears read the codes.
|
||||
// every quantised linear, with the previous branch's gated residual folded in. Three passes over a
|
||||
// 16384 x 4096 activation are ~0.9 GB of traffic per norm; this reads the delta and the residual
|
||||
// and writes the residual and the E4M3 pair. The bf16 norm output is written only when bound.
|
||||
//
|
||||
// BIT-IDENTICAL TO THE THREE IT REPLACES, which the picture comparing equal across builds needs:
|
||||
// the residual is the gate_add arithmetic rounded to bf16 as its store rounds it, the mean and the
|
||||
// variance fold each thread's 8-wide chunks in ln_mod_kernel's order through the same block_sum,
|
||||
// the norm output is rounded to bf16 before it is quantised as quant_act_fp8 reads it, and the
|
||||
// codes are r4d_q8.h's. A 128-column group is sixteen consecutive chunks, so sixteen consecutive
|
||||
// lanes, and its amax is a half-wave reduction.
|
||||
// Bit-identical to the three kernels it replaces: the residual is gate_add's arithmetic rounded to
|
||||
// bf16 as its store rounds it, mean and variance fold each thread's 8-wide chunks in
|
||||
// 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.
|
||||
constexpr int kLnqChunks = 4; // 8-wide chunks a thread keeps: n <= kT * 8 * 4 = 8192
|
||||
|
||||
template <bool GATED>
|
||||
@@ -224,8 +223,8 @@ __global__ __launch_bounds__(kT) void gather2_kernel(
|
||||
*(uint4*)(y + (size_t)r * y_ld + c) = src ? *(const uint4*)(src + c) : make_uint4(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
// The lane copies move WORDS: a row is `words` 32-bit words (64 bf16 latent channels are 32, an f32
|
||||
// mask value is one), so one kernel serves every dtype the lanes hold.
|
||||
// The lane copies move 32-bit words: a row is `words` words (64 bf16 latent channels are 32, an
|
||||
// f32 mask value is one), so one kernel serves every dtype the lanes hold.
|
||||
__global__ __launch_bounds__(kT) void lane_gather_kernel(
|
||||
const uint32_t* __restrict__ src, const int* __restrict__ lane, const int* __restrict__ cu,
|
||||
uint32_t* __restrict__ y, int words, int n_seq, int stride, int s_ldw, int y_ldw, int64_t total) {
|
||||
@@ -317,8 +316,8 @@ __global__ __launch_bounds__(kT) void flow_euler_kernel(
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- per-channel ops
|
||||
// The two lists ride in the kernel's arguments, whose segment the backend caps at 768 bytes: 64
|
||||
// channels a list (a latent's) is 512 of them.
|
||||
// The two lists ride in the kernel arguments, whose segment the backend caps at 768 bytes; two
|
||||
// lists of 64 channels (a latent's) take 512.
|
||||
constexpr int kChanMax = 64;
|
||||
struct ChanLists { float mul[kChanMax], add[kChanMax]; };
|
||||
|
||||
@@ -424,24 +423,22 @@ __global__ __launch_bounds__(kT) void gelu_tanh_kernel(
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- conv2d_nhwc
|
||||
// AN IMPLICIT GEMM: y[pixel][cout] = sum over (tap, cin) of x_virtual[pixel's tap][cin] *
|
||||
// w[cout][tap][cin], the weight stored TAP-MAJOR (r4d_layout.cpp relayouts PyTorch's
|
||||
// [cout][cin][k][k] at load) so K runs over taps and then channels and a 64-wide K tile of the
|
||||
// image is eight 16-byte reads of NHWC rows -- the im2col never exists.
|
||||
// An implicit GEMM: y[pixel][cout] = sum over (tap, cin) of x_virtual[pixel's tap][cin] *
|
||||
// w[cout][tap][cin]. The weight is stored tap-major (r4d_layout.cpp relayouts PyTorch's
|
||||
// [cout][cin][k][k] at load), so K runs over taps then channels and a 64-wide K tile of the image
|
||||
// is eight 16-byte reads of NHWC rows; no im2col buffer.
|
||||
//
|
||||
// The block is r4d_gemm_bf16_nt_tiled's: eight waves, an activation tile of BP pixels and a weight
|
||||
// tile of BC output channels staged through LDS 64 K a time, the next tile's loads in flight under
|
||||
// the current one's WMMA. The weight is the WMMA's A operand and the pixels its B, so a lane's
|
||||
// accumulator is eight CONSECUTIVE output channels of one pixel and the store is 16 bytes.
|
||||
// tile of BC output channels staged through LDS 64 K at a time, with the next tile's loads in
|
||||
// flight under the current WMMA. The weight is the WMMA's A operand and the pixels its B, so a
|
||||
// lane's accumulator is eight consecutive output channels of one pixel and the store is 16 bytes.
|
||||
//
|
||||
// An input chunk of eight channels never straddles a tap because cin is a multiple of eight (the
|
||||
// shim sends anything else to the direct kernel below); a chunk past the image, past K or past the
|
||||
// last pixel is zeros.
|
||||
// An eight-channel input chunk never straddles a tap because cin is a multiple of eight (the shim
|
||||
// sends anything else to the direct kernel); a chunk past the image, K or the last pixel is zeros.
|
||||
//
|
||||
// THE KERNEL SIZE AND THE UPSAMPLING ARE TEMPLATE PARAMETERS (KS, UP; 0 reads the argument). A tap
|
||||
// index over a runtime k and a source row over a runtime `up` are two integer divisions per staged
|
||||
// chunk -- four chunks a thread a K tile, ~500 integer instructions beside 48 WMMA a wave -- and at
|
||||
// 3 and 2 they are a multiply-shift and a shift. The arithmetic is unchanged.
|
||||
// Kernel size and upsampling are template parameters (KS, UP; 0 reads the argument): at runtime
|
||||
// they cost two integer divisions per staged chunk (~500 integer instructions beside 48 WMMA a
|
||||
// wave), at 3 and 2 a multiply-shift and a shift.
|
||||
#define CV_BK 64
|
||||
#define CV_PITCH (CV_BK + 8)
|
||||
|
||||
@@ -826,7 +823,10 @@ extern "C" int r4d_rad_randn_lanes(const RadArgs* a, RadStream s) {
|
||||
const long long dl = r4d_rows_pitch(dst, n, &rd);
|
||||
if (dl < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
const long long n_seq = r4d_numel(cu) - 1;
|
||||
if (n <= 0 || stride <= 0 || n_seq <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
if (n <= 0 || stride <= 0 || n_seq <= 0 || rd < stride) return R4D_NO(RAD_E_SHAPE);
|
||||
/* One flag and lane an entry, two seed words. A lane's rows (device data) are not checked. */
|
||||
if (r4d_numel(fl) < n_seq || r4d_numel(lane) < n_seq || r4d_numel(seed) < 2 * n_seq)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
hipLaunchKernelGGL(randn_lanes_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT),
|
||||
0, (hipStream_t)s, (const int*)fl->data, (const uint32_t*)seed->data,
|
||||
(const int*)lane->data, (const int*)cu->data, (uint16_t*)dst->data, (int)n,
|
||||
@@ -851,7 +851,14 @@ extern "C" int r4d_rad_flow_euler(const RadArgs* a, RadStream s) {
|
||||
const long long il = inp ? r4d_rows_pitch(inp, n, &ri) : 0;
|
||||
if (vl < 0 || sl < 0 || pl < 0 || il < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
const long long n_seq = r4d_numel(cu) - 1;
|
||||
if (n <= 0 || stride <= 0 || n_seq <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
if (n <= 0 || stride <= 0 || n_seq <= 0 || rst < stride) return R4D_NO(RAD_E_SHAPE);
|
||||
/* One scalar of each kind an entry, two seed words; inp, mask and preview are addressed by the
|
||||
* state's rows. A lane's rows and a pair's entry (device data) are not checked. */
|
||||
for (const RadTensor* e : { sg, sgn, cfg, pair, lane, fl })
|
||||
if (r4d_numel(e) < n_seq) return R4D_NO(RAD_E_SHAPE);
|
||||
if (r4d_numel(seed) < 2 * n_seq || (pv && rp < rst) || (inp && ri < rst) ||
|
||||
(mask && r4d_numel(mask) < rst))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
hipLaunchKernelGGL(flow_euler_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), 0,
|
||||
(hipStream_t)s, (const uint16_t*)v->data, (const float*)sg->data,
|
||||
(const float*)sgn->data, (const float*)cfg->data, (const int*)pair->data,
|
||||
@@ -918,11 +925,11 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
|
||||
(int)x->stride[0], (int)y->stride[0], (int64_t)total);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
// 128 pixels a block, and the widest channel tile -- 192, 128, then 64 -- that leaves under a
|
||||
// third of its last block idle. A wider tile does twice or three times the WMMA a K step for
|
||||
// the same two barriers, and that pays even with the last block partly empty: on Qwen-Image's
|
||||
// decoder the 192 tile against the 64 one is 144 channels 39.7 -> 26.3 ms, 288 125.9 -> 95.2
|
||||
// (an upsampling layer), 576 109.9 -> 70.8, the same bytes out. 96 channels take 128.
|
||||
// 128 pixels a block, and the widest channel tile (192, 128, then 64) that leaves under a third
|
||||
// of its last block idle. A wider tile does two or three times the WMMA per K step for the same
|
||||
// two barriers, which pays even with the last block partly empty: on Qwen-Image's decoder the
|
||||
// 192 tile is 1.3-1.55x faster than the 64 tile at 144, 288 and 576 channels. 96 channels
|
||||
// take 128.
|
||||
auto fits = [cout](long long bc) {
|
||||
const long long padded = (cout + bc - 1) / bc * bc;
|
||||
return (padded - cout) * 3 < padded;
|
||||
|
||||
+24
-30
@@ -1,30 +1,27 @@
|
||||
// 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) does the same job in `stages` dependent LDS rounds a group and is
|
||||
// latency bound (~100-130 GB/s of ~640); this one spends ~8x the multiply-adds on the f16 WMMA, which
|
||||
// is 5 us of math for a 2048-row part, and quantises in the epilogue -- int8 (scale amax / 127, for the
|
||||
// int8 prefill GEMMs) or E4M3 (amax / 448, for the mxfp4a8 GEMMs), the same scale grid as the
|
||||
// sequential producer's. About 3x faster at prefill sizes and no slower at decode.
|
||||
// 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 and stores them as the
|
||||
// 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 it is, so the serving side never walks a Givens network. The channel scale stays a separate table (`rscale`), a
|
||||
// divide on the way in: folding 1/D into T would put entries of very different magnitude in one f16
|
||||
// matrix.
|
||||
// (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 A (part, group) x row chunk. The group's T (32 KiB of f16) is staged in LDS once and each
|
||||
// of the block's 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 lane m
|
||||
// and lane m + 16 and its amax is a max over 64 registers and one xor-16 shuffle.
|
||||
// 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.
|
||||
//
|
||||
// WHAT MOVED THE TIME (selftest, 2048 rows x K 5120): the first version waited on one activation load a
|
||||
// k step and spilled ~190 registers (186 us). A tile's eight loads are now issued together and the
|
||||
// issue order is pinned per k step (sched_barrier), which is what keeps the A fragments from being
|
||||
// hoisted whole into registers: 137 VGPRs, no spills, ~100 us. Double-buffering the next tile and
|
||||
// coalescing the stores through LDS were tried and did not move it.
|
||||
// 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"
|
||||
@@ -40,8 +37,8 @@ namespace {
|
||||
constexpr uint32_t kGroup = 128;
|
||||
constexpr uint32_t kThreads = 128;
|
||||
constexpr uint32_t kWaves = kThreads / 32;
|
||||
constexpr uint32_t kTStride = kGroup + 8;
|
||||
static_assert(kThreads == kGroup, "a thread stages one channel scale of the group (invd[tid])"); // f16 per LDS row of T: 16 B pad, conflict-free b128 reads
|
||||
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)));
|
||||
|
||||
@@ -73,9 +70,8 @@ __global__ __launch_bounds__(kThreads) void givens_dense_kernel(
|
||||
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) {
|
||||
// The activation row a lane reads: lane (col, h) takes columns 8h .. 8h+7 of every 16-wide k step of
|
||||
// row (tile * 16 + col). All eight k steps of a tile are loaded at once, so a tile costs one load
|
||||
// latency and not eight.
|
||||
// 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;
|
||||
@@ -133,7 +129,7 @@ __global__ __launch_bounds__(kThreads) void givens_dense_kernel(
|
||||
// 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 };
|
||||
|
||||
static int givens_dense_body(const RadArgs* a, const R4dSink& sk) {
|
||||
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);
|
||||
@@ -162,12 +158,10 @@ static int givens_dense_body(const RadArgs* a, const R4dSink& sk) {
|
||||
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(sk, (givens_dense_kernel<I8_>), grid, dim3(kThreads), 0, \
|
||||
#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
|
||||
if (rc != RAD_OK) return rc;
|
||||
return (!sk.desc && hipGetLastError() != hipSuccess) ? RAD_E_DEVICE : RAD_OK;
|
||||
return rc;
|
||||
}
|
||||
R4D_ENTRY(r4d_rad_givens_dense_quant, givens_dense_body)
|
||||
@@ -1,30 +1,27 @@
|
||||
// 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 -- decode). The weight it pairs with is stored
|
||||
// as v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens"), so the product <v, x'> with
|
||||
// x' = x . D^-1 . G_1 ... G_S is <w, x>: the rotation is the activation's to do, once a token, and the
|
||||
// weight is read by the GEMM unchanged. The quantising form, for prefill-sized rows and for MXFP4, is
|
||||
// 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.
|
||||
//
|
||||
// WHY THE ROTATION IS A GROUP AT A TIME. ParoQuant's pairs never leave a group of 128 columns -- that is
|
||||
// how the checkpoint is trained, and the converter and the loader (r4d_rad_relayout_givens_pairs) refuse
|
||||
// one that does -- so a group is a closed system:
|
||||
// its 128 values are rotated by S stages of 64 disjoint pairs. A wave owns a group. The values sit in LDS
|
||||
// (128 floats a wave, no barrier needed: a wave's LDS accesses are in order, and the pairs of a stage are
|
||||
// disjoint so no two lanes touch one address) and each lane takes two pairs a stage.
|
||||
// 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) was rotated per piece, so a row yields `parts` rotated
|
||||
// copies, side by side: y is [M, parts * K]. A (part, group) pair is one unit of work, one wave's (a row
|
||||
// is 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.
|
||||
// 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 DIVIDE, because the encoding's t.scale is the factor the stored row was
|
||||
// multiplied by (D), and the activation takes its inverse. A true IEEE divide on both sides: the
|
||||
// reference (libref) divides in f32 too, so the two agree on this step exactly.
|
||||
// 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).
|
||||
//
|
||||
// COS AND SIN ARE COMPUTED HERE, in f32, from the stored angle: sincosf is accurate to an ulp or two,
|
||||
// which is also what libref's libm is.
|
||||
//
|
||||
// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip.
|
||||
// Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip.
|
||||
|
||||
#include "r4d.h"
|
||||
#include "r4d_emit.h"
|
||||
@@ -39,10 +36,9 @@ 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 angles' sine and cosine taken BEFORE the first of them is
|
||||
// applied, so the dependent chain a stage would otherwise be -- table load, LDS read, rotate, LDS
|
||||
// write -- overlaps its neighbours' loads. At decode (M of a handful of rows) the kernel is latency
|
||||
// and not bandwidth: a row is 40 groups of 128 and each group is eight serial stages.
|
||||
// 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() {
|
||||
@@ -51,10 +47,10 @@ __device__ __forceinline__ void wave_sync() {
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront");
|
||||
}
|
||||
|
||||
// One wave rotates one (part, group) of one row: grid.x is the row, and grid.y spreads a row's
|
||||
// `parts * nkb` groups over blocks of kWaves waves -- one group a wave, so a row is several blocks and a
|
||||
// decode step of a few rows still fills the part. A wave that has no group returns at once; nothing in
|
||||
// the kernel is a block barrier. The rotated row is written as f16 into `y`, y_ld elements a row.
|
||||
// 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,
|
||||
@@ -119,8 +115,8 @@ __global__ __launch_bounds__(kThreads) void givens_rotate_kernel(
|
||||
|
||||
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 orders below that, and the clamp keeps an outlier
|
||||
// finite instead of inf
|
||||
// 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));
|
||||
@@ -136,7 +132,7 @@ __global__ __launch_bounds__(kThreads) void givens_rotate_kernel(
|
||||
// y [M][parts*K] f16
|
||||
enum { GV_X = 0, GV_PAIRS = 1, GV_ANGLE = 2, GV_RSCALE = 3, GV_Y = 4 };
|
||||
|
||||
static int givens_rotate_body(const RadArgs* a, const R4dSink& sk) {
|
||||
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);
|
||||
@@ -159,16 +155,16 @@ static int givens_rotate_body(const RadArgs* a, const R4dSink& sk) {
|
||||
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);
|
||||
if (!r4d_aligned(rs->data, 16) || !r4d_aligned(pr->data, 8) || !r4d_aligned(y->data, 4))
|
||||
// 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;
|
||||
const int rc = R4D_EMIT(sk, 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));
|
||||
if (rc != RAD_OK) return rc;
|
||||
return (!sk.desc && hipGetLastError() != hipSuccess) ? RAD_E_DEVICE : RAD_OK;
|
||||
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));
|
||||
}
|
||||
R4D_ENTRY(r4d_rad_givens_rotate, givens_rotate_body)
|
||||
@@ -1,39 +1,25 @@
|
||||
// H += X^T X, in f32, over an E4M3 activation with a per-(row, group) scale, or over a plain bf16
|
||||
// one.
|
||||
//
|
||||
// WHAT IT IS FOR. GPTQ needs a Gram matrix of the layer's real input -- the second moment
|
||||
// `H = sum_t x_t x_t^T` over a calibration corpus -- and this is the device half of producing one;
|
||||
// `rad_quantize` alone cannot, because it has no calibration harness to run the activations
|
||||
// through. The 4-bit expert format is the caller: see docs/MOE-W4.md.
|
||||
// Purpose: the device half of GPTQ's Gram matrix `H = sum_t x_t x_t^T` over a calibration corpus,
|
||||
// for the 4-bit expert format (docs/MOE-W4.md).
|
||||
//
|
||||
// IT IS NOT A GEMM AND CANNOT BE ONE. `gemm_nt` contracts the LAST axis of both operands; this
|
||||
// contracts the FIRST axis of both. Declaring it as a GEMM would need X transposed in memory,
|
||||
// which is a 26 MB scratch buffer and a transpose kernel for an op whose whole body is an FMA
|
||||
// loop. So it is its own row.
|
||||
// Not a GEMM: `gemm_nt` contracts the last axis of both operands, this contracts the first.
|
||||
// Expressing it as a GEMM would need a transposed copy of X (a 26 MB scratch and a transpose).
|
||||
//
|
||||
// WHY THE INPUT IS E4M3 AND NOT bf16. The two taps are the MoE block's own quantiser outputs --
|
||||
// `had_quant_act_fp8`'s (q, scale) for gate_up, and `gated_had_quant_fp8`'s for down. Those are
|
||||
// literally the bytes the expert GEMM contracts, so a Hessian built from them is a Hessian of the
|
||||
// arithmetic that actually runs rather than of the bf16 that preceded it. It is also the only
|
||||
// form the rotated path HAS: nothing stores the rotated activation as bf16.
|
||||
// E4M3 input: the taps are the MoE block's own quantiser outputs (`had_quant_act_fp8` for gate_up,
|
||||
// `gated_had_quant_fp8` for down), the bytes the expert GEMM actually contracts, and the only form
|
||||
// the rotated path stores. A bf16 instantiation reads the plain activation of a bf16-served model;
|
||||
// everything past the staging is shared.
|
||||
//
|
||||
// AND A bf16 FORM BESIDE IT, for the same reason pointing the other way. A model served at bf16
|
||||
// contracts its experts against the plain bf16 activation, so that IS the operand there, and the
|
||||
// bf16 instantiation reads it with no scale. Everything past the staging is shared.
|
||||
// The gate_up tap is the unsorted activation. Every token is routed to exactly top_k experts, so
|
||||
// the expert GEMM's input distribution gives H_sorted = top_k * H_token, and GPTQ is invariant to a
|
||||
// positive scale on H (damping is a fraction of the trace, LDLQ uses ratios). Taking M token rows
|
||||
// instead of M*top_k gathered ones saves a factor of top_k.
|
||||
//
|
||||
// THE TOP-K WEIGHTING IS FREE AND THIS IS WHY THE gate_up TAP IS THE UNSORTED ACTIVATION.
|
||||
// The expert GEMM reads token rows through a `sorted` index list, so its true input distribution
|
||||
// is every token repeated top_k times. Every token is routed to EXACTLY top_k experts, so that
|
||||
// distribution is the token distribution scaled by top_k -- H_sorted = top_k * H_token, exactly --
|
||||
// and GPTQ is invariant to a positive scale on H (the damping is a fraction of the trace and the
|
||||
// LDLQ update uses ratios). So the tap takes the M token rows once and not the M*top_k gathered
|
||||
// ones, at a top_k-fold saving, and loses nothing.
|
||||
//
|
||||
// ACCUMULATION IS f32 AND DELIBERATELY NOT f64. A block keeps its whole tile in registers across
|
||||
// the M loop and touches global once, so the error over a 2048-row launch is a register tree, not
|
||||
// a 2048-deep serial sum. Across launches the global f32 accumulator sees ~one add per launch.
|
||||
// The consumer damps H by a percent of its trace before inverting it, which is four orders of
|
||||
// magnitude above anything this rounds away; f64 would double 1.3 GB of state to buy nothing.
|
||||
// Accumulation is f32, not f64: a block keeps its tile in registers across the M loop and adds to
|
||||
// global once per launch. The consumer damps H by a percent of its trace, far above this rounding;
|
||||
// f64 would double 1.3 GB of state.
|
||||
//
|
||||
// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip.
|
||||
|
||||
@@ -43,19 +29,16 @@
|
||||
|
||||
namespace {
|
||||
|
||||
// A 64-wide C tile, 256 threads, 4x4 accumulators a thread: 16x16 threads x 16 = 4096 = 64*64.
|
||||
// 64 is chosen against the SCALE GRID as much as against the register file -- a 64-column tile
|
||||
// whose start is a multiple of 64 lies entirely inside one 128-wide scale group, so a row's scale
|
||||
// is ONE load a tile rather than one a column. The launcher enforces that by refusing a group the
|
||||
// tile does not divide.
|
||||
// A 64-wide C tile, 256 threads, 4x4 accumulators per thread (16x16 threads x 16 = 64*64). A
|
||||
// 64-aligned tile lies inside one scale group, so a row's scale is one load per tile; the launcher
|
||||
// refuses a group the tile does not divide.
|
||||
constexpr int kTile = 64;
|
||||
constexpr int kThreads = 256;
|
||||
constexpr int kMB = 32; // M rows staged a pass; 2 * 32 * 64 * 4 = 16 KiB of LDS
|
||||
constexpr int kTT = 4;
|
||||
|
||||
/* BF16 reads a plain bf16 activation and no scale: a staging slot is then four elements in two
|
||||
* dwords, and everything after the staging -- the tile, the accumulation order, the store -- is the
|
||||
* fp8 form's. The fp8 instantiation carries none of the bf16 staging. */
|
||||
/* BF16 reads a plain bf16 activation with no scale: a staging slot is four elements in two dwords.
|
||||
* Everything after the staging is shared with the fp8 form. */
|
||||
template <bool BF16>
|
||||
__global__ __launch_bounds__(kThreads) void gram_accum_kernel(
|
||||
const void* __restrict__ qv, const float* __restrict__ sc, float* __restrict__ h,
|
||||
@@ -78,8 +61,8 @@ __global__ __launch_bounds__(kThreads) void gram_accum_kernel(
|
||||
|
||||
for (uint32_t m0 = 0; m0 < M; m0 += (uint32_t)kMB) {
|
||||
__syncthreads();
|
||||
// 32 rows x 16 dwords = 512 staging slots for 256 threads, twice, for each of the two
|
||||
// tiles. A dword is four E4M3 codes and decodes in two v_cvt_pk_f32_fp8.
|
||||
// 32 rows x 16 slots = 512 per tile, two per thread. An fp8 slot is a dword of four E4M3
|
||||
// codes, decoded by two v_cvt_pk_f32_fp8.
|
||||
for (uint32_t idx = threadIdx.x; idx < (uint32_t)(kMB * kTile / 4);
|
||||
idx += (uint32_t)kThreads) {
|
||||
const uint32_t mi = idx >> 4, cq = (idx & 15u) * 4u;
|
||||
@@ -103,9 +86,8 @@ __global__ __launch_bounds__(kThreads) void gram_accum_kernel(
|
||||
}
|
||||
} else {
|
||||
if (c1 < K) {
|
||||
// The row is owned out to K rounded up to four bytes -- quant_act_fp8's
|
||||
// own contract -- so a dword load at c1 < K is inside the caller's
|
||||
// allocation even when the last group is ragged.
|
||||
// The row is owned out to K rounded up to four bytes (quant_act_fp8's
|
||||
// contract), so a dword load at c1 < K stays inside the allocation.
|
||||
const uint32_t w = *(const uint32_t*)((const uint8_t*)qv + qrow + c1);
|
||||
const float s = sc[(size_t)m * s_ld + g1];
|
||||
const v2f lo = r4d_fp8::e4m3_pk<false>(w), hi = r4d_fp8::e4m3_pk<true>(w);
|
||||
@@ -139,8 +121,8 @@ __global__ __launch_bounds__(kThreads) void gram_accum_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// One block owns one C tile, so this read-modify-write races with nothing. It is an ACCUMULATE
|
||||
// and not a store: the caller zeroes H once and then drives the whole corpus through it.
|
||||
// One block owns one C tile, so the read-modify-write is race-free. The caller zeroes H once
|
||||
// and accumulates the whole corpus into it.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < kTT; ++i) {
|
||||
const uint32_t k1 = k1_0 + ty * kTT + (uint32_t)i;
|
||||
@@ -159,7 +141,7 @@ extern "C" int r4d_gram_accum_fp8_tile(void) { return kTile; }
|
||||
|
||||
// q [M][K] E4M3, `q_ld` bytes a row (0 = K), owned out to a multiple of 4
|
||||
// s [M][ceil(K/grp)] f32, `s_ld` elements a row (0 = ceil(K/grp))
|
||||
// h [K][K] f32, `h_ld` elements a row (0 = K) -- READ AND WRITTEN
|
||||
// h [K][K] f32, `h_ld` elements a row (0 = K), read and written
|
||||
extern "C" int r4d_gram_accum_fp8(long q, long s, long h, int M, int K, int grp,
|
||||
int q_ld, int s_ld, int h_ld, long stream) {
|
||||
if (!q || !s || !h) return -1;
|
||||
@@ -179,7 +161,7 @@ extern "C" int r4d_gram_accum_fp8(long q, long s, long h, int M, int K, int grp,
|
||||
}
|
||||
|
||||
// a [M][K] bf16, `a_ld` elements a row (0 = K)
|
||||
// h [K][K] f32, `h_ld` elements a row (0 = K) -- READ AND WRITTEN
|
||||
// h [K][K] f32, `h_ld` elements a row (0 = K), read and written
|
||||
extern "C" int r4d_gram_accum_bf16(long a, long h, int M, int K, int a_ld, int h_ld, long stream) {
|
||||
if (!a || !h) return -1;
|
||||
if (M <= 0 || K <= 0) return -2;
|
||||
@@ -203,9 +185,10 @@ extern "C" int r4d_rad_gram_accum(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* sc = r4d_opt(a, GA_S);
|
||||
const RadTensor* h = r4d_opt(a, GA_H);
|
||||
if (!q || !sc || !h) return R4D_NO(RAD_E_INVAL);
|
||||
/* ROWS ARE DIM 0 AND EVERYTHING AFTER IT IS THE ROW, the same reading r4d_rad_quant_act_fp8
|
||||
* takes: a rank-3 activation is one row a token and its K is the product of the rest. `sc`
|
||||
* and `h` stay rank 2 because this op's meaning fixes them. */
|
||||
if (q->dtype != RAD_F8E4M3 || sc->dtype != RAD_F32 || h->dtype != RAD_F32)
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
/* Rows are dim 0 and everything after is the row, as in r4d_rad_quant_act_fp8; `sc` and `h`
|
||||
* are rank 2 by definition. */
|
||||
if (q->rank < 2 || sc->rank != 2 || h->rank != 2) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long M = q->shape[0];
|
||||
if (M < 1 || r4d_numel(q) % M) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -225,8 +208,7 @@ extern "C" int r4d_rad_gram_accum_bf16(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* x = r4d_opt(a, GA_Q);
|
||||
const RadTensor* h = r4d_opt(a, GA_H);
|
||||
if (!x || !h) return R4D_NO(RAD_E_INVAL);
|
||||
/* No scale: the bf16 form reads the activation as it stands. One handed over anyway is a
|
||||
* caller that believes the input is quantised, and it is refused rather than ignored. */
|
||||
/* A scale operand means the caller believes the input is quantised; refuse it. */
|
||||
if (r4d_opt(a, GA_S)) return R4D_NO(RAD_E_INVAL);
|
||||
if (x->dtype != RAD_BF16 || h->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
|
||||
if (x->rank < 2 || h->rank != 2) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
@@ -1,38 +1,28 @@
|
||||
// r4d_had_quant_act_i8.hip - r4d_had_quant_act_i8: a block Hadamard along K, then per-row symmetric
|
||||
// int8 quantisation, written in the order r4d_gemm_w4a8_nt_m64's A fragment wants.
|
||||
//
|
||||
// WHY THE ROTATION LIVES HERE. Plain per-token int8 activations are unusable on these models: the
|
||||
// KL against the bf16 model is an order of magnitude worse than per-token e4m3. A block Hadamard
|
||||
// first puts int8 several times BETTER than e4m3 instead. The mechanism is that a rotation fixes
|
||||
// RANGE, not precision: int8 spends its whole grid covering a few outlier channels, and mixing each
|
||||
// value with 127 others removes them. The same rotation does nothing for e4m3 -- marginally worse,
|
||||
// in fact -- because four exponent bits already carry the outliers and Gaussianising does not add
|
||||
// mantissa bits.
|
||||
// Why the rotation: plain per-token int8 activations are unusable on these models (KL against bf16
|
||||
// an order of magnitude worse than per-token e4m3); a block Hadamard first makes int8 several times
|
||||
// better than e4m3. A rotation fixes range, not precision: int8 spends its grid covering a few
|
||||
// outlier channels, and mixing each value with 127 others removes them. It does not help e4m3
|
||||
// (marginally worse), whose four exponent bits already carry the outliers. It must happen before
|
||||
// the absmax, since the benefit is a smaller row maximum, so it belongs in the quantiser.
|
||||
//
|
||||
// It has to happen BEFORE the absmax, which is why it belongs in the quantiser rather than in front
|
||||
// of it: the entire benefit is that the row maximum the int8 grid is scaled by gets smaller.
|
||||
// The seven butterfly stages (~14 ops per element) ride on a launch the quantiser pays anyway. The
|
||||
// remaining cost is one launch per rotated site per layer, which fusing into the producing RMSNorm
|
||||
// or SwiGLU removes.
|
||||
//
|
||||
// THE ROTATION IS FREE, THE LAUNCH IS NOT. A quantiser has to run either way, so seven butterfly
|
||||
// stages ride along on a launch already being paid -- ~14 ops per element on a kernel that already
|
||||
// touches every element twice. What costs is the number of these a decode step needs: one per
|
||||
// rotated site per layer. That cost comes out by fusing the rotation into the RMSNorm or SwiGLU
|
||||
// that produces the input, not by making the transform cheaper.
|
||||
// Width: 128, 256 and 512 are built; 1024 is not, for sharding reasons. A rotation block cannot
|
||||
// straddle a tensor-parallel boundary, so the width must divide the per-rank K, and a down_proj of
|
||||
// 17408 at TP=2 is 8704 = 2^9 * 17. The weight error barely moves from 128 to 1024, so the width
|
||||
// is picked on the activation's terms alone.
|
||||
//
|
||||
// WIDTH. 128, 256 and 512 are all buildable; 1024 is NOT, and the reason is sharding rather than
|
||||
// quality. A rotation block cannot straddle a tensor-parallel boundary, so the width has to divide
|
||||
// the PER-RANK K, and a down_proj of 17408 at TP=2 is 8704 = 2^9 * 17. 512 divides it, 1024 does
|
||||
// not. Width is nearly free to choose because the weight error barely moves across 128 through
|
||||
// 1024, so it is picked on the activation's terms alone.
|
||||
// The transform is in registers (r4d_fwht.h): one wave owns a `had`-wide block, and the only LDS
|
||||
// traffic left is one staging write so the row absmax can see the whole row.
|
||||
//
|
||||
// THE TRANSFORM IS IN REGISTERS, NOT LDS. See r4d_fwht.h for why staging the butterfly in LDS
|
||||
// costs several times the whole quantiser. One wave owns a `had`-wide block in registers and the
|
||||
// only shared traffic left is a single staging write, because the row absmax still has to see the
|
||||
// whole row.
|
||||
//
|
||||
// NORMALISATION IS FOLDED INTO THE SCALE. The stages below compute the UNNORMALISED transform, whose
|
||||
// values are sqrt(had) times the orthonormal ones. Rather than a pass to divide them, the row scale
|
||||
// carries it: quantising with inv = 127/absmax_unnorm gives exactly the codes the normalised
|
||||
// transform would, and S[row] = absmax_unnorm / (sqrt(had) * 127) is the scale that undoes both.
|
||||
// Normalisation is folded into the scale. The stages compute the unnormalised transform (sqrt(had)
|
||||
// times the orthonormal one); quantising with inv = 127/absmax_unnorm gives exactly the normalised
|
||||
// codes, and S[row] = absmax_unnorm / (sqrt(had) * 127) undoes both.
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_common.h"
|
||||
@@ -41,12 +31,6 @@
|
||||
#include <cstdint>
|
||||
#include <cmath>
|
||||
|
||||
// 0 = choose the workgroup width from M at launch (see r4d_act_threads in r4d_common.h); a
|
||||
// non-zero build-time value pins one width for every M.
|
||||
#ifndef R4D_HQAI8_THREADS
|
||||
#define R4D_HQAI8_THREADS 0
|
||||
#endif
|
||||
|
||||
template <int HAD, int THR>
|
||||
__global__ __launch_bounds__(THR) void r4d_had_quant_act_i8_kernel(
|
||||
const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S,
|
||||
@@ -96,10 +80,8 @@ __global__ __launch_bounds__(THR) void r4d_had_quant_act_i8_kernel(
|
||||
// The launch, as the plugin ABI's RadLaunchFn. See the note at the head of r4d_quant_act_i8.hip on
|
||||
// the argument list and the status return.
|
||||
//
|
||||
// THE WIDTH SET IS A PROPERTY OF THIS FILE, not of the row that selects it: the rows bound the
|
||||
// rotation with `had <= 512` and nothing else, and the kernel compiles exactly 128, 256 and 512.
|
||||
// 1024 cannot tile a down_proj of 8704 per rank, and nothing narrower than 128 is instantiated, so
|
||||
// a legal-looking 64 is refused here.
|
||||
// The width set belongs to this file, not the row: the rows only bound `had <= 512`, and the kernel
|
||||
// compiles exactly 128, 256 and 512, so a legal-looking 64 is refused here.
|
||||
enum { HQ_X = 0, HQ_Q, HQ_S };
|
||||
|
||||
extern "C" int r4d_rad_had_quant_act_i8(const RadArgs* args, RadStream stream) {
|
||||
@@ -116,11 +98,11 @@ extern "C" int r4d_rad_had_quant_act_i8(const RadArgs* args, RadStream stream) {
|
||||
|
||||
const long long had = r4d_geti_or(args, "group", 0);
|
||||
if (had != 128 && had != 256 && had != 512) return R4D_NO(RAD_E_SHAPE);
|
||||
// A rotation block cannot straddle a tensor-parallel shard boundary, so the PER-RANK K is what
|
||||
// it has to divide -- which is why 512 is the widest that down_proj's 8704 admits.
|
||||
// A rotation block cannot straddle a tensor-parallel shard, so it must divide the per-rank K
|
||||
// (down_proj's 8704 admits at most 512).
|
||||
if (K % had) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
const int thr = R4D_HQAI8_THREADS ? R4D_HQAI8_THREADS : r4d_act_threads((int)M, (int)K);
|
||||
const int thr = r4d_act_threads((int)M, (int)K);
|
||||
const size_t shmem = (size_t)K * sizeof(float) + (thr / 32) * sizeof(float);
|
||||
if (shmem > 65536) return R4D_NO(RAD_E_SCRATCH); // K too large to stage in LDS
|
||||
const float rn = 1.f / sqrtf((float)had);
|
||||
@@ -128,7 +110,6 @@ extern "C" int r4d_rad_had_quant_act_i8(const RadArgs* args, RadStream stream) {
|
||||
dim3(T), shmem, (hipStream_t)stream, (const __hip_bfloat16*)r4d_p(x), \
|
||||
(signed char*)r4d_wp(q), (float*)r4d_wp(sc), (int)K, rn)
|
||||
#define R4D_HQ_T(H) switch (thr) { \
|
||||
case 128: R4D_HQ_LAUNCH(H, 128); break; \
|
||||
case 256: R4D_HQ_LAUNCH(H, 256); break; \
|
||||
case 512: R4D_HQ_LAUNCH(H, 512); break; \
|
||||
case 1024: R4D_HQ_LAUNCH(H, 1024); break; \
|
||||
@@ -140,5 +121,5 @@ extern "C" int r4d_rad_had_quant_act_i8(const RadArgs* args, RadStream stream) {
|
||||
}
|
||||
#undef R4D_HQ_T
|
||||
#undef R4D_HQ_LAUNCH
|
||||
return RAD_OK;
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
|
||||
}
|
||||
+585
-1014
File diff suppressed because it is too large.
Load diff
+20
-21
@@ -1,25 +1,24 @@
|
||||
// r4d_hc_fp8.h -- the STORED ROW GEOMETRY of hc_read's two mixing matrices at E4M3, and nothing
|
||||
// else. Pure C++: no HIP, no r4d.h, so the host layout hook (r4d_fp8_layout.cpp), the kernels
|
||||
// (r4d_hc_bf16.hip) and the selftest derive a row from the same lines.
|
||||
// r4d_hc_fp8.h -- stored row geometry of hc_read's two mixing matrices at E4M3. Pure C++ (no HIP,
|
||||
// no r4d.h), so the host layout hook (r4d_fp8_layout.cpp), the kernels (r4d_hc_bf16.hip) and the
|
||||
// selftest share one definition.
|
||||
//
|
||||
// A stored row is [K E4M3 codes][K/G f32 scales][pad to 16 bytes], one row after another, for the
|
||||
// reason r4d_rad_layout_fp8_logits gives: the scales ride in the row that uses them, so a row is
|
||||
// self-contained and a kernel finds its scales at a fixed offset from its codes.
|
||||
// A stored row is [K E4M3 codes][K/G f32 scales][pad to 16 bytes], rows back to back. As in
|
||||
// r4d_rad_layout_fp8_logits, the scales ride in their row, so a kernel finds them at a fixed
|
||||
// offset from its codes.
|
||||
//
|
||||
// THE GROUP IS A PROPERTY OF THE KERNEL THAT READS THE ROW, not a tuning choice, and the two
|
||||
// matrices get different ones for that reason:
|
||||
// The group size is set by the kernel that reads the row, not by tuning:
|
||||
//
|
||||
// mix_down [lowrank rows, K = hc*n] G = 128. A wave walks the row in 256-element steps with
|
||||
// eight codes a lane, so every lane's eight sit inside one group and a step needs two
|
||||
// eight codes a lane, so each lane's eight sit in one group and a step needs two
|
||||
// scales a wave.
|
||||
// mix_up [hc*n rows, K = lowrank] G = K/4. Four threads share a row, each taking one
|
||||
// contiguous quarter of it -- 80 codes at lowrank 320 -- so a thread's quarter IS its
|
||||
// group and it multiplies by one scale after its whole partial sum. lowrank must be a
|
||||
// multiple of 64 for the quarter to be sixteen-code loads.
|
||||
// contiguous quarter (80 codes at lowrank 320), so a thread's quarter is its group and
|
||||
// it applies one scale after its partial sum. lowrank must be a multiple of 64 so a
|
||||
// quarter splits into sixteen-code loads.
|
||||
//
|
||||
// Both are FINER than the 128 x 128 blocks the GEMMs use, which is deliberate: these rows are
|
||||
// read against a normalised stream whose every element matters, and a per-row group costs one f32
|
||||
// per G codes -- 3.1% of mix_down's bytes and 5% of mix_up's.
|
||||
// Both are finer than the GEMMs' 128 x 128 blocks on purpose: these rows meet a normalised stream
|
||||
// where every element matters, and a per-row group costs one f32 per G codes (3.1% of mix_down's
|
||||
// bytes, 5% of mix_up's).
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
@@ -27,17 +26,17 @@ namespace r4d_hc8 {
|
||||
|
||||
constexpr int64_t kDownGroup = 128;
|
||||
|
||||
// constexpr and not merely inline, which is what makes them callable from device code too: the
|
||||
// compiler treats a constexpr function as both host and device.
|
||||
// constexpr rather than inline so device code can call them: a constexpr function is implicitly
|
||||
// host and device.
|
||||
constexpr int64_t down_group(int64_t /*K*/) { return kDownGroup; }
|
||||
constexpr int64_t up_group(int64_t K) { return K / 4; }
|
||||
|
||||
// Whether a K can be stored with the given group at all. The kernels' loads are what decide it:
|
||||
// sixteen codes at a time, a group a whole number of those.
|
||||
// Whether K can be stored with group G: the kernels load sixteen codes at a time, and a group must
|
||||
// be a whole number of those.
|
||||
constexpr bool group_ok(int64_t K, int64_t G) { return G > 0 && G % 16 == 0 && K % G == 0; }
|
||||
|
||||
// The BYTES one stored row occupies, and where its pad starts. The row starts 16-byte aligned so
|
||||
// every code load is a uint4 or a uint2 at a 16- or 8-byte boundary.
|
||||
// Bytes one stored row occupies, and where its pad starts. Rows start 16-byte aligned so every
|
||||
// code load is a uint4 or uint2 at a 16- or 8-byte boundary.
|
||||
constexpr int64_t row_used(int64_t K, int64_t G) { return K + 4 * (K / G); }
|
||||
constexpr int64_t row_bytes(int64_t K, int64_t G) { return (row_used(K, G) + 15) & ~(int64_t)15; }
|
||||
|
||||
|
||||
+13
-7
@@ -1,15 +1,21 @@
|
||||
/* r4d_launch.h -- the one spelling of a kernel launch in the libr4d units tests/r4d_emu runs on the
|
||||
* host: the windowed paged attention, pair_argmax, the sandwich-norm joins and expert_scale.
|
||||
/* r4d_launch.h -- the kernel-launch spelling for the libr4d units tests/r4d_emu runs on the host:
|
||||
* the windowed paged attention, pair_argmax, the sandwich-norm joins, expert_scale and the QSA
|
||||
* block selection.
|
||||
*
|
||||
* A template kernel's name carries commas, so it goes through R4D_KNAME the way HIP_KERNEL_NAME
|
||||
* exists for hipLaunchKernelGGL. R4D_KLAUNCH is overridable so the same sources can be driven by a
|
||||
* host-side SIMT emulator in a test -- the kernels are ordinary C++ once the HIP names are
|
||||
* supplied. A build never defines it, and gets the triple-chevron launch, which the engine answers
|
||||
* through hipLaunchKernel on its own queues (docs/PLUGIN.md §5). */
|
||||
* R4D_KNAME wraps a template kernel name containing commas, as HIP_KERNEL_NAME does for
|
||||
* hipLaunchKernelGGL. A test may define R4D_KLAUNCH to drive the same sources through a host SIMT
|
||||
* emulator; a build does not, and gets the triple-chevron launch, which the engine services via
|
||||
* hipLaunchKernel on its own queues (docs/PLUGIN.md §5).
|
||||
*
|
||||
* R4D_DYN_LDS declares a kernel's dynamic LDS, sized by the launch: `extern __shared__` in a
|
||||
* build. The emulator has no such storage class and defines its own. */
|
||||
#ifndef R4D_LAUNCH_H
|
||||
#define R4D_LAUNCH_H
|
||||
#define R4D_KNAME(...) __VA_ARGS__
|
||||
#ifndef R4D_KLAUNCH
|
||||
#define R4D_KLAUNCH(kernel, grid, block, stream, ...) kernel<<<grid, block, 0, stream>>>(__VA_ARGS__)
|
||||
#endif
|
||||
#ifndef R4D_DYN_LDS
|
||||
#define R4D_DYN_LDS(type, name) extern __shared__ type name[]
|
||||
#endif
|
||||
#endif
|
||||
+145
-172
@@ -1,38 +1,36 @@
|
||||
/* r4d_layout.cpp -- what libr4d's integer and MXFP4 GEMMs store for a weight, and the relayouts
|
||||
/* r4d_layout.cpp -- the stored form of libr4d's integer and MXFP4 GEMM weights, and the relayouts
|
||||
* that produce it from the weight's canonical planes (spec.md §4.3). Pure host C++: nothing here
|
||||
* includes r4d.h or <hip/hip_runtime.h>, so it compiles and can be exercised on a box with no
|
||||
* ROCm, which is where a packing bug is cheapest to find.
|
||||
* includes r4d.h or <hip/hip_runtime.h>, so packing can be tested without ROCm.
|
||||
*
|
||||
* A container holds each weight's encoding -- codes, scales and zero points, canonical and
|
||||
* row-major -- and the kernel that reads it rearranges it at load. That is what lets this file
|
||||
* change a fragment order without anyone converting a model again; the numbers were chosen by a
|
||||
* quantiser (libquant), and nothing here chooses one.
|
||||
* A container holds each weight's encoding (codes, scales and zero points, canonical and
|
||||
* row-major), and the kernel that reads it rearranges it at load, so a fragment order can change
|
||||
* without reconverting models. The numbers are chosen by a quantiser (libquant), never here.
|
||||
*
|
||||
* THE FRAGMENT ORDER IS THE WHOLE POINT. gfx1201's wave32 WMMA fragment layout is
|
||||
* Fragment order. gfx1201's wave32 WMMA fragment layout is
|
||||
*
|
||||
* idx = lane % 16 , k = 8*(e>>2) + 4*(lane>>4) + (e&3)
|
||||
*
|
||||
* so a B fragment maps lane l onto output row l&15: in canonical order the sixteen lanes of a
|
||||
* half-wave read sixteen rows K/2 bytes apart, which is a fully strided read on the operand that
|
||||
* dominates traffic. Rearranged, a wave's weight load for four k steps is one 512-byte
|
||||
* global_load_b128 with a constant stride and no address arithmetic in the loop.
|
||||
* so a B fragment maps lane l onto output row l&15. In canonical order the sixteen lanes of a
|
||||
* half-wave read sixteen rows K/2 bytes apart, a fully strided read on the operand that dominates
|
||||
* traffic. Rearranged, a wave's weight load for four k steps is one 512-byte global_load_b128 with
|
||||
* a constant stride and no address arithmetic in the loop.
|
||||
*
|
||||
* Every element->slot map below is transcribed from the kernel that reads it; the comment at the
|
||||
* top of each libr4d GEMM states it in closed form.
|
||||
* Every element->slot map below is transcribed from the kernel that reads it; each libr4d GEMM's
|
||||
* header states it in closed form.
|
||||
*/
|
||||
|
||||
#include "r4d_plugin.h"
|
||||
#include "r4d_enc.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
/* ------------------------------------------------------------------ half-precision
|
||||
*
|
||||
* Written out rather than pulled from a header because this file must build without ROCm and
|
||||
* without any float16 extension: __fp16 is not portable and _Float16 is not guaranteed on every
|
||||
* host compiler the converter might be built with. */
|
||||
* Written out so the file builds without ROCm or a float16 extension: __fp16 is not portable and
|
||||
* _Float16 is not available on every host compiler. */
|
||||
|
||||
static uint16_t f32_to_f16(float f) {
|
||||
uint32_t x;
|
||||
@@ -84,12 +82,10 @@ static float f16_to_f32(uint16_t h) {
|
||||
return f;
|
||||
}
|
||||
|
||||
/* THE SCALE DWORD. libr4d packs the group's two quantiser parameters into one 32-bit word: the f16
|
||||
* scale in the low half and the f16 of -(1024 + zero) in the high half, ready to be broadcast into
|
||||
* a v_pk_add_f16. The kernel builds 1024 + code and adds that constant, which is what makes the
|
||||
* subtraction of an INTEGER zero point exact. A symmetric 4-bit grid is expressed in the same
|
||||
* encoding with zero == 8, which is why one packed weight can feed both the f16 and the int8
|
||||
* kernel byte for byte. */
|
||||
/* The scale dword: a group's f16 scale in the low half and the f16 of -(1024 + zero) in the high
|
||||
* half, broadcast into a v_pk_add_f16. The kernel builds 1024 + code and adds that constant, which
|
||||
* subtracts an integer zero point exactly. A symmetric 4-bit grid uses zero == 8, so one packed
|
||||
* weight feeds both the f16 and the int8 kernel. */
|
||||
static uint32_t scale_zero_dword(float scale, int zero) {
|
||||
const uint32_t lo = f32_to_f16(scale);
|
||||
const uint32_t hi = f32_to_f16(-(1024.0f + (float)zero));
|
||||
@@ -120,20 +116,18 @@ static void fill(RadLayout* o, const char* tag, uint32_t dtype, long long r0, lo
|
||||
o->rank = 2;
|
||||
o->shape[0] = r0;
|
||||
o->shape[1] = r1;
|
||||
/* Every one of these streams is read with 128-bit loads; 256 is a cacheline on the
|
||||
* architectures in scope, and the .rad plane alignment. */
|
||||
/* Every stream is read with 128-bit loads; 256 bytes is a cacheline on the target
|
||||
* architectures and the .rad plane alignment. */
|
||||
o->align = 256;
|
||||
o->bytes = bytes;
|
||||
}
|
||||
|
||||
/* THE ASYMMETRIC 4-BIT GRID IS A DIFFERENT WEIGHT, and `dtype` is what says so. `w4a8_asym`'s
|
||||
* kernels read the nibble UNSIGNED and subtract a per-group integer zero from the scale dword's
|
||||
* high half; the symmetric grid stores a two's-complement nibble with the zero pinned at 8. The
|
||||
* packing, the extents and the byte counts are identical, so a plane written for one and read by
|
||||
* the other is accepted everywhere and decodes to the wrong numbers -- a symmetric plane read
|
||||
* unsigned is eight levels off at every code. The test is the kernels' own (r4d_gemm_args.h's
|
||||
* is_asym), so the encoding the layout hook accepts -- i4 with no zero, or u4 with one -- is the
|
||||
* grid the launch selects, and the other is refused at declare. */
|
||||
/* The asymmetric 4-bit grid is a different weight, and `dtype` says which. `w4a8_asym` kernels
|
||||
* read the nibble unsigned and subtract a per-group integer zero from the scale dword's high half;
|
||||
* the symmetric grid stores a two's-complement nibble with the zero fixed at 8. Packing, extents
|
||||
* and byte counts are identical, so a plane read as the other grid decodes eight levels off. This
|
||||
* is the kernels' own test (r4d_gemm_args.h is_asym), so the layout hook accepts only the matching
|
||||
* encoding (i4 without a zero, u4 with one) and refuses the other at declare. */
|
||||
static bool w4_asym(const RadParam* p, int n_p) {
|
||||
const char* d = r4d_pgets(p, n_p, "dtype");
|
||||
return d && std::strstr(d, "_asym") != nullptr;
|
||||
@@ -141,80 +135,66 @@ static bool w4_asym(const RadParam* p, int n_p) {
|
||||
|
||||
/* ================================================================== moe w4
|
||||
*
|
||||
* THE GROUPED MoE GEMM'S 4-BIT EXPERT WEIGHT, and it is a different plane from the dense w4 above
|
||||
* for one structural reason: the dense kernels read a WMMA fragment straight out of a coalesced
|
||||
* global load, so their weight is stored PERMUTED into fragment order; the grouped kernel stages
|
||||
* its weight through LDS -- it has to, because eight M tiles share one N tile of it -- so a
|
||||
* permutation would buy nothing and would have to be undone on the way in.
|
||||
* The grouped MoE GEMM's 4-bit expert weight. Unlike the dense w4 it is not permuted into fragment
|
||||
* order: the grouped kernel stages its weight through LDS (eight M tiles share one N tile), so a
|
||||
* permutation would only have to be undone.
|
||||
*
|
||||
* WHAT THE FORMAT IS
|
||||
* weight [N][K/2] bytes, row-major, two's complement codes -8..7: an ordinary symmetric int4
|
||||
* grid, as GPTQ writes.
|
||||
* scale [N][K/group] bf16, one per row per 128 of K. w ~= code * scale.
|
||||
*
|
||||
* weight [N][K/2] bytes, row-major, TWO'S COMPLEMENT codes -8..7 -- an ordinary symmetric
|
||||
* int4 grid, the one GPTQ and every other 4-bit method is written against.
|
||||
* scale [N][K/group] bf16, one per row per group of 128 along K. w ~= code * scale.
|
||||
* Decode: V_PERM_B32 permutes the bytes of an eight-byte source, so one table holds eight entries
|
||||
* and a two's complement nibble needs sixteen. Two perms index a positive and a negative table
|
||||
* with the low three bits, and a third selects on bit 3 by adding 4 to a selector byte (which
|
||||
* cannot carry): all sixteen levels for five more VALU per eight weights than a fifteen-level
|
||||
* sign-magnitude grid. See r4d_moe.hip w4_e4m3.
|
||||
*
|
||||
* THE DECODE IS TWO V_PERM_B32 AND A THIRD THAT CHOOSES BETWEEN THEM. A perm is a byte permute of
|
||||
* an EIGHT-byte source, so one table holds eight entries and a two's complement nibble needs
|
||||
* sixteen. Indexing both a positive and a negative table with the low three bits and selecting on
|
||||
* bit 3 -- by ADDING 4 to a selector byte, which cannot carry -- gets all sixteen levels for five
|
||||
* more VALU per eight weights than a fifteen-level sign-magnitude grid would cost. r4d_moe.hip's
|
||||
* w4_e4m3 is the five lines.
|
||||
* The integers -8..7 are exact in E4M3 (three mantissa bits reach 16), so expanding a code to an
|
||||
* E4M3 byte is lossless and the weight runs on the existing f32_16x16x16_fp8_fp8 inner loop; only
|
||||
* the staging differs.
|
||||
*
|
||||
* THE INTEGERS -8..7 ARE ALL EXACT IN E4M3 (three mantissa bits reach 16), so expanding a code to an
|
||||
* E4M3 byte is lossless and the product the WMMA computes is code * activation with no rounding
|
||||
* the fp8 path did not already have. That is the whole reason this weight can ride the existing
|
||||
* f32_16x16x16_fp8_fp8 inner loop untouched: only the STAGING changes.
|
||||
* Nibble order: byte b of a packed dword holds element b in its low nibble and element b+4 in its
|
||||
* high nibble, so the two masks yield elements 0..3 and 4..7 already in order, as in the dense
|
||||
* w4a8 kernel.
|
||||
*
|
||||
* THE NIBBLE ORDER IS THE ONE THE EXPANSION WANTS. Byte b of a packed dword holds element b in its
|
||||
* low nibble and element b+4 in its high nibble, so the two masks above produce elements 0..3 and
|
||||
* 4..7 already in order and nothing has to be interleaved afterwards. It is the same argument the
|
||||
* dense w4a8 kernel's header makes for the same pair of masks.
|
||||
*
|
||||
* IT IS NOT SHARDABLE AND THE ARCHITECTURE SAYS SO. A packed row is K/2 bytes and a column shard
|
||||
* would cut a byte in half; an expert under expert parallelism is whole on one rank, which is the
|
||||
* only configuration that declares this format. rad_block_moe_fp8.h refuses a width-sharded
|
||||
* declaration by name rather than leaving it to the loader to discover.
|
||||
* Not shardable: a packed row is K/2 bytes and a column shard could cut a byte in half. Under
|
||||
* expert parallelism an expert is whole on one rank, the only configuration that declares this
|
||||
* format; rad_block_moe_fp8.h refuses a width-sharded declaration.
|
||||
*/
|
||||
/* THE ROTATED FORM IS THE SAME BYTES WITH DIFFERENT NUMBERS IN THEM, and that is exactly why the
|
||||
* encoding says so. `dtype=w4a8h` serves `i4*bf16[1x128]/fwht128`: every group of K was multiplied
|
||||
* by a `group`-wide Hadamard before it was quantised. Nothing in the packing, the extents or the
|
||||
* byte count would say so, and a weight quantised one way and served the other reads as noise --
|
||||
* so the layout hook accepts exactly the encoding the dtype names, and refuses the other at
|
||||
* declare.
|
||||
/* `dtype=w4a8h` serves `i4*bf16[1x128]/fwht128`: the same bytes, but every group of K was
|
||||
* multiplied by a `group`-wide Hadamard before quantisation. Nothing in packing, extents or byte
|
||||
* count shows this, and a weight served the other way reads as noise, so the layout hook accepts
|
||||
* only the encoding the dtype names.
|
||||
*
|
||||
* THE KERNEL DOES NOT BRANCH ON IT. <Hw, Ha> = group * <w, a>, and the residual factor is folded
|
||||
* into the stored weight scale by the quantiser (docs/MOE-W4.md), so the GEMM multiplies codes by
|
||||
* scales exactly as it does for the unrotated grid. What has to agree is the ACTIVATION: the
|
||||
* routed experts' input must be quantised by the rotated quantiser at the same width, which is
|
||||
* what had_quant_act_fp8 is for. That pairing is not checkable from here -- it is a property of the
|
||||
* graph, and the arch block that declares one declares the other. */
|
||||
/* THE CODEBOOK FORM IS THE ROTATED FORM WITH OTHER NUMBERS FOR THE SAME CODES. `dtype=w4nla8h`
|
||||
* serves `u4*bf16[1x128]/fwht128` whose codes index a sixteen-entry `table` plane -- libquant's
|
||||
* `table=w4nl` -- and the kernel decodes that table and no other (r4d_args.h). An encoding cannot
|
||||
* say what its table holds, so the codes view selects the table plane beside the codes and the
|
||||
* relayout compares it with the kernel's, value for value, before it serves a byte: a container
|
||||
* quantised against another table is refused at load rather than served as other numbers. */
|
||||
* The kernel does not branch on it: <Hw, Ha> = group * <w, a>, and the quantiser folds the
|
||||
* residual factor into the stored scale (docs/MOE-W4.md). What must agree is the activation, which
|
||||
* had_quant_act_fp8 quantises with the same rotation width. That pairing is a property of the
|
||||
* graph and is not checked here; the arch block that declares one declares the other. */
|
||||
/* `dtype=w4nla8h` serves `u4*bf16[1x128]/fwht128` whose codes index a sixteen-entry `table` plane
|
||||
* (libquant `table=w4nl`), and the kernel decodes only its own table (r4d_args.h). The codes view
|
||||
* selects the table plane and the relayout compares it with the kernel's value for value, so a
|
||||
* container quantised against another table is refused at load. */
|
||||
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);
|
||||
}
|
||||
/* `w5nl64a8h` IS w4nl64a8h AT FIVE BITS: `u5*fp8_e4m3[1x64]*f32[*x*]/fwht128` whose codes index
|
||||
* 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 the high bit of every code, the sign,
|
||||
* a dword a 32 elements (moew5_row says in which order) -- and compares the table with
|
||||
* kW5nlTable as w4nla8h's is; its scale view is w4nl64a8h's. */
|
||||
/* `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
|
||||
* 32 elements in moew5_row's order) and checks the table against kW5nlTable. Its scale view is
|
||||
* w4nl64a8h's. */
|
||||
static bool moe_w5(const RadParam* p, int n_p) {
|
||||
const char* d = r4d_pgets(p, n_p, "dtype");
|
||||
return d && std::strcmp(d, "w5nl64a8h") == 0;
|
||||
}
|
||||
/* `w4nl64a8h` IS THE CODEBOOK FORM WITH ITS SCALES A 64 OF K, as E4M3 under the fixed
|
||||
* kW4G64Scale -- `u4*fp8_e4m3[1x64]*f32[*x*]/fwht128` with the table, the f32 second level being
|
||||
* that constant, stated once a weight. The codes are stored as w4nla8h's; the scale view selects
|
||||
* the E4M3 plane and the second level, and its relayout compares the second with the kernel's
|
||||
* constant, as the codes view does the table, and stores the E4M3 plane as it is. */
|
||||
/* And `w4nl32a8h` the same at one a (row, 32 of K). The value is the scale groups a 128 of K the
|
||||
* dtype has beside its bf16 forms' one: 2, 4, or 0 for neither. */
|
||||
/* `w4nl64a8h` is the codebook form with one E4M3 scale per (row, 64 of K) under a fixed f32
|
||||
* second level, kW4G64Scale, stored once per weight (`u4*fp8_e4m3[1x64]*f32[*x*]/fwht128` with the
|
||||
* table). Codes are stored as w4nla8h's. The scale view selects the E4M3 plane and the second
|
||||
* level; its relayout checks the second level against the kernel's constant and stores the E4M3
|
||||
* plane unchanged. `w4nl32a8h` is the same with one scale per (row, 32 of K).
|
||||
*
|
||||
* Returns the scale groups per 128 of K (the bf16 forms have one): 2, 4, or 0 for neither. */
|
||||
static int moe_w4_g64(const RadParam* p, int n_p) {
|
||||
const char* d = r4d_pgets(p, n_p, "dtype");
|
||||
if (!d) return 0;
|
||||
@@ -229,10 +209,9 @@ static int moe_w4_rot(const RadParam* p, int n_p) {
|
||||
/* ================================================================== moe_gemm_q's two classes
|
||||
*
|
||||
* `moe_gemm_q` takes its experts as two tables by parity: operands 2 and 3 hold the even experts
|
||||
* at [N, K], operands 6 and 7 the odd ones at [N_odd, K_odd] (r4d_rows.cpp's schema says why). A
|
||||
* hook asked about 6 or 7 answers exactly as it would for 2 or 3 at the odd geometry, so every
|
||||
* hook below is the plain one behind this view, and the two classes cannot come to disagree about
|
||||
* a format they share. */
|
||||
* at [N, K], operands 6 and 7 the odd ones at [N_odd, K_odd] (see the schema in r4d_rows.cpp). A
|
||||
* hook asked about 6 or 7 answers as for 2 or 3 at the odd geometry, so both classes share one
|
||||
* format definition. */
|
||||
namespace {
|
||||
struct MoeView {
|
||||
RadParam p[32];
|
||||
@@ -258,8 +237,7 @@ int moe_view(const RadParam* p, int n_p, int operand, MoeView* v) {
|
||||
}
|
||||
|
||||
/* `moe_gemm_q_mod4`'s four classes: operands 6/7, 8/9 and 10/11 are classes 1, 2 and 3 at
|
||||
* N_1/K_1, N_2/K_2 and N_3/K_3, answered as 2/3 at that geometry -- the same view, one class
|
||||
* further along. */
|
||||
* N_1/K_1, N_2/K_2 and N_3/K_3, answered as 2/3 at that geometry. */
|
||||
int moe_view_mod4(const RadParam* p, int n_p, int operand, MoeView* v) {
|
||||
if (n_p < 0 || n_p > 32 || (n_p > 0 && !p)) return RAD_E_INVAL;
|
||||
v->n = n_p;
|
||||
@@ -283,10 +261,9 @@ int moe_view_mod4(const RadParam* p, int n_p, int operand, MoeView* v) {
|
||||
|
||||
/* ================================================================== the hooks
|
||||
*
|
||||
* The codes and scales arrive chosen, by a quantiser, and what is left here is the arrangement the
|
||||
* kernel reads -- fragment order, the (scale, zero) dword, a tile-major scale plane, a nibble
|
||||
* order -- which moves bits and chooses none. Each refuses, with RAD_E_DTYPE, an encoding its
|
||||
* kernel does not read. */
|
||||
* Codes and scales arrive chosen by a quantiser; the hooks only arrange them as the kernel reads
|
||||
* them (fragment order, the (scale, zero) dword, a tile-major scale plane, a nibble order). Each
|
||||
* refuses an encoding its kernel does not read with RAD_E_DTYPE. */
|
||||
namespace {
|
||||
|
||||
using r4d_enc::selects;
|
||||
@@ -295,7 +272,7 @@ using r4d_enc::dims;
|
||||
/* A selected plane's dense bytes. */
|
||||
const uint8_t* pdata(const RadTensor& t) { return (const uint8_t*)t.data; }
|
||||
|
||||
/* The f16 scale of a canonical plane, as f32 -- the value scale_zero_dword re-narrows exactly. */
|
||||
/* The f16 scale of a canonical plane as f32; scale_zero_dword narrows it back exactly. */
|
||||
float f16_at(const RadTensor& t, long long i) { return f16_to_f32(((const uint16_t*)t.data)[i]); }
|
||||
|
||||
/* An integer zero point from a u4 or u8 plane. */
|
||||
@@ -327,9 +304,9 @@ void sz_write(const WGeom& g, const RadTensor* pl, int zfixed, uint32_t* sz) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Every zero point a code of `bits` bits: what an asymmetric grid's zero is, and what the int8
|
||||
* prefill kernel reads back out of the scale dword (r4d_gemm_wpa8i8_tiled.hip takes five bits of it,
|
||||
* where the f16 kernel takes the whole value -- a larger zero would make the two disagree). */
|
||||
/* Whether every zero point fits in `bits` bits. The int8 prefill kernel (r4d_gemm_wpa8i8_tiled.hip)
|
||||
* reads five bits of the zero out of the scale dword where the f16 kernel reads the whole value,
|
||||
* so a larger zero would make the two disagree. */
|
||||
bool sz_zeros_fit(const WGeom& g, const RadTensor& zp, int bits) {
|
||||
const long long nz = g.N * (g.K / g.group);
|
||||
for (long long i = 0; i < nz; ++i) {
|
||||
@@ -354,9 +331,9 @@ void sz_read(const WGeom& g, const uint32_t* sz, const RadTensor* pl, bool asym)
|
||||
}
|
||||
}
|
||||
|
||||
/* A ROTATED asymmetric grid (ParoQuant): codes of `codes` dtype, an f16 scale and a u8 zero point a
|
||||
* group, then a `givens` transform and its tables -- the same bytes as the unrotated grid, the
|
||||
* rotation being the activation's. */
|
||||
/* A rotated asymmetric grid (ParoQuant): codes of dtype `codes`, an f16 scale and a zero point
|
||||
* per group, optionally with a `givens` transform and its tables. The bytes are the unrotated
|
||||
* grid's; the rotation is applied to the activation. */
|
||||
static bool paro_asym_enc(const RadEncoding* e, uint32_t codes, long long group) {
|
||||
if (!e || !rad_enc_is(e, "affine") || e->n_planes < 3) return false;
|
||||
const bool giv = std::strncmp(e->transform, "givens", RAD_ENC_STR) == 0;
|
||||
@@ -428,10 +405,11 @@ extern "C" int r4d_rad_relayout_w4(const RadParam* p, int n_p, int operand, cons
|
||||
if (dst_bytes != L.bytes) return RAD_E_SHAPE;
|
||||
std::memset(dst, 0, (size_t)dst_bytes);
|
||||
if (operand == Q_BSCALE) {
|
||||
/* a ROTATED (ParoQuant) grid's zero is a 4-bit code */
|
||||
if (w4_asym(p, n_p) && std::strncmp(enc->transform, "givens", RAD_ENC_STR) == 0 &&
|
||||
const bool asym = w4_asym(p, n_p);
|
||||
/* A rotated (ParoQuant) grid's zero must fit a 4-bit code. */
|
||||
if (asym && std::strncmp(enc->transform, "givens", RAD_ENC_STR) == 0 &&
|
||||
!sz_zeros_fit(g, pl[1], 4)) return RAD_E_FORMAT;
|
||||
sz_write(g, pl, w4_asym(p, n_p) ? -1 : 8, (uint32_t*)dst);
|
||||
sz_write(g, pl, asym ? -1 : 8, (uint32_t*)dst);
|
||||
return RAD_OK;
|
||||
}
|
||||
uint32_t* wq = (uint32_t*)dst;
|
||||
@@ -473,13 +451,13 @@ extern "C" int r4d_rad_unrelayout_w4(const RadParam* p, int n_p, int operand,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- w5: ParoQuant's int5, asymmetric: u5 codes, an f16 scale and a u8 zero point (0..31) a 128 of K.
|
||||
* The blob is w4's fragment order for the low four bits of every code (offset binary, no sign flip)
|
||||
* followed by a plane of 32-bit words holding the fifth bits, one a (n-tile, 64 of K, lane): byte s
|
||||
* is k step s of the block and bit e the fragment element e -- the element whose nibble is
|
||||
* 2e (e < 4) or 2(e-4)+1 in dword s of that lane's 16 bytes (r4d_gemm_w5a16_nt_m64.hip). The scale
|
||||
* operand is w4u's (scale, zero) dword plane. A ROTATED weight (a `givens` transform and its
|
||||
* tables beside the first three planes) is the same bytes: the rotation is the activation's. */
|
||||
/* ---- w5: ParoQuant's asymmetric int5: u5 codes, an f16 scale and a u8 zero point (0..31) per
|
||||
* 128 of K. The blob is w4's fragment order for the low four bits of every code (offset binary, no
|
||||
* sign flip), then 32-bit words of fifth bits, one per (n-tile, 64 of K, lane): byte s is k step s
|
||||
* of the block and bit e is fragment element e, whose nibble is 2e (e < 4) or 2(e-4)+1 in dword s
|
||||
* of that lane's 16 bytes (r4d_gemm_w5a16_nt_m64.hip). The scale operand is w4u's (scale, zero)
|
||||
* dword plane. A rotated weight (a `givens` transform and its tables beside the first three
|
||||
* planes) has the same bytes; the rotation is the activation's. */
|
||||
namespace {
|
||||
bool w5_enc(const RadEncoding* e, long long group) { return paro_asym_enc(e, RAD_U5, group); }
|
||||
|
||||
@@ -571,10 +549,10 @@ extern "C" int r4d_rad_unrelayout_w5(const RadParam* p, int n_p, int operand, co
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- givens pairs: ParoQuant's rotation pairs (i32 [P*S, K]), stored as they are but CHECKED.
|
||||
* The rotate kernels index a group's 128 LDS slots with them unchecked, so a stage that is not a
|
||||
* pairing of its own group -- an index outside the group, or one column twice -- is refused here,
|
||||
* at load, rather than read out of bounds. Operand 1 of the givens rows; the rest is as stored. */
|
||||
/* ---- givens pairs: ParoQuant's rotation pairs (i32 [P*S, K]), stored unchanged but checked. The
|
||||
* rotate kernels index a group's 128 LDS slots with them unchecked, so a stage that is not a
|
||||
* pairing within its own group (an index outside the group, or a column twice) is refused at load.
|
||||
* Operand 1 of the givens rows; the other operands are stored as they are. */
|
||||
namespace {
|
||||
constexpr int GV_PAIRS_OPERAND = 1;
|
||||
constexpr long long GV_GROUP = 128;
|
||||
@@ -636,14 +614,14 @@ extern "C" int r4d_rad_unrelayout_givens_pairs(const RadParam* p, int n_p, int o
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- givens_dense: ParoQuant's rotation as one dense matrix a (part, group).
|
||||
/* ---- 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 columns as
|
||||
* T (x / D), T being their composition. rad-convert composes T and stores it as the "givens" encoding's
|
||||
* "t.dense" table, f16 [P * K/128, 128 * 128], row p * (K/128) + g element j * 128 + i the output j for the
|
||||
* unit input e_i (abi/rad_encoding.h) -- which is the order the kernel stages a (part, group), 32 KiB, whole.
|
||||
* So the layout is the table as stored: a relayout that moves bytes and derives none (abi/rad_abi.h).
|
||||
* Operand 1 of givens_dense_quant; everything else stays as stored. */
|
||||
* The dense kernel (r4d_givens_dense.hip) applies a part's Givens stages over each group of 128
|
||||
* columns as T (x / D), T being their composition. rad-convert composes T and stores it as the
|
||||
* "givens" encoding's "t.dense" table, f16 [P * K/128, 128 * 128]: in row p * (K/128) + g, element
|
||||
* j * 128 + i is output j for unit input e_i (abi/rad_encoding.h). The kernel stages a (part,
|
||||
* group), 32 KiB, whole in that order, so the layout is the table as stored. Operand 1 of
|
||||
* givens_dense_quant; everything else stays as stored. */
|
||||
namespace {
|
||||
constexpr int GD_OPERAND = 1;
|
||||
constexpr long long GD_GROUP = 128;
|
||||
@@ -676,14 +654,14 @@ extern "C" int r4d_rad_relayout_gdense(const RadParam* p, int n_p, int operand,
|
||||
RadLayout L;
|
||||
int rc = r4d_rad_layout_gdense(p, n_p, operand, enc, sel, pl, n, &L);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (dst_bytes != L.bytes) return RAD_E_SHAPE;
|
||||
if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
|
||||
std::memcpy(dst, pdata(pl[0]), (size_t)L.bytes);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- w8: i8 codes, symmetric about zero, an f16 scale a group. The f16 kernel (a16) reads the
|
||||
* code offset binary with zero 128 in the shared dword; the int8 kernel (a8) reads it signed with a
|
||||
* bare f16 scale plane. */
|
||||
/* ---- w8: i8 codes, symmetric about zero, an f16 scale per group. The f16 kernel (a16) reads the
|
||||
* code as offset binary with zero 128 in the shared dword; the int8 kernel (a8) reads it signed
|
||||
* with a bare f16 scale plane. */
|
||||
namespace {
|
||||
int w8_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, int a16) {
|
||||
@@ -766,7 +744,7 @@ extern "C" int r4d_rad_relayout_w8a8(const RadParam* p, int n_p, int operand,
|
||||
return w8_relayout(p, n_p, operand, enc, sel, pl, n, dst, dst_bytes, 0);
|
||||
}
|
||||
|
||||
/* ---- w2a8: u2 codes, asymmetric, an f16 scale and an integer zero a group, both streams
|
||||
/* ---- w2a8: u2 codes, asymmetric, an f16 scale and an integer zero per group, both streams
|
||||
* tile-major. */
|
||||
namespace {
|
||||
int w2_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
@@ -855,17 +833,15 @@ extern "C" int r4d_rad_unrelayout_w2a8(const RadParam* p, int n_p, int operand,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- MXFP4: fp4 e2m1 codes with an E8M0 exponent a 32. The codes go to fragment order, the
|
||||
* exponents to [K/32][N], and b_ref is each row's largest exponent -- a reduction over the plane,
|
||||
* which is a derivation any reader of the plane could make and so not a choice. */
|
||||
/* ---- MXFP4: fp4 e2m1 codes with an E8M0 exponent per 32. The codes go to fragment order, the
|
||||
* exponents to [K/32][N], and b_ref is each row's largest exponent: a reduction any reader of the
|
||||
* plane could compute, so not a choice. */
|
||||
namespace {
|
||||
/* A ROTATED MXFP4 WEIGHT (ParoQuant): the same two planes -- e2m1 codes, an E8M0 exponent a 32 --
|
||||
* stored in the basis the "givens" transform names, with the rotation's tables beside them. The
|
||||
* GEMM reads the codes and exponents exactly as it reads an unrotated weight; the rotation is the
|
||||
* activation's (givens_dense_quant), and the tables are separate weight operands of that op, so
|
||||
* nothing here touches them. What is checked is that they are there and are the kind of
|
||||
* rotation the quantiser applies: a transform this library does not read would hand the kernel
|
||||
* codes that decode to other numbers. */
|
||||
/* A rotated MXFP4 weight (ParoQuant): the same two planes stored in the basis the "givens"
|
||||
* transform names, with the rotation's tables beside them. The GEMM reads codes and exponents as
|
||||
* for an unrotated weight; the rotation is applied to the activation (givens_dense_quant), whose
|
||||
* tables are separate weight operands. This only checks that the tables are present and are the
|
||||
* rotation the quantiser applies; any other transform would decode to other numbers. */
|
||||
bool mx_paro_enc(const RadEncoding* e, long long K) {
|
||||
if (!e || !rad_enc_is(e, "affine") || std::strncmp(e->transform, "givens", RAD_ENC_STR) != 0) return false;
|
||||
if (e->n_planes < 5 || !rad_enc_valid(e)) return false;
|
||||
@@ -878,7 +854,7 @@ bool mx_paro_enc(const RadEncoding* e, long long K) {
|
||||
if (p < 0 || an < 0 || sc < 0) return false;
|
||||
if (e->plane[p].dtype != RAD_I32 || e->plane[an].dtype != RAD_F32 || e->plane[sc].dtype != RAD_F32)
|
||||
return false;
|
||||
// the quantiser rotates whole groups of 128 columns, one scale per group
|
||||
/* The quantiser rotates whole groups of 128 columns, one scale per group. */
|
||||
return K % 128 == 0 && e->plane[p].extent[1] == K;
|
||||
}
|
||||
|
||||
@@ -956,11 +932,10 @@ extern "C" int r4d_rad_relayout_mxfp4(const RadParam* p, int n_p, int operand,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- the MoE experts. Their weight is staged through LDS, so it is not permuted: the int4 plane
|
||||
* is the canonical one with each dword's nibbles reordered for the expansion (byte b holds element
|
||||
* b low and element b+4 high), and the fp8 plane is the canonical one exactly. `w4a8h` is the same
|
||||
* plane with the weight rotated by the group's Hadamard, and only an encoding that says so is
|
||||
* accepted for it. */
|
||||
/* ---- the MoE experts. The weight is staged through LDS, so it is not permuted: the int4 plane is
|
||||
* the canonical one with each dword's nibbles reordered for the expansion (byte b holds element b
|
||||
* low and element b+4 high), and the fp8 plane is the canonical one unchanged. `w4a8h` is the same
|
||||
* plane with the weight Hadamard-rotated per group, accepted only from an encoding that says so. */
|
||||
namespace {
|
||||
int moew4_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) {
|
||||
@@ -1024,12 +999,12 @@ bool moew5_table_is_kernels(const RadTensor& t) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* THE EXPANSION'S NIBBLE ORDER, two dwords a word. Canonical element 8g+i is 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 and then each half's middle nibbles
|
||||
* makes it; each step exchanges two fields, so the same steps in the other order undo it. Done
|
||||
* a nibble at a time, with the read-modify-write that implies, the same permutation costs most of
|
||||
* a Flash-Next load's CPU: every routed expert goes through it. */
|
||||
/* The expansion's nibble order, applied to a 64-bit word (two dwords). Canonical element 8g+i is
|
||||
* 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. */
|
||||
inline uint64_t moew4_bytes(uint64_t x) {
|
||||
return (x & 0xFF0000FFFF0000FFull) | ((x & 0x0000FF000000FF00ull) << 8) |
|
||||
((x >> 8) & 0x0000FF000000FF00ull);
|
||||
@@ -1039,7 +1014,7 @@ inline uint64_t moew4_nibbles(uint64_t x) {
|
||||
((x >> 4) & 0x00F000F000F000F0ull);
|
||||
}
|
||||
|
||||
/* `bytes` of codes, a multiple of four, from `s` to `d` -- forward or back. */
|
||||
/* 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) {
|
||||
@@ -1057,16 +1032,15 @@ void moew4_permute(const uint8_t* s, uint8_t* d, int64_t bytes, bool forward) {
|
||||
std::memcpy(d + i, &w, 4);
|
||||
}
|
||||
}
|
||||
/* ONE w5nl64a8h ROW BETWEEN THE CONTAINER AND THE KERNEL. Stored, a row is K five-bit codes,
|
||||
* LSB first (rad_plugin.h's packing), so every eight codes are five bytes. Served, it is the
|
||||
* codes' low nibbles in the canonical 4-bit order -- two a byte, element 2i low -- put through
|
||||
* moew4_permute as w4nla8h's are, then their high bits, one dword a 32 elements: K/2 + K/8 bytes,
|
||||
* the same count.
|
||||
/* One w5nl64a8h row between container and kernel. Stored, a row is K five-bit codes, LSB first
|
||||
* (rad_plugin.h packing), so every eight codes are five bytes. Served, it is the codes' low nibbles
|
||||
* in canonical 4-bit order (two per byte, element 2i low) put through moew4_permute as w4nla8h's
|
||||
* are, then their high bits, one dword per 32 elements: K/2 + K/8 bytes, the same count.
|
||||
*
|
||||
* THE SIGN DWORD IS TRANSPOSED for the kernel's merge: element 4m+b of a 32 -- byte b of the
|
||||
* expansion's output dword m -- is bit 7-m of byte b, so `sg << m` lines dword m's four signs up
|
||||
* on E4M3's sign bits at once (r4d_moe.hip, w5_expand). `nib` is a scratch row of K/2 bytes. */
|
||||
inline uint32_t moew5_sign_bit(int64_t j) { /* j: an element's place in its 32 */
|
||||
* The sign dword is transposed for the kernel's merge: element 4m+b of a 32 (byte b of the
|
||||
* expansion's output dword m) is bit 7-m of byte b, so `sg << m` aligns dword m's four signs with
|
||||
* E4M3's sign bits at once (r4d_moe.hip, w5_expand). `nib` is a scratch row of K/2 bytes. */
|
||||
inline uint32_t moew5_sign_bit(int64_t j) { /* j: the element's index within its 32 */
|
||||
return 8u * (uint32_t)(j & 3) + 7u - (uint32_t)(j >> 2);
|
||||
}
|
||||
void moew5_row(const uint8_t* s, uint8_t* d, int64_t K, uint8_t* nib, bool forward) {
|
||||
@@ -1131,7 +1105,7 @@ int moew4_relayout_by(MoeViewFn view, const RadParam* p, int n_p, int operand,
|
||||
if (rc == RAD_OK) rc = moew4_enc_layout(v.p, v.n, v.operand, enc, sel, pl, n, &L, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (dst_bytes != L.bytes) return RAD_E_SHAPE;
|
||||
if (v.operand == Q_BSCALE) { /* w4nl64a8h's: the second level is ours */
|
||||
if (v.operand == Q_BSCALE) { /* g64 forms: the second level is fixed */
|
||||
float s2 = 0.0f;
|
||||
std::memcpy(&s2, pdata(pl[1]), sizeof s2);
|
||||
if (s2 != kW4G64Scale) return RAD_E_DTYPE;
|
||||
@@ -1233,13 +1207,12 @@ extern "C" int r4d_rad_layout_moe_fp8_mod4(const RadParam* p, int n_p, int opera
|
||||
n, out);
|
||||
}
|
||||
|
||||
/* ---- conv2d_nhwc: PyTorch's [cout][cin][k][k] stored TAP-MAJOR, [cout][k][k][cin].
|
||||
/* ---- conv2d_nhwc: PyTorch's [cout][cin][k][k] stored tap-major, [cout][k][k][cin].
|
||||
*
|
||||
* The implicit-GEMM convolution (r4d_gen.hip) contracts over K = (tap, channel) with the channel
|
||||
* innermost, so that eight consecutive K are eight channels of one input pixel -- one 16-byte read
|
||||
* of an NHWC row. The weight's K has to run the same way, and PyTorch's runs channel-major. A
|
||||
* permutation of a bf16 plane, so the inverse is the same loop backwards. Operand 1 of
|
||||
* conv2d_nhwc; the bias is read as it is. */
|
||||
* innermost, so eight consecutive K are eight channels of one input pixel, one 16-byte read of an
|
||||
* NHWC row. The weight's K must run the same way; PyTorch's is channel-major. Operand 1 of
|
||||
* conv2d_nhwc; the bias is read as stored. */
|
||||
namespace {
|
||||
constexpr int CONV_W_OPERAND = 1;
|
||||
|
||||
|
||||
+265
-539
File diff suppressed because it is too large.
Load diff
+775
-1281
File diff suppressed because it is too large.
Load diff
+20
-25
@@ -1,10 +1,9 @@
|
||||
// Shared device-side machinery for the OCP-MXFP4 GEMMs (r4d_gemm_mxfp4a8_nt_m64, _tiled, _decode):
|
||||
// the folded-magnitude table and the eight-element unpack that reads it. One definition, because
|
||||
// the three kernels must fold every weight element to the same e4m3 byte -- a model whose step
|
||||
// crosses from one row's band into another's must not change what the weight is.
|
||||
// Shared device code for the OCP-MXFP4 GEMMs (r4d_gemm_mxfp4a8_nt_m64, _tiled, _decode): the
|
||||
// folded-magnitude table and the eight-element unpack that reads it. Shared so all three fold every
|
||||
// weight element to the same e4m3 byte, and a step crossing M bands sees the same weight.
|
||||
//
|
||||
// r4d_gemm_mxfp4a8_nt_m64.hip explains the fold: d = Wref[n] - E8M0[n][blk] is pushed into the
|
||||
// e4m3 value through this table, and 2^(Wref[n]-127) is applied once in the epilogue.
|
||||
// The fold is explained in r4d_gemm_mxfp4a8_nt_m64.hip: d = Wref[n] - E8M0[n][blk] is applied
|
||||
// through this table, and 2^(Wref[n]-127) once in the epilogue.
|
||||
#pragma once
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
@@ -12,14 +11,12 @@
|
||||
#define R4D_MXFP4_GROUP 32 // K per E8M0 exponent, fixed by the OCP MX format
|
||||
|
||||
// kMxfp4Mag[d] is the eight e2m1 magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} scaled by 2^-d, as packed
|
||||
// e4m3 bytes, low word then high word, indexed by the 3-bit magnitude through v_perm_b32.
|
||||
// Every entry is the round-to-nearest-EVEN e4m3 of that product, which is exact for d <= 8 and a
|
||||
// rounding for d >= 9 -- three entries there (d=9 mag 1.5, d=10 mag 3, d=11 mag 6) are the same
|
||||
// exact tie 1.5*2^-9 and take the even neighbour 2^-8, not the smaller one. They matter little
|
||||
// (such an element is 2.9e-3 of its row's reference), but the table is generated, not hand-rounded,
|
||||
// so it agrees with the hardware's own conversion. d >= 13 is zero: below the row's range.
|
||||
// e4m3 bytes (low word, high word), indexed by the 3-bit magnitude through v_perm_b32. Entries are
|
||||
// the round-to-nearest-even e4m3 of the product, matching the hardware conversion: exact for
|
||||
// d <= 8; for d >= 9 the ties at 1.5*2^-9 (d=9 mag 1.5, d=10 mag 3, d=11 mag 6) round to 2^-8.
|
||||
// d >= 13 is zero.
|
||||
//
|
||||
// Static: each kernel's code object carries its own copy, and no two define the same symbol.
|
||||
// Static: each kernel's code object carries its own copy.
|
||||
static __device__ __constant__ unsigned int kMxfp4Mag[16][2] = {
|
||||
{0x3c383000u, 0x4c484440u}, {0x34302800u, 0x44403c38u},
|
||||
{0x2c282000u, 0x3c383430u}, {0x24201800u, 0x34302c28u},
|
||||
@@ -31,21 +28,20 @@ static __device__ __constant__ unsigned int kMxfp4Mag[16][2] = {
|
||||
{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
|
||||
};
|
||||
|
||||
// The exponent difference a block is folded at, clamped to the table: a block above its row's
|
||||
// reference cannot occur (the reference is the row's maximum), and one 15 or more below is zero.
|
||||
// The exponent difference a block is folded at, clamped to the table. d < 0 cannot occur (the
|
||||
// reference is the row's maximum); d >= 15 is zero.
|
||||
static __device__ __forceinline__ int r4d_mxfp4_fold_d(int ref, int e8) {
|
||||
const int d = ref - e8;
|
||||
return d < 0 ? 0 : (d > 15 ? 15 : d);
|
||||
}
|
||||
|
||||
// Eight e2m1 codes (four packed bytes, element 2j in the low nibble of byte j) -> eight e4m3 bytes
|
||||
// in k order, word 0 holding elements 0..3 and word 1 elements 4..7, with the block's exponent
|
||||
// difference `d` already folded in. Splitting the nibbles gives the even and odd elements; each is
|
||||
// mapped through the table by a v_perm_b32 indexed with the 3-bit magnitude, the sign rides along
|
||||
// as bit 3 shifted into the e4m3 sign position, and two more v_perm_b32 interleave the halves.
|
||||
// in k order (word 0 = elements 0..3, word 1 = 4..7), with exponent difference `d` folded in. Even
|
||||
// and odd nibbles are each mapped through the table by a v_perm_b32 on the 3-bit magnitude, bit 3
|
||||
// is shifted into the e4m3 sign, and two more v_perm_b32 interleave the halves.
|
||||
//
|
||||
// `_t` takes the table row (t0, t1) the caller already holds -- a kernel that copies the table to
|
||||
// LDS reads it there, off the global load counter its weight and activation loads wait on.
|
||||
// `_t` takes a table row (t0, t1) the caller already holds, e.g. from an LDS copy, which keeps the
|
||||
// lookup off the global load counter the weight and activation loads wait on.
|
||||
static __device__ __forceinline__ void r4d_mxfp4_unpack8_t(unsigned int wv, unsigned int t0,
|
||||
unsigned int t1, unsigned int* lo,
|
||||
unsigned int* hi) {
|
||||
@@ -61,10 +57,9 @@ static __device__ __forceinline__ void r4d_mxfp4_unpack8(unsigned int wv, int d,
|
||||
r4d_mxfp4_unpack8_t(wv, kMxfp4Mag[d][0], kMxfp4Mag[d][1], lo, hi);
|
||||
}
|
||||
|
||||
// THE ACTIVATION SCALE A ROW'S ACCUMULATOR IS CARRIED IN, for the per-(row, 128 of K) grid: the
|
||||
// last non-zero entry of row `row` at or before block `kb`, or 1 when there is none. A block whose
|
||||
// scale is zero has zero codes and adds nothing whichever scale the sum is carried in, so it keeps
|
||||
// the previous one rather than dividing by zero.
|
||||
// The activation scale a row's accumulator is carried in, for the per-(row, 128 of K) grid: the
|
||||
// last non-zero entry of `row` at or before block `kb`, or 1 if none. A zero-scale block has zero
|
||||
// codes and contributes nothing, so it keeps the previous scale instead of dividing by zero.
|
||||
static __device__ __forceinline__ float r4d_mxfp4_carried(const float* __restrict__ row, int kb) {
|
||||
for (int j = kb; j >= 0; --j) {
|
||||
const float s = row[j];
|
||||
|
||||
+50
-73
@@ -1,36 +1,22 @@
|
||||
// r4d_ngram_ids.hip -- the hashed row ids of Qwen4-Exp's Per-Layer Embedding.
|
||||
//
|
||||
// ============================== WHAT IT COMPUTES ==============================
|
||||
//
|
||||
// mixed(k) = t0*mult[0] ^ t1*mult[1] ^ ... ^ tk*mult[k] int64, wrapping
|
||||
// ids[h] = mixed(b+1) % vocab_sizes[h] + offsets[h] h in block b
|
||||
//
|
||||
// with `heads` laid out as `ngram - 1` equal blocks, block b using the (b+2)-gram, and `t_s` the
|
||||
// token `s` positions back OR the EOS id if the shift would cross one. libref/ref_ngram.cpp holds
|
||||
// the derivation of that EOS rule -- it collapses a cummax over segment starts into "once a shift
|
||||
// falls back, every deeper one does" -- and docs/OPS.md holds the operand contract.
|
||||
// `heads` is laid out as `ngram - 1` equal blocks, block b using the (b+2)-gram, and `t_s` is the
|
||||
// token `s` positions back, or the EOS id if the shift would cross one. libref/ref_ngram.cpp
|
||||
// derives that EOS rule (a cummax over segment starts reduces to "once a shift falls back, every
|
||||
// deeper one does"); docs/OPS.md holds the operand contract.
|
||||
//
|
||||
// ============================== ONE THREAD A TOKEN, NOT A HEAD ==============================
|
||||
// One thread a token, looping its heads. A token's heads share the shifted tokens, the EOS walk
|
||||
// and the `ngram - 1` hash mixes and differ only in the modulus, so a thread per head would redo
|
||||
// that work per head, and at decode (one token) would be partial waves either way. At prefill the
|
||||
// grid is thousands of tokens; at decode the kernel is negligible beside the gather that follows.
|
||||
//
|
||||
// The obvious grid is one thread per (token, head): 16x the parallelism and every thread doing one
|
||||
// modulo. It is the wrong one. The sixteen heads of a token share the THREE shifted tokens and the
|
||||
// `ngram - 1` hash mixes -- the whole EOS walk and every multiply -- and differ only in which
|
||||
// constant they reduce against. A thread per head redoes that work sixteen times, and at decode the
|
||||
// grid is one token: sixteen threads either way, and the per-head form is sixteen partial waves
|
||||
// instead of one.
|
||||
//
|
||||
// So a thread owns a token and loops its heads. At prefill the grid is the token count, which is
|
||||
// thousands; at decode it is 1 to 8 and the kernel is a rounding error beside the 5 KB gather that
|
||||
// follows it. Neither end wants more threads.
|
||||
//
|
||||
// ============================== THE MODULO IS THE COST, AND IT IS FINE ==============================
|
||||
//
|
||||
// `mixed % vocab_sizes[h]` is a 64-bit division by a runtime value -- no reciprocal, no strength
|
||||
// reduction, ~70 cycles on this part -- sixteen per token. At decode that is ~1100 cycles for the
|
||||
// whole step's ids. Magic-number division would remove it and would mean the ARCHITECTURE computing
|
||||
// a multiplier and a shift per head at declare and passing them as a second weight; it is not worth
|
||||
// a second source of truth for sixteen divisions a token. If a model ever hashes at prefill width
|
||||
// with a hundred heads, that is the change to make.
|
||||
// `mixed % vocab_sizes[h]` is a 64-bit division by a runtime value (~70 cycles on this part),
|
||||
// sixteen per token. Magic-number division would need the architecture to compute a multiplier
|
||||
// and shift per head and pass them as a second weight; not worth it at this head count, but the
|
||||
// change to make if a model hashes at prefill width with many more heads.
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
@@ -39,10 +25,9 @@
|
||||
|
||||
namespace {
|
||||
|
||||
/* THE SAME TWO OPERATIONS libref SPELLS OUT, and for the same reason: a signed overflow is UB and
|
||||
* torch's `remainder` FLOORS where C truncates. On a real checkpoint neither can fire -- the
|
||||
* multipliers are bounded so a real token's product has its sign bit clear -- but the kernel and
|
||||
* the oracle have to agree on inputs a harness draws, not only on the ones a model produces. */
|
||||
/* The same two operations libref spells out: signed overflow is UB, and torch's `remainder` floors
|
||||
* where C truncates. On a real checkpoint neither fires (the multipliers keep a real token's
|
||||
* product non-negative), but kernel and oracle must also agree on test inputs. */
|
||||
__device__ __forceinline__ long long ng_wrap_mul(long long a, long long b) {
|
||||
return (long long)((unsigned long long)a * (unsigned long long)b);
|
||||
}
|
||||
@@ -53,18 +38,15 @@ __device__ __forceinline__ long long ng_floor_mod(long long a, long long b) {
|
||||
|
||||
enum { kNgMaxShift = 8, kNgThreads = 256 };
|
||||
|
||||
/* ONE WORKGROUP A (TOKEN TILE, SEQUENCE), AND THE WINDOW WRITE-BACK IS IN IT.
|
||||
/* One workgroup per (token tile, sequence), with the window write-back in the same launch.
|
||||
*
|
||||
* `s` is blockIdx.y, so the sequence scan is gone and so is the second launch. What makes the
|
||||
* fold legal is WHICH THREADS READ THE WINDOW: only a token with `t - bos < ctx` reaches back
|
||||
* past its own sequence's first row, and those are the first `ctx` tokens, which live in tile
|
||||
* ZERO. So tile 0's block is the only reader of state[slot], its threads are ordered against each
|
||||
* other by __syncthreads(), and thread 0 writes the new window after that barrier. No other block
|
||||
* touches those bytes and no grid-wide barrier is needed.
|
||||
* `s` is blockIdx.y. The fold is legal because only a token with `t - bos < ctx` reads past its
|
||||
* sequence's first row into the window, and those are the first `ctx` tokens, all in tile 0. So
|
||||
* tile 0's block is the only reader of state[slot]; its threads are ordered by __syncthreads(), and
|
||||
* thread 0 writes the new window after it. No other block touches those bytes.
|
||||
*
|
||||
* AT DECODE THIS OP IS NOTHING BUT LAUNCHES: its cost is flat from M=1 to M=512, which is the
|
||||
* dispatches and none of the work. Folding the write-back into the same launch, rather than
|
||||
* taking a second one for it, is therefore most of what the op costs. */
|
||||
* 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,
|
||||
@@ -79,8 +61,8 @@ __global__ __launch_bounds__(kNgThreads) void ngram_ids_kernel(
|
||||
const uint32_t bos = (uint32_t)cu[s];
|
||||
const uint32_t eot = (uint32_t)cu[s + 1];
|
||||
const uint32_t ctx = ngram - 1u;
|
||||
/* UNIFORM EXITS ONLY before the barrier below: an empty sequence and a negative slot are
|
||||
* properties of the block, not of the thread, so every thread of the block leaves together. */
|
||||
/* Only block-uniform exits before the barrier below: an empty sequence and a negative slot are
|
||||
* properties of the block, so all its threads leave together. */
|
||||
if (eot <= bos) return;
|
||||
const int32_t slot = sidx ? sidx[s] : (int32_t)s;
|
||||
if (slot < 0) return;
|
||||
@@ -90,21 +72,20 @@ __global__ __launch_bounds__(kNgThreads) void ngram_ids_kernel(
|
||||
const long long o = nacc ? (long long)nacc[s] - 1 : 0;
|
||||
const uint32_t lt = blockIdx.x * kNgThreads + threadIdx.x; /* this thread's row, in-sequence */
|
||||
|
||||
/* THE PROMPT THAT FOLLOWS continues the LAST sequence: its tokens sit in `tok` right after
|
||||
* the step's, so a row past the sequence's end hashes exactly as that row will when the next
|
||||
* step runs it -- same history, same EOS rule -- and lands in `ahead` instead of `ids`. The
|
||||
* window below is the step's own and never sees them. */
|
||||
/* The following prompt continues the last sequence: its tokens sit in `tok` after the step's,
|
||||
* so a row past the sequence's end hashes exactly as it will when the next step runs it, and
|
||||
* lands in `ahead` instead of `ids`. The window below is the step's own and never sees them. */
|
||||
const uint32_t reach = slen + ((ahead && s + 1u == gridDim.y) ? n_ahead : 0u);
|
||||
if (lt < reach) {
|
||||
const uint32_t t = bos + lt;
|
||||
/* The `ctx` committed ids in front of this sequence's first row. A COLD slot's window is
|
||||
* EOS and not what the slot last held -- and not zero, which is a real token id. */
|
||||
/* The `ctx` committed ids before this sequence's first row. A cold slot's window is EOS,
|
||||
* not its stale contents and not zero (a real token id). */
|
||||
long long prev[kNgMaxShift];
|
||||
for (uint32_t i = 0; i < ctx; ++i)
|
||||
prev[i] = warm ? (long long)state[(long long)slot * W + o + i] : eos;
|
||||
|
||||
/* The shifted tokens. `p` indexes the history `prev ++ this sequence's rows`, so row `lt`
|
||||
* sits at `ctx + lt` and every shift is in range without a bounds test. */
|
||||
/* `p` indexes the history `prev ++ this sequence's rows`, so row `lt` sits at `ctx + lt`
|
||||
* and every shift is in range without a bounds test. */
|
||||
const uint32_t p = ctx + lt;
|
||||
long long sh[kNgMaxShift];
|
||||
sh[0] = (long long)tok[t];
|
||||
@@ -116,7 +97,7 @@ __global__ __launch_bounds__(kNgThreads) void ngram_ids_kernel(
|
||||
}
|
||||
|
||||
/* One mix per n-gram order, extended in place: the (b+2)-gram's mix is the (b+1)-gram's
|
||||
* XOR'd with one more term, which is the reference's own inner loop. */
|
||||
* XOR one more term, as in the reference's inner loop. */
|
||||
long long mixed = 0;
|
||||
int blk = -1;
|
||||
for (uint32_t k = 0; k < ngram; ++k) {
|
||||
@@ -133,20 +114,20 @@ __global__ __launch_bounds__(kNgThreads) void ngram_ids_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
/* THE WINDOW THIS STEP LEAVES BEHIND, in libref/ref_ngram.cpp's two layouts.
|
||||
/* The window this step leaves, in libref/ref_ngram.cpp's two layouts.
|
||||
*
|
||||
* WITH `num_accepted` the step is a decode step whose drafts a verify may reject, so the
|
||||
* window is shifted down by one and EVERY id of the step follows it: slot i holds position
|
||||
* i + 1 of (window read ++ step). A next step that kept k of these ids reads at k - 1 and
|
||||
* finds the `ctx` ids ending at the k-th. Slot i is read from o + i + 1, which is past every
|
||||
* slot already written, so the ascending walk is safe in place. Slots past W are not written;
|
||||
* the manager sizes the window ctx + n_spec, which covers a step of 1 + n_spec ids.
|
||||
* With `num_accepted` this is a decode step whose drafts a verify may reject: the window shifts
|
||||
* down by one and every id of the step follows it, so slot i holds position i + 1 of
|
||||
* (window read ++ step). A next step that kept k of these ids reads at k - 1 and finds the
|
||||
* `ctx` ids ending at the k-th. Slot i is read from o + i + 1, past every slot already written,
|
||||
* so the ascending walk is safe in place. Slots past W are not written; the manager sizes the
|
||||
* window ctx + n_spec, enough for a step of 1 + n_spec ids.
|
||||
*
|
||||
* WITHOUT it every id commits and the last `ctx` land at offset zero.
|
||||
* Without it every id commits and the last `ctx` land at offset zero.
|
||||
*
|
||||
* ONE THREAD, not one per slot: a thread per (sequence, k) races within the sequence -- at
|
||||
* ctx = 2 and slen = 1, thread 0 reads slot o+1 while thread 1 writes slot 1 -- and at decode
|
||||
* the serial form is a loop of ctx - 1 + slen stores, so removing the class costs nothing. */
|
||||
* One thread, not one per slot: a thread per (sequence, k) races within the sequence (at
|
||||
* ctx = 2 and slen = 1, thread 0 reads slot o+1 while thread 1 writes slot 1), and at decode
|
||||
* the serial loop is only ctx - 1 + slen stores. */
|
||||
__syncthreads();
|
||||
if (blockIdx.x != 0 || threadIdx.x != 0) return;
|
||||
int32_t* const win = state + (long long)slot * W;
|
||||
@@ -170,7 +151,7 @@ __global__ __launch_bounds__(kNgThreads) void ngram_ids_kernel(
|
||||
enum { NG_TOK = 0, NG_STATE, NG_CU, NG_MULT, NG_VSZ, NG_OFF, NG_CIDX, NG_HINIT, NG_NACC, NG_IDS,
|
||||
NG_AHEAD };
|
||||
|
||||
static int ngram_ids_body(const RadArgs* a, const R4dSink& sk) {
|
||||
extern "C" int r4d_rad_ngram_ids(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* tok = r4d_opt(a, NG_TOK);
|
||||
const RadTensor* st = r4d_opt(a, NG_STATE);
|
||||
const RadTensor* cu = r4d_opt(a, NG_CU);
|
||||
@@ -202,8 +183,8 @@ static int ngram_ids_body(const RadArgs* a, const R4dSink& sk) {
|
||||
long long rows = 0;
|
||||
const long long ids_ld = r4d_rows_pitch(ids, heads, &rows);
|
||||
if (ids_ld < 0 || rows <= 0) return R4D_NO(RAD_E_STRIDE);
|
||||
/* THE ROW COUNT COMES FROM THE OPERAND. `M` is RANGED, so the value in the args is the band's
|
||||
* upper bound and a grid sized by it walks off the arena. */
|
||||
/* The row count comes from the operand: `M` is ranged, so the arg holds the band's upper bound
|
||||
* and a grid sized by it would run off the arena. */
|
||||
const long long T = rows;
|
||||
/* The prompt that follows: `ahead`'s rows, whose tokens `tok` holds after the step's. */
|
||||
long long A = 0, ahead_ld = heads;
|
||||
@@ -221,12 +202,11 @@ static int ngram_ids_body(const RadArgs* a, const R4dSink& sk) {
|
||||
const long long W = st->rank >= 2 ? r4d_dim(st, (int)st->rank - 1) : ctx;
|
||||
if (W < ctx) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* (token tiles, sequences). The tile count is taken from the batch's TOTAL token count,
|
||||
* which is an upper bound on any one sequence's -- a short sequence in a mixed batch launches
|
||||
* a few blocks that find their rows past its end, and the waste is bounded by the sequence
|
||||
* count. Reading a per-sequence tile count would mean reading `cu` on the host. */
|
||||
/* (token tiles, sequences). Tiles are sized by the batch's total token count, an upper bound on
|
||||
* 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(sk, ngram_ids_kernel, dim3(tiles, (uint32_t)N), dim3(kNgThreads), 0,
|
||||
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),
|
||||
@@ -238,6 +218,3 @@ static int ngram_ids_body(const RadArgs* a, const R4dSink& sk) {
|
||||
A > 0 ? (int32_t*)r4d_addr(ahd) : nullptr, (uint32_t)A,
|
||||
(uint32_t)ahead_ld);
|
||||
}
|
||||
|
||||
/* ABI v10: the launch and its description, from the body above. */
|
||||
R4D_ENTRY(r4d_rad_ngram_ids, ngram_ids_body)
|
||||
Loaded 100 of 739 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user