Archived
radiance 1.15.0
New models and formats: - IQR for Qwen3.8-27B: weights on the int8 grid under GPTQ, a trellis down each GPTQ column (IQR-V2), and IQR-V3, a computed trellis code under one scale a row, kept at its codes' width in VRAM and decoded in the GEMM; 15 IQR-V3 recipes from ~2 to ~7 bits a weight (data/recipes/q38-27b-*-v3.recipe, docs/IQR.md) - libhalo: a kernel library for Strix Halo (gfx1151), preferred there over libr3d - Nemotron 3.5 Embed 1B and 8B (nemotron35_embed): text and image embeddings through a Pixtral tower, on the card and on the CPU - Nemotron 3.5 Rerank 8B - /v1/systemone: Cloudflare's clef and clef-flash, Convai Innovations' Laya and Mica beside LiquidAI d1; scored steps read the candidates' logits from the head table with no lm_head pass - LFM2's 8-bit trunk: block-fp8 or int8 linears with the fused producers, and the d1-3B recipe - DeepSeek-V4.1's reply format with DSML tool calls and typed argument tags Weights on the drive: - The file tier reads only the experts the pass routes rows to; the draft head's weights stay in the host pool - A hot VRAM cache for routed experts read off the drive, reads deposited straight into free host pool slots, and copyless evictions; the file tier's counters are now ssd_* - GLM-5 Next shards its routed experts by expert, not by width, so they can live on the drive - The stall watch counts drive reads as progress, and the DMA lane's room check reads the lane's own completion fence Quantisation tooling: - --calib-corpus, --calib-dir and --calib-layers record each linear's input Hessian; beside --kld-record the reference's own run records them - --kld-top N records a sparse KL reference (the N most likely tokens and the tail's mass) - GPTQ in a third of the time with the same codes, trellis GPTQ on the card, vector codebooks with coordinate descent, and rad-convert --reuse repeated, each container supplying what the earlier ones lack Speculation: - Prompt lookup alone (--spec-ngram K, --spec-ngram-min/-max): each sequence keeps an index of its n-grams, and a proposal is verified only when its measured step cost says it pays; --draft-window adaptive follows it Speed: - IQR decode: the narrow tile splits K for four times the int8 tile's waves and folds each 128-K block once; at 8 tokens down and the output projections run in 0.61-0.82x and 0.70-0.92x FP8's time (2-6 bits); IQ6R-S-V3 with its DFlash2 drafter steps in 26.3 ms at TP2, against 29.4 ms before and FP8's 27.3 - Qwen MXFP4 feed-forward: the gated fold up to 16 rows, not 8 - libr4d: the gated prefill fold, the short-prompt split row, and the rows forms of rmsnorm and rope; KLATE again for the head-256 gqa6 paged prefill; gram_accum on the matrix cores Features: - /health, /v1/health and /ping answer 503 with "status": "stuck" once the device has advanced nothing for a minute or a queue has faulted, so a supervisor can restart a wedged server (#356) - --image-gen-max-pixels and --image-gen-max-refs size an image generator's buffers (#344) - The startup report lists only the options not at their default, with a count; -v lists all (#250) - --preempt-wait-ms bounds how long a preempted prefill waits for its whole-recompute room - --placement layer_offload spills dense layers so one --max-model-len sequence fits - Startup refuses amdgpu with CWSR off and says how to fix it; --proceed-with-incompatible-configuration starts anyway under an UNSUPPORTED banner Fixes: - The n-gram read-ahead hands each row to the reader once and reads only as far ahead as the row cache holds, and pauses while decode reads: about one drive read a row instead of two (#355) - A file-tier window reads each of its runs once, not once a run per run - The decode split law's verify floor is bounded by the batch's workgroups: max_seqs 256 no longer declares 64x the scratch (#342) - A prefetch DMA list's mark stays out of the signal pool until the engine has read it, and a prefill stage copies only the blocks its own tables name (#343) - The split-KV row sum is read with fetch-inactive (#328) - LFM2 on the host backend: libref and libavx serve the row-form ops it declares (#348) - The preempted-prefill gate skips a KV group that holds no blocks (#352) - Every request entry point bounded, gated and sanitised (JSON depth, invalid UTF-8, control bytes in the log, the dashboard's CSP, cross-origin browsers on the loopback-only routes); a prompt id outside the vocabulary refused at admission; --api-key "" refused at startup - The telemetry the HTTP thread reads is atomic - An RMS norm row no longer depends on how many rows its launch carries; prefill attention's rescale is decided by live rows only - A --kld-record prefill chunk that finishes no sequence gets its logits on a tied-head model - A kernel's lazily made counter block is zeroed outside the lock other ranks take (a TP2 first-step hang) Changes: Plugin ABI 32. Every plugin exports a layout fingerprint of the ABI structs and the loader refuses a plugin without it or with another (#302), so out-of-tree plugins must be rebuilt. Appended: RadBuildCtx calib_* and gen_max_*, RadArchProbe gen_max_*, RadBatch score_only and plugin_words, RadDeviceProps::unified, RadChatFormat arg_json_value_prefix.
This commit is contained in:
commit
9ed3ef7a7b
452 files changed
+167762
-1346
No files matched your search
@@ -0,0 +1,211 @@
|
||||
# libhalo serves Strix Halo (gfx1151, RDNA 3.5) only, declared here and nowhere else. Its kernels
|
||||
# rely on wave32, the gfx11 WMMA fragment layouts and unified memory; built for other targets they
|
||||
# would compute garbage.
|
||||
#
|
||||
# A build targeting other cards skips libhalo. 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.
|
||||
#
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S libhalo -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`, naming the HIP compiler as for
|
||||
# the tree); see cmake/RadAddPlugin.cmake.
|
||||
#
|
||||
# Declaration (schemas, rows, layouts) is shared with libr4d by design -- see libhalo/README.md.
|
||||
# Kernel units land family by family in HALO_UNITS; until one does, halo_stubs.cpp answers its rows
|
||||
# with RAD_E_UNSUPPORTED so the library loads and the gap is reported by name.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(libhalo LANGUAGES CXX HIP)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_plugin_gpu_targets(HALO_GPU_TARGETS "^gfx1151$")
|
||||
if(NOT HALO_GPU_TARGETS)
|
||||
message(STATUS
|
||||
"libhalo: Strix Halo (gfx1151) only, and this build targets ${RAD_GPU_TARGETS} -- not built")
|
||||
return()
|
||||
endif()
|
||||
|
||||
# HALO_UNITS is generated: libhalo/gen_stubs.py writes the list below from the halo_*.hip files
|
||||
# present (each "unit|extra flags", mirroring libr4d's R4D_UNITS), so add a unit by adding its
|
||||
# .hip, not by editing the list. Every unit compiles -ffp-contract=off (rad_hipify): the
|
||||
# quantised all-reduce requires it, for the reason libr4d/CMakeLists.txt gives.
|
||||
set(HALO_UNITS
|
||||
"halo_ar_entry|"
|
||||
"halo_ar_gather_2rank|"
|
||||
"halo_ar_gather_Nrank|"
|
||||
"halo_ar_ln_had_quant_i8|"
|
||||
"halo_ar_oneshot_2rank_exact|"
|
||||
"halo_ar_oneshot_2rank_wht6|"
|
||||
"halo_ar_oneshot_Nrank_exact|"
|
||||
"halo_ar_twoshot_Nrank_exact|"
|
||||
"halo_ar_twoshot_Nrank_ti8|"
|
||||
"halo_attn_dense_bf16|"
|
||||
"halo_attn_gen|"
|
||||
"halo_attn_paged_gqa8|"
|
||||
"halo_attn_paged_h128_gqa1|"
|
||||
"halo_attn_paged_h128_gqa2|"
|
||||
"halo_attn_paged_h128_gqa2w|"
|
||||
"halo_attn_paged_h128_gqa4|"
|
||||
"halo_attn_paged_h256_gqa12|"
|
||||
"halo_attn_paged_h256_gqa2|"
|
||||
"halo_attn_paged_h256_gqa4|"
|
||||
"halo_attn_paged_h256_gqa6|"
|
||||
"halo_attn_paged_h256_gqa6_bs4|"
|
||||
"halo_attn_paged_window|"
|
||||
"halo_attn_vit_h72_bf16|"
|
||||
"halo_audio|"
|
||||
"halo_conv2d_nhwc|"
|
||||
"halo_conv_t1d|"
|
||||
"halo_dequant_w4_bf16|"
|
||||
"halo_dflash_conv_t2_g16_bf16|"
|
||||
"halo_dflash_select_bf16|"
|
||||
"halo_dsa|"
|
||||
"halo_encoder_bf16|"
|
||||
"halo_expert_scale_bf16|"
|
||||
"halo_fused_quant_fp8|"
|
||||
"halo_gated_had_quant_i8|"
|
||||
"halo_gdn_chunk_scan|"
|
||||
"halo_gdn_conv_w4_h128_bf16|"
|
||||
"halo_gdn_gated_norm_had_quant_i8|"
|
||||
"halo_gdn_gated_rmsnorm_h128_bf16|"
|
||||
"halo_gdn_kkt_solve|"
|
||||
"halo_gdn_recurrent_update_k128_v128_bf16_fp32state|"
|
||||
"halo_gelu_mul_quant_i8|"
|
||||
"halo_gemm_bf16_nt_m16|"
|
||||
"halo_gemm_bf16_nt_m64|"
|
||||
"halo_gemm_bf16_nt_tiled|"
|
||||
"halo_gemm_f32_nt_bias|"
|
||||
"halo_gemm_fp8_f32scale|"
|
||||
"halo_gemm_fp8a16_m1|"
|
||||
"halo_gemm_fp8a8|"
|
||||
"halo_gemm_mxfp4a8_decode|"
|
||||
"halo_gemm_mxfp4a8_gated|"
|
||||
"halo_gemm_mxfp4a8_gemv|"
|
||||
"halo_gemm_mxfp4a8_nt_m64|"
|
||||
"halo_gemm_mxfp4a8_tiled|"
|
||||
"halo_gemm_nt_bias|"
|
||||
"halo_gemm_nt_f32|"
|
||||
"halo_gemm_w2a8_nt|"
|
||||
"halo_gemm_w4a16_nt_m64|"
|
||||
"halo_gemm_w4a8_nt_m64|"
|
||||
"halo_gemm_w4a8_tiled|"
|
||||
"halo_gemm_w5a16_nt_m64|"
|
||||
"halo_gemm_w8a16_nt_m64|"
|
||||
"halo_gemm_w8a8_nt_m64|"
|
||||
"halo_gemm_w8a8_tiled|"
|
||||
"halo_gemm_wpa8i8_tiled|"
|
||||
"halo_gen|"
|
||||
"halo_givens_dense|"
|
||||
"halo_givens_rotate|"
|
||||
"halo_glm|"
|
||||
"halo_gram_accum_fp8|"
|
||||
"halo_had_quant_act_i8|"
|
||||
"halo_hc_bf16|"
|
||||
"halo_hc_read|"
|
||||
"halo_kda|"
|
||||
"halo_kv_len_trim|"
|
||||
"halo_kv_resolve|"
|
||||
"halo_logits_gemm|"
|
||||
"halo_lora_bf16|"
|
||||
"halo_ltx|"
|
||||
"halo_mhc|"
|
||||
"halo_mla|"
|
||||
"halo_model_bf16|"
|
||||
"halo_moe|"
|
||||
"halo_moe_gemm_bf16|"
|
||||
"halo_moe_gemm_q|"
|
||||
"halo_moe_mxfp4|"
|
||||
"halo_mtp_enter|"
|
||||
"halo_ngram_ids|"
|
||||
"halo_norm_join_bf16|"
|
||||
"halo_p2p_copy2d|"
|
||||
"halo_pair_argmax_f32|"
|
||||
"halo_ple_conv_bf16|"
|
||||
"halo_ple_gate_bf16|"
|
||||
"halo_prefetch|"
|
||||
"halo_qk_norm_rope_gate|"
|
||||
"halo_qkv_norm_rope|"
|
||||
"halo_qsa_block_key_bf16|"
|
||||
"halo_qsa_score_bf16|"
|
||||
"halo_qsa_select_bf16|"
|
||||
"halo_qsa_tail_store_bf16|"
|
||||
"halo_qsa_work_bf16|"
|
||||
"halo_quant_act_fp8|"
|
||||
"halo_quant_act_i8|"
|
||||
"halo_rmsnorm_had_quant_i8|"
|
||||
"halo_rmsnorm_quant_i8|"
|
||||
"halo_router_gemm_scatter|"
|
||||
"halo_router_scatter|"
|
||||
"halo_router_sigmoid_topk_f32|"
|
||||
"halo_router_topk_bf16|"
|
||||
"halo_rowtopk_bf16|"
|
||||
"halo_sam_attn_bf16|"
|
||||
"halo_sample_chain_f32|"
|
||||
"halo_sample_ngram_f32|"
|
||||
"halo_sample_stages_f32|"
|
||||
"halo_scale_rows_bf16|"
|
||||
"halo_upscaler|"
|
||||
"halo_video|"
|
||||
"halo_vit_norm_embed|"
|
||||
"halo_vsa|"
|
||||
)
|
||||
|
||||
set(HALO_SRC "")
|
||||
foreach(u ${HALO_UNITS})
|
||||
string(REPLACE "|" ";" parts "${u}")
|
||||
list(GET parts 0 unit)
|
||||
list(LENGTH parts n)
|
||||
set(extra "")
|
||||
if(n GREATER 1)
|
||||
list(GET parts 1 extra)
|
||||
endif()
|
||||
set(src "${CMAKE_CURRENT_SOURCE_DIR}/${unit}.hip")
|
||||
if(NOT EXISTS "${src}")
|
||||
message(FATAL_ERROR "libhalo unit ${unit}.hip is missing from ${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
endif()
|
||||
if(extra)
|
||||
set_source_files_properties("${src}" PROPERTIES COMPILE_OPTIONS "${extra}")
|
||||
endif()
|
||||
list(APPEND HALO_SRC "${src}")
|
||||
endforeach()
|
||||
|
||||
# The host sources are declaration only: the row table, weight layouts and relayouts, operand
|
||||
# descriptions and fusion claims, plus the generated stubs for units not yet ported. They are pure
|
||||
# host C++ that includes neither halo.h nor hip_runtime.h, so these tables compile and can be
|
||||
# inspected without ROCm.
|
||||
set(HALO_DECLARATION halo_rows.cpp halo_layout.cpp halo_fp8_layout.cpp halo_shapes.cpp halo_fuse.cpp
|
||||
halo_stubs.cpp)
|
||||
|
||||
rad_add_plugin(libhalo kernels
|
||||
SOURCES ${HALO_DECLARATION}
|
||||
HIP_SOURCES ${HALO_SRC}
|
||||
GPU_TARGETS ${HALO_GPU_TARGETS}
|
||||
INCLUDES ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
# 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. Derived from libr4d's r4d_selftest.cpp (row
|
||||
# names are shared, so its cases address libhalo's rows); it dlopens the plugin so an undefined
|
||||
# symbol in the .so is caught too.
|
||||
add_executable(halo_selftest ${CMAKE_CURRENT_SOURCE_DIR}/halo_selftest.cpp)
|
||||
# Links the HIP runtime to allocate the device buffers it feeds the kernels.
|
||||
target_link_libraries(halo_selftest PRIVATE radiance::abi ${CMAKE_DL_LIBS} ${RAD_HIP_RUNTIME})
|
||||
target_include_directories(halo_selftest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
set_target_properties(halo_selftest PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
install(TARGETS halo_selftest RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
|
||||
# Interface parity with libr4d (halo_parity.cpp): schemas, rows, constraints, tunables and the
|
||||
# concurrency/collective promises, compared table against table. Only a build that produces both
|
||||
# plugins (RAD_GPU_TARGETS naming a gfx12 part and gfx1151) can run it; tests/CMakeLists.txt adds
|
||||
# the test then.
|
||||
if(TARGET libr4d)
|
||||
add_executable(halo_parity ${CMAKE_CURRENT_SOURCE_DIR}/halo_parity.cpp)
|
||||
target_link_libraries(halo_parity PRIVATE radiance::abi ${CMAKE_DL_LIBS})
|
||||
set_target_properties(halo_parity PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
endif()
|
||||
|
||||
# C++17 for the same reason as libr4d: kernel cost figures are for C++17, and the ported units are
|
||||
# written against it.
|
||||
set_target_properties(libhalo PROPERTIES HIP_STANDARD 17 HIP_STANDARD_REQUIRED ON)
|
||||
@@ -0,0 +1,150 @@
|
||||
# Porting a unit from libr4d to libhalo (gfx1151)
|
||||
|
||||
`libhalo` is radiance's kernel library for Strix Halo (gfx1151, RDNA 3.5, the Radeon 8060S in the
|
||||
Ryzen AI Max+ 395): HIP kernels behind the plain C ABI `halo.h`, plus the plugin rows the engine
|
||||
selects from (`halo_rows.cpp`), loaded as `radiance_home/kernels/libhalo.so`.
|
||||
|
||||
`libr4d/` in the same tree is the **shipped** library for gfx1201 (RDNA4, R9700) and is the source
|
||||
every unit is ported *from*. Shared by design and never to be changed by a port: op schemas, row
|
||||
names, parameter keys, layout tags and the stored weight bytes (`libhalo/README.md` §"What is
|
||||
shared"). Everything measured is libhalo's own and must be re-measured here: priorities,
|
||||
constraint bands, tunable defaults, launch geometry, kernel bodies. The shape of the part drives
|
||||
most of it: ~256 GB/s of LPDDR5X shared with the CPU, 40 CUs, wave32, unified memory.
|
||||
|
||||
Entry points come in two flavours and both must exist before a row can select a unit:
|
||||
`halo_rad_<row>(const RadArgs*, RadStream)` shims declared in `halo_plugin.h` (the row table takes
|
||||
their addresses) and the plain C entries of `halo.h` the engine dlsyms. Unimplemented ones are
|
||||
weak stubs in `halo_stubs.cpp` returning `RAD_E_UNSUPPORTED` (-18); see §5.
|
||||
|
||||
## 1. Start a unit: the rename transform (one command)
|
||||
|
||||
```sh
|
||||
# from the repository root. u = the libr4d unit's name without the r4d_ prefix.
|
||||
u=attn_paged_gqa8
|
||||
sed -e 's/libr4d/libhalo/g' -e 's/r4dchain/halo_r4dchain/g' \
|
||||
-e 's/R4D_/HALO_/g' -e 's/R4d/Halo/g' -e 's/R4D/Halo/g' \
|
||||
-e 's/r4d_/halo_/g' -e 's/"r4d\.h"/"halo.h"/g' \
|
||||
-e 's/__builtin_amdgcn_cvt_pk_fp8_f32/halo_fp8::cvt_pk_fp8_f32/g' \
|
||||
libr4d/r4d_$u.hip > libhalo/halo_$u.hip
|
||||
grep -nE '\br4d\b|R4d|R4D' libhalo/halo_$u.hip # leftovers must all be inside message strings
|
||||
```
|
||||
|
||||
Order matters: `libr4d` and `r4dchain` first, then `R4D_` before `R4D`, then `r4d_`. A chained
|
||||
kernel keeps `r4dchain` inside its name (`halo_r4dchain_rmsnorm`): it is the ABI's marker, not a
|
||||
library prefix -- the AQL backend gives a chain record only to a kernel whose name contains it
|
||||
(`core/device/aql.cpp`, RadKernelChainFn in `abi/rad_abi.h`), so a chained form renamed to
|
||||
`halochain_*` would silently run unchained. Quoted
|
||||
includes (`#include "r4d_dt16.h"`) are renamed by the `r4d_` rule; the bare `"r4d.h"` needs its
|
||||
own rule, which is why it is listed. The remaining `r4d` spellings are error-message strings; the
|
||||
ported units keep them (`halo_dequant_w4_bf16.hip` says `"r4d dequant_w4_bf16: ..."`) — just make
|
||||
sure no *identifier* was missed. Replace the file's leading comment with the two lines every ported
|
||||
unit carries:
|
||||
|
||||
```
|
||||
/* Derived from libr4d/r4d_<unit>.hip by the libhalo rename transform (<date>),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
```
|
||||
|
||||
A rename is not a port: the file now compiles for gfx1151 or it does not, and either way it has
|
||||
not been checked. §2-§4 are the actual work.
|
||||
|
||||
## 2. gfx1151 fragment rules: `libhalo/halo_dt16.h` states them
|
||||
|
||||
Read the header comment of `libhalo/halo_dt16.h` before touching an attention body; it is the whole
|
||||
story, summarised here so you know what to look for:
|
||||
|
||||
| | a lane's A/B fragment | the k its element `e` holds |
|
||||
|---|---|---|
|
||||
| gfx1201 | 8 x 16-bit (4 dwords) | `k = 8*(lane>>4) + e` |
|
||||
| gfx1151 | 16 x 16-bit (8 dwords) | `k = e` (lanes 16-31 replicate) |
|
||||
|
||||
libr4d's attention kernels keep the score matrix transposed (`S^T = K.Q^T`) so the D column — the
|
||||
query — stays on `lane & 15` on **both** architectures; that is why they port at all. What changes
|
||||
is the accumulator's ROW: element `e` is key `8*(lane>>4) + e` on gfx12, key `2*e + (lane>>4)` on
|
||||
gfx1151. Both spread the tile's sixteen keys over the half-pair, so the kernels' existing
|
||||
`swap16` (`lane ^ 16`) row-max / row-sum reductions keep their meaning: a port changes the *key
|
||||
index* and the *fragment width*, never the softmax algebra. Per body that means
|
||||
|
||||
- `mk()` takes the lane's **eight** dwords (16 values), not four;
|
||||
- the fragment gather reads **32 bytes** at the un-split k offset (drop libr4d's `+ 8*h` term) and
|
||||
masks on key `2*e + (lane>>4)`;
|
||||
- the P fragment is assembled across the half-pair (`p16w`): a lane holds one parity, keys
|
||||
`2*e + (lane>>4)`;
|
||||
- the store scatters at head dim `2*e + (lane>>4)`, not at a contiguous run.
|
||||
|
||||
`halo_wmma.h` has the measured WMMA layouts and `halo::mma`; `halo_fp8_wmma.h` has `e4m3_pk` (an
|
||||
exact e4m3 widen) and `cvt_pk_fp8_f32`. gfx1151 has **no** fp8 convert instruction
|
||||
(`v_cvt_pk_fp8_f32`), **no** `v_cvt_pk_bf16_f32` (use `halo::pk_bf16`, software RTNE) and **no**
|
||||
`global_load_tr_b128` (the shuffle transpose in `halo_common.h` stands in). fp8 KV forms therefore
|
||||
take `halo_fp8::e4m3_pk`; bf16/f16 forms take `halo::mma` and `DT16<0>` / `DT16<1>`.
|
||||
|
||||
## 3. Wrapper units: `#define` + `#include`
|
||||
|
||||
A family body is parameterised by macros and reused by small wrapper files, as in libr4d. The
|
||||
wrapper is the translation unit (it is what `HALO_UNITS` lists and compiles); the body is text:
|
||||
|
||||
```c
|
||||
#define HALO_ATTN_GQA 1
|
||||
#define HALO_ATTN_H128 1
|
||||
#include "halo_attn_paged_gqa8.hip"
|
||||
```
|
||||
|
||||
The body builds its entry names by token pasting (`GQ_SYM(halo_rad_attn_prefill_h256_gqa, _fp8)`),
|
||||
so no text scan can see which symbols it defines. That is exactly why the stubs are weak (§5): a
|
||||
macro-built definition overrides its stub at link time with nothing to regenerate.
|
||||
|
||||
## 4. Done means numerically checked
|
||||
|
||||
A unit is done when a numeric harness says so, never because the build passes: with weak stubs a
|
||||
row whose entry is missing answers -18 and a row whose entry exists but is wrong computes garbage,
|
||||
and both leave the build green.
|
||||
|
||||
- Row smoke/numeric checks: `halo_selftest <plugin.so> --case <row>` (row names are shared with
|
||||
libr4d, so the case names are too). Add a case to `libhalo/halo_selftest.cpp` when the row has
|
||||
none — an unwritten case is a row nobody has measured.
|
||||
- A row with no case, and every kernel with a new fragment path: write a float64 reference checker
|
||||
modelled on `.../scratch/pad/attn_dense_check.cpp` — `dlopen` the `.so`, `dlsym` the C entry,
|
||||
fill small exactly-representable inputs, compute a straightforward `double` reference on the
|
||||
host, print the worst relative L2. 16-bit and fp8 paths land in the 1e-3 class; byte-identical
|
||||
contracts (see `STRIX_HALOD_RADIANCE.md` §6.3) must compare bytes, not rel_l2. Build the checker
|
||||
on the node with
|
||||
`/opt/rocm/lib/llvm/bin/clang++ -x hip --offload-arch=gfx1151 -std=c++17 -O2 check.cpp -o check`
|
||||
and run `./check <plugin.so> 3`.
|
||||
- Then `rad-kbench --kernels libhalo,libref` for the row set, and time it against the shape's
|
||||
roofline on the card (`--perfmxd`, `--perfw8`, `--perfq`, ... in `halo_selftest`).
|
||||
|
||||
## 5. Stubs and `HALO_UNITS` are generated now
|
||||
|
||||
`python3 libhalo/gen_stubs.py` rewrites `halo_stubs.cpp` and the `HALO_UNITS` list from the tree;
|
||||
`--check` fails instead of writing (use it before committing). What it derives: the entries from
|
||||
every `halo_*` declaration in `halo_plugin.h` and `halo.h` plus any line already in the file whose
|
||||
symbol neither header declares; what is implemented from definitions found in the sources
|
||||
`CMakeLists.txt` compiles; the unit list from the `halo_*.hip` files present, minus pure bodies
|
||||
(§3). So a new unit needs no edit to either file — add `libhalo/halo_<unit>.hip` and run the
|
||||
generator. Never edit `halo_stubs.cpp` or the `HALO_UNITS` list by hand, and never delete a stub
|
||||
line to "make room": every line is `__attribute__((weak))`, so your definition wins anyway.
|
||||
|
||||
## 6. Lane workflow
|
||||
|
||||
One lane = one git worktree on its own branch outside the shared tree, rsynced to one node;
|
||||
builds and selftests run **on the node**, detached, never in the shared tree. The recipe, the node
|
||||
list (node2; never node1), the per-node configure flags and the merge rules
|
||||
live in the project notebook note `halo-port-lane-workflow`; the current state of the port and
|
||||
what is already proven are in `strix-halo-libhalo-task` and `STRIX_HALOD_RADIANCE.md`.
|
||||
|
||||
## 7. Gotchas already paid for in shared code
|
||||
|
||||
- **`mx_frag16x` takes `exp` and `ref` and folds `exp - ref`**, not the e4m3 table's
|
||||
`d = ref - exp`. Passing the table's sign flips every staged weight exponent (~1e4 relative error, see
|
||||
`halo_gemm_mxfp4a8_tiled.hip`'s note and `halo_gemm_mxfp4a8_nt_m64.hip`'s `mx_frag16x`).
|
||||
- **`load_tr_b128` in `halo_common.h` was wrong** until recently: a shuffle's argument is evaluated
|
||||
at the SOURCE lane, so the dword it fetched was the wrong one. It is fixed; re-check any kernel
|
||||
that uses the transposed load and recompile any probe you copy from an older session.
|
||||
- **`core/build/` is checked-in SOURCE** — never delete it, never regenerate it, never treat it as
|
||||
build output.
|
||||
- Each unit compiles `-ffp-contract=off` (see `CMakeLists.txt`): the quantised all-reduce's byte
|
||||
contracts depend on it. Do not add fast-math or let the port re-associate a reduction.
|
||||
- Two int8 planes exist and are not interchangeable: `quant_act_i8`'s shuffled plane (the skinny
|
||||
w4a8/w8a8 GEMMs) and `quant_act_i8g`'s natural row-major plane (the i8a8 twins, `wpa8i8`).
|
||||
- fp8 `deq16_e4m3` underflows values near 2⁻¹²⁰; the `HALO_FP8_FIX` compensation applies to the
|
||||
**weight only** (both operands would underflow) — `STRIX_HALOD_RADIANCE.md` §6.3.
|
||||
@@ -0,0 +1,67 @@
|
||||
# libhalo
|
||||
|
||||
libhalo is radiance's kernel library for Strix Halo (gfx1151, RDNA 3.5, the Radeon 8060S in the
|
||||
Ryzen AI Max+ 395): specialised HIP kernels behind the same plain C ABI libr4d exposes, with
|
||||
`halo_` in place of `r4d_` ([`halo.h`](halo.h)), and the kernel-plugin rows the engine selects from
|
||||
(`halo_rows.cpp`).
|
||||
|
||||
## libhalo and libr3d
|
||||
|
||||
libr3d serves the whole RDNA3 family (`^gfx11`), gfx1151 included; libhalo serves gfx1151 only.
|
||||
Both are built when `RAD_GPU_TARGETS` names gfx1151, and on a Strix Halo libhalo is the one used:
|
||||
|
||||
- with no `--kernels` list the loader takes libraries in file-name order, so `libhalo.so` comes
|
||||
ahead of `libr3d.so`, and the first library with a row for an op supplies it (docs/PLUGIN.md).
|
||||
An op libhalo has no row for falls through to libr3d;
|
||||
- `rad_plugin_open` (`halo_rows.cpp`) declines every machine whose KFD topology lists no gfx1151,
|
||||
so on another RDNA3 card libhalo is not loaded at all and declares no schema: libr3d serves it
|
||||
alone. The loader would leave libhalo's device rows out there anyway (its code objects are
|
||||
gfx1151's); declining also keeps its schemas out.
|
||||
|
||||
An explicit `--kernels` list orders the libraries as given; name `libhalo` before `libr3d`.
|
||||
|
||||
## What is shared with libr4d, and what is not
|
||||
|
||||
Shared, by design, so one container serves both cards:
|
||||
|
||||
- the op vocabulary and schemas (the loader refuses a library whose schema for an op disagrees
|
||||
with the first declaration, so these cannot drift silently);
|
||||
- row names, so `halo_selftest` (derived from `r4d_selftest`, whose cases address rows by name)
|
||||
and `rad-kbench` check libhalo's kernels against the same cases and recordings as libr4d's;
|
||||
- stored weight layouts whose bytes do not encode a WMMA fragment order, tags included (`r4d.*`
|
||||
layout tags name arrangements, not libraries).
|
||||
|
||||
Not shared: anything measured. Priorities, constraint bands, tunable defaults, launch geometries
|
||||
and the kernel bodies themselves are libhalo's own, derived from libr4d's sources (each file says
|
||||
so) and re-measured on gfx1151. Fragment-ordered weights are stored in gfx1151's fragment order
|
||||
under `halo.*` tags: a fragment order is a statement about one architecture's WMMA lanes
|
||||
(see `halo_wmma.h`), and storing gfx1201 order would make every halo GEMM pay an in-register
|
||||
shuffle to read it. The canonical planes a container holds, the dequantised values and the
|
||||
reference outputs are identical either way (spec §4.3).
|
||||
|
||||
Two properties of the part shape everything here and are not restated per kernel:
|
||||
|
||||
- unified memory: device memory is host memory (a 120 GiB GTT pool inside the machine's RAM).
|
||||
There is no link, so "stream the weight" and "stage the weight" differ only in which copy of
|
||||
the bytes a kernel reads, and the core's unified-memory path keeps one ledger for both pools;
|
||||
- ~256 GB/s of LPDDR5X shared with the CPU, 40 CUs, wave32. Decode is a pure weight stream at
|
||||
a quarter of the R9700's bandwidth; launch geometry that fills 64 CUs idles here.
|
||||
|
||||
## Porting state
|
||||
|
||||
Kernel units land family by family in `HALO_UNITS` (`CMakeLists.txt`). Until a unit lands, its
|
||||
rows resolve to generated stubs in `halo_stubs.cpp` that return `RAD_E_UNSUPPORTED`, so the
|
||||
library loads, selection works, and the gap is reported by name at first use. The stub count is
|
||||
the parity scoreboard; done means zero. Chained launch forms (`halo_chain.h`) follow the plain
|
||||
forms per family; `rad_kernel_chain` names a row only once all of its kernels have one.
|
||||
|
||||
## Adding a kernel
|
||||
|
||||
As in libr4d: write the `.hip` named for its entry point and geometry, declare it in `halo.h`,
|
||||
add or adjust the `RadKernelInfo` row in `halo_rows.cpp`, and add a case to `halo_selftest.cpp`.
|
||||
`HALO_UNITS` and the stubs are generated: run `python3 libhalo/gen_stubs.py` after adding the
|
||||
file instead of editing either by hand (`libhalo/PORTING.md`). Stubs are weak, so there is no
|
||||
stub line to delete when a unit lands. Check numerics with `halo_selftest <path to libhalo.so>
|
||||
--case <row>` and `rad-kbench --kernels libhalo,libref`; check speed on the card, in the same
|
||||
run, against the shape's roofline. `libhalo/PORTING.md` is the porting guide: the rename
|
||||
transform, the gfx1151 fragment rules, the wrapper-file pattern and the gotchas already paid for.
|
||||
Executable
+371
@@ -0,0 +1,371 @@
|
||||
#!/usr/bin/env python3
|
||||
"""gen_stubs.py -- regenerate libhalo/halo_stubs.cpp and libhalo's HALO_UNITS.
|
||||
|
||||
python3 libhalo/gen_stubs.py # rewrite both files in place
|
||||
python3 libhalo/gen_stubs.py --check # exit 1 if either is not what this would write
|
||||
python3 libhalo/gen_stubs.py --check --verbose
|
||||
|
||||
WHAT IT DERIVES, AND FROM WHERE (nothing is guessed; every input is read from the tree)
|
||||
|
||||
* The entries that must exist: every `halo_*` function declaration in libhalo/halo_plugin.h
|
||||
(the shims the row table, the layout hooks and the fusion claims take the addresses of) and
|
||||
in libhalo/halo.h (the plain C ABI the engine dlsyms), PLUS every line already in
|
||||
halo_stubs.cpp whose symbol neither header declares -- a tuning hook a unit calls without a
|
||||
public declaration stays alive. So the stub set never shrinks by accident.
|
||||
* What is already implemented: a *definition* of that symbol -- a declaration whose parameter
|
||||
list is followed by `{` -- in a source the build compiles, i.e. the HALO_UNITS device units
|
||||
and the HALO_DECLARATION host sources listed in libhalo/CMakeLists.txt. A comment or a call
|
||||
mentioning the name does not count, and a file the build does not compile does not count
|
||||
(its symbol must stay stubbed, or the shared object would come out with an undefined entry).
|
||||
* HALO_UNITS: every libhalo/halo_*.hip present, minus the pure bodies -- a file another file
|
||||
`#include`s as text and that defines no `extern "C"` entry point of its own (the
|
||||
`#define`+`#include` wrapper pattern: the wrapper is the unit, the body is not). A file that
|
||||
is both included and defines its own entries (libr4d's r4d_attn_paged_gqa8.hip is the
|
||||
precedent) stays a unit. Per-unit extra flags already in CMakeLists.txt are preserved.
|
||||
|
||||
WHY `__attribute__((weak))`
|
||||
|
||||
A stub is a weak definition, so a real definition of the same symbol in any unit -- including one
|
||||
written via a token-pasting macro, which this script cannot see -- wins at link time without
|
||||
touching this file. Consequence: an entry's stub line does NOT have to be deleted when its unit
|
||||
lands. Two runs over the same tree produce byte-identical files, so regenerating after a merge is
|
||||
safe, and a branch that adds a unit and forgets the stub merges cleanly.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
STUBS = os.path.join(HERE, "halo_stubs.cpp")
|
||||
CMAKE = os.path.join(HERE, "CMakeLists.txt")
|
||||
DECL_HEADERS = ("halo_plugin.h", "halo.h")
|
||||
|
||||
# A declaration of one of the entries, at the start of a line: what halo_plugin.h and halo.h use.
|
||||
DECL_RE = re.compile(
|
||||
r'^[ \t]*(?:extern[ \t]+"C"[ \t]+)?'
|
||||
r'(?:unsigned[ \t]+|signed[ \t]+)?'
|
||||
r'(int64_t|uint64_t|int32_t|uint32_t|int|void|long|float|double|char|size_t|unsigned)'
|
||||
r'[ \t\*]+(halo_[A-Za-z0-9_]+)[ \t]*\(', re.M)
|
||||
|
||||
# A kernel unit's file name is built from an op name, so only .hip files are units.
|
||||
UNIT_RE = re.compile(r'^halo_[A-Za-z0-9_]+\.hip$')
|
||||
BODY_INCLUDE_RE = re.compile(r'#include\s+"(halo_[A-Za-z0-9_]+\.hip)"')
|
||||
EXTERN_C_RE = re.compile(r'extern\s+"C"')
|
||||
|
||||
# One generated stub line, as this script writes it (so a re-run reproduces it exactly).
|
||||
STUB_LINE_RE = re.compile(r'^(?P<lead>(?:extern "C" )?)(?P<attr>__attribute__\(\(weak\)\) )?'
|
||||
r'(?P<rest>.*?\b(?P<name>halo_[A-Za-z0-9_]+)[ \t]*\(.*)$')
|
||||
|
||||
# Return types whose a stub body can only say "not ported".
|
||||
BODY = {
|
||||
"int": "{ return RAD_E_UNSUPPORTED; }",
|
||||
"int32_t": "{ return RAD_E_UNSUPPORTED; }",
|
||||
"uint32_t": "{ return -1; }",
|
||||
"long": "{ return -1; }",
|
||||
"int64_t": "{ return -1; }",
|
||||
"uint64_t": "{ return -1; }",
|
||||
"size_t": "{ return 0; }",
|
||||
"unsigned": "{ return 0; }",
|
||||
"char": "{ return 0; }",
|
||||
"float": "{ return 0.0f; }",
|
||||
"double": "{ return 0.0; }",
|
||||
"void": "{}",
|
||||
}
|
||||
|
||||
# Type words that are never a parameter name (a trailing one must not be dropped).
|
||||
KEYWORDS = {"int", "long", "short", "char", "void", "float", "double", "unsigned", "signed",
|
||||
"const", "struct", "union", "enum", "bool"}
|
||||
|
||||
HEADER = """/* halo_stubs.cpp -- GENERATED by libhalo/gen_stubs.py; do not edit by hand.
|
||||
*
|
||||
* One weak body per hook libhalo/halo_plugin.h or libhalo/halo.h declares whose definition is not
|
||||
* in a source libhalo/CMakeLists.txt compiles yet. Every body is __attribute__((weak)), so a real
|
||||
* definition in any unit overrides it at link time and this file never has to be edited while a
|
||||
* port lands: run gen_stubs.py when the set of units changes, not per unit. An unimplemented
|
||||
* launch or init returns RAD_E_UNSUPPORTED, so a row that resolves to it fails by name at first
|
||||
* use instead of at dlopen. The line count is the parity scoreboard: done means zero. */
|
||||
|
||||
#include "halo_plugin.h"
|
||||
#include "halo.h" /* the C entries' types (HaloArgs, hipStream_t); this file is
|
||||
scaffolding, not one of the ROCm-free declaration sources */
|
||||
"""
|
||||
|
||||
# The name list the generated file exports (see HOOKS). Not a stub: a fixed trailer whose body is
|
||||
# the set of names just written, so a caller can tell a weak no-op hook from a real one.
|
||||
HOOKS_SYMBOL = "halo_stub_hooks"
|
||||
HOOKS = """
|
||||
/* The hooks this file still stubs, space separated, empty when the port is complete.
|
||||
*
|
||||
* A weak no-op body is RESOLVED, so a dlsym of a test hook answers even though the plugin does not
|
||||
* implement it -- and a pinned-form test built on that answer asserts about a pin that pins
|
||||
* nothing (a vacuous pass, or one spurious FAILure per form when the row itself is a stub). This
|
||||
* list is the only place that knows which hooks are still stubs, and it is generated from the same
|
||||
* scan as the bodies above, so a unit that lands a real hook drops its name here on the next run.
|
||||
* halo_selftest reads it through libhalo/halo_selftest.cpp's `hook()`. */
|
||||
extern \"C\" const char* %s(void) { return \"%s\"; }
|
||||
"""
|
||||
|
||||
CMAKE_MARK = """# HALO_UNITS is generated: libhalo/gen_stubs.py writes the list below from the halo_*.hip files
|
||||
# present (each "unit|extra flags", mirroring libr4d's R4D_UNITS), so add a unit by adding its
|
||||
# .hip, not by editing the list. Every unit compiles -ffp-contract=off (rad_hipify): the
|
||||
# quantised all-reduce requires it, for the reason libr4d/CMakeLists.txt gives."""
|
||||
|
||||
|
||||
def read(path):
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def code_only(text):
|
||||
"""`text` with its comments removed: a commented-out definition defines nothing."""
|
||||
text = re.sub(r'/\*.*?\*/', '', text, flags=re.S)
|
||||
return re.sub(r'//[^\n]*', '', text)
|
||||
|
||||
|
||||
def declarations():
|
||||
"""name -> (return type, header it was declared in)."""
|
||||
decl = {}
|
||||
for h in DECL_HEADERS:
|
||||
path = os.path.join(HERE, h)
|
||||
if not os.path.exists(path):
|
||||
sys.exit("gen_stubs.py: %s is missing" % path)
|
||||
for m in DECL_RE.finditer(read(path)):
|
||||
decl.setdefault(m.group(2), (m.group(1), h))
|
||||
return decl
|
||||
|
||||
|
||||
def cmake_lists():
|
||||
"""(per-unit extra flags from the current HALO_UNITS, the HALO_DECLARATION host sources)."""
|
||||
text = read(CMAKE)
|
||||
flags = {}
|
||||
m = re.search(r'set\(\s*HALO_UNITS\b(.*?)\n[ \t]*\)', text, re.S)
|
||||
if m:
|
||||
for unit, extra in re.findall(r'"(halo_[A-Za-z0-9_]+)\|([^"]*)"', m.group(1)):
|
||||
flags[unit] = extra
|
||||
m = re.search(r'set\(\s*HALO_DECLARATION\b(.*?)\)', text, re.S)
|
||||
if not m:
|
||||
sys.exit("gen_stubs.py: CMakeLists.txt has no HALO_DECLARATION list")
|
||||
host = re.findall(r'([A-Za-z0-9_]+\.cpp)', m.group(1))
|
||||
if not host:
|
||||
sys.exit("gen_stubs.py: HALO_DECLARATION names no host source")
|
||||
return flags, host
|
||||
|
||||
|
||||
def bodies(names):
|
||||
"""(all units, the included files that are units too, the pure bodies)."""
|
||||
hips = sorted(f for f in os.listdir(HERE) if UNIT_RE.match(f))
|
||||
included = set()
|
||||
for f in os.listdir(HERE):
|
||||
if not f.endswith((".hip", ".cpp", ".h")):
|
||||
continue
|
||||
for inc in BODY_INCLUDE_RE.findall(read(os.path.join(HERE, f))):
|
||||
if inc != f:
|
||||
included.add(inc)
|
||||
pure = set()
|
||||
for inc in sorted(included):
|
||||
path = os.path.join(HERE, inc)
|
||||
# A file that defines an entry point of its own is a unit even when a wrapper includes it
|
||||
# (libr4d's r4d_attn_paged_gqa8.hip is the precedent: its ratios are built by the wrappers
|
||||
# that include it, and its own gqa-8 entries come from compiling it).
|
||||
if defined_in(path, names, set()):
|
||||
continue
|
||||
if not EXTERN_C_RE.search(code_only(read(path))):
|
||||
pure.add(inc)
|
||||
return hips, included - pure, pure
|
||||
|
||||
|
||||
def match_close(text, start):
|
||||
"""Index just past the ')' that closes the '(' at `start`, or -1."""
|
||||
depth = 0
|
||||
i = start
|
||||
while i < len(text):
|
||||
c = text[i]
|
||||
if c == "(":
|
||||
depth += 1
|
||||
elif c == ")":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return i + 1
|
||||
elif c in "\";'":
|
||||
j = i + 1
|
||||
while j < len(text) and text[j] != c:
|
||||
j += 2 if text[j] == "\\" else 1
|
||||
i = j
|
||||
i += 1
|
||||
return -1
|
||||
|
||||
|
||||
def defined_in(path, names, under):
|
||||
"""The subset of `names` this file defines: `type name(...) {` -- a definition, not a call."""
|
||||
text = code_only(read(path))
|
||||
found = set()
|
||||
for name in names:
|
||||
if name in under:
|
||||
continue
|
||||
pat = re.compile(r'(?<![A-Za-z0-9_])' + re.escape(name) + r'[ \t]*\(')
|
||||
for m in pat.finditer(text):
|
||||
line_start = text.rfind("\n", 0, m.start()) + 1
|
||||
head = text[line_start:m.start()]
|
||||
# A definition's line starts with the return type (and any storage class), never with
|
||||
# a comment, a call, `return`, `if`, or an assignment.
|
||||
if not re.match(r'^[ \t]*(?:(?:extern[ \t]+"C"|static|inline|constexpr|const)[ \t]+)*'
|
||||
r'(?:unsigned[ \t]+|signed[ \t]+)?'
|
||||
r'[A-Za-z_][A-Za-z0-9_:<>]*[ \t\*&]*$', head):
|
||||
continue
|
||||
close = match_close(text, m.end() - 1)
|
||||
if close < 0:
|
||||
continue
|
||||
tail = text[close:]
|
||||
if re.match(r'[ \t\n]*(?:const[ \t\n]*)?[{]', tail):
|
||||
found.add(name)
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def implemented(units, host):
|
||||
"""The entry names a compiled source defines."""
|
||||
names = set(declarations())
|
||||
srcs = [os.path.join(HERE, u + ".hip") for u in units]
|
||||
srcs += [os.path.join(HERE, h) for h in host if h != "halo_stubs.cpp"]
|
||||
done = set()
|
||||
for s in srcs:
|
||||
if os.path.exists(s):
|
||||
done |= defined_in(s, names, done)
|
||||
return done
|
||||
|
||||
|
||||
def existing_stubs():
|
||||
"""name -> the line already in halo_stubs.cpp, with any weak attribute removed."""
|
||||
if not os.path.exists(STUBS):
|
||||
return {}
|
||||
out = {}
|
||||
for line in read(STUBS).splitlines():
|
||||
if not line.strip() or line.lstrip().startswith(("/*", "*", "#")):
|
||||
continue
|
||||
m = STUB_LINE_RE.match(line)
|
||||
if not m or not line.rstrip().endswith("}"):
|
||||
continue
|
||||
if m.group("name") == HOOKS_SYMBOL: # this script's own trailer, not a stub
|
||||
continue
|
||||
stripped = m.group("lead") + m.group("rest")
|
||||
out[m.group("name")] = stripped
|
||||
return out
|
||||
|
||||
|
||||
def signature(decl_type, hole, cxx_c):
|
||||
"""A definition's declarator from the header's, with parameter names and defaults dropped."""
|
||||
close = match_close(hole, 0)
|
||||
if close < 0 or close != len(hole) or not hole.startswith("("):
|
||||
return None
|
||||
params = hole[1:-1]
|
||||
out = []
|
||||
for p in params.split(","):
|
||||
p = re.sub(r'=.*$', '', p).strip()
|
||||
if not p:
|
||||
continue
|
||||
toks = p.split()
|
||||
# Drop the parameter's name when there is a type left without it, so the stub does not
|
||||
# warn about an unused parameter (-Wunused-parameter) and matches the file's style.
|
||||
if len(toks) > 1 and re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', toks[-1]) \
|
||||
and toks[-1] not in KEYWORDS:
|
||||
p = " ".join(toks[:-1])
|
||||
out.append(p)
|
||||
return ("extern \"C\" " if cxx_c else "") + decl_type + " " + "%s(" + ", ".join(out) + ")"
|
||||
|
||||
|
||||
def weak(lead, rest):
|
||||
"""The line with the weak attribute where the tree's style puts it: after `extern "C" `."""
|
||||
return lead + "__attribute__((weak)) " + rest
|
||||
|
||||
|
||||
def stub_line(name, decl, existing, decl_text):
|
||||
if name in existing:
|
||||
line = existing[name]
|
||||
lead, rest = ("extern \"C\" ", line[len("extern \"C\" "):]) \
|
||||
if line.startswith("extern \"C\" ") else ("", line)
|
||||
return weak(lead, rest)
|
||||
decl_type, header = decl[name]
|
||||
sig = signature(decl_type, decl_text[name], header == "halo.h")
|
||||
if sig is None:
|
||||
sys.exit("gen_stubs.py: cannot read the declaration of %s in %s" % (name, header))
|
||||
lead, rest = (("extern \"C\" ", sig[len("extern \"C\" "):]) \
|
||||
if sig.startswith("extern \"C\" ") else ("", sig))
|
||||
return weak(lead, rest) % name + " " + BODY[decl_type]
|
||||
|
||||
|
||||
def decl_param_text():
|
||||
"""name -> the header's parameter list text, from '(' to ')'."""
|
||||
out = {}
|
||||
for h in DECL_HEADERS:
|
||||
text = read(os.path.join(HERE, h))
|
||||
for m in DECL_RE.finditer(text):
|
||||
after = text[m.end() - 1:]
|
||||
close = match_close(after, 0)
|
||||
if close < 0:
|
||||
sys.exit("gen_stubs.py: unbalanced declaration of %s in %s" % (m.group(2), h))
|
||||
out.setdefault(m.group(2), after[:close])
|
||||
return out
|
||||
|
||||
|
||||
def generate(verbose=False):
|
||||
decl = declarations()
|
||||
flags, host = cmake_lists()
|
||||
hips, units_keep, bodies_pure = bodies(set(decl))
|
||||
units = sorted(f[:-4] for f in hips if f not in bodies_pure)
|
||||
done = implemented(units, host)
|
||||
existing = existing_stubs()
|
||||
|
||||
# The stub set: every declared entry with no definition, plus every line already here whose
|
||||
# symbol no header declares (kept so a hook a unit calls cannot vanish).
|
||||
undeclared = {n: ("void", "halo_plugin.h") for n in existing if n not in decl}
|
||||
want = {n: decl[n] for n in decl if n not in done}
|
||||
want.update(undeclared)
|
||||
params = decl_param_text()
|
||||
|
||||
lines = [stub_line(n, want, existing, params) for n in sorted(want)]
|
||||
stub_text = HEADER + "\n" + "\n".join(lines) + "\n" + HOOKS % (HOOKS_SYMBOL,
|
||||
" ".join(sorted(want)))
|
||||
|
||||
cmake_text = read(CMAKE)
|
||||
block = "\n".join(' "%s|%s"' % (u, flags.get(u, "")) for u in units)
|
||||
new_units = "set(HALO_UNITS\n%s\n)" % block
|
||||
old = re.search(r'set\(\s*HALO_UNITS\b.*?\n[ \t]*\)', cmake_text, re.S)
|
||||
if not old:
|
||||
sys.exit("gen_stubs.py: CMakeLists.txt has no HALO_UNITS block")
|
||||
# Replace the comment block that documents HALO_UNITS along with the list, so a re-run
|
||||
# reproduces the file byte for byte; everything outside that block is left alone.
|
||||
head = cmake_text[:old.start()]
|
||||
comment = re.search(r'(?:^[ \t]*#[^\n]*\n)+\Z', head, re.M)
|
||||
if comment:
|
||||
head = head[:comment.start()]
|
||||
cmake_out = head + CMAKE_MARK + "\n" + new_units + cmake_text[old.end():]
|
||||
|
||||
old_stub = read(STUBS) if os.path.exists(STUBS) else ""
|
||||
changed = []
|
||||
if old_stub != stub_text:
|
||||
changed.append(STUBS)
|
||||
if cmake_text != cmake_out:
|
||||
changed.append(CMAKE)
|
||||
if verbose:
|
||||
print("gen_stubs.py: %d unit(s), %d stub(s) (%d kept verbatim, %d synthesised), "
|
||||
"%d declaration(s) implemented, %d undeclared line(s) kept"
|
||||
% (len(units), len(want), len(want) - len([n for n in want if n not in existing]),
|
||||
len([n for n in want if n not in existing]), len(done), len(undeclared)))
|
||||
for b in sorted(bodies_pure):
|
||||
print("gen_stubs.py: %s is included as a body and defines no entry point: not a unit" % b)
|
||||
if "--check" in sys.argv:
|
||||
for c in changed:
|
||||
print("gen_stubs.py: %s is out of date -- run python3 libhalo/gen_stubs.py" % c)
|
||||
return 1 if changed else 0
|
||||
for path, text in ((STUBS, stub_text), (CMAKE, cmake_out)):
|
||||
if read(path) != text:
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
if changed:
|
||||
for c in changed:
|
||||
print("gen_stubs.py: rewrote %s" % c)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(generate("--verbose" in sys.argv))
|
||||
+1046
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,183 @@
|
||||
/* Derived from libr4d/r4d_ar_gather_2rank.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_ar_gather_2rank.hip: halo_ar_gather_2rank -- multi-block one-shot P2P all-GATHER, exactly two
|
||||
// ranks, for dual R9700 (gfx1201/RDNA4, PCIe).
|
||||
//
|
||||
// A kernel rather than halo_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).
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// `dtype` only converts n_elem to bytes.
|
||||
#include "halo.h"
|
||||
#include "halo_ar_seq.h"
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#define HALO_AR_GATHER_SPIN_MAX 4000000000ULL
|
||||
#define HALO_AR_GATHER_MAX_BLOCKS 512
|
||||
|
||||
__device__ __forceinline__ void halo_g_store_rel(unsigned int* p, unsigned int v) {
|
||||
__hip_atomic_store(p, v, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
__device__ __forceinline__ unsigned int halo_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.
|
||||
//
|
||||
// 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 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. `dp16` is the output's row pitch in words: 2 * row16 for a tight
|
||||
// [rows][2][row16], more when the gathered rows are the leading columns of a wider buffer.
|
||||
__device__ __forceinline__ int halo_g_dst(int k, int row16, int n16, int who, int dp16) {
|
||||
if (row16 <= 0 || row16 >= n16) return who * n16 + k;
|
||||
const int m = k / row16, c = k - m * row16;
|
||||
return m * dp16 + who * row16 + c;
|
||||
}
|
||||
|
||||
// Where word k of this rank's contribution is read: `sp16` is the input's row pitch in words,
|
||||
// row16 when its rows are tight, more when they are a window of a wider row.
|
||||
__device__ __forceinline__ int halo_g_src(int k, int row16, int n16, int sp16) {
|
||||
if (row16 <= 0 || row16 >= n16 || sp16 == row16) return k;
|
||||
const int m = k / row16, c = k - m * row16;
|
||||
return m * sp16 + c;
|
||||
}
|
||||
|
||||
// Block b owns words [start,end) of the 16B-word space and drives its own flag handshake; no
|
||||
// cross-block sync, as in the all-reduce.
|
||||
__global__ void halo_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,
|
||||
int n16, int slot_stride16, int rank, int row16, int dp16, int sp16, int drain, int acq,
|
||||
unsigned int nbw) {
|
||||
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
|
||||
__shared__ unsigned int s_seq, s_slot;
|
||||
halo_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int slot = (int)s_slot;
|
||||
int4* ps = peer_base + (size_t)slot * slot_stride16;
|
||||
const int4* ms = my_base + (size_t)slot * slot_stride16;
|
||||
|
||||
const int w = (n16 + nb - 1) / nb;
|
||||
const int start = b * w;
|
||||
int end = start + w; if (end > n16) end = n16;
|
||||
unsigned int hck = 0u; // the push check (halo_ar_seq.h)
|
||||
|
||||
// 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) {
|
||||
int4 v0 = in4[halo_g_src(k, row16, n16, sp16)], v1 = in4[halo_g_src(k + nt, row16, n16, sp16)],
|
||||
v2 = in4[halo_g_src(k + 2 * nt, row16, n16, sp16)],
|
||||
v3 = in4[halo_g_src(k + 3 * nt, row16, n16, sp16)];
|
||||
ps[k] = v0; ps[k + nt] = v1; ps[k + 2 * nt] = v2; ps[k + 3 * nt] = v3;
|
||||
hck += halo_archk_u4(v0, 4u * (unsigned)k) + halo_archk_u4(v1, 4u * (unsigned)(k + nt)) +
|
||||
halo_archk_u4(v2, 4u * (unsigned)(k + 2 * nt)) + halo_archk_u4(v3, 4u * (unsigned)(k + 3 * nt));
|
||||
out4[halo_g_dst(k, row16, n16, rank, dp16)] = v0;
|
||||
out4[halo_g_dst(k + nt, row16, n16, rank, dp16)] = v1;
|
||||
out4[halo_g_dst(k + 2 * nt, row16, n16, rank, dp16)] = v2;
|
||||
out4[halo_g_dst(k + 3 * nt, row16, n16, rank, dp16)] = v3;
|
||||
}
|
||||
for (; k < end; k += nt) {
|
||||
int4 v = in4[halo_g_src(k, row16, n16, sp16)];
|
||||
ps[k] = v;
|
||||
hck += halo_archk_u4(v, 4u * (unsigned)k);
|
||||
out4[halo_g_dst(k, row16, n16, rank, dp16)] = v;
|
||||
}
|
||||
}
|
||||
// Drain modes, as in the all-reduce: order the pushes before the release flag so the peer cannot
|
||||
// see the flag before the data.
|
||||
halo_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s);
|
||||
if (drain == 1) __threadfence_system();
|
||||
else if (drain == 3) asm volatile("s_waitcnt vmcnt(0)" ::: "memory"); // pre-gfx12 store wait
|
||||
__syncthreads();
|
||||
if (tid == 0) {
|
||||
if (drain == 2) __threadfence_system();
|
||||
halo_g_store_rel(&peer_flags[b], s);
|
||||
unsigned long long z = 0;
|
||||
// A handshake that cannot complete is a lockstep violation; trap rather than pass on stale
|
||||
// bytes as the peer's.
|
||||
while (halo_ar_seq_behind(halo_g_load_acq(&my_flags[b]), s)) {
|
||||
if (++z > HALO_AR_GATHER_SPIN_MAX) __builtin_trap();
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (acq) __threadfence_system();
|
||||
halo_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) {
|
||||
for (int k = start + tid; k < end; k += nt) h += halo_archk_u4(ms[k], 4u * (unsigned)k);
|
||||
});
|
||||
|
||||
// Place the peer's slice, now staged in this rank's scratch.
|
||||
{
|
||||
const int who = 1 - rank;
|
||||
int k = start + tid;
|
||||
for (; k + 3 * nt < end; k += 4 * nt) {
|
||||
out4[halo_g_dst(k, row16, n16, who, dp16)] = ms[k];
|
||||
out4[halo_g_dst(k + nt, row16, n16, who, dp16)] = ms[k + nt];
|
||||
out4[halo_g_dst(k + 2 * nt, row16, n16, who, dp16)] = ms[k + 2 * nt];
|
||||
out4[halo_g_dst(k + 3 * nt, row16, n16, who, dp16)] = ms[k + 3 * nt];
|
||||
}
|
||||
for (; k < end; k += nt) out4[halo_g_dst(k, row16, n16, who, dp16)] = ms[k];
|
||||
}
|
||||
}
|
||||
|
||||
void halo_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
|
||||
long seq_ctrs, long slot_stride16, long inp, long out, long n_elem,
|
||||
long dtype, long rank, long row_elems, long stream_i, long nblocks,
|
||||
long nthreads, long drain, long acq, long dpitch, long spitch) {
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
const int esize = (dtype == 2) ? 4 : 2;
|
||||
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 (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");
|
||||
const int row16 = row_elems > 0 ? (int)(rowb / 16) : 0;
|
||||
// The output's row pitch in elements, 0 for a tight [rows][2][row]: whole words, at least the
|
||||
// two ranks' row.
|
||||
const long dpb = (long)dpitch * esize;
|
||||
if (dpitch > 0 && (row16 <= 0 || dpb % 16 != 0 || dpitch < 2 * row_elems))
|
||||
throw std::runtime_error("all_gather: the output pitch is not a whole number of 16B words "
|
||||
"at least two rows wide");
|
||||
const int dp16 = dpitch > 0 ? (int)(dpb / 16) : 2 * row16;
|
||||
// The input's row pitch in elements, 0 for tight rows: whole words, at least a row.
|
||||
const long spb = (long)spitch * esize;
|
||||
if (spitch > 0 && (row16 <= 0 || spb % 16 != 0 || spitch < row_elems))
|
||||
throw std::runtime_error("all_gather: the input pitch is not a whole number of 16B words "
|
||||
"at least a row wide");
|
||||
const int sp16 = spitch > 0 ? (int)(spb / 16) : row16;
|
||||
int nb = (int)nblocks;
|
||||
if (nb < 1) nb = 1;
|
||||
if (nb > n16) nb = n16;
|
||||
if (nb > HALO_AR_GATHER_MAX_BLOCKS) nb = HALO_AR_GATHER_MAX_BLOCKS;
|
||||
// Block capacity of the counter allocation shared with the all-reduce (halo_ar_seq.h).
|
||||
const unsigned nbw = (unsigned)halo_ar_max_blocks();
|
||||
if ((unsigned)nb > nbw) nb = (int)nbw;
|
||||
int nt = (int)nthreads;
|
||||
if (nt < 64) nt = 64;
|
||||
if (nt > 1024) nt = 1024;
|
||||
nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes
|
||||
halo_ar_gather_2rank_kernel<<<nb, nt, 0, st>>>(
|
||||
(const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out,
|
||||
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16,
|
||||
(int)slot_stride16, (int)rank, row16, dp16, sp16, (int)drain, (int)acq, nbw);
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
/* Derived from libr4d/r4d_ar_gather_Nrank.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_ar_gather_Nrank.hip: halo_ar_gather_3rank, halo_ar_gather_4rank, halo_ar_gather_8rank -- one-shot P2P all-GATHER,
|
||||
// 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.
|
||||
//
|
||||
// halo_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 (u32 token id, f32 logit) pairs, so it is moved and never summed. `dtype` only
|
||||
// converts n_elem to bytes.
|
||||
//
|
||||
// Placement: row16 is one row of this rank's contribution in 16-byte words. halo_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
|
||||
// halo_ar_gather_2rank.hip).
|
||||
//
|
||||
// The IPC helpers and the handshake live in halo_ar_wide.h; halo_ar_entry.hip owns the instance and
|
||||
// the peer arrays.
|
||||
#include "halo.h"
|
||||
#include "halo_ar_wide.h"
|
||||
#include "halo_chain.h"
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
// 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;
|
||||
// halo_ar_entry.hip repeats the prototypes at its call site, since halo.h does not declare them.
|
||||
extern "C" void halo_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, long n_elem,
|
||||
long dtype, long rank, long row_elems, long stream,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub,
|
||||
long dpitch, long spitch);
|
||||
extern "C" void halo_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 gate, long gate_ctr, long dpitch, long spitch, long chain);
|
||||
extern "C" void halo_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,
|
||||
long peer_flags2, long peer_flags3, long peer_flags4,
|
||||
long peer_flags5, long peer_flags6, 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 dpitch, long spitch);
|
||||
|
||||
// Where a rank's words land: the 2-rank halo_g_dst generalised to WS. Named differently because two
|
||||
// __device__ definitions of one name in the two units would violate the ODR.
|
||||
// `dp16` is the output's row pitch in words, WS * row16 when the gathered rows are tight.
|
||||
__device__ __forceinline__ int halo_g_dst_ws(int k, int row16, int n16, int who, int dp16) {
|
||||
if (row16 <= 0 || row16 >= n16) return who * n16 + k;
|
||||
const int m = k / row16, c = k - m * row16;
|
||||
return m * dp16 + who * row16 + c;
|
||||
}
|
||||
|
||||
// Where word k of this rank's contribution is read: `sp16` is the input's row pitch in words,
|
||||
// row16 when its rows are tight, more when they are a window of a wider row.
|
||||
__device__ __forceinline__ int halo_g_src_ws(int k, int row16, int n16, int sp16) {
|
||||
if (row16 <= 0 || row16 >= n16 || sp16 == row16) return k;
|
||||
const int m = k / row16, c = k - m * row16;
|
||||
return m * sp16 + c;
|
||||
}
|
||||
|
||||
// Block b owns words [start,end) of the 16B-word space and drives its own handshake; no cross-block
|
||||
// sync, as in the all-reduce.
|
||||
// The body; the plain kernel and its chained form (halo_chain.h) wrap it below. The chained form
|
||||
// waits before the sequence take, so a block of the next launch on the instance never starts
|
||||
// ahead of this one's; no block returns early.
|
||||
template <int WS>
|
||||
__device__ __forceinline__ void halo_ar_gather_wide_body(
|
||||
const int4* __restrict__ in4, HaloArWidePeers<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 dp16, int sp16, int drain, int acq,
|
||||
int pub, long long* gate, unsigned int* gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
// 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 = halo_ar_link_word(gate, (unsigned int)tid);
|
||||
halo_ar_seq_take(seq_ctrs, HALO_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int parity = (int)s_slot;
|
||||
|
||||
const int w = (n16 + nb - 1) / nb;
|
||||
const int start = b * w;
|
||||
int end = start + w; if (end > n16) end = n16;
|
||||
|
||||
// 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; 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) {
|
||||
const int4 v0 = in4[halo_g_src_ws(k, row16, n16, sp16)];
|
||||
const int4 v1 = in4[halo_g_src_ws(k + nt, row16, n16, sp16)];
|
||||
const int4 v2 = in4[halo_g_src_ws(k + 2 * nt, row16, n16, sp16)];
|
||||
const int4 v3 = in4[halo_g_src_ws(k + 3 * nt, row16, n16, sp16)];
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p) {
|
||||
ps[p][k] = v0; ps[p][k + nt] = v1; ps[p][k + 2 * nt] = v2; ps[p][k + 3 * nt] = v3;
|
||||
}
|
||||
}
|
||||
for (; k < end; k += nt) {
|
||||
const int4 v = in4[halo_g_src_ws(k, row16, n16, sp16)];
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p) ps[p][k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
// 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 halo_ar_wide.h's, shared with the all-reduces on these buffers; a
|
||||
// handshake that cannot complete traps rather than pass on stale bytes.
|
||||
halo_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.
|
||||
halo_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
// 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, read at its own pitch.
|
||||
const int4* src[WS];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < WS; ++r)
|
||||
src[r] = (r == rank) ? in4
|
||||
: (my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16);
|
||||
{
|
||||
int k = start + tid;
|
||||
if (RU == 2) {
|
||||
for (; k + nt < end; k += 2 * nt) {
|
||||
const int k0 = halo_g_src_ws(k, row16, n16, sp16), k1 = halo_g_src_ws(k + nt, row16, n16, sp16);
|
||||
#pragma unroll
|
||||
for (int r = 0; r < WS; ++r) {
|
||||
out4[halo_g_dst_ws(k, row16, n16, r, dp16)] = src[r][r == rank ? k0 : k];
|
||||
out4[halo_g_dst_ws(k + nt, row16, n16, r, dp16)] = src[r][r == rank ? k1 : k + nt];
|
||||
}
|
||||
}
|
||||
}
|
||||
for (; k < end; k += nt) {
|
||||
const int k0 = halo_g_src_ws(k, row16, n16, sp16);
|
||||
#pragma unroll
|
||||
for (int r = 0; r < WS; ++r)
|
||||
out4[halo_g_dst_ws(k, row16, n16, r, dp16)] = src[r][r == rank ? k0 : k];
|
||||
}
|
||||
}
|
||||
}
|
||||
template <int WS>
|
||||
__global__ void halo_ar_gather_wide_kernel(
|
||||
const int4* __restrict__ in4, HaloArWidePeers<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 dp16, int sp16, int drain, int acq,
|
||||
int pub, long long* gate, unsigned int* gate_ctr) {
|
||||
halo_ar_gather_wide_body<WS>(in4, peers, my_base, out4, my_flags, seq_ctrs, n16, slot_stride16,
|
||||
rank, row16, dp16, sp16, drain, acq, pub, gate, gate_ctr);
|
||||
}
|
||||
template <int WS>
|
||||
__global__ void halo_r4dchain_ar_gather_wide(
|
||||
const int4* __restrict__ in4, HaloArWidePeers<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 dp16, int sp16, int drain, int acq,
|
||||
int pub, long long* gate, unsigned int* gate_ctr) {
|
||||
halo_chain_wait();
|
||||
halo_ar_gather_wide_body<WS>(in4, peers, my_base, out4, my_flags, seq_ctrs, n16, slot_stride16,
|
||||
rank, row16, dp16, sp16, drain, acq, pub, gate, gate_ctr);
|
||||
halo_chain_done();
|
||||
}
|
||||
|
||||
// --- host side ---
|
||||
// `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 gate, long gate_ctr, long dpitch, long spitch,
|
||||
bool chain = false) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
static_assert(NPEERS <= HALO_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound");
|
||||
|
||||
if (rank < 0 || rank >= WS)
|
||||
throw std::runtime_error("all_gather: rank " + std::to_string(rank) +
|
||||
" out of range for the " + std::to_string(WS) +
|
||||
" ranks this entry point is compiled for");
|
||||
|
||||
const int esize = (dtype == 2) ? 4 : 2;
|
||||
const long nbytes = (long)n_elem * esize;
|
||||
if (nbytes % 16 != 0) throw std::runtime_error("all_gather: n_elem*esize not 16B-aligned");
|
||||
const long n16l = nbytes / 16;
|
||||
if (n16l > (long)slot_stride16)
|
||||
throw std::runtime_error("all_gather: message (" + std::to_string(n16l) +
|
||||
" 16B words) exceeds the per-source slot stride (" +
|
||||
std::to_string(slot_stride16) + ")");
|
||||
const int n16 = (int)n16l;
|
||||
|
||||
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");
|
||||
const int row16 = row_elems > 0 ? (int)(rowb / 16) : 0;
|
||||
// The output's row pitch in elements, 0 for a tight [rows][WS][row]: whole words, at least the
|
||||
// WS ranks' row (the gathered rows as the leading columns of a wider buffer).
|
||||
const long dpb = (long)dpitch * esize;
|
||||
if (dpitch > 0 && (row16 <= 0 || dpb % 16 != 0 || dpitch < (long)WS * row_elems))
|
||||
throw std::runtime_error("all_gather: the output pitch is not a whole number of 16B words "
|
||||
"at least " + std::to_string(WS) + " rows wide");
|
||||
const int dp16 = dpitch > 0 ? (int)(dpb / 16) : WS * row16;
|
||||
// The input's row pitch in elements, 0 for tight rows: whole words, at least a row (a rank's
|
||||
// window of a wider row).
|
||||
const long spb = (long)spitch * esize;
|
||||
if (spitch > 0 && (row16 <= 0 || spb % 16 != 0 || spitch < row_elems))
|
||||
throw std::runtime_error("all_gather: the input pitch is not a whole number of 16B words "
|
||||
"at least a row wide");
|
||||
const int sp16 = spitch > 0 ? (int)(spb / 16) : row16;
|
||||
|
||||
int nb = (int)nblocks;
|
||||
if (nb < 1) nb = HALO_AR_NB_DESIGN;
|
||||
if (nb > n16) nb = n16;
|
||||
if (nb > HALO_AR_WIDE_MAX_BLOCKS) nb = HALO_AR_WIDE_MAX_BLOCKS;
|
||||
int nt = (int)nthreads;
|
||||
if (nt < 64) nt = 64;
|
||||
if (nt > 1024) nt = 1024;
|
||||
|
||||
HaloArWidePeers<int4, NPEERS> peers{};
|
||||
for (int i = 0; i < NPEERS; ++i) {
|
||||
if (!peer_scratch[i] || !peer_flags[i])
|
||||
throw std::runtime_error("all_gather: null peer scratch/flag pointer at index " +
|
||||
std::to_string(i));
|
||||
peers.scratch[i] = (int4*)peer_scratch[i];
|
||||
peers.flags[i] = (unsigned int*)peer_flags[i];
|
||||
peers.rank[i] = (i < (int)rank) ? i : i + 1;
|
||||
}
|
||||
|
||||
// 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);
|
||||
halo_ar_check_extent(my_scratch, slot_bytes, "all_gather", "my_scratch");
|
||||
halo_ar_check_extent(my_flags, flag_bytes, "all_gather", "my_flags");
|
||||
halo_ar_check_extent(seq_ctrs, 2L * HALO_AR_WIDE_MAX_BLOCKS * (long)sizeof(unsigned int),
|
||||
"all_gather", "seq_ctrs");
|
||||
for (int i = 0; i < NPEERS; ++i) {
|
||||
halo_ar_check_extent(peer_scratch[i], slot_bytes, "all_gather", "peer scratch");
|
||||
halo_ar_check_extent(peer_flags[i], flag_bytes, "all_gather", "peer flags");
|
||||
}
|
||||
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
(chain ? halo_r4dchain_ar_gather_wide<WS> : halo_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, dp16, sp16, (int)drain,
|
||||
(int)acq, (int)pub, (long long*)gate, (unsigned int*)gate_ctr);
|
||||
}
|
||||
|
||||
/* Three ranks, e.g. Qwen3.8-Flash-Next padded to 36 heads / 3 KV heads (docs/TP3.md). */
|
||||
void halo_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,
|
||||
long n_elem, long dtype, long rank, long row_elems, long stream,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub, long dpitch,
|
||||
long spitch) {
|
||||
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,
|
||||
0L, 0L, dpitch, spitch);
|
||||
}
|
||||
|
||||
void halo_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 gate,
|
||||
long gate_ctr, long dpitch, long spitch, long chain) {
|
||||
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,
|
||||
gate, gate_ctr, dpitch, spitch, chain != 0);
|
||||
}
|
||||
|
||||
void halo_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, long peer_flags2,
|
||||
long peer_flags3, long peer_flags4, long peer_flags5, long peer_flags6,
|
||||
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 dpitch, long spitch) {
|
||||
const long ps[7] = {peer_scratch0, peer_scratch1, peer_scratch2, peer_scratch3,
|
||||
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,
|
||||
0L, 0L, dpitch, spitch);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
/* Derived from libr4d/r4d_ar_hc.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
#pragma once
|
||||
// halo_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
|
||||
// (halo_ar_oneshot_2rank_exact.hip) and the rotated 6-bit ones (halo_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
|
||||
// of eight, so a word never straddles a row.
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
// The gated residual's own bf16 arithmetic -- f2bf / f2bf2 / bf2f -- is halo_gdn_wmma.h's, the
|
||||
// single definition shared with the HC and GDN units: round-half-away (u + 0x8000, one add), NOT
|
||||
// the round-to-nearest-even every other narrow in libhalo uses. Kept bit-identical to libr4d on
|
||||
// purpose -- ar_hc_write's bytes are a shared contract. gfx1151 has a bf16 convert instruction, but
|
||||
// it rounds RTNE, so the arithmetic stays in software there.
|
||||
#include "halo_gdn_wmma.h"
|
||||
|
||||
// LDS slot table bounds: rows per block, and slots per row.
|
||||
#define HALO_ARG_ROWS 8
|
||||
#define HALO_ARG_SLOTS 64
|
||||
|
||||
__device__ __forceinline__ unsigned short arg_bf16_rne(float f) {
|
||||
const unsigned u = __builtin_bit_cast(unsigned, f);
|
||||
return (unsigned short)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
|
||||
struct HaloArGather {
|
||||
const unsigned short* ye; // [T, ye_ld] the routed experts' outputs, sorted-row order
|
||||
const unsigned short* ew; // [M, ew_ld] each token's slot weights
|
||||
const int* sorted; // [T] the (token * top_k + slot) each sorted row holds
|
||||
const unsigned short* sh; // [M, sh_ld] the shared arm, or null
|
||||
const unsigned short* sg; // [M, sg_ld] its gate, or null
|
||||
long ye_ld, ew_ld, sh_ld, sg_ld;
|
||||
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 in as moe_gather
|
||||
// does it. Its narrows are round-to-nearest-even, unlike hc_write's.
|
||||
//
|
||||
// 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 halo_ar_gather_word(const HaloArGather& G,
|
||||
const int* __restrict__ inv, const int* s_i,
|
||||
const float* s_w, const float* s_g, int row,
|
||||
int r, int i0) {
|
||||
const int K = G.top_k;
|
||||
float acc[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) acc[e] = 0.0f;
|
||||
/* 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];
|
||||
int ii[kU];
|
||||
#pragma unroll
|
||||
for (int u = 0; u < kU; ++u) {
|
||||
ii[u] = j0 + u < K ? (INV ? inv[(long)row * K + j0 + u] : s_i[r * K + j0 + u]) : -1;
|
||||
v[u] = *reinterpret_cast<const int4*>(G.ye + (long)(ii[u] < 0 ? 0 : ii[u]) * G.ye_ld + i0);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int u = 0; u < kU; ++u) {
|
||||
if (ii[u] < 0) continue;
|
||||
const float wj = INV ? bf2f(G.ew[(long)row * G.ew_ld + j0 + u]) : s_w[r * K + j0 + u];
|
||||
const unsigned short* ve = reinterpret_cast<const unsigned short*>(&v[u]);
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) acc[e] += wj * bf2f(ve[e]);
|
||||
}
|
||||
}
|
||||
int4 out;
|
||||
unsigned short* oe = reinterpret_cast<unsigned short*>(&out);
|
||||
if (!G.sh) {
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) oe[e] = arg_bf16_rne(acc[e]);
|
||||
} else {
|
||||
float gate;
|
||||
if (INV) {
|
||||
const float v0 = bf2f(G.sg[(long)row * G.sg_ld]);
|
||||
gate = G.sig ? (1.0f / (1.0f + __expf(-v0))) : v0;
|
||||
} else {
|
||||
gate = s_g[r];
|
||||
}
|
||||
const unsigned short* shp = G.sh + (long)row * G.sh_ld + i0;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const unsigned short g = arg_bf16_rne(acc[e]);
|
||||
const unsigned short pr = arg_bf16_rne(bf2f(shp[e]) * gate);
|
||||
oe[e] = arg_bf16_rne(bf2f(pr) + bf2f(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 (halo_hc_bf16.hip). `yv` is the reduced word as stored bf16, which is what
|
||||
// hc_write reads back from memory.
|
||||
__device__ __forceinline__ void halo_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,
|
||||
const unsigned short* yv) {
|
||||
float v[8];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) v[j] = bf2f(yv[j]);
|
||||
for (int c = 0; c < hc; ++c) {
|
||||
const float g = bf2f(inj[(long)row * irow + c]);
|
||||
int4* hp = reinterpret_cast<int4*>(h + (long)row * hrow + (long)c * n + i0);
|
||||
int4 hv = *hp;
|
||||
unsigned short* he = reinterpret_cast<unsigned short*>(&hv);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) he[j] = f2bf(bf2f(he[j]) + g * v[j]);
|
||||
*hp = hv;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/* Derived from libr4d/r4d_ar_links.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
#pragma once
|
||||
// halo_ar_links.h: the eight-rank two-shot's shard weights from the PCIe links (host only).
|
||||
//
|
||||
// A card's link to the CPU is as fast as its slowest hop. The R9700 sits behind an on-card switch
|
||||
// whose endpoint reports full speed in any slot, so a degraded slot shows only at the root port:
|
||||
// every hop from the root port down is read, as core/diag/sysinfo.cpp (read_card) reads it, from
|
||||
// the kernel's sysfs under `root` ("" on a real machine, a directory tree in tests). Nothing that
|
||||
// a file does not say is guessed; a card with no readable hop has no rate.
|
||||
//
|
||||
// Weight from the rate relative to the fastest card: w = round(4 * (rate / max)^2), so x16 4,
|
||||
// half the rate 1, a quarter 0. A rank's bytes per direction grow with its shard, so the weights
|
||||
// fall faster than the rate; the measured best on four Gen5 x16, two Gen5 x8 and two Gen4 x8 was
|
||||
// 4,1,0,4,0,1,4,4 (docs/GUIDE.md, 4.7).
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
struct HaloArLink {
|
||||
std::string bdf; // the slowest hop, "" when none was readable
|
||||
double gts = 0.0; // its current speed in GT/s
|
||||
int width = 0; // its current width in lanes
|
||||
};
|
||||
|
||||
// Payload GB/s of one direction: 8b/10b below 8 GT/s, 128b/130b from Gen3 on.
|
||||
inline double halo_ar_link_gbs(const HaloArLink& l) {
|
||||
if (l.gts <= 0.0 || l.width <= 0) return 0.0;
|
||||
const double enc = l.gts < 8.0 ? 8.0 / 10.0 : 128.0 / 130.0;
|
||||
return l.gts * l.width * enc / 8.0;
|
||||
}
|
||||
|
||||
inline std::string halo_ar_sysfs_line(const std::string& path) {
|
||||
std::ifstream f(path);
|
||||
std::string s;
|
||||
if (!f || !std::getline(f, s)) return std::string();
|
||||
return s;
|
||||
}
|
||||
|
||||
inline bool halo_ar_is_bdf(const std::string& s) {
|
||||
unsigned d, b, dv, f;
|
||||
char tail;
|
||||
return s.size() == 12 && std::sscanf(s.c_str(), "%4x:%2x:%2x.%1x%c", &d, &b, &dv, &f, &tail) == 4;
|
||||
}
|
||||
|
||||
// The slowest hop between the root port and the card `bdf` ("0000:03:00.0", lower case). False
|
||||
// when no hop on the path says its current speed and width.
|
||||
inline bool halo_ar_link_bottleneck(const std::string& root, const std::string& bdf,
|
||||
HaloArLink* out) {
|
||||
namespace fs = std::filesystem;
|
||||
const std::string devs = root + "/sys/bus/pci/devices/";
|
||||
std::error_code ec;
|
||||
const fs::path real = fs::canonical(devs + bdf, ec);
|
||||
if (ec) return false;
|
||||
HaloArLink best;
|
||||
for (const fs::path& part : real) {
|
||||
const std::string p = part.string();
|
||||
if (!halo_ar_is_bdf(p)) continue;
|
||||
HaloArLink h;
|
||||
h.bdf = p;
|
||||
h.gts = std::strtod(halo_ar_sysfs_line(devs + p + "/current_link_speed").c_str(), nullptr);
|
||||
h.width = std::atoi(halo_ar_sysfs_line(devs + p + "/current_link_width").c_str());
|
||||
const double r = halo_ar_link_gbs(h);
|
||||
if (r <= 0.0) continue;
|
||||
if (best.bdf.empty() || r < halo_ar_link_gbs(best)) best = h;
|
||||
}
|
||||
if (best.bdf.empty()) return false;
|
||||
*out = best;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Weights from every rank's rate (GB/s). False when a rank's rate is unknown.
|
||||
inline bool halo_ar_weights_from_rates(const double* gbs, int ws, int* w) {
|
||||
double top = 0.0;
|
||||
for (int r = 0; r < ws; ++r) {
|
||||
if (!(gbs[r] > 0.0)) return false;
|
||||
if (gbs[r] > top) top = gbs[r];
|
||||
}
|
||||
for (int r = 0; r < ws; ++r) {
|
||||
const double q = gbs[r] / top;
|
||||
w[r] = (int)std::lround(4.0 * q * q);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// The duplex model: the weights that minimise the two-shot's link time when both directions of a
|
||||
// link run at once (the pieced kernel's aim). Rank r with shard fraction x_r sends
|
||||
// (1 - x_r) of the message in the first hop and (ws - 1) x_r in the second, and receives the same,
|
||||
// so each direction carries (1 + (ws - 2) x_r) N at rate B_r. The slowest rank sets the time T, so
|
||||
// the best table makes every rank with a shard finish together: x_r = (T B_r - 1) / (ws - 2) where
|
||||
// that is positive, 0 elsewhere, with the x summing to 1 (water filling from the fastest rank
|
||||
// down). Four ranks at B and four at B / 2 give x of 2/9 and 1/36, 8 to 1 where the quadratic rule
|
||||
// above gives 4 to 1, and a time 10% lower (7/6 N / B / 2 against 1.3 N / B / 2). Scaled so the
|
||||
// largest weight is 64. False when a rank's rate is unknown.
|
||||
//
|
||||
// The engine keeps halo_ar_weights_from_rates: on eight R9700 these weights lost their lead within
|
||||
// a timing run and served no faster at TP8. halo_selftest --perfar8 prints this table beside the
|
||||
// engine's, to be set with --ar8-weights when timing another board.
|
||||
inline bool halo_ar_weights_duplex(const double* gbs, int ws, int* w) {
|
||||
if (ws < 3 || ws > 16) return false;
|
||||
int order[16];
|
||||
for (int r = 0; r < ws; ++r) {
|
||||
if (!(gbs[r] > 0.0)) return false;
|
||||
order[r] = r;
|
||||
}
|
||||
for (int i = 1; i < ws; ++i)
|
||||
for (int j = i; j > 0 && gbs[order[j]] > gbs[order[j - 1]]; --j) {
|
||||
const int t = order[j]; order[j] = order[j - 1]; order[j - 1] = t;
|
||||
}
|
||||
// With the k fastest ranks holding shards, sum (T B_r - 1) = ws - 2 gives T; the set is right
|
||||
// when the slowest of them still gets a positive share and the next one would not.
|
||||
double sum = 0.0, t = 0.0;
|
||||
int k = 0;
|
||||
for (int n = 1; n <= ws; ++n) {
|
||||
sum += gbs[order[n - 1]];
|
||||
const double tn = (double)(ws - 2 + n) / sum;
|
||||
if (tn * gbs[order[n - 1]] <= 1.0) break;
|
||||
k = n;
|
||||
t = tn;
|
||||
}
|
||||
double x[16] = { 0 }, top = 0.0;
|
||||
for (int i = 0; i < k; ++i) {
|
||||
const int r = order[i];
|
||||
x[r] = (t * gbs[r] - 1.0) / (double)(ws - 2);
|
||||
if (x[r] > top) top = x[r];
|
||||
}
|
||||
for (int r = 0; r < ws; ++r) w[r] = (int)std::lround(64.0 * x[r] / top);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
/* Derived from libr4d/r4d_ar_ln_had_quant_i8.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_ar_ln_had_quant_i8.hip -- halo_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.
|
||||
//
|
||||
// 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. 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`.
|
||||
//
|
||||
// Partition by row. halo_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.
|
||||
//
|
||||
// Below the handshake this is halo_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 "halo.h"
|
||||
#include "halo_ar_seq.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_fwht.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#define HALO_ARN_SPIN_MAX 4000000000ULL
|
||||
#define HALO_ARN_MAXVALS 72
|
||||
|
||||
__device__ __forceinline__ void arn_store_rel(unsigned int* p, unsigned int v) {
|
||||
__hip_atomic_store(p, v, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
__device__ __forceinline__ unsigned int arn_load_acq(const unsigned int* p) {
|
||||
return __hip_atomic_load(p, __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Rotated 6-bit wire: same format and arithmetic as halo_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.
|
||||
//
|
||||
// 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 from halo_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, 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
|
||||
#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, 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;
|
||||
u += 0x7fffu + lsb;
|
||||
return __uint_as_float(u & 0xffff0000u);
|
||||
}
|
||||
|
||||
|
||||
// `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;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < ARN_EPL; ++i) {
|
||||
const float o = halo_xor_lane<M>(v[i]);
|
||||
v[i] = __int_as_float(__float_as_int(v[i]) ^ sm) + o;
|
||||
}
|
||||
}
|
||||
|
||||
// Orthonormal Walsh-Hadamard over one group; its own inverse, so this routine also undoes it.
|
||||
// A group is ARN_LPG lanes x ARN_EPL elements: the in-register butterflies are free ALU, and with
|
||||
// ROW_XMASK the cross-lane stages are free too.
|
||||
__device__ __forceinline__ void arn_wht(float* v, int lig) {
|
||||
static_assert(ARN_LPG == 8, "the cross-lane stages are unrolled for a group of 8 lanes");
|
||||
#pragma unroll
|
||||
for (int h = 1; h < ARN_EPL; h <<= 1)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < ARN_EPL; ++i)
|
||||
if ((i & h) == 0) { const float x = v[i], y = v[i ^ h]; v[i] = x + y; v[i ^ h] = x - y; }
|
||||
arn_xstage<1>(v, lig);
|
||||
arn_xstage<2>(v, lig);
|
||||
arn_xstage<4>(v, lig);
|
||||
const float nrm = rsqrtf((float)ARN_GROUP);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < ARN_EPL; ++i) v[i] *= nrm;
|
||||
}
|
||||
|
||||
template <int HAD, int THR, bool WOUT, int WIRE>
|
||||
__global__ __launch_bounds__(THR) void halo_ar_ln_had_quant_i8_kernel(
|
||||
const __hip_bfloat16* __restrict__ X, __hip_bfloat16* __restrict__ RES,
|
||||
const __hip_bfloat16* __restrict__ Wg, __hip_bfloat16* __restrict__ OUTB,
|
||||
signed char* __restrict__ Q, float* __restrict__ S,
|
||||
int4* peer_base, const int4* my_base,
|
||||
unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs,
|
||||
int M, int K, int slot_stride16, int drain, int acq,
|
||||
float eps, float wadd, float rnorm, unsigned int nbw) {
|
||||
constexpr int VPL = HAD / 32, NW = THR / 32;
|
||||
constexpr int MAXB = HALO_ARN_MAXVALS / VPL;
|
||||
extern __shared__ float lds[];
|
||||
// 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;
|
||||
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x;
|
||||
const int lane = tid & 31, wave = tid >> 5;
|
||||
const int nblk = K / HAD;
|
||||
// Contiguous row range. 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);
|
||||
|
||||
__shared__ unsigned int s_seq, s_slot;
|
||||
halo_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int sq = s_seq;
|
||||
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 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;
|
||||
const char* m_pay = (const char*)ms;
|
||||
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 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;
|
||||
|
||||
unsigned int hck = 0u; // the push check (halo_ar_seq.h)
|
||||
if constexpr (WIRE == 0) {
|
||||
// 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;
|
||||
int k = wstart + tid;
|
||||
for (; k + 3 * THR < wend; k += 4 * THR) {
|
||||
int4 v0 = in4[k], v1 = in4[k + THR], v2 = in4[k + 2 * THR], v3 = in4[k + 3 * THR];
|
||||
ps[k] = v0; ps[k + THR] = v1; ps[k + 2 * THR] = v2; ps[k + 3 * THR] = v3;
|
||||
hck += halo_archk_u4(v0, 4u * (unsigned)k) + halo_archk_u4(v1, 4u * (unsigned)(k + THR)) +
|
||||
halo_archk_u4(v2, 4u * (unsigned)(k + 2 * THR)) + halo_archk_u4(v3, 4u * (unsigned)(k + 3 * THR));
|
||||
}
|
||||
for (; k < wend; k += THR) { const int4 v = in4[k]; ps[k] = v; hck += halo_archk_u4(v, 4u * (unsigned)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.
|
||||
for (int ci = wave; ci < cpb; ci += NW) {
|
||||
const int c = c00 + ci;
|
||||
unsigned int acc[ARN_NWORD];
|
||||
#pragma unroll
|
||||
for (int w = 0; w < ARN_NWORD; ++w) acc[w] = 0u;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < ARN_ITERS; ++t) {
|
||||
const int gl = t * ARN_GPW + gw; // group within the chunk
|
||||
const long off = (long)(c * ARN_CG + gl) * ARN_GROUP + (long)lig * ARN_EPL;
|
||||
float v[ARN_EPL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < ARN_EPL; ++i) v[i] = __bfloat162float(X[off + i]);
|
||||
arn_wht(v, lig);
|
||||
float a = 0.f;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < ARN_EPL; ++i) a = fmaxf(a, fabsf(v[i]));
|
||||
a = fmaxf(a, halo_xor_lane<1>(a));
|
||||
a = fmaxf(a, halo_xor_lane<2>(a));
|
||||
a = fmaxf(a, halo_xor_lane<4>(a));
|
||||
float scl = (a > 0.f) ? arn_bf16_round(a * (1.0f / (float)ARN_QMAX)) : 1.0f;
|
||||
if (!(scl > 0.f)) scl = 1.0f;
|
||||
if (lig == 0) {
|
||||
const unsigned short sc16 = (unsigned short)(__float_as_uint(scl) >> 16);
|
||||
p_sc[c * ARN_CG + gl] = sc16;
|
||||
Lsc[(size_t)ci * ARN_CG + gl] = scl;
|
||||
hck += halo_archk_mix(sc16, HALO_ARCHK_U16 + (unsigned)(c * ARN_CG + gl));
|
||||
}
|
||||
const float inv = 1.0f / scl;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < ARN_EPL; ++i) {
|
||||
const unsigned int sym =
|
||||
(unsigned int)(min(max((int)rintf(v[i] * inv), ARN_QMIN), ARN_QMAX) - ARN_QMIN);
|
||||
const int bit = (t * ARN_EPL + i) * ARN_BITS, wi = bit >> 5, bo = bit & 31;
|
||||
acc[wi] |= sym << bo;
|
||||
if (bo + ARN_BITS > 32) acc[wi + 1] |= sym >> (32 - bo);
|
||||
}
|
||||
}
|
||||
// Flush lane-contiguously region by region, widest first, so each region is one coalesced
|
||||
// store of ARN_WV x width bytes (ARN_NWORD is 3).
|
||||
char* pb = p_pay + (size_t)c * ARN_CBYTES;
|
||||
const unsigned int cd = (unsigned)c * (ARN_CBYTES / 4); // the chunk's first dword
|
||||
#pragma unroll
|
||||
for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4) {
|
||||
*(uint4*)(pb + w4 * 4 * ARN_WV + lane * 16) =
|
||||
make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]);
|
||||
hck += halo_archk_u4(make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]),
|
||||
cd + (unsigned)(w4 * ARN_WV + lane * 4));
|
||||
}
|
||||
if constexpr (ARN_NWORD % 4 >= 2) {
|
||||
*(uint2*)(pb + (ARN_NWORD & ~3) * 4 * ARN_WV + lane * 8) =
|
||||
make_uint2(acc[ARN_NWORD & ~3], acc[(ARN_NWORD & ~3) + 1]);
|
||||
const unsigned int e = cd + (unsigned)((ARN_NWORD & ~3) * ARN_WV + lane * 2);
|
||||
hck += halo_archk_mix(acc[ARN_NWORD & ~3], e) + halo_archk_mix(acc[(ARN_NWORD & ~3) + 1], e + 1u);
|
||||
}
|
||||
if constexpr (ARN_NWORD % 2 == 1) {
|
||||
*(unsigned int*)(pb + (ARN_NWORD - 1) * 4 * ARN_WV + lane * 4) = acc[ARN_NWORD - 1];
|
||||
hck += halo_archk_mix(acc[ARN_NWORD - 1], cd + (unsigned)((ARN_NWORD - 1) * ARN_WV + lane));
|
||||
}
|
||||
#pragma unroll
|
||||
for (int w = 0; w < ARN_NWORD; ++w)
|
||||
Lpk[((size_t)ci * ARN_NWORD + w) * ARN_WV + lane] = acc[w];
|
||||
}
|
||||
}
|
||||
halo_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, sq);
|
||||
if (drain == 1) __threadfence_system();
|
||||
else if (drain == 3) asm volatile("s_waitcnt vmcnt(0)" ::: "memory"); // pre-gfx12 store wait
|
||||
__syncthreads();
|
||||
if (tid == 0) {
|
||||
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; trap rather than use stale bytes.
|
||||
while (halo_ar_seq_behind(arn_load_acq(&my_flags[b]), sq)) {
|
||||
if (++z > HALO_ARN_SPIN_MAX) __builtin_trap();
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (acq) __threadfence_system();
|
||||
halo_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) {
|
||||
if constexpr (WIRE == 0) {
|
||||
const int wpr = K >> 3;
|
||||
for (int k = r0 * wpr + tid; k < r1 * wpr; k += THR) h += halo_archk_u4(ms[k], 4u * (unsigned)k);
|
||||
} else {
|
||||
for (int ci = wave; ci < cpb; ci += NW) {
|
||||
const int c = c00 + ci;
|
||||
const char* pb = m_pay + (size_t)c * ARN_CBYTES;
|
||||
const unsigned int cd = (unsigned)c * (ARN_CBYTES / 4);
|
||||
#pragma unroll
|
||||
for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4)
|
||||
h += halo_archk_u4(*(const uint4*)(pb + w4 * 4 * ARN_WV + lane * 16),
|
||||
cd + (unsigned)(w4 * ARN_WV + lane * 4));
|
||||
if constexpr (ARN_NWORD % 4 >= 2) {
|
||||
const uint2 u = *(const uint2*)(pb + (ARN_NWORD & ~3) * 4 * ARN_WV + lane * 8);
|
||||
const unsigned int e = cd + (unsigned)((ARN_NWORD & ~3) * ARN_WV + lane * 2);
|
||||
h += halo_archk_mix(u.x, e) + halo_archk_mix(u.y, e + 1u);
|
||||
}
|
||||
if constexpr (ARN_NWORD % 2 == 1)
|
||||
h += halo_archk_mix(*(const unsigned int*)(pb + (ARN_NWORD - 1) * 4 * ARN_WV + lane * 4),
|
||||
cd + (unsigned)((ARN_NWORD - 1) * ARN_WV + lane));
|
||||
#pragma unroll
|
||||
for (int t = 0; t < ARN_ITERS; ++t) {
|
||||
const int gl = t * ARN_GPW + gw;
|
||||
if (lig == 0) h += halo_archk_mix(m_sc[c * ARN_CG + gl], HALO_ARCHK_U16 + (unsigned)(c * ARN_CG + gl));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 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 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;
|
||||
unsigned int pac[ARN_NWORD], lac[ARN_NWORD];
|
||||
#pragma unroll
|
||||
for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4) {
|
||||
const uint4 pq = *(const uint4*)(pb + w4 * 4 * ARN_WV + lane * 16);
|
||||
pac[w4] = pq.x; pac[w4 + 1] = pq.y; pac[w4 + 2] = pq.z; pac[w4 + 3] = pq.w;
|
||||
}
|
||||
if constexpr (ARN_NWORD % 4 >= 2) {
|
||||
const uint2 pu = *(const uint2*)(pb + (ARN_NWORD & ~3) * 4 * ARN_WV + lane * 8);
|
||||
pac[ARN_NWORD & ~3] = pu.x; pac[(ARN_NWORD & ~3) + 1] = pu.y;
|
||||
}
|
||||
if constexpr (ARN_NWORD % 2 == 1)
|
||||
pac[ARN_NWORD - 1] = *(const unsigned int*)(pb + (ARN_NWORD - 1) * 4 * ARN_WV + lane * 4);
|
||||
#pragma unroll
|
||||
for (int w = 0; w < ARN_NWORD; ++w)
|
||||
lac[w] = Lpk[((size_t)ci * ARN_NWORD + w) * ARN_WV + lane];
|
||||
#pragma unroll
|
||||
for (int t = 0; t < ARN_ITERS; ++t) {
|
||||
const int gl = t * ARN_GPW + gw;
|
||||
const float psc = __uint_as_float((unsigned int)m_sc[c * ARN_CG + gl] << 16);
|
||||
const float lsc = Lsc[(size_t)ci * ARN_CG + gl];
|
||||
float v[ARN_EPL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < ARN_EPL; ++i) {
|
||||
const int bit = (t * ARN_EPL + i) * ARN_BITS, wi = bit >> 5, bo = bit & 31;
|
||||
unsigned int psy = pac[wi] >> bo, lsy = lac[wi] >> bo;
|
||||
if (bo + ARN_BITS > 32) {
|
||||
psy |= pac[wi + 1] << (32 - bo);
|
||||
lsy |= lac[wi + 1] << (32 - bo);
|
||||
}
|
||||
// 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 (libhalo/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)
|
||||
lds[e0 + i] = __bfloat162float(__float2bfloat16(v[i]));
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
for (int row = r0; row < r1; ++row) {
|
||||
float* rl = lds + (size_t)(WIRE ? (row - r0) : 0) * K;
|
||||
const __hip_bfloat16* x = X + (size_t)row * K;
|
||||
const __hip_bfloat16* p = P + (size_t)row * K;
|
||||
__hip_bfloat16* res = RES ? RES + (size_t)row * K : nullptr;
|
||||
(void)x; (void)p;
|
||||
float u[WOUT ? MAXB : 1][VPL];
|
||||
float ss = 0.f, m = 0.f;
|
||||
int nbk = 0;
|
||||
for (int blk = wave; blk < nblk; blk += NW, nbk++) {
|
||||
const int base = blk * HAD + lane * VPL;
|
||||
float v[VPL];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPL; j++) {
|
||||
// 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(
|
||||
__bfloat162float(x[base + j]) + __bfloat162float(p[base + j])));
|
||||
} else {
|
||||
t = rl[base + j];
|
||||
}
|
||||
if (res) {
|
||||
t += __bfloat162float(res[base + j]);
|
||||
res[base + j] = __float2bfloat16(t);
|
||||
}
|
||||
ss += t * t;
|
||||
v[j] = t * (__bfloat162float(Wg[base + j]) + wadd);
|
||||
if (WOUT) u[nbk][j] = v[j];
|
||||
}
|
||||
halo_fwht_wave<HAD>(v, lane);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPL; j++) {
|
||||
rl[base + j] = v[j];
|
||||
m = fmaxf(m, fabsf(v[j]));
|
||||
}
|
||||
}
|
||||
ss = halo_wave_sum(ss);
|
||||
m = halo_wave_max(m);
|
||||
if (lane == 0) { red[wave] = ss; red[NW + wave] = m; }
|
||||
__syncthreads();
|
||||
ss = 0.f; m = 0.f;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NW; i++) { ss += red[i]; m = fmaxf(m, red[NW + i]); }
|
||||
const float inv_rms = rsqrtf(ss / (float)K + eps);
|
||||
m = fmaxf(m, 1e-8f);
|
||||
const float inv = 127.f / m;
|
||||
if (tid == 0) S[row] = m * inv_rms * rnorm / 127.f;
|
||||
|
||||
if (WOUT) {
|
||||
nbk = 0;
|
||||
for (int blk = wave; blk < nblk; blk += NW, nbk++) {
|
||||
const int base = blk * HAD + lane * VPL;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPL; j++)
|
||||
OUTB[(size_t)row * K + base + j] = __float2bfloat16(u[nbk][j] * inv_rms);
|
||||
}
|
||||
}
|
||||
|
||||
signed char* q = Q + (size_t)row * K;
|
||||
for (int i = tid; i < K; i += THR) {
|
||||
const int s = i >> 4, j = i & 15;
|
||||
const int sr = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3);
|
||||
const int t = __float2int_rn(rl[sr] * inv);
|
||||
q[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
|
||||
}
|
||||
// lds and red are reused by the block's next row.
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
|
||||
// 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 halo_ar_ln_wire_dims(int* stage_bits, int* chunk_elems, int* chunk_bytes, int* scale_bytes) {
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 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 halo_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) {
|
||||
const size_t cpb = (size_t)rows_max * (K / ARN_CE);
|
||||
b += cpb * ARN_WV * ARN_NWORD * sizeof(unsigned int) + cpb * ARN_CG * sizeof(float);
|
||||
}
|
||||
return b;
|
||||
}
|
||||
// Dynamic LDS ceiling: a workgroup's 64 KiB less the kernel's static words, which the runtime places
|
||||
// in front of it: seq and slot, and the push check's (halo_ar_seq.h: two 32-word sums and a flag,
|
||||
// 260 bytes), rounded up.
|
||||
static constexpr size_t kArnLdsCap = 65536 - 16 - 512;
|
||||
|
||||
// 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 halo_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;
|
||||
if (wire && K % ARN_CE) return -1;
|
||||
const int thr = nthreads ? nthreads : halo_act_threads(M, K);
|
||||
if (thr < 32) return -1;
|
||||
if ((K / had + thr / 32 - 1) / (thr / 32) * (had / 32) > HALO_ARN_MAXVALS) return -1;
|
||||
if (!wire) return ar_ln_lds_bytes(1, K, thr, 0) <= kArnLdsCap ? 1 : -1;
|
||||
const size_t fixed = ar_ln_lds_bytes(0, K, thr, wire);
|
||||
const size_t row = ar_ln_lds_bytes(1, K, thr, wire) - fixed;
|
||||
if (fixed + row > kArnLdsCap) return -1;
|
||||
const long fit = (long)((kArnLdsCap - fixed) / row);
|
||||
return (int)(((long)M + fit - 1) / fit);
|
||||
}
|
||||
|
||||
void halo_ar_ln_had_quant_i8(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
|
||||
long seq_ctrs, long slot_stride16,
|
||||
long x, long residual, long wgain, long out_bf16, long q, long s,
|
||||
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("halo ar_ln_had_quant_i8: K must be a multiple of 16");
|
||||
if (M < 1) throw std::runtime_error("halo ar_ln_had_quant_i8: M must be positive");
|
||||
if (had < 2 || (had & (had - 1))) throw std::runtime_error(
|
||||
"halo ar_ln_had_quant_i8: had must be a power of two");
|
||||
if (K % had) throw std::runtime_error(
|
||||
"halo ar_ln_had_quant_i8: had must divide K -- a rotation block cannot straddle a "
|
||||
"tensor-parallel shard boundary");
|
||||
int nb = nblocks < 1 ? 1 : nblocks;
|
||||
if (nb > M) nb = M; // row-aligned: a block owns whole rows
|
||||
const int nbw = halo_ar_max_blocks(); // the counter capacity; see halo_ar_seq.h
|
||||
if (nb > nbw) nb = nbw;
|
||||
const int thr = nthreads ? nthreads : halo_act_threads(M, K);
|
||||
if ((K / had + thr / 32 - 1) / (thr / 32) * (had / 32) > HALO_ARN_MAXVALS)
|
||||
throw std::runtime_error(
|
||||
"halo ar_ln_had_quant_i8: K too large for the register staging at this width");
|
||||
const int rows_max = (M + nb - 1) / nb;
|
||||
if (wire) {
|
||||
if (wire != 6) throw std::runtime_error("halo ar_ln_had_quant_i8: wire must be 0 or 6");
|
||||
// A chunk may not straddle a row, or the ranks would disagree on byte ownership.
|
||||
if (K % ARN_CE) throw std::runtime_error(
|
||||
"halo 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(
|
||||
"halo ar_ln_had_quant_i8: the rows a block owns do not fit LDS at this block count");
|
||||
const float rn = 1.f / sqrtf((float)had);
|
||||
#define HALO_ARN_LAUNCH(H, T, W, R) \
|
||||
hipLaunchKernelGGL((halo_ar_ln_had_quant_i8_kernel<H, T, W, R>), \
|
||||
dim3(nb), dim3(T), shmem, (hipStream_t)stream, (const __hip_bfloat16*)x, \
|
||||
(__hip_bfloat16*)residual, (const __hip_bfloat16*)wgain, (__hip_bfloat16*)out_bf16, \
|
||||
(signed char*)q, (float*)s, (int4*)peer_scratch, (const int4*)my_scratch, \
|
||||
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, M, K, (int)slot_stride16, \
|
||||
drain, acq, eps, wadd, rn, (unsigned)nbw)
|
||||
#define HALO_ARN_T(H, W, R) switch (thr) { \
|
||||
case 128: HALO_ARN_LAUNCH(H, 128, W, R); break; \
|
||||
case 256: HALO_ARN_LAUNCH(H, 256, W, R); break; \
|
||||
case 512: HALO_ARN_LAUNCH(H, 512, W, R); break; \
|
||||
case 1024: HALO_ARN_LAUNCH(H, 1024, W, R); break; \
|
||||
default: throw std::runtime_error( \
|
||||
"halo ar_ln_had_quant_i8: workgroup width must be 128, 256, 512 or 1024"); }
|
||||
#define HALO_ARN_W(W, R) switch (had) { \
|
||||
case 128: HALO_ARN_T(128, W, R); break; \
|
||||
case 256: HALO_ARN_T(256, W, R); break; \
|
||||
case 512: HALO_ARN_T(512, W, R); break; \
|
||||
default: throw std::runtime_error( \
|
||||
"halo ar_ln_had_quant_i8: only widths 128, 256 and 512 are compiled"); }
|
||||
if (wire) {
|
||||
if (out_bf16) { HALO_ARN_W(true, 6); } else { HALO_ARN_W(false, 6); }
|
||||
} else {
|
||||
if (out_bf16) { HALO_ARN_W(true, 0); } else { HALO_ARN_W(false, 0); }
|
||||
}
|
||||
#undef HALO_ARN_W
|
||||
#undef HALO_ARN_T
|
||||
#undef HALO_ARN_LAUNCH
|
||||
}
|
||||
@@ -0,0 +1,518 @@
|
||||
/* Derived from libr4d/r4d_ar_oneshot_2rank_exact.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_ar_oneshot_2rank_exact.hip: halo_ar_oneshot_2rank_exact -- multi-block one-shot P2P-BAR
|
||||
// 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 halo.h; the caller passes raw pointers, element count, dtype and stream.
|
||||
//
|
||||
// Design:
|
||||
// * 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 (halo_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 "halo.h"
|
||||
#include "halo_ar_seq.h"
|
||||
#include "halo_ar_hc.h" // the gather word and the hc write word, shared with the rotated wire
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#define HALO_AR_SPIN_MAX 4000000000ULL
|
||||
#define HALO_AR_MAX_BLOCKS 512
|
||||
#define HIPOK(e) do { hipError_t _e = (e); if (_e != hipSuccess) \
|
||||
throw std::runtime_error(std::string("hip: ") + hipGetErrorString(_e)); } while (0)
|
||||
|
||||
__device__ __forceinline__ void store_sys_rel(unsigned int* p, unsigned int v) {
|
||||
__hip_atomic_store(p, v, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
__device__ __forceinline__ unsigned int load_sys_acq(const unsigned int* p) {
|
||||
return __hip_atomic_load(p, __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
__device__ __forceinline__ float rd_to_f(const float& x) { return x; }
|
||||
__device__ __forceinline__ float rd_to_f(const __half& x) { return __half2float(x); }
|
||||
__device__ __forceinline__ float rd_to_f(const __hip_bfloat16& x) { return (float)x; }
|
||||
__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; }
|
||||
|
||||
// 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;
|
||||
const T* pa = reinterpret_cast<const T*>(&a);
|
||||
const T* pb = reinterpret_cast<const T*>(&b);
|
||||
T* pr = reinterpret_cast<T*>(&r);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < LANES; ++j) rd_from_f(rd_to_f(pa[j]) + rd_to_f(pb[j]), pr[j]);
|
||||
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; no cross-block sync.
|
||||
template <typename T, int LANES>
|
||||
__global__ void halo_ar_oneshot_2rank_exact_kernel(
|
||||
const int4* __restrict__ in4, int4* peer_base, const int4* my_base, int4* __restrict__ out4,
|
||||
unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs,
|
||||
int n16, int slot_stride16, int drain, int acq, unsigned int nbw) {
|
||||
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
|
||||
__shared__ unsigned int s_seq, s_slot;
|
||||
halo_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int slot = (int)s_slot;
|
||||
int4* ps = peer_base + (size_t)slot * slot_stride16;
|
||||
const int4* ms = my_base + (size_t)slot * slot_stride16;
|
||||
|
||||
const int w = (n16 + nb - 1) / nb; // 16B words per block
|
||||
const int start = b * w;
|
||||
int end = start + w; if (end > n16) end = n16;
|
||||
unsigned int hck = 0u; // the push check (halo_ar_seq.h)
|
||||
|
||||
// drain 4, tests only (halo_ar_late_push_pin, halo_selftest): the flag goes out before the push
|
||||
// and the push ~20 us after it, so the peer sees a flag whose bytes have not landed -- what a
|
||||
// push over PCIe P2P now and then does on its own -- on every launch.
|
||||
if (drain == 4) {
|
||||
if (tid == 0) store_sys_rel(&peer_flags[b], s);
|
||||
const unsigned long long t0 = wall_clock64();
|
||||
while (wall_clock64() - t0 < 2000ull) __builtin_amdgcn_s_sleep(8); // 100 MHz: 20 us
|
||||
}
|
||||
// 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) {
|
||||
int4 v0 = in4[k], v1 = in4[k + nt], v2 = in4[k + 2 * nt], v3 = in4[k + 3 * nt];
|
||||
ps[k] = v0; ps[k + nt] = v1; ps[k + 2 * nt] = v2; ps[k + 3 * nt] = v3;
|
||||
hck += halo_archk_u4(v0, 4u * (unsigned)k) + halo_archk_u4(v1, 4u * (unsigned)(k + nt)) +
|
||||
halo_archk_u4(v2, 4u * (unsigned)(k + 2 * nt)) + halo_archk_u4(v3, 4u * (unsigned)(k + 3 * nt));
|
||||
}
|
||||
for (; k < end; k += nt) { const int4 v = in4[k]; ps[k] = v; hck += halo_archk_u4(v, 4u * (unsigned)k); }
|
||||
}
|
||||
// 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_waitcnt vmcnt(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).
|
||||
halo_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s, drain == 4);
|
||||
if (drain == 1) __threadfence_system();
|
||||
else if (drain == 3) asm volatile("s_waitcnt vmcnt(0)" ::: "memory"); // pre-gfx12 store wait
|
||||
__syncthreads();
|
||||
if (tid == 0) {
|
||||
if (drain == 2) __threadfence_system();
|
||||
if (drain != 4) store_sys_rel(&peer_flags[b], s);
|
||||
unsigned long long z = 0;
|
||||
// A handshake that cannot complete is a lockstep violation; trap rather than sum stale bytes.
|
||||
while (halo_ar_seq_behind(load_sys_acq(&my_flags[b]), s)) {
|
||||
if (++z > HALO_AR_SPIN_MAX) __builtin_trap();
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (acq) __threadfence_system();
|
||||
halo_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) {
|
||||
for (int k = start + tid; k < end; k += nt) h += halo_archk_u4(ms[k], 4u * (unsigned)k);
|
||||
});
|
||||
// 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) {
|
||||
out4[k] = vadd<T, LANES>(in4[k], ms[k]);
|
||||
out4[k + nt] = vadd<T, LANES>(in4[k + nt], ms[k + nt]);
|
||||
out4[k + 2 * nt] = vadd<T, LANES>(in4[k + 2 * nt], ms[k + 2 * nt]);
|
||||
out4[k + 3 * nt] = vadd<T, LANES>(in4[k + 3 * nt], ms[k + 3 * nt]);
|
||||
}
|
||||
for (; k < end; k += nt) out4[k] = vadd<T, LANES>(in4[k], ms[k]);
|
||||
}
|
||||
}
|
||||
|
||||
// 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 (halo_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).
|
||||
//
|
||||
// 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 halo_ar_hc_write_kernel(
|
||||
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
|
||||
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
|
||||
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
|
||||
int slot_stride16, int drain, int acq, unsigned int nbw, long long* gate,
|
||||
unsigned int* gate_ctr) {
|
||||
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 = halo_ar_link_word(gate, (unsigned int)tid);
|
||||
halo_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int slot = (int)s_slot;
|
||||
int4* ps = peer_base + (size_t)slot * slot_stride16;
|
||||
const int4* ms = my_base + (size_t)slot * slot_stride16;
|
||||
|
||||
const int w = (n16 + nb - 1) / nb; // 16B words per block
|
||||
const int start = b * w;
|
||||
int end = start + w; if (end > n16) end = n16;
|
||||
unsigned int hck = 0u; // the push check (halo_ar_seq.h)
|
||||
|
||||
{
|
||||
int k = start + tid;
|
||||
for (; k + 3 * nt < end; k += 4 * nt) {
|
||||
int4 v0 = y4[k], v1 = y4[k + nt], v2 = y4[k + 2 * nt], v3 = y4[k + 3 * nt];
|
||||
ps[k] = v0; ps[k + nt] = v1; ps[k + 2 * nt] = v2; ps[k + 3 * nt] = v3;
|
||||
hck += halo_archk_u4(v0, 4u * (unsigned)k) + halo_archk_u4(v1, 4u * (unsigned)(k + nt)) +
|
||||
halo_archk_u4(v2, 4u * (unsigned)(k + 2 * nt)) + halo_archk_u4(v3, 4u * (unsigned)(k + 3 * nt));
|
||||
}
|
||||
for (; k < end; k += nt) { const int4 v = y4[k]; ps[k] = v; hck += halo_archk_u4(v, 4u * (unsigned)k); }
|
||||
}
|
||||
halo_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s);
|
||||
if (drain == 1) __threadfence_system();
|
||||
else if (drain == 3) asm volatile("s_waitcnt vmcnt(0)" ::: "memory"); // pre-gfx12 store wait
|
||||
__syncthreads();
|
||||
if (tid == 0) {
|
||||
if (drain == 2) __threadfence_system();
|
||||
store_sys_rel(&peer_flags[b], s);
|
||||
unsigned long long z = 0;
|
||||
while (halo_ar_seq_behind(load_sys_acq(&my_flags[b]), s)) {
|
||||
if (++z > HALO_AR_SPIN_MAX) __builtin_trap();
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (acq) __threadfence_system();
|
||||
halo_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) {
|
||||
for (int k = start + tid; k < end; k += nt) h += halo_archk_u4(ms[k], 4u * (unsigned)k);
|
||||
});
|
||||
halo_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
const int wpr = n >> 3; // 16B words a row
|
||||
for (int k = start + tid; k < end; k += nt) {
|
||||
const int4 r = vadd<__hip_bfloat16, 8>(y4[k], ms[k]);
|
||||
y4[k] = r;
|
||||
const int row = k / wpr, i0 = (k - row * wpr) * 8;
|
||||
halo_ar_hc_write_word(inj, h, row, i0, n, hc, irow, hrow,
|
||||
reinterpret_cast<const unsigned short*>(&r));
|
||||
}
|
||||
}
|
||||
|
||||
// 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 (halo_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 HALO_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.
|
||||
//
|
||||
// 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 halo_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 halo_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;
|
||||
__syncthreads();
|
||||
for (int i = threadIdx.x; i < T; i += blockDim.x) {
|
||||
const int f = sorted[i];
|
||||
if (f >= 0 && f < T) inv[f] = i;
|
||||
}
|
||||
}
|
||||
|
||||
template <bool INV>
|
||||
__global__ void halo_ar_gather_hc_write_kernel(
|
||||
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
|
||||
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
|
||||
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
|
||||
int slot_stride16, int drain, int acq, unsigned int nbw, HaloArGather G,
|
||||
const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr) {
|
||||
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
|
||||
__shared__ unsigned int s_seq, s_slot;
|
||||
__shared__ int s_i[HALO_ARG_ROWS * HALO_ARG_SLOTS];
|
||||
__shared__ float s_w[HALO_ARG_ROWS * HALO_ARG_SLOTS];
|
||||
__shared__ float s_g[HALO_ARG_ROWS];
|
||||
const long long gate_word = halo_ar_link_word(gate, (unsigned int)tid);
|
||||
halo_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int slot = (int)s_slot;
|
||||
int4* ps = peer_base + (size_t)slot * slot_stride16;
|
||||
const int4* ms = my_base + (size_t)slot * slot_stride16;
|
||||
|
||||
const int w = (n16 + nb - 1) / nb; // 16B words per block
|
||||
const int start = b * w;
|
||||
int end = start + w; if (end > n16) end = n16;
|
||||
unsigned int hck = 0u; // the push check (halo_ar_seq.h)
|
||||
const int wpr = n >> 3; // 16B words a row
|
||||
const int row_lo = start / wpr;
|
||||
const int nrow = end > start ? (end - 1) / wpr - row_lo + 1 : 0;
|
||||
const int K = G.top_k;
|
||||
|
||||
/* 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();
|
||||
{
|
||||
const int lo = row_lo * K, hi = (row_lo + nrow) * K;
|
||||
for (int i = tid; i < G.T; i += nt) {
|
||||
const int f = G.sorted[i];
|
||||
if (f >= lo && f < hi) s_i[f - lo] = i;
|
||||
}
|
||||
}
|
||||
for (int x = tid; x < nrow * K; x += nt)
|
||||
s_w[x] = bf2f(G.ew[(long)(row_lo + x / K) * G.ew_ld + x % K]);
|
||||
if (G.sh)
|
||||
for (int r = tid; r < nrow; r += nt) {
|
||||
const float v0 = bf2f(G.sg[(long)(row_lo + r) * G.sg_ld]);
|
||||
s_g[r] = G.sig ? (1.0f / (1.0f + __expf(-v0))) : v0;
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
/* 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 = halo_ar_gather_word<INV>(G, inv, s_i, s_w, s_g, row, row - row_lo, i0);
|
||||
y4[k] = out;
|
||||
ps[k] = out;
|
||||
hck += halo_archk_u4(out, 4u * (unsigned)k);
|
||||
}
|
||||
halo_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s);
|
||||
if (drain == 1) __threadfence_system();
|
||||
else if (drain == 3) asm volatile("s_waitcnt vmcnt(0)" ::: "memory"); // pre-gfx12 store wait
|
||||
__syncthreads();
|
||||
if (tid == 0) {
|
||||
if (drain == 2) __threadfence_system();
|
||||
store_sys_rel(&peer_flags[b], s);
|
||||
unsigned long long z = 0;
|
||||
while (halo_ar_seq_behind(load_sys_acq(&my_flags[b]), s)) {
|
||||
if (++z > HALO_AR_SPIN_MAX) __builtin_trap();
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (acq) __threadfence_system();
|
||||
halo_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) {
|
||||
for (int k = start + tid; k < end; k += nt) h += halo_archk_u4(ms[k], 4u * (unsigned)k);
|
||||
});
|
||||
halo_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
for (int k = start + tid; k < end; k += nt) {
|
||||
const int4 r = vadd<__hip_bfloat16, 8>(y4[k], ms[k]);
|
||||
y4[k] = r;
|
||||
const int row = k / wpr, i0 = (k - row * wpr) * 8;
|
||||
halo_ar_hc_write_word(inj, h, row, i0, n, hc, irow, hrow,
|
||||
reinterpret_cast<const unsigned short*>(&r));
|
||||
}
|
||||
}
|
||||
|
||||
// The IPC handle goes into a caller-owned buffer of HALO_AR_HANDLE_BYTES so this stays a C ABI.
|
||||
static_assert(sizeof(hipIpcMemHandle_t) <= HALO_AR_HANDLE_BYTES, "ipc handle larger than the ABI buffer");
|
||||
|
||||
long halo_ar_ipc_alloc(long size, int finegrained, char* out_handle, int* out_len) {
|
||||
void* p = nullptr;
|
||||
if (finegrained) HIPOK(hipExtMallocWithFlags(&p, size, hipDeviceMallocFinegrained));
|
||||
else HIPOK(hipMalloc(&p, size));
|
||||
HIPOK(hipMemset(p, 0, size));
|
||||
// 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));
|
||||
// The handle is for an out-of-process peer. libhalo's ranks are threads of one process and share
|
||||
// the pointer itself (halo_ar_entry.hip), so a refused export is not fatal: beside another engine
|
||||
// on the same cards hipIpcGetMemHandle answers invalid argument while the allocation is fine.
|
||||
hipIpcMemHandle_t h;
|
||||
if (hipIpcGetMemHandle(&h, p) == hipSuccess) {
|
||||
std::memcpy(out_handle, &h, sizeof(h));
|
||||
*out_len = (int)sizeof(h);
|
||||
} else {
|
||||
(void)hipGetLastError();
|
||||
std::memset(out_handle, 0, HALO_AR_HANDLE_BYTES);
|
||||
*out_len = 0;
|
||||
}
|
||||
return (long)p;
|
||||
}
|
||||
/* halo_p2p_copy2d_kernel, halo_p2p_fence and halo_p2p_copy2d are libhalo's own unit
|
||||
* (halo_p2p_copy2d.hip), declared in halo.h; libr4d keeps them in this file. Not repeated here. */
|
||||
|
||||
void halo_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
|
||||
long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n,
|
||||
long hc, long irow, long hrow, long stream_i, long nblocks, long nthreads,
|
||||
long drain, long acq, long gate, long gate_ctr) {
|
||||
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;
|
||||
if (nb > n16) nb = n16;
|
||||
if (nb > HALO_AR_MAX_BLOCKS) nb = HALO_AR_MAX_BLOCKS;
|
||||
const unsigned nbw = (unsigned)halo_ar_max_blocks();
|
||||
if ((unsigned)nb > nbw) nb = (int)nbw;
|
||||
int nt = (int)nthreads;
|
||||
if (nt < 64) nt = 64;
|
||||
if (nt > 1024) nt = 1024;
|
||||
nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes
|
||||
halo_ar_hc_write_kernel<<<nb, nt, 0, st>>>(
|
||||
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags,
|
||||
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h,
|
||||
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw,
|
||||
(long long*)gate, (unsigned int*)gate_ctr);
|
||||
}
|
||||
|
||||
int halo_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
|
||||
long seq_ctrs, long slot_stride16, long y, long inj, long h, long M,
|
||||
long n, long hc, long irow, long hrow, long 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 stream_i, long nblocks, long nthreads,
|
||||
long drain, long acq, long inv, long gate, long gate_ctr) {
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
if (n <= 0 || M <= 0 || n % 8 || hc < 1 || hrow % 8) return -1;
|
||||
if (top_k < 1 || top_k > HALO_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)halo_ar_max_blocks();
|
||||
int nb = (int)nblocks;
|
||||
if (nb < 1) nb = 1;
|
||||
/* Enough blocks that none spans more than HALO_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 = (HALO_ARG_ROWS - 2) * wpr + 1;
|
||||
const int nb_min = (n16 + wmax - 1) / wmax;
|
||||
/* 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;
|
||||
if (nb > HALO_AR_MAX_BLOCKS || (unsigned)nb > nbw) return -4;
|
||||
int nt = (int)nthreads;
|
||||
if (nt < 64) nt = 64;
|
||||
if (nt > 1024) nt = 1024;
|
||||
nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes
|
||||
/* 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. */
|
||||
HaloArGather G;
|
||||
std::memset(&G, 0, sizeof G);
|
||||
G.ye = (const unsigned short*)ye;
|
||||
G.ew = (const unsigned short*)ew;
|
||||
G.sorted = (const int*)sorted;
|
||||
G.sh = (const unsigned short*)sh;
|
||||
G.sg = (const unsigned short*)sg;
|
||||
G.ye_ld = ye_ld; G.ew_ld = ew_ld; G.sh_ld = sh_ld; G.sg_ld = sg_ld;
|
||||
G.top_k = (int)top_k; G.T = (int)(M * top_k); G.sig = (int)sig;
|
||||
if (by_inv) {
|
||||
halo_ar_gather_inv_kernel<<<1, 1024, 0, st>>>((int*)inv, (const int*)sorted, G.T);
|
||||
halo_ar_gather_hc_write_kernel<true><<<nb, nt, 0, st>>>(
|
||||
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags,
|
||||
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h,
|
||||
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G,
|
||||
(const int*)inv, (long long*)gate, (unsigned int*)gate_ctr);
|
||||
} else {
|
||||
halo_ar_gather_hc_write_kernel<false><<<nb, nt, 0, st>>>(
|
||||
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags,
|
||||
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h,
|
||||
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G,
|
||||
nullptr, (long long*)gate, (unsigned int*)gate_ctr);
|
||||
}
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
|
||||
/* The inverse slot table alone, for the wide fused gather (halo_ar_oneshot_Nrank_exact.hip); same
|
||||
* kernel and launch as above. */
|
||||
int halo_ar_gather_inv(long inv, long sorted, long T, long stream_i) {
|
||||
if (!inv || !sorted || T < 1) return -1;
|
||||
halo_ar_gather_inv_kernel<<<1, 1024, 0, (hipStream_t)stream_i>>>((int*)inv, (const int*)sorted,
|
||||
(int)T);
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
|
||||
void halo_ar_ipc_free(long p) { if (p) (void)hipFree((void*)p); }
|
||||
|
||||
// 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 halo_ar_host_alloc(long size) {
|
||||
void* p = nullptr;
|
||||
HIPOK(hipHostMalloc(&p, size, hipHostMallocCoherent | hipHostMallocMapped |
|
||||
hipHostMallocPortable));
|
||||
std::memset(p, 0, (size_t)size);
|
||||
void* d = nullptr;
|
||||
const hipError_t e = hipHostGetDevicePointer(&d, p, 0);
|
||||
if (e != hipSuccess || d != p) {
|
||||
(void)hipHostFree(p);
|
||||
throw std::runtime_error(e != hipSuccess
|
||||
? std::string("host mailbox: no card address: ") + hipGetErrorString(e)
|
||||
: std::string("host mailbox: the card address differs from the CPU address"));
|
||||
}
|
||||
return (long)p;
|
||||
}
|
||||
void halo_ar_host_free(long p) { if (p) (void)hipHostFree((void*)p); }
|
||||
|
||||
// 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 halo_ar_entry.hip).
|
||||
void halo_ar_ipc_enable_peer(long peer) {
|
||||
hipError_t e = hipDeviceEnablePeerAccess((int)peer, 0);
|
||||
if (e == hipErrorPeerAccessAlreadyEnabled) { (void)hipGetLastError(); return; }
|
||||
if (e != hipSuccess)
|
||||
throw std::runtime_error(std::string("enable_peer: ") + hipGetErrorString(e));
|
||||
}
|
||||
|
||||
/* halo_ar_late_push_pin: 1 makes every 2-rank exact all-reduce send its flags before its pushes
|
||||
* (drain 4). A test hook (halo_selftest); nothing else sets it. */
|
||||
static int g_ar_late_push = 0;
|
||||
extern "C" void halo_ar_late_push_pin(int on) { g_ar_late_push = on; }
|
||||
|
||||
void halo_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_flags,
|
||||
long my_flags, long seq_ctrs, long slot_stride16,
|
||||
long inp, long out, long n_elem, long dtype,
|
||||
long stream_i, long nblocks, long nthreads,
|
||||
long drain, long acq) {
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
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 > HALO_AR_MAX_BLOCKS) nb = HALO_AR_MAX_BLOCKS;
|
||||
// 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 (halo_ar_seq.h).
|
||||
const unsigned nbw = (unsigned)halo_ar_max_blocks();
|
||||
if ((unsigned)nb > nbw) nb = (int)nbw;
|
||||
int nt = (int)nthreads;
|
||||
if (nt < 64) nt = 64;
|
||||
if (nt > 1024) nt = 1024;
|
||||
nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes
|
||||
// Tests only: every push lands after its flag (drain 4 above). Not in the tuning table, so no
|
||||
// tuner can pick it.
|
||||
if (g_ar_late_push) drain = 4;
|
||||
#define L(T, LN) halo_ar_oneshot_2rank_exact_kernel<T, LN><<<nb, nt, 0, st>>>( \
|
||||
(const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out, \
|
||||
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16, \
|
||||
(int)slot_stride16, (int)drain, (int)acq, nbw)
|
||||
if (dtype == 0) L(__hip_bfloat16, 8);
|
||||
else if (dtype == 1) L(__half, 8);
|
||||
else if (dtype == 2) L(float, 4);
|
||||
else throw std::runtime_error("all_reduce: bad dtype");
|
||||
#undef L
|
||||
}
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
/* Derived from libr4d/r4d_ar_oneshot_2rank_wht6.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
#pragma once
|
||||
// halo_ar_oneshot_2rank_wht6.h: device code for halo_ar_oneshot_2rank_wht6, the rotated 6-bit payload of the
|
||||
// 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 halo_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
|
||||
// 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 halo_ar_oneshot_2rank_exact.hip: per-block
|
||||
// device-resident seq counter, slot from the per-launch parity counters (halo_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 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 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>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include "halo_ar_seq.h"
|
||||
#include "halo_common.h" // halo_xor_lane
|
||||
|
||||
#define HALO_AR_SPIN_MAX 4000000000ULL
|
||||
#define HALO_AR_MAX_BLOCKS 512
|
||||
#define GROUP 64 // elements per rotation + scaling group
|
||||
#define BITS 6 // bits per symbol
|
||||
#define EPL 8 // elements per lane per group
|
||||
#define LPG (GROUP / EPL) // 8 lanes span one group
|
||||
#define WAVE 32
|
||||
#define GPW (WAVE * EPL / GROUP) // 4 groups per wave per iteration
|
||||
#define CHUNK_GROUPS 32 // groups per wave-chunk (makes 64 symbols/lane = 3 uint4)
|
||||
#define CHUNK_ELEMS (CHUNK_GROUPS * GROUP)
|
||||
|
||||
__device__ __forceinline__ void store_sys_rel(unsigned int* p, unsigned int v) {
|
||||
__hip_atomic_store(p, v, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
__device__ __forceinline__ unsigned int load_sys_acq(const unsigned int* p) {
|
||||
return __hip_atomic_load(p, __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
__device__ __forceinline__ void do_drain(int drain) {
|
||||
if (drain == 1) __threadfence_system();
|
||||
else if (drain == 3) asm volatile("s_waitcnt vmcnt(0)" ::: "memory"); // pre-gfx12 store wait
|
||||
}
|
||||
|
||||
__device__ __forceinline__ float rd_to_f(const __half& x) { return __half2float(x); }
|
||||
__device__ __forceinline__ float rd_to_f(const __hip_bfloat16& x) { return (float)x; }
|
||||
__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, 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;
|
||||
u += 0x7fffu + lsb;
|
||||
return __uint_as_float(u & 0xffff0000u);
|
||||
}
|
||||
|
||||
|
||||
// `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;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < EPL; ++i) {
|
||||
const float o = halo_xor_lane<M>(v[i]);
|
||||
v[i] = __int_as_float(__float_as_int(v[i]) ^ sm) + o;
|
||||
}
|
||||
}
|
||||
|
||||
// Orthonormal Walsh-Hadamard over one group; its own inverse, so this routine also undoes it.
|
||||
// A group is LPG lanes x EPL elements: the in-register butterflies are free ALU, and with
|
||||
// ROW_XMASK the cross-lane stages are free too.
|
||||
__device__ __forceinline__ void wht(float* v, int lig) {
|
||||
static_assert(LPG == 8, "the cross-lane stages are unrolled for a group of 8 lanes");
|
||||
#pragma unroll
|
||||
for (int h = 1; h < EPL; h <<= 1)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < EPL; ++i)
|
||||
if ((i & h) == 0) { const float x = v[i], y = v[i ^ h]; v[i] = x + y; v[i ^ h] = x - y; }
|
||||
ar6_xstage<1>(v, lig);
|
||||
ar6_xstage<2>(v, lig);
|
||||
ar6_xstage<4>(v, lig);
|
||||
const float nrm = rsqrtf((float)GROUP);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < EPL; ++i) v[i] *= nrm;
|
||||
}
|
||||
|
||||
// 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 halo_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 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
|
||||
static constexpr int NW = ITERS * EPL * BITS / 32; // packed words a lane holds
|
||||
static constexpr int ELEMS = CG * GROUP;
|
||||
static constexpr bool U4 = NW % 4 == 0;
|
||||
static_assert(ITERS >= 1 && ITERS * WAVE * EPL == CG * GROUP, "a chunk is whole wave-iterations");
|
||||
static_assert(ITERS * EPL * BITS % 32 == 0, "a lane's symbols fill whole words");
|
||||
};
|
||||
|
||||
// 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,
|
||||
unsigned short* p_sc, uint4* l_pay, float* l_sc,
|
||||
unsigned int& hck) {
|
||||
using Ch = Wht6Chunk<CG>;
|
||||
const int qmin = -(1 << (BITS - 1)), qmax = (1 << (BITS - 1)) - 1;
|
||||
unsigned int acc[Ch::NW];
|
||||
#pragma unroll
|
||||
for (int k = 0; k < Ch::NW; ++k) acc[k] = 0u;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < Ch::ITERS; ++t) {
|
||||
const int g = c * CG + t * GPW + gw;
|
||||
const bool live = (g < n_groups); // uniform across a group's lanes
|
||||
const long off = (long)g * GROUP + (long)lig * EPL;
|
||||
float v[EPL];
|
||||
if (live) {
|
||||
ld(off, v);
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < EPL; ++i) v[i] = 0.f;
|
||||
}
|
||||
wht(v, lig);
|
||||
float a = 0.f;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < EPL; ++i) a = fmaxf(a, fabsf(v[i]));
|
||||
a = fmaxf(a, halo_xor_lane<1>(a));
|
||||
a = fmaxf(a, halo_xor_lane<2>(a));
|
||||
a = fmaxf(a, halo_xor_lane<4>(a));
|
||||
float sc = (a > 0.f) ? bf16_round(a * (1.0f / (float)qmax)) : 1.0f;
|
||||
if (!(sc > 0.f)) sc = 1.0f;
|
||||
if (lig == 0 && live) {
|
||||
const unsigned short sc16 = (unsigned short)(__float_as_uint(sc) >> 16);
|
||||
p_sc[g] = sc16;
|
||||
l_sc[g] = sc;
|
||||
hck += halo_archk_mix(sc16, HALO_ARCHK_U16 + (unsigned)g);
|
||||
}
|
||||
const float inv = 1.0f / sc;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < EPL; ++i) {
|
||||
const int q = min(max((int)rintf(v[i] * inv), qmin), qmax) - qmin;
|
||||
const unsigned int sym = (unsigned int)q;
|
||||
const int bit = (t * EPL + i) * BITS, wi = bit >> 5, bo = bit & 31;
|
||||
acc[wi] |= sym << bo;
|
||||
if (bo + BITS > 32) acc[wi + 1] |= sym >> (32 - bo);
|
||||
}
|
||||
}
|
||||
if constexpr (Ch::U4) {
|
||||
#pragma unroll
|
||||
for (int u = 0; u < Ch::NW / 4; ++u) {
|
||||
const uint4 q = make_uint4(acc[4 * u], acc[4 * u + 1], acc[4 * u + 2], acc[4 * u + 3]);
|
||||
const long o = (long)c * (Ch::NW / 4 * WAVE) + (long)u * WAVE + lane;
|
||||
p_pay[o] = q;
|
||||
l_pay[o] = q;
|
||||
hck += halo_archk_u4(q, 4u * (unsigned)o);
|
||||
}
|
||||
} else {
|
||||
unsigned int* pp = reinterpret_cast<unsigned int*>(p_pay);
|
||||
unsigned int* lp = reinterpret_cast<unsigned int*>(l_pay);
|
||||
#pragma unroll
|
||||
for (int u = 0; u < Ch::NW; ++u) {
|
||||
const long o = (long)c * (Ch::NW * WAVE) + (long)u * WAVE + lane;
|
||||
pp[o] = acc[u];
|
||||
lp[o] = acc[u];
|
||||
hck += halo_archk_mix(acc[u], (unsigned)o);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
do_drain(drain);
|
||||
__syncthreads();
|
||||
if (tid == 0) {
|
||||
if (drain == 2) __threadfence_system();
|
||||
store_sys_rel(&peer_flags[b], s);
|
||||
unsigned long long z = 0;
|
||||
while (halo_ar_seq_behind(load_sys_acq(&my_flags[b]), s)) {
|
||||
if (++z > HALO_AR_SPIN_MAX) __builtin_trap();
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (acq) __threadfence_system();
|
||||
}
|
||||
|
||||
// The push check's re-hash of one chunk (halo_ar_seq.h): the payload words and live scales the
|
||||
// reduce below reads, at the indices wht6_push_chunk hashed them.
|
||||
template <int CG = CHUNK_GROUPS>
|
||||
__device__ __forceinline__ void wht6_rehash_chunk(unsigned int& h, int c, int n_groups, int lane,
|
||||
int lig, int gw, const uint4* m_pay,
|
||||
const unsigned short* m_sc) {
|
||||
using Ch = Wht6Chunk<CG>;
|
||||
if constexpr (Ch::U4) {
|
||||
#pragma unroll
|
||||
for (int u = 0; u < Ch::NW / 4; ++u) {
|
||||
const long o = (long)c * (Ch::NW / 4 * WAVE) + (long)u * WAVE + lane;
|
||||
h += halo_archk_u4(m_pay[o], 4u * (unsigned)o);
|
||||
}
|
||||
} else {
|
||||
const unsigned int* mp = reinterpret_cast<const unsigned int*>(m_pay);
|
||||
#pragma unroll
|
||||
for (int u = 0; u < Ch::NW; ++u) {
|
||||
const long o = (long)c * (Ch::NW * WAVE) + (long)u * WAVE + lane;
|
||||
h += halo_archk_mix(mp[o], (unsigned)o);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int t = 0; t < Ch::ITERS; ++t) {
|
||||
const int g = c * CG + t * GPW + gw;
|
||||
if (lig == 0 && g < n_groups) h += halo_archk_mix(m_sc[g], HALO_ARCHK_U16 + (unsigned)g);
|
||||
}
|
||||
}
|
||||
|
||||
// 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,
|
||||
const unsigned short* m_sc,
|
||||
const uint4* l_pay, const float* l_sc) {
|
||||
using Ch = Wht6Chunk<CG>;
|
||||
const int qmin = -(1 << (BITS - 1));
|
||||
const unsigned int MASK = (1u << BITS) - 1u;
|
||||
unsigned int pac[Ch::NW], lac[Ch::NW];
|
||||
if constexpr (Ch::U4) {
|
||||
#pragma unroll
|
||||
for (int u = 0; u < Ch::NW / 4; ++u) {
|
||||
const long o = (long)c * (Ch::NW / 4 * WAVE) + (long)u * WAVE + lane;
|
||||
const uint4 pq = m_pay[o], lq = l_pay[o];
|
||||
pac[4 * u] = pq.x; pac[4 * u + 1] = pq.y; pac[4 * u + 2] = pq.z; pac[4 * u + 3] = pq.w;
|
||||
lac[4 * u] = lq.x; lac[4 * u + 1] = lq.y; lac[4 * u + 2] = lq.z; lac[4 * u + 3] = lq.w;
|
||||
}
|
||||
} else {
|
||||
const unsigned int* mp = reinterpret_cast<const unsigned int*>(m_pay);
|
||||
const unsigned int* lp = reinterpret_cast<const unsigned int*>(l_pay);
|
||||
#pragma unroll
|
||||
for (int u = 0; u < Ch::NW; ++u) {
|
||||
const long o = (long)c * (Ch::NW * WAVE) + (long)u * WAVE + lane;
|
||||
pac[u] = mp[o];
|
||||
lac[u] = lp[o];
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int t = 0; t < Ch::ITERS; ++t) {
|
||||
const int g = c * CG + t * GPW + gw;
|
||||
if (g >= n_groups) continue; // whole group: no shuffle is split
|
||||
const long off = (long)g * GROUP + (long)lig * EPL;
|
||||
const float psc = __uint_as_float((unsigned int)m_sc[g] << 16);
|
||||
const float lsc = l_sc[g];
|
||||
float v[EPL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < EPL; ++i) {
|
||||
const int bit = (t * EPL + i) * BITS, wi = bit >> 5, bo = bit & 31;
|
||||
unsigned int ps = pac[wi] >> bo, ls = lac[wi] >> bo;
|
||||
if (bo + BITS > 32) { ps |= pac[wi + 1] << (32 - bo); ls |= lac[wi + 1] << (32 - bo); }
|
||||
v[i] = (float)((int)(ps & MASK) + qmin) * psc + (float)((int)(ls & MASK) + qmin) * lsc;
|
||||
}
|
||||
wht(v, lig);
|
||||
st(off, v);
|
||||
}
|
||||
}
|
||||
|
||||
// The slot's regions, as the kernels below address them.
|
||||
struct Wht6Slot {
|
||||
uint4* p_pay; unsigned short* p_sc; // the peer's scratch: payload, bf16 scales
|
||||
const uint4* m_pay; const unsigned short* m_sc; // this rank's scratch, which the peer filled
|
||||
uint4* l_pay; float* l_sc; // this rank's own half, local only
|
||||
};
|
||||
__device__ __forceinline__ Wht6Slot wht6_slot(char* peer_scratch, const char* my_scratch,
|
||||
char* loc_pack, int slot, long slot_stride_bytes,
|
||||
long scale_off_bytes) {
|
||||
char* pbase = peer_scratch + (size_t)slot * slot_stride_bytes;
|
||||
const char* mbase = my_scratch + (size_t)slot * slot_stride_bytes;
|
||||
Wht6Slot w;
|
||||
w.p_pay = (uint4*)pbase;
|
||||
w.p_sc = (unsigned short*)(pbase + scale_off_bytes);
|
||||
w.m_pay = (const uint4*)mbase;
|
||||
w.m_sc = (const unsigned short*)(mbase + scale_off_bytes);
|
||||
w.l_pay = (uint4*)loc_pack;
|
||||
w.l_sc = (float*)(loc_pack + scale_off_bytes);
|
||||
return w;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
__global__ void halo_ar_oneshot_2rank_wht6_kernel(
|
||||
const T* __restrict__ in, char* peer_scratch, const char* my_scratch, char* loc_pack,
|
||||
T* __restrict__ out, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs,
|
||||
int n_groups, int n_chunks, long slot_stride_bytes, long scale_off_bytes, int drain, int acq,
|
||||
unsigned int nbw) {
|
||||
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
|
||||
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;
|
||||
halo_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);
|
||||
|
||||
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;
|
||||
|
||||
const auto ld = [&](long off, float* v) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < EPL; ++i) v[i] = rd_to_f(in[off + i]);
|
||||
};
|
||||
unsigned int hck = 0u; // the push check (halo_ar_seq.h)
|
||||
for (int c = c0 + wid; c < c1; c += nwarp)
|
||||
wht6_push_chunk(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc, hck);
|
||||
halo_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, s);
|
||||
|
||||
wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq);
|
||||
halo_archk_wait(my_flags, nbw, s_slot, (unsigned)b, s, [&](unsigned int& h) {
|
||||
for (int c = c0 + wid; c < c1; c += nwarp)
|
||||
wht6_rehash_chunk(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc);
|
||||
});
|
||||
|
||||
const auto st = [&](long off, const float* v) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < EPL; ++i) rd_from_f(v[i], out[off + i]);
|
||||
};
|
||||
for (int c = c0 + wid; c < c1; c += nwarp)
|
||||
wht6_reduce_chunk(st, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc, w.l_pay, w.l_sc);
|
||||
}
|
||||
|
||||
static int clamp_blocks(int nb, int upper) {
|
||||
if (nb < 1) nb = 1; if (nb > upper) nb = upper;
|
||||
if (nb > HALO_AR_MAX_BLOCKS) nb = HALO_AR_MAX_BLOCKS; return nb;
|
||||
}
|
||||
static int clamp_threads(int nt) { if (nt < 64) nt = 64; if (nt > 1024) nt = 1024; return (nt / 64) * 64; }
|
||||
|
||||
// Operates on scratch/flags/seq allocated by halo_ar_ipc_alloc; slot_stride_bytes = max_bytes,
|
||||
// scale_off_bytes = max_bytes/2. loc_pack is a plain local buffer (not IPC) holding this rank's
|
||||
// packed half and its fp32 scales, split at the same scale_off_bytes.
|
||||
// bf16/fp16 payloads only; n_elem must be a multiple of GROUP.
|
||||
static void halo_ar_wht6_launch(int64_t peer_scratch, int64_t my_scratch, int64_t peer_flags,
|
||||
int64_t my_flags, int64_t seq_ctrs, int64_t loc_pack,
|
||||
int64_t slot_stride_bytes, int64_t scale_off_bytes, int64_t inp,
|
||||
int64_t out, int64_t n_elem, int64_t dtype, int64_t stream_i,
|
||||
int64_t nblocks, int64_t nthreads, int64_t drain, int64_t acq) {
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
if (dtype != 0 && dtype != 1) throw std::runtime_error("pack ar: only bf16/fp16 payloads");
|
||||
if (n_elem % GROUP != 0) throw std::runtime_error("pack ar: n_elem not a multiple of GROUP");
|
||||
const int n_groups = (int)(n_elem / GROUP);
|
||||
const int n_chunks = (n_groups + CHUNK_GROUPS - 1) / CHUNK_GROUPS;
|
||||
const int nb = clamp_blocks((int)nblocks, n_chunks);
|
||||
const int nt = clamp_threads((int)nthreads);
|
||||
#define LF(T) halo_ar_oneshot_2rank_wht6_kernel<T><<<nb, nt, 0, st>>>( \
|
||||
(const T*)inp, (char*)peer_scratch, (const char*)my_scratch, (char*)loc_pack, (T*)out, \
|
||||
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n_groups, n_chunks, \
|
||||
(long)slot_stride_bytes, (long)scale_off_bytes, (int)drain, (int)acq, \
|
||||
(unsigned)HALO_AR_MAX_BLOCKS)
|
||||
if (dtype == 0) LF(__hip_bfloat16);
|
||||
else LF(__half);
|
||||
#undef LF
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
/* Derived from libr4d/r4d_ar_oneshot_2rank_wht6.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_ar_oneshot_2rank_wht6.hip: translation unit for halo_ar_oneshot_2rank_wht6, the all-reduce whose wire
|
||||
// payload is Walsh-Hadamard rotated and quantised to 6 bits. Device code and launcher live in
|
||||
// halo_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 halo_ar_hc.h.
|
||||
#include "halo.h"
|
||||
#include "halo_ar_hc.h" // the gather word and the hc write word, shared with the exact wire
|
||||
#include "halo_ar_oneshot_2rank_wht6.h"
|
||||
#include <cstring>
|
||||
|
||||
void halo_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,
|
||||
long scale_off_bytes, long inp, long out, long n_elem, long dtype,
|
||||
long stream, long nblocks, long nthreads, long drain, long acq) {
|
||||
halo_ar_wht6_launch(peer_scratch, my_scratch, peer_flags, my_flags, seq_ctrs, loc_pack,
|
||||
slot_stride_bytes, scale_off_bytes, inp, out, n_elem, dtype, stream, nblocks,
|
||||
nthreads, drain, acq);
|
||||
}
|
||||
|
||||
// Block cap of both all-reduce kernels (the flag array is sized from it).
|
||||
int halo_ar_max_blocks(void) { return HALO_AR_MAX_BLOCKS; }
|
||||
|
||||
// Rotated 6-bit wire format dimensions, for sizing the caller's packed scratch.
|
||||
void halo_ar_wht6_dims(int* group, int* bits, int* chunk_elems) {
|
||||
if (group) *group = GROUP;
|
||||
if (bits) *bits = BITS;
|
||||
if (chunk_elems) *chunk_elems = CHUNK_ELEMS;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The rotated wire with the gated residual write as epilogue and, with GATHER, the MoE gather as
|
||||
// prologue: 6-bit counterparts of halo_ar_hc_write_kernel and halo_ar_gather_hc_write_kernel
|
||||
// (halo_ar_oneshot_2rank_exact.hip). Each matches the unfused chain (moe_gather,
|
||||
// halo_ar_oneshot_2rank_wht6, hc_write) byte for byte because every stage is the same code: the
|
||||
// gather and write words from halo_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 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 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 HALO_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 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).
|
||||
__device__ __forceinline__ void wht6_block_rows(int c0, int c1, int ce, int n_groups, int n,
|
||||
int& row_lo, int& nrow) {
|
||||
const long e0 = (long)c0 * ce;
|
||||
long e1 = (long)c1 * ce;
|
||||
if (e1 > (long)n_groups * GROUP) e1 = (long)n_groups * GROUP;
|
||||
row_lo = (int)(e0 / n);
|
||||
nrow = e1 > e0 ? (int)((e1 - 1) / n) - row_lo + 1 : 0;
|
||||
}
|
||||
|
||||
template <bool GATHER, int CG>
|
||||
__global__ void halo_ar_hc_write_wht6_kernel(
|
||||
unsigned short* __restrict__ y, char* peer_scratch, const char* my_scratch, char* loc_pack,
|
||||
unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs,
|
||||
const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int n, int hc,
|
||||
long irow, long hrow, int n_groups, int n_chunks, long slot_stride_bytes,
|
||||
long scale_off_bytes, int drain, int acq, unsigned int nbw, HaloArGather G, int rows_max,
|
||||
long long* gate, unsigned int* gate_ctr) {
|
||||
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
|
||||
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;
|
||||
extern __shared__ int s_tab[]; // slots, weights: [rows_max * top_k]; gates: [rows_max]
|
||||
const long long gate_word = halo_ar_link_word(gate, (unsigned int)tid);
|
||||
halo_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);
|
||||
|
||||
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;
|
||||
|
||||
/* 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;
|
||||
int row_lo = 0, nrow = 0;
|
||||
if (GATHER) {
|
||||
wht6_block_rows(c0, c1, Wht6Chunk<CG>::ELEMS, n_groups, n, row_lo, nrow);
|
||||
const int K = G.top_k;
|
||||
for (int x = tid; x < nrow * K; x += nt) s_i[x] = -1;
|
||||
__syncthreads();
|
||||
{
|
||||
const int lo = row_lo * K, hi = (row_lo + nrow) * K;
|
||||
for (int i = tid; i < G.T; i += nt) {
|
||||
const int f = G.sorted[i];
|
||||
if (f >= lo && f < hi) s_i[f - lo] = i;
|
||||
}
|
||||
}
|
||||
for (int x = tid; x < nrow * K; x += nt)
|
||||
s_w[x] = bf2f(G.ew[(long)(row_lo + x / K) * G.ew_ld + x % K]);
|
||||
if (G.sh)
|
||||
for (int r = tid; r < nrow; r += nt) {
|
||||
const float v0 = bf2f(G.sg[(long)(row_lo + r) * G.sg_ld]);
|
||||
s_g[r] = G.sig ? (1.0f / (1.0f + __expf(-v0))) : v0;
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
const auto ld = [&](long off, float* v) {
|
||||
int4 q;
|
||||
if (GATHER) {
|
||||
const int row = (int)(off / n), i0 = (int)(off - (long)row * n);
|
||||
q = halo_ar_gather_word<false>(G, nullptr, s_i, s_w, s_g, row, row - row_lo, i0);
|
||||
} else {
|
||||
q = *reinterpret_cast<const int4*>(y + off);
|
||||
}
|
||||
const unsigned short* e = reinterpret_cast<const unsigned short*>(&q);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < EPL; ++i) v[i] = bf2f(e[i]);
|
||||
};
|
||||
const auto st = [&](long off, const float* v) {
|
||||
int4 q;
|
||||
__hip_bfloat16* e = reinterpret_cast<__hip_bfloat16*>(&q);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < EPL; ++i) rd_from_f(v[i], e[i]);
|
||||
*reinterpret_cast<int4*>(y + off) = q;
|
||||
const int row = (int)(off / n), i0 = (int)(off - (long)row * n);
|
||||
halo_ar_hc_write_word(inj, h, row, i0, n, hc, irow, hrow,
|
||||
reinterpret_cast<const unsigned short*>(&q));
|
||||
};
|
||||
unsigned int hck = 0u; // the push check (halo_ar_seq.h)
|
||||
for (int c = c0 + wid; c < c1; c += nwarp)
|
||||
wht6_push_chunk<CG>(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc, hck);
|
||||
halo_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, s);
|
||||
|
||||
wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq);
|
||||
halo_archk_wait(my_flags, nbw, s_slot, (unsigned)b, s, [&](unsigned int& h) {
|
||||
for (int c = c0 + wid; c < c1; c += nwarp)
|
||||
wht6_rehash_chunk<CG>(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc);
|
||||
});
|
||||
halo_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
for (int c = c0 + wid; c < c1; c += nwarp)
|
||||
wht6_reduce_chunk<CG>(st, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc, w.l_pay, w.l_sc);
|
||||
}
|
||||
|
||||
int halo_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
|
||||
long seq_ctrs, long loc_pack, long slot_stride_bytes,
|
||||
long scale_off_bytes, 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 stream_i, long nblocks, long nthreads, long drain, long acq,
|
||||
long gate, long gate_ctr) {
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
if (n <= 0 || M <= 0 || n % 8 || hc < 1 || hrow % 8) return -1;
|
||||
if ((M * n) % GROUP) return -1;
|
||||
const bool gather = ye != 0;
|
||||
if (gather && (!ew || !sorted || top_k < 1 || top_k > HALO_ARG_SLOTS || ye_ld % 8 ||
|
||||
(sh && sh_ld < n)))
|
||||
return -2;
|
||||
const int n_groups = (int)(M * n / GROUP);
|
||||
const int ce = Wht6Chunk<kWht6FusedCG>::ELEMS;
|
||||
const int n_chunks = (n_groups + kWht6FusedCG - 1) / kWht6FusedCG;
|
||||
int nb = clamp_blocks((int)nblocks, n_chunks);
|
||||
const int nt = clamp_threads((int)nthreads);
|
||||
/* 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;
|
||||
if (gather) {
|
||||
for (;;) {
|
||||
const long cpb = (n_chunks + nb - 1) / nb;
|
||||
rows_max = (int)((cpb * ce - 1) / n + 2);
|
||||
lds = (size_t)rows_max * (size_t)top_k * 8 + (size_t)rows_max * 4;
|
||||
if (lds <= kWht6TableBytes || nb >= n_chunks) break;
|
||||
++nb;
|
||||
}
|
||||
if (lds > kWht6TableBytes || nb > HALO_AR_MAX_BLOCKS) return -3;
|
||||
}
|
||||
/* Zeroed including padding, as in halo_ar_gather_hc_write: the tail padding is part of the
|
||||
* kernel-argument bytes a recorded pass's audit compares. */
|
||||
HaloArGather G;
|
||||
std::memset(&G, 0, sizeof G);
|
||||
if (gather) {
|
||||
G.ye = (const unsigned short*)ye;
|
||||
G.ew = (const unsigned short*)ew;
|
||||
G.sorted = (const int*)sorted;
|
||||
G.sh = (const unsigned short*)sh;
|
||||
G.sg = (const unsigned short*)sg;
|
||||
G.ye_ld = ye_ld; G.ew_ld = ew_ld; G.sh_ld = sh_ld; G.sg_ld = sg_ld;
|
||||
G.top_k = (int)top_k; G.T = (int)(M * top_k); G.sig = (int)sig;
|
||||
}
|
||||
#define LF(GA, CG) halo_ar_hc_write_wht6_kernel<GA, CG><<<nb, nt, lds, st>>>( \
|
||||
(unsigned short*)y, (char*)peer_scratch, (const char*)my_scratch, (char*)loc_pack, \
|
||||
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, \
|
||||
(unsigned short*)h, (int)n, (int)hc, irow, hrow, n_groups, n_chunks, slot_stride_bytes, \
|
||||
scale_off_bytes, (int)drain, (int)acq, (unsigned)HALO_AR_MAX_BLOCKS, G, rows_max, \
|
||||
(long long*)gate, (unsigned int*)gate_ctr)
|
||||
if (gather) LF(true, kWht6FusedCG);
|
||||
else LF(false, kWht6FusedCG);
|
||||
#undef LF
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
@@ -0,0 +1,600 @@
|
||||
/* Derived from libr4d/r4d_ar_oneshot_Nrank_exact.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_ar_oneshot_Nrank_exact.hip: halo_ar_oneshot_3rank_exact, halo_ar_oneshot_4rank_exact,
|
||||
// halo_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). 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 halo_ar_hc_write_4rank (the same one-shot with hc_write as epilogue) and
|
||||
// halo_ar_gather_hc_write_4rank (that plus moe_gather as prologue), exact wire only.
|
||||
//
|
||||
// The IPC helpers live in halo_ar_oneshot_2rank_exact.hip; this unit links beside it.
|
||||
#include "halo.h"
|
||||
#include <cstring>
|
||||
#include "halo_ar_wide.h"
|
||||
#include "halo_ar_hc.h" // the gather and hc write words, shared with the two-rank fused forms
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
// src[] is pre-ordered by global rank with our own entry pointing at the local input, so the
|
||||
// accumulate order is identical on every rank and there is no branch here.
|
||||
template <typename T, int LANES, int WS>
|
||||
__device__ __forceinline__ int4 ar_vsum(const int4* const* __restrict__ src, int k) {
|
||||
float acc[LANES];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < LANES; ++j) acc[j] = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < WS; ++r) {
|
||||
const int4 v = src[r][k];
|
||||
const T* pv = reinterpret_cast<const T*>(&v);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < LANES; ++j) acc[j] += halo_ar_to_f(pv[j]);
|
||||
}
|
||||
int4 o;
|
||||
T* po = reinterpret_cast<T*>(&o);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < LANES; ++j) halo_ar_from_f(acc[j], po[j]);
|
||||
return o;
|
||||
}
|
||||
|
||||
template <typename T, int LANES, int WS>
|
||||
__global__ void halo_ar_oneshot_wide_exact_kernel(
|
||||
const int4* __restrict__ in4, HaloArWidePeers<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, long long* gate, unsigned int* gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
// 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 = halo_ar_link_word(gate, (unsigned int)tid);
|
||||
halo_ar_seq_take(seq_ctrs, HALO_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int parity = (int)s_slot;
|
||||
|
||||
const int w = (n16 + nb - 1) / nb;
|
||||
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.
|
||||
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; loaded words are reused across peers so the input is read once.
|
||||
{
|
||||
int k = start + tid;
|
||||
for (; k + 3 * nt < end; k += 4 * nt) {
|
||||
const int4 v0 = in4[k], v1 = in4[k + nt], v2 = in4[k + 2 * nt], v3 = in4[k + 3 * nt];
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p) {
|
||||
ps[p][k] = v0; ps[p][k + nt] = v1; ps[p][k + 2 * nt] = v2; ps[p][k + 3 * nt] = v3;
|
||||
}
|
||||
}
|
||||
for (; k < end; k += nt) {
|
||||
const int4 v = in4[k];
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p) ps[p][k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
halo_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 (halo_ar_seq.h).
|
||||
halo_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];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < WS; ++r)
|
||||
src[r] = (r == rank) ? in4
|
||||
: (my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16);
|
||||
{
|
||||
int k = start + tid;
|
||||
if (RU == 2) {
|
||||
for (; k + nt < end; k += 2 * nt) {
|
||||
out4[k] = ar_vsum<T, LANES, WS>(src, k);
|
||||
out4[k + nt] = ar_vsum<T, LANES, WS>(src, k + nt);
|
||||
}
|
||||
}
|
||||
for (; k < end; k += nt) out4[k] = ar_vsum<T, LANES, WS>(src, k);
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
// (halo_ar_hc_write_word, as in the two-rank halo_ar_hc_write_kernel).
|
||||
//
|
||||
// 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 halo_ar_hc_write_wide_kernel(
|
||||
int4* __restrict__ y4, HaloArWidePeers<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,
|
||||
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 = halo_ar_link_word(gate, (unsigned int)tid);
|
||||
halo_ar_seq_take(seq_ctrs, HALO_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int parity = (int)s_slot;
|
||||
|
||||
const int w = (n16 + nb - 1) / nb;
|
||||
const int start = b * w;
|
||||
int end = start + w; if (end > n16) end = n16;
|
||||
|
||||
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;
|
||||
|
||||
{
|
||||
int k = start + tid;
|
||||
for (; k + 3 * nt < end; k += 4 * nt) {
|
||||
const int4 v0 = y4[k], v1 = y4[k + nt], v2 = y4[k + 2 * nt], v3 = y4[k + 3 * nt];
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p) {
|
||||
ps[p][k] = v0; ps[p][k + nt] = v1; ps[p][k + 2 * nt] = v2; ps[p][k + 3 * nt] = v3;
|
||||
}
|
||||
}
|
||||
for (; k < end; k += nt) {
|
||||
const int4 v = y4[k];
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p) ps[p][k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
halo_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 (halo_ar_seq.h).
|
||||
halo_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
const int4* src[WS];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < WS; ++r)
|
||||
src[r] = (r == rank) ? (const int4*)y4
|
||||
: (my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16);
|
||||
|
||||
const int wpr = n >> 3; // 16B words a row
|
||||
for (int k = start + tid; k < end; k += nt) {
|
||||
const int4 v = ar_vsum<__hip_bfloat16, 8, WS>(src, k);
|
||||
y4[k] = v;
|
||||
const int row = k / wpr, i0 = (k - row * wpr) * 8;
|
||||
halo_ar_hc_write_word(inj, h, row, i0, n, hc, irow, hrow,
|
||||
reinterpret_cast<const unsigned short*>(&v));
|
||||
}
|
||||
}
|
||||
|
||||
// The same write with the MoE gather as its prologue, bf16 only; the four-rank form of the two-rank
|
||||
// halo_ar_gather_hc_write_kernel. `y` is produced, not read: halo_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.
|
||||
//
|
||||
// Slot table as in the two-rank kernel: without INV a block's rows (at most HALO_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 halo_ar_gather_inv built beforehand.
|
||||
template <int WS, bool INV>
|
||||
__global__ void halo_ar_gather_hc_write_wide_kernel(
|
||||
int4* __restrict__ y4, HaloArWidePeers<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,
|
||||
HaloArGather 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;
|
||||
__shared__ unsigned int s_seq, s_slot;
|
||||
__shared__ int s_i[HALO_ARG_ROWS * HALO_ARG_SLOTS];
|
||||
__shared__ float s_w[HALO_ARG_ROWS * HALO_ARG_SLOTS];
|
||||
__shared__ float s_g[HALO_ARG_ROWS];
|
||||
const long long gate_word = halo_ar_link_word(gate, (unsigned int)tid);
|
||||
halo_ar_seq_take(seq_ctrs, HALO_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int parity = (int)s_slot;
|
||||
|
||||
const int w = (n16 + nb - 1) / nb;
|
||||
const int start = b * w;
|
||||
int end = start + w; if (end > n16) end = n16;
|
||||
const int wpr = n >> 3; // 16B words a row
|
||||
const int row_lo = start / wpr;
|
||||
const int nrow = end > start ? (end - 1) / wpr - row_lo + 1 : 0;
|
||||
const int K = G.top_k;
|
||||
|
||||
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;
|
||||
|
||||
/* 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();
|
||||
{
|
||||
const int lo = row_lo * K, hi = (row_lo + nrow) * K;
|
||||
for (int i = tid; i < G.T; i += nt) {
|
||||
const int f = G.sorted[i];
|
||||
if (f >= lo && f < hi) s_i[f - lo] = i;
|
||||
}
|
||||
}
|
||||
for (int x = tid; x < nrow * K; x += nt)
|
||||
s_w[x] = bf2f(G.ew[(long)(row_lo + x / K) * G.ew_ld + x % K]);
|
||||
if (G.sh)
|
||||
for (int r = tid; r < nrow; r += nt) {
|
||||
const float v0 = bf2f(G.sg[(long)(row_lo + r) * G.sg_ld]);
|
||||
s_g[r] = G.sig ? (1.0f / (1.0f + __expf(-v0))) : v0;
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
/* 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 = halo_ar_gather_word<INV>(G, inv, s_i, s_w, s_g, row, row - row_lo, i0);
|
||||
y4[k] = out;
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p) ps[p][k] = out;
|
||||
}
|
||||
|
||||
halo_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 (halo_ar_seq.h).
|
||||
halo_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
const int4* src[WS];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < WS; ++r)
|
||||
src[r] = (r == rank) ? (const int4*)y4
|
||||
: (my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16);
|
||||
|
||||
for (int k = start + tid; k < end; k += nt) {
|
||||
const int4 v = ar_vsum<__hip_bfloat16, 8, WS>(src, k);
|
||||
y4[k] = v;
|
||||
const int row = k / wpr, i0 = (k - row * wpr) * 8;
|
||||
halo_ar_hc_write_word(inj, h, row, i0, n, hc, irow, hrow,
|
||||
reinterpret_cast<const unsigned short*>(&v));
|
||||
}
|
||||
}
|
||||
|
||||
// --- host side ---
|
||||
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 gate,
|
||||
long gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
static_assert(NPEERS <= HALO_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound");
|
||||
|
||||
if (rank < 0 || rank >= WS)
|
||||
throw std::runtime_error("all_reduce: rank " + std::to_string(rank) +
|
||||
" out of range for the " + std::to_string(WS) +
|
||||
" ranks this entry point is compiled for");
|
||||
|
||||
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");
|
||||
const long n16l = nbytes / 16;
|
||||
if (n16l > (long)slot_stride16)
|
||||
throw std::runtime_error("all_reduce: message (" + std::to_string(n16l) +
|
||||
" 16B words) exceeds the per-source slot stride (" +
|
||||
std::to_string(slot_stride16) + ")");
|
||||
const int n16 = (int)n16l;
|
||||
|
||||
int nb = (int)nblocks;
|
||||
if (nb < 1) nb = HALO_AR_NB_DESIGN;
|
||||
if (nb > n16) nb = n16;
|
||||
if (nb > HALO_AR_WIDE_MAX_BLOCKS) nb = HALO_AR_WIDE_MAX_BLOCKS;
|
||||
int nt = (int)nthreads;
|
||||
if (nt < 64) nt = 64;
|
||||
if (nt > 1024) nt = 1024;
|
||||
|
||||
HaloArWidePeers<int4, NPEERS> peers{};
|
||||
for (int i = 0; i < NPEERS; ++i) {
|
||||
if (!peer_scratch[i] || !peer_flags[i])
|
||||
throw std::runtime_error("all_reduce: null peer scratch/flag pointer at index " +
|
||||
std::to_string(i));
|
||||
peers.scratch[i] = (int4*)peer_scratch[i];
|
||||
peers.flags[i] = (unsigned int*)peer_flags[i];
|
||||
peers.rank[i] = (i < (int)rank) ? i : i + 1;
|
||||
}
|
||||
|
||||
// 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 (halo_ar_seq.h).
|
||||
const long slot_bytes = 2L * WS * (long)slot_stride16 * 16;
|
||||
const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int);
|
||||
halo_ar_check_extent(my_scratch, slot_bytes, "all_reduce", "my_scratch");
|
||||
halo_ar_check_extent(my_flags, flag_bytes, "all_reduce", "my_flags");
|
||||
halo_ar_check_extent(seq_ctrs, 2L * HALO_AR_WIDE_MAX_BLOCKS * (long)sizeof(unsigned int),
|
||||
"all_reduce", "seq_ctrs");
|
||||
for (int i = 0; i < NPEERS; ++i) {
|
||||
halo_ar_check_extent(peer_scratch[i], slot_bytes, "all_reduce", "peer scratch");
|
||||
halo_ar_check_extent(peer_flags[i], flag_bytes, "all_reduce", "peer flags");
|
||||
}
|
||||
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
#define HALO_AR_WIDE_LAUNCH(T, LN) \
|
||||
halo_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, (long long*)gate, (unsigned int*)gate_ctr)
|
||||
if (dtype == 0) HALO_AR_WIDE_LAUNCH(__hip_bfloat16, 8);
|
||||
else if (dtype == 1) HALO_AR_WIDE_LAUNCH(__half, 8);
|
||||
else if (dtype == 2) HALO_AR_WIDE_LAUNCH(float, 4);
|
||||
else throw std::runtime_error("all_reduce: bad dtype");
|
||||
#undef HALO_AR_WIDE_LAUNCH
|
||||
}
|
||||
|
||||
// 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 halo_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,
|
||||
long inp, long out, long n_elem, long dtype, long rank,
|
||||
long stream, 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_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, 0L, 0L);
|
||||
}
|
||||
|
||||
void halo_ar_oneshot_4rank_exact(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 stream, 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_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, gate, gate_ctr);
|
||||
}
|
||||
|
||||
void halo_ar_oneshot_8rank_exact(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,
|
||||
long peer_flags2, long peer_flags3, long peer_flags4,
|
||||
long peer_flags5, long peer_flags6, 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) {
|
||||
const long ps[7] = {peer_scratch0, peer_scratch1, peer_scratch2, peer_scratch3,
|
||||
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, 0L, 0L);
|
||||
}
|
||||
|
||||
// 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 gate, long gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
static_assert(NPEERS <= HALO_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound");
|
||||
|
||||
if (rank < 0 || rank >= WS)
|
||||
throw std::runtime_error("ar_hc_write: rank " + std::to_string(rank) +
|
||||
" out of range for the " + std::to_string(WS) +
|
||||
" ranks this entry point is compiled for");
|
||||
if (M <= 0 || n <= 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");
|
||||
|
||||
const long n16l = M * n / 8; // bf16: eight elements a 16B word
|
||||
if (n16l > (long)slot_stride16)
|
||||
throw std::runtime_error("ar_hc_write: message (" + std::to_string(n16l) +
|
||||
" 16B words) exceeds the per-source slot stride (" +
|
||||
std::to_string(slot_stride16) + ")");
|
||||
const int n16 = (int)n16l;
|
||||
|
||||
int nb = (int)nblocks;
|
||||
if (nb < 1) nb = HALO_AR_NB_DESIGN;
|
||||
if (nb > n16) nb = n16;
|
||||
if (nb > HALO_AR_WIDE_MAX_BLOCKS) nb = HALO_AR_WIDE_MAX_BLOCKS;
|
||||
int nt = (int)nthreads;
|
||||
if (nt < 64) nt = 64;
|
||||
if (nt > 1024) nt = 1024;
|
||||
|
||||
HaloArWidePeers<int4, NPEERS> peers{};
|
||||
for (int i = 0; i < NPEERS; ++i) {
|
||||
if (!peer_scratch[i] || !peer_flags[i])
|
||||
throw std::runtime_error("ar_hc_write: null peer scratch/flag pointer at index " +
|
||||
std::to_string(i));
|
||||
peers.scratch[i] = (int4*)peer_scratch[i];
|
||||
peers.flags[i] = (unsigned int*)peer_flags[i];
|
||||
peers.rank[i] = (i < (int)rank) ? i : i + 1;
|
||||
}
|
||||
|
||||
const long slot_bytes = 2L * WS * (long)slot_stride16 * 16;
|
||||
const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int);
|
||||
halo_ar_check_extent(my_scratch, slot_bytes, "ar_hc_write", "my_scratch");
|
||||
halo_ar_check_extent(my_flags, flag_bytes, "ar_hc_write", "my_flags");
|
||||
halo_ar_check_extent(seq_ctrs, 2L * HALO_AR_WIDE_MAX_BLOCKS * (long)sizeof(unsigned int),
|
||||
"ar_hc_write", "seq_ctrs");
|
||||
for (int i = 0; i < NPEERS; ++i) {
|
||||
halo_ar_check_extent(peer_scratch[i], slot_bytes, "ar_hc_write", "peer scratch");
|
||||
halo_ar_check_extent(peer_flags[i], flag_bytes, "ar_hc_write", "peer flags");
|
||||
}
|
||||
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
halo_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, (long long*)gate,
|
||||
(unsigned int*)gate_ctr);
|
||||
}
|
||||
|
||||
void halo_ar_hc_write_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 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 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, gate, gate_ctr);
|
||||
}
|
||||
|
||||
// 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 HALO_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 gate,
|
||||
long gate_ctr) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
static_assert(NPEERS <= HALO_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound");
|
||||
|
||||
if (rank < 0 || rank >= WS)
|
||||
throw std::runtime_error("ar_gather_hc_write: rank " + std::to_string(rank) +
|
||||
" out of range for the " + std::to_string(WS) +
|
||||
" ranks this entry point is compiled for");
|
||||
if (M <= 0 || n <= 0 || n % 8)
|
||||
throw std::runtime_error("ar_gather_hc_write: n must be a positive multiple of 8");
|
||||
if (hc < 1 || hrow % 8)
|
||||
throw std::runtime_error("ar_gather_hc_write: the streams must be whole 16B words");
|
||||
if (top_k < 1 || top_k > HALO_ARG_SLOTS)
|
||||
throw std::runtime_error("ar_gather_hc_write: top_k " + std::to_string(top_k) +
|
||||
" outside 1.." + std::to_string(HALO_ARG_SLOTS));
|
||||
if (!ye || !ew || !sorted || ye_ld % 8 || (sh && sh_ld < n) || (sh != 0) != (sg != 0))
|
||||
throw std::runtime_error("ar_gather_hc_write: the gather's operands are not 16B rows");
|
||||
|
||||
const long n16l = M * n / 8; // bf16: eight elements a 16B word
|
||||
if (n16l > (long)slot_stride16)
|
||||
throw std::runtime_error("ar_gather_hc_write: message (" + std::to_string(n16l) +
|
||||
" 16B words) exceeds the per-source slot stride (" +
|
||||
std::to_string(slot_stride16) + ")");
|
||||
const int n16 = (int)n16l;
|
||||
const int wpr = (int)(n / 8);
|
||||
|
||||
int nb = (int)nblocks;
|
||||
if (nb < 1) nb = HALO_AR_NB_DESIGN;
|
||||
if (nb > HALO_AR_WIDE_MAX_BLOCKS) nb = HALO_AR_WIDE_MAX_BLOCKS;
|
||||
/* A block of w words starting anywhere touches at most (w - 1) / wpr + 2 rows. */
|
||||
const int wmax = (HALO_ARG_ROWS - 2) * wpr + 1;
|
||||
const int nb_min = (n16 + wmax - 1) / wmax;
|
||||
const bool by_inv = inv != 0 && nb_min > nb;
|
||||
if (!by_inv && nb < nb_min) nb = nb_min;
|
||||
if (nb > n16) nb = n16;
|
||||
if (nb > HALO_AR_WIDE_MAX_BLOCKS)
|
||||
throw std::runtime_error("ar_gather_hc_write: the slot table needs " + std::to_string(nb) +
|
||||
" blocks, above the " + std::to_string(HALO_AR_WIDE_MAX_BLOCKS) +
|
||||
" the flags hold, and no inverse table was given");
|
||||
int nt = (int)nthreads;
|
||||
if (nt < 64) nt = 64;
|
||||
if (nt > 1024) nt = 1024;
|
||||
|
||||
HaloArWidePeers<int4, NPEERS> peers{};
|
||||
for (int i = 0; i < NPEERS; ++i) {
|
||||
if (!peer_scratch[i] || !peer_flags[i])
|
||||
throw std::runtime_error("ar_gather_hc_write: null peer scratch/flag pointer at index " +
|
||||
std::to_string(i));
|
||||
peers.scratch[i] = (int4*)peer_scratch[i];
|
||||
peers.flags[i] = (unsigned int*)peer_flags[i];
|
||||
peers.rank[i] = (i < (int)rank) ? i : i + 1;
|
||||
}
|
||||
|
||||
const long slot_bytes = 2L * WS * (long)slot_stride16 * 16;
|
||||
const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int);
|
||||
halo_ar_check_extent(my_scratch, slot_bytes, "ar_gather_hc_write", "my_scratch");
|
||||
halo_ar_check_extent(my_flags, flag_bytes, "ar_gather_hc_write", "my_flags");
|
||||
halo_ar_check_extent(seq_ctrs, 2L * HALO_AR_WIDE_MAX_BLOCKS * (long)sizeof(unsigned int),
|
||||
"ar_gather_hc_write", "seq_ctrs");
|
||||
for (int i = 0; i < NPEERS; ++i) {
|
||||
halo_ar_check_extent(peer_scratch[i], slot_bytes, "ar_gather_hc_write", "peer scratch");
|
||||
halo_ar_check_extent(peer_flags[i], flag_bytes, "ar_gather_hc_write", "peer flags");
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
HaloArGather G;
|
||||
std::memset(&G, 0, sizeof G);
|
||||
G.ye = (const unsigned short*)ye;
|
||||
G.ew = (const unsigned short*)ew;
|
||||
G.sorted = (const int*)sorted;
|
||||
G.sh = (const unsigned short*)sh;
|
||||
G.sg = (const unsigned short*)sg;
|
||||
G.ye_ld = ye_ld; G.ew_ld = ew_ld; G.sh_ld = sh_ld; G.sg_ld = sg_ld;
|
||||
G.top_k = (int)top_k; G.T = (int)(M * top_k); G.sig = (int)sig;
|
||||
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
if (by_inv) {
|
||||
const int irc = halo_ar_gather_inv(inv, sorted, (long)G.T, stream_i);
|
||||
if (irc != 0)
|
||||
throw std::runtime_error("ar_gather_hc_write: the inverse table's launch failed (" +
|
||||
std::to_string(irc) + ")");
|
||||
halo_ar_gather_hc_write_wide_kernel<WS, true><<<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,
|
||||
(const int*)inv, (long long*)gate, (unsigned int*)gate_ctr);
|
||||
} else {
|
||||
halo_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, (long long*)gate, (unsigned int*)gate_ctr);
|
||||
}
|
||||
}
|
||||
|
||||
void halo_ar_gather_hc_write_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 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,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub,
|
||||
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, gate, gate_ctr);
|
||||
}
|
||||
|
||||
void halo_ar_wide_dims(int* max_blocks, int* nb_design, int* max_peers) {
|
||||
if (max_blocks) *max_blocks = HALO_AR_WIDE_MAX_BLOCKS;
|
||||
if (nb_design) *nb_design = HALO_AR_NB_DESIGN;
|
||||
if (max_peers) *max_peers = HALO_AR_WIDE_MAX_PEERS;
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
/* Derived from libr4d/r4d_ar_seq.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
#pragma once
|
||||
// halo_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.
|
||||
//
|
||||
// Counter allocation: 2 * nbw words, zeroed once (nbw = block capacity the flag array was sized
|
||||
// for), then the landed counter (halo_ar_link_landed):
|
||||
//
|
||||
// [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 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] Landed counter: blocks of the running launch that have seen their peer's push
|
||||
// land; back at zero when the launch ends.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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>
|
||||
#include "halo_common.h" // halo_xor_lane_u32: the wave sum on DPP instead of the LDS crossbar
|
||||
|
||||
// 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. `steps` handshake values are taken at once (s_seq is the
|
||||
// first): a kernel that handshakes more than twice per launch reserves the flag values it
|
||||
// publishes, so every kernel on the instance stays in the same monotone flag space. All ranks must
|
||||
// take the same number for the same block.
|
||||
//
|
||||
// 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 halo_ar_seq_take(unsigned int* __restrict__ ctrs, unsigned int nbw,
|
||||
unsigned int& s_seq, unsigned int& s_slot,
|
||||
unsigned int steps = 1u) {
|
||||
const unsigned int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
|
||||
unsigned int* const par = ctrs + nbw;
|
||||
const unsigned int pt = nt > 32u ? 32u : 0u; // first lane of the second wave, if there is one
|
||||
if (tid == 0) s_seq = atomicAdd(&ctrs[b], steps) + 1u;
|
||||
if (tid == pt) s_slot = (atomicAdd(&par[b], 1u) + 1u) & 1u;
|
||||
for (unsigned int j = b + (tid + 1u) * nb; j < nbw; j += nt * nb) atomicAdd(&par[j], 1u);
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local");
|
||||
__builtin_amdgcn_s_barrier();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local");
|
||||
}
|
||||
|
||||
// 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
|
||||
// (halo_ar_link_word), where the host-memory read overlaps the push instead of delaying the reduce.
|
||||
//
|
||||
// Every block calls halo_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 halo_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;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ void halo_ar_link_landed(long long* gate, long long word,
|
||||
unsigned int* ctr, unsigned int nb,
|
||||
unsigned int tid) {
|
||||
if (!gate || tid != 0) return;
|
||||
const unsigned int prev = __hip_atomic_fetch_add(ctr, 1u, __ATOMIC_RELAXED,
|
||||
__HIP_MEMORY_SCOPE_AGENT);
|
||||
if (prev + 1u != nb) return;
|
||||
__hip_atomic_store(ctr, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
|
||||
if (word & 1) __hip_atomic_fetch_add(gate, -1LL, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
|
||||
// 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 halo_ar_seq_behind(unsigned int flag, unsigned int want) {
|
||||
return (int)(flag - want) < 0;
|
||||
}
|
||||
|
||||
// ---- The push check. A peer's push over PCIe P2P can land after its release flag (measured on 2x
|
||||
// R9700: the reader sometimes found the slot's previous contents right after the handshake, and
|
||||
// the new bytes ~1 us later), so the flag alone does not say the bytes are there. The pushed bytes
|
||||
// wait in the writer's L2 for the release's writeback, and that writeback and the flag store reach
|
||||
// the peer by different paths. The writer sums mix(dword, index) over what it pushes and stores the
|
||||
// block's sum, salted with its handshake value, into the peer's check word for (slot, block):
|
||||
// fine-grained words after the flags (halo_ar_entry.hip sizes the allocation). The reader sums the
|
||||
// same over the bytes it is about to read and reads again until the two agree. A stale element and
|
||||
// a stale check word (an older handshake value) both disagree, so only the landed push passes; the
|
||||
// order the two land in does not matter. The sum is order-free, so writer and reader may split the
|
||||
// bytes differently.
|
||||
#define HALO_ARCHK_SALT 0x6C8E9CF5u
|
||||
// wall_clock64 ticks (100 MHz): 2 s. A push that never lands is a lockstep fault, so the reader traps.
|
||||
#define HALO_ARCHK_DEADLINE 200000000ull
|
||||
#define HALO_ARCHK_U16 0x80000000u // index space of 16-bit fields (wire scales), apart from dwords
|
||||
|
||||
// MurmurHash3's finalizer over (value, index): every bit of the value reaches every bit of the term,
|
||||
// so a sum of terms changes when any value does. A linear mix is not enough: (v ^ c_e) summed over
|
||||
// a run of indices can lose v entirely, and a message of one repeated value (a test pattern, a
|
||||
// zero-filled row) would then pass whatever the slot held.
|
||||
__device__ __forceinline__ unsigned int halo_archk_mix(unsigned int v, unsigned int e) {
|
||||
unsigned int x = v ^ (e * 0x9E3779B9u);
|
||||
x ^= x >> 16; x *= 0x85EBCA6Bu;
|
||||
x ^= x >> 13; x *= 0xC2B2AE35u;
|
||||
x ^= x >> 16;
|
||||
return x;
|
||||
}
|
||||
// A 16B word at dword index `e`.
|
||||
__device__ __forceinline__ unsigned int halo_archk_u4(int4 v, unsigned int e) {
|
||||
return halo_archk_mix((unsigned int)v.x, e) + halo_archk_mix((unsigned int)v.y, e + 1u) +
|
||||
halo_archk_mix((unsigned int)v.z, e + 2u) + halo_archk_mix((unsigned int)v.w, e + 3u);
|
||||
}
|
||||
__device__ __forceinline__ unsigned int halo_archk_u4(uint4 v, unsigned int e) {
|
||||
return halo_archk_mix(v.x, e) + halo_archk_mix(v.y, e + 1u) + halo_archk_mix(v.z, e + 2u) +
|
||||
halo_archk_mix(v.w, e + 3u);
|
||||
}
|
||||
// The check word of (slot, block) in a flags allocation: two parity slots of nbw words after the
|
||||
// nbw flags.
|
||||
__device__ __forceinline__ unsigned int* halo_archk_word(unsigned int* flags, unsigned int nbw,
|
||||
unsigned int slot, unsigned int b) {
|
||||
return flags + nbw + slot * nbw + b;
|
||||
}
|
||||
// The same partners in the same order as `for (o = 16; o; o >>= 1) h += __shfl_xor(h, o, 32)`,
|
||||
// on DPP and permlanex16 (halo_xor_lane) rather than one ds_bpermute_b32 per stage: this sum sits
|
||||
// on the handshake path of every block. Integer adds commute, so the bits are the same either way.
|
||||
__device__ __forceinline__ unsigned int halo_archk_wave_sum(unsigned int h) {
|
||||
h += halo_xor_lane_u32<16>(h);
|
||||
h += halo_xor_lane_u32<8>(h);
|
||||
h += halo_xor_lane_u32<4>(h);
|
||||
h += halo_xor_lane_u32<2>(h);
|
||||
h += halo_xor_lane_u32<1>(h);
|
||||
return h;
|
||||
}
|
||||
|
||||
// Writer: every thread of the block calls this after its pushes, before the handshake's barrier.
|
||||
// Thread 0 stores the block's sum into the peer's check word.
|
||||
__device__ __forceinline__ void halo_archk_put(unsigned int h, unsigned int* peer_flags,
|
||||
unsigned int nbw, unsigned int slot,
|
||||
unsigned int b, unsigned int seq,
|
||||
bool release = false) {
|
||||
__shared__ unsigned int s_ckp[32];
|
||||
const unsigned int tid = threadIdx.x, nt = blockDim.x;
|
||||
h = halo_archk_wave_sum(h);
|
||||
if ((tid & 31u) == 0u) s_ckp[tid >> 5] = h;
|
||||
__syncthreads();
|
||||
if (tid == 0) {
|
||||
unsigned int t = 0u;
|
||||
for (unsigned int w = 0; w < (nt + 31u) / 32u; ++w) t += s_ckp[w];
|
||||
/* The pushed bytes sit in this card's L2 until a system-scope release writes them back. The
|
||||
* flag's release, right after this, does that, so the word itself can be relaxed (the reader
|
||||
* re-reads until the bytes agree with it). Where the flag went out before the push (the test
|
||||
* mode, drain 4) nothing else would write them back before the kernel ends: a release. */
|
||||
unsigned int* const cw = halo_archk_word(peer_flags, nbw, slot, b);
|
||||
if (release)
|
||||
__hip_atomic_store(cw, t + seq * HALO_ARCHK_SALT, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
else
|
||||
__hip_atomic_store(cw, t + seq * HALO_ARCHK_SALT, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
}
|
||||
|
||||
// Reader: every thread of the block calls this after the handshake; `rehash(h)` adds the thread's
|
||||
// share of the bytes the block is about to read, with the same loads the kernel then makes.
|
||||
template <typename F>
|
||||
__device__ __forceinline__ void halo_archk_wait(unsigned int* my_flags, unsigned int nbw,
|
||||
unsigned int slot, unsigned int b,
|
||||
unsigned int seq, const F& rehash) {
|
||||
__shared__ unsigned int s_ckw[32];
|
||||
__shared__ unsigned int s_ckok;
|
||||
const unsigned int tid = threadIdx.x, nt = blockDim.x;
|
||||
const unsigned long long t0 = tid == 0 ? wall_clock64() : 0ull;
|
||||
for (;;) {
|
||||
/* The check word first, so its round trip overlaps the re-hash's loads. Read before the bytes
|
||||
* it is compared with, it can only be older than them, and an older word just fails this try. */
|
||||
const unsigned int want = tid == 0 ? __hip_atomic_load(halo_archk_word(my_flags, nbw, slot, b),
|
||||
__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM)
|
||||
: 0u;
|
||||
unsigned int h = 0u;
|
||||
rehash(h);
|
||||
h = halo_archk_wave_sum(h);
|
||||
if ((tid & 31u) == 0u) s_ckw[tid >> 5] = h;
|
||||
__syncthreads();
|
||||
if (tid == 0) {
|
||||
unsigned int t = 0u;
|
||||
for (unsigned int w = 0; w < (nt + 31u) / 32u; ++w) t += s_ckw[w];
|
||||
const bool ok = t + seq * HALO_ARCHK_SALT == want;
|
||||
if (!ok && wall_clock64() - t0 > HALO_ARCHK_DEADLINE) __builtin_trap();
|
||||
s_ckok = ok ? 1u : 0u;
|
||||
}
|
||||
__syncthreads();
|
||||
if (s_ckok) return;
|
||||
__syncthreads(); // s_ckw and s_ckok are rewritten by the next try
|
||||
/* Drop the vector caches, so the next try reads the bytes from where the push lands. */
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "");
|
||||
__builtin_amdgcn_s_sleep(2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/* Derived from libr4d/r4d_ar_shards.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
#pragma once
|
||||
// halo_ar_shards.h: the exact two-shot's shard table. Shard s is the 16-byte words
|
||||
// [off[s], off[s+1]) and is reduced by rank s. Host only and HIP-free: the launcher, the plugin
|
||||
// shim (which sizes scratch and picks the block count from it) and the selftest (which prints it)
|
||||
// must derive the same table from the same inputs.
|
||||
//
|
||||
// The even split is n16 / ws words a shard with the first n16 % ws shards one word longer. Weights
|
||||
// split proportionally (floor(n16 * w_s / sum)) and hand the few remaining words, one each, to the
|
||||
// weighted ranks in ascending order; equal weights therefore reproduce the even split exactly, and
|
||||
// a zero weight always means an empty shard. Which rank owns a word changes only the link it
|
||||
// crosses, not its fold (fp32, ascending rank), so every table gives the same bits.
|
||||
#include <cstdlib>
|
||||
|
||||
// Below HALO_AR8_MIN_ELEMS_DEFAULT elements the weights and the pieces do not apply: a
|
||||
// decode-sized message pays more for the extra handshakes and the uneven split than its link time
|
||||
// saves (measured on the eight R9700: 196608 elements run fastest even and in one piece, 524288
|
||||
// already gain from weights and two pieces).
|
||||
// The eight-rank two-shot's form, its launch parameter `form` (halo_ar_twoshot_Nrank_exact.hip):
|
||||
// lockstep (one handshake a step), ring (the first hop sent to the ranks in ring order from the
|
||||
// next one) or split (ring, and a flag after each half of a step, each awaited only where its data
|
||||
// is read). Every form folds the same words in the same order, so all give the same bits. The
|
||||
// engine runs lockstep; the other two exist to time a board (halo_selftest --perfar8).
|
||||
enum { HALO_AR8_FORM_LOCKSTEP = 0, HALO_AR8_FORM_RING = 1, HALO_AR8_FORM_SPLIT = 2 };
|
||||
enum {
|
||||
HALO_AR_SHARD_WEIGHT_MAX = 65535,
|
||||
HALO_AR8_MIN_ELEMS_DEFAULT = 262144,
|
||||
};
|
||||
|
||||
// The eight-rank two-shot's settings. The engine runs the defaults: weights from each card's
|
||||
// slowest PCIe hop (halo_ar_weights_from_rates, halo_ar_links.h), the piece count from the message
|
||||
// size (halo_ar8_auto_pieces), both from HALO_AR8_MIN_ELEMS_DEFAULT elements. halo_selftest sets
|
||||
// others through halo_ar8_test_settings (halo.h) to check unequal and empty shards, fixed piece
|
||||
// counts and the floors, and to time another board's weights.
|
||||
enum { HALO_AR8_WEIGHTS_AUTO = 0, HALO_AR8_WEIGHTS_EVEN = 1, HALO_AR8_WEIGHTS_SET = 2 };
|
||||
struct HaloAr8Settings {
|
||||
int weights = HALO_AR8_WEIGHTS_AUTO;
|
||||
int w[8] = { 0 }; // HALO_AR8_WEIGHTS_SET: the eight weights
|
||||
int pieces = 0; // 0: halo_ar8_auto_pieces
|
||||
long long weights_min = HALO_AR8_MIN_ELEMS_DEFAULT;
|
||||
long long pieces_min = HALO_AR8_MIN_ELEMS_DEFAULT;
|
||||
};
|
||||
|
||||
// The piece count when none is set, by message size in elements: more pieces
|
||||
// shorten the one-way first and last steps ((K+1)/K of the link time) but add a handshake each,
|
||||
// which only a large message amortises (measured at 4,1,0,4,0,1,4,4: K2 best at 524288, K4 at
|
||||
// 2097152, K8 at 8388608).
|
||||
inline int halo_ar8_auto_pieces(long long numel) {
|
||||
if (numel < 262144) return 1;
|
||||
if (numel < 1048576) return 2;
|
||||
if (numel < 4194304) return 4;
|
||||
return 8;
|
||||
}
|
||||
|
||||
// "lockstep", "ring" or "split" as HALO_AR8_FORM_*; -1 for anything else.
|
||||
inline int halo_ar8_form_parse(const char* s) {
|
||||
if (!s) return -1;
|
||||
const char* names[3] = { "lockstep", "ring", "split" };
|
||||
for (int f = 0; f < 3; ++f) {
|
||||
const char* a = names[f];
|
||||
const char* b = s;
|
||||
while (*a && *a == *b) { ++a; ++b; }
|
||||
if (!*a && !*b) return f;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// `ws` non-negative integers separated by commas, each at most HALO_AR_SHARD_WEIGHT_MAX, summing
|
||||
// to more than zero; nothing else (no blanks, signs or trailing text).
|
||||
inline bool halo_ar_shard_weights_parse(const char* s, int ws, int* w) {
|
||||
if (!s) return false;
|
||||
long sum = 0;
|
||||
for (int i = 0; i < ws; ++i) {
|
||||
if (*s < '0' || *s > '9') return false;
|
||||
long v = 0;
|
||||
while (*s >= '0' && *s <= '9') {
|
||||
v = v * 10 + (*s++ - '0');
|
||||
if (v > HALO_AR_SHARD_WEIGHT_MAX) return false;
|
||||
}
|
||||
w[i] = (int)v;
|
||||
sum += v;
|
||||
if (i + 1 < ws) {
|
||||
if (*s != ',') return false;
|
||||
++s;
|
||||
}
|
||||
}
|
||||
return *s == '\0' && sum > 0;
|
||||
}
|
||||
|
||||
// Fills off[0..ws] and returns the longest shard. `w` null: the even split.
|
||||
inline long halo_ar_shard_table(long n16, int ws, const int* w, long* off) {
|
||||
long len[16];
|
||||
if (!w) {
|
||||
const long base = n16 / ws, rem = n16 % ws;
|
||||
for (int s = 0; s < ws; ++s) len[s] = base + (s < rem ? 1 : 0);
|
||||
} else {
|
||||
long sum = 0;
|
||||
for (int s = 0; s < ws; ++s) sum += w[s];
|
||||
long left = n16;
|
||||
for (int s = 0; s < ws; ++s) {
|
||||
len[s] = n16 * w[s] / sum;
|
||||
left -= len[s];
|
||||
}
|
||||
for (int s = 0; s < ws && left > 0; ++s)
|
||||
if (w[s] > 0) { ++len[s]; --left; }
|
||||
}
|
||||
long sh_max = 0;
|
||||
off[0] = 0;
|
||||
for (int s = 0; s < ws; ++s) {
|
||||
off[s + 1] = off[s] + len[s];
|
||||
if (len[s] > sh_max) sh_max = len[s];
|
||||
}
|
||||
return sh_max;
|
||||
}
|
||||
|
||||
// The longest shard any message of at most n16 words can get under `w` (null: even): what the
|
||||
// scratch slot must hold twice.
|
||||
inline long halo_ar_shard_max_bound(long n16, int ws, const int* w) {
|
||||
if (!w) return (n16 + ws - 1) / ws;
|
||||
long sum = 0, wmax = 0;
|
||||
for (int s = 0; s < ws; ++s) {
|
||||
sum += w[s];
|
||||
if (w[s] > wmax) wmax = w[s];
|
||||
}
|
||||
const long b = n16 * wmax / sum + 1;
|
||||
return b < n16 ? b : n16;
|
||||
}
|
||||
|
||||
// The two-shot timeline, a diagnostic (halo.h, `timeline`): per block HALO_AR_TL_WORDS stamps of the
|
||||
// device wall clock (hipDeviceAttributeWallClockRate), [0] after the sequence step, an (arrive,
|
||||
// release) pair per handshake, then the end of the block's last local work, so a launch in K
|
||||
// pieces fills 2 + 2 * (K + 1). HALO_AR_TL_BLOCKS is the wide family's block ceiling.
|
||||
enum { HALO_AR_TL_WORDS = 2 + 2 * (16 + 1), HALO_AR_TL_BLOCKS = 64 };
|
||||
@@ -0,0 +1,226 @@
|
||||
/* Derived from libr4d/r4d_ar_ti8.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
#pragma once
|
||||
// halo_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. 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) 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: 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)
|
||||
#define TI8_RLIM 253.0f // the ratio limit: the int8 zero-line
|
||||
#define TI8_FLOOR_INV (1.0f / 96.0f) // floor divisor, influences rotation use rate
|
||||
|
||||
__device__ __forceinline__ float ti8_to_f(const float& x) { return x; }
|
||||
__device__ __forceinline__ float ti8_to_f(const __half& x) { return __half2float(x); }
|
||||
__device__ __forceinline__ float ti8_to_f(const __hip_bfloat16& x) { return (float)x; }
|
||||
__device__ __forceinline__ void ti8_from_f(float v, __half& o) { o = __float2half(v); }
|
||||
__device__ __forceinline__ void ti8_from_f(float v, __hip_bfloat16& o) { o = (__hip_bfloat16)v; }
|
||||
|
||||
// one 16-byte load of a lane's 8 consecutive payload elements, widened to fp32
|
||||
__device__ __forceinline__ void ti8_load8(const __hip_bfloat16* p, float* out) {
|
||||
const uint4 raw = *reinterpret_cast<const uint4*>(p);
|
||||
const unsigned int w[4] = {raw.x, raw.y, raw.z, raw.w};
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
out[2 * j] = __uint_as_float((w[j] & 0xFFFFu) << 16);
|
||||
out[2 * j + 1] = __uint_as_float(w[j] & 0xFFFF0000u);
|
||||
}
|
||||
}
|
||||
__device__ __forceinline__ void ti8_load8(const __half* p, float* out) {
|
||||
const uint4 raw = *reinterpret_cast<const uint4*>(p);
|
||||
const __half2* h = reinterpret_cast<const __half2*>(&raw);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
const float2 f = __half22float2(h[j]);
|
||||
out[2 * j] = f.x;
|
||||
out[2 * j + 1] = f.y;
|
||||
}
|
||||
}
|
||||
template <typename T>
|
||||
__device__ __forceinline__ void ti8_store8(T* p, const float* v) {
|
||||
union {
|
||||
uint4 u;
|
||||
T t[8];
|
||||
} o;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) ti8_from_f(v[i], o.t[i]);
|
||||
*reinterpret_cast<uint4*>(p) = o.u;
|
||||
}
|
||||
|
||||
// 16-bit payload-dtype bit pattern for the Tier 2 record value
|
||||
template <typename T>
|
||||
__device__ __forceinline__ unsigned short ti8_bits16(float f) {
|
||||
union {
|
||||
T t;
|
||||
unsigned short u;
|
||||
} c;
|
||||
ti8_from_f(f, c.t);
|
||||
return c.u;
|
||||
}
|
||||
template <typename T>
|
||||
__device__ __forceinline__ float ti8_from_bits16(unsigned short u) {
|
||||
union {
|
||||
T t;
|
||||
unsigned short u;
|
||||
} c;
|
||||
c.u = u;
|
||||
return ti8_to_f(c.t);
|
||||
}
|
||||
|
||||
// orthonormal WHT-32 over one group (4 lanes x 8 elements): h=1,2,4 in-register,
|
||||
// h=8,16 cross-lane; its own inverse (1/sqrt(32) each way). Must be reached by all
|
||||
// 4 lanes of the group together.
|
||||
__device__ __forceinline__ void ti8_wht32(float* v, int lig) {
|
||||
#pragma unroll
|
||||
for (int h = 1; h < TI8_EPL; h <<= 1)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TI8_EPL; ++i)
|
||||
if ((i & h) == 0) {
|
||||
const float x = v[i], y = v[i ^ h];
|
||||
v[i] = x + y;
|
||||
v[i ^ h] = x - y;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int m = 1; m < TI8_LPG; m <<= 1) {
|
||||
const bool lo = (lig & m) == 0;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TI8_EPL; ++i) {
|
||||
const float o = __shfl_xor(v[i], m);
|
||||
v[i] = lo ? (v[i] + o) : (o - v[i]);
|
||||
}
|
||||
}
|
||||
const float nrm = 0.17677669529663687f; // 1/sqrt(32)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TI8_EPL; ++i) v[i] *= nrm;
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// classifier: max1(+idx,+value), max2, sumsq in one scan, 2-shuffle merges
|
||||
float m1 = -1.f, m2 = 0.f, sumsq = 0.f;
|
||||
int li = 0;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TI8_EPL; ++i) {
|
||||
const float a = fabsf(v[i]);
|
||||
sumsq += v[i] * v[i];
|
||||
if (a > m1) { m2 = m1; m1 = a; li = i; }
|
||||
else if (a > m2) m2 = a;
|
||||
}
|
||||
int gidx = lig * TI8_EPL + li;
|
||||
float mval = v[li];
|
||||
#pragma unroll
|
||||
for (int m = 1; m < TI8_LPG; m <<= 1) {
|
||||
const float om1 = __shfl_xor(m1, m);
|
||||
const float om2 = __shfl_xor(m2, m);
|
||||
const float osq = __shfl_xor(sumsq, m);
|
||||
const int ogidx = __shfl_xor(gidx, m);
|
||||
const float omval = __shfl_xor(mval, m);
|
||||
m2 = fmaxf(fminf(m1, om1), fmaxf(m2, om2));
|
||||
if (om1 > m1) { m1 = om1; gidx = ogidx; mval = omval; }
|
||||
sumsq += osq;
|
||||
}
|
||||
const float rms_rest = sqrtf(fmaxf(0.f, sumsq - m1 * m1) * (1.0f / 31.0f));
|
||||
const float delta = rms_rest * TI8_FLOOR_INV;
|
||||
float mn = FLT_MAX;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TI8_EPL; ++i) {
|
||||
const float a = fabsf(v[i]);
|
||||
if (a >= delta && a > 0.f && a < mn) mn = a;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int m = 1; m < TI8_LPG; m <<= 1) mn = fminf(mn, __shfl_xor(mn, m));
|
||||
|
||||
// tier choice; degenerate groups (all zero / nothing significant) hit Tier 1
|
||||
float amax;
|
||||
if (m1 <= TI8_RLIM * mn) {
|
||||
amax = m1;
|
||||
*rec = 0u;
|
||||
} else if (m2 <= TI8_RLIM * mn) {
|
||||
amax = m2;
|
||||
*rec = 1u | ((unsigned int)gidx << 4) |
|
||||
((unsigned int)ti8_bits16<T>(mval) << 16);
|
||||
} else {
|
||||
ti8_wht32(v, lig);
|
||||
float a = 0.f;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TI8_EPL; ++i) a = fmaxf(a, fabsf(v[i]));
|
||||
#pragma unroll
|
||||
for (int m = 1; m < TI8_LPG; m <<= 1) a = fmaxf(a, __shfl_xor(a, m));
|
||||
amax = a;
|
||||
*rec = 2u;
|
||||
}
|
||||
*scale = __float2half(amax * (1.0f / 127.0f));
|
||||
float s = __half2float(*scale);
|
||||
if (!(s > 0.f)) { s = 1.0f; *scale = __float2half(1.0f); }
|
||||
const float inv = 1.0f / s;
|
||||
unsigned int w[2] = {0u, 0u};
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TI8_EPL; ++i) {
|
||||
int qi = (int)rintf(v[i] * inv);
|
||||
qi = (qi < -127) ? -127 : ((qi > 127) ? 127 : qi);
|
||||
w[i >> 2] |= ((unsigned int)(unsigned char)(signed char)qi) << ((i & 3) << 3);
|
||||
}
|
||||
*codes = make_uint2(w[0], w[1]);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
__device__ __forceinline__ void ti8_encode_group(const T* p, int lig, uint2* codes,
|
||||
unsigned int* rec, __half* scale) {
|
||||
float v[TI8_EPL];
|
||||
ti8_load8(p, v);
|
||||
ti8_encode_group_v<T>(v, lig, codes, rec, scale);
|
||||
}
|
||||
|
||||
// Decode one lane's 8 elements back to the original domain (dequant, then the Tier 2
|
||||
// patch or the Tier 3 inverse rotation per the tag). Group-uniform tags keep the Tier 3
|
||||
// shuffles convergent.
|
||||
template <typename T>
|
||||
__device__ __forceinline__ void ti8_decode_group(uint2 codes, unsigned int rec, float s,
|
||||
int lig, float* v) {
|
||||
const unsigned int w[2] = {codes.x, codes.y};
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TI8_EPL; ++i) {
|
||||
const signed char n = (signed char)((w[i >> 2] >> ((i & 3) << 3)) & 0xFFu);
|
||||
v[i] = (float)n * s;
|
||||
}
|
||||
const unsigned int tag = rec & 3u;
|
||||
if (tag == 2u) {
|
||||
ti8_wht32(v, lig);
|
||||
} else if (tag == 1u) {
|
||||
const int oi = (int)((rec >> 4) & 31u);
|
||||
if (oi / TI8_EPL == lig)
|
||||
v[oi % TI8_EPL] = ti8_from_bits16<T>((unsigned short)(rec >> 16));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,685 @@
|
||||
/* Derived from libr4d/r4d_ar_twoshot_Nrank_exact.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_ar_twoshot_Nrank_exact.hip: halo_ar_twoshot_{3,4,8}rank_exact -- reduce-scatter +
|
||||
// all-gather at 3, 4 or 8 ranks, exact bf16/fp16/fp32 wire. Per-block pipelined handshake
|
||||
// instead of a grid arrival election. Sends 2*(ws-1)/ws*N bytes per rank in two hops, so it
|
||||
// covers the sizes where the one-shot's (ws-1)*N send is too heavy.
|
||||
//
|
||||
// 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
|
||||
// 0, B at sh_max; the slot stride must hold 2*sh_max.
|
||||
//
|
||||
// The shard table (halo_ar_shards.h) comes in as a kernel argument. By default it is the even
|
||||
// split (the first n16 % ws shards one word longer); at 3 ranks engine residuals rarely divide (a
|
||||
// 2048-wide bf16 row is 256 words). At 8 ranks it is weighted per link (halo_ar_links.h); a rank with weight 0 owns nothing and only pushes, gathers and
|
||||
// handshakes. Over both phases a rank moves N + (ws-2)*len_r each way, but phase 1 only sends
|
||||
// N - len_r (receiving (ws-1)*len_r) and phase 2 the reverse, so a short shard on a slow link pays
|
||||
// only as far as the phases overlap on that link (docs/GUIDE.md, 4.7). Each word is the same fp32
|
||||
// fold in ascending rank order whoever owns it, so the bits match the one-shot's.
|
||||
//
|
||||
// At 8 ranks the message may also run in pieces (a count from the message size, halo_ar_shards.h): each block's words split into `pieces` runs pipelined so
|
||||
// piece j+1's phase 1 shares the link with piece j's phase 2. A rank with a short shard then
|
||||
// sends and receives at once instead of one direction per phase.
|
||||
//
|
||||
// Also at 8 ranks, two more forms of the same work, chosen by the `form` launch parameter to time
|
||||
// a board (the engine runs lockstep, halo_ar_entry.hip):
|
||||
// * ring sends the first hop to the peers in ring order from rank + 1 instead of ascending, so
|
||||
// no card receives from all seven at once, as the lowest rank does when every sender starts
|
||||
// at its lowest peer;
|
||||
// * split also replaces the one handshake a step, which waits for every peer to finish the whole
|
||||
// step, by a flag after each half (the first hop of the next piece, the reduce of this one),
|
||||
// each awaited only before its data is read: before reducing piece j the peers' first hop of
|
||||
// j, before assembling j their reduce of j. A rank whose own half is done goes on with the
|
||||
// next piece's first hop while a slower one still reduces, so the links run at their own pace
|
||||
// instead of in lockstep. 2 * pieces + 1 flag values, pieces + 1 steps reserved.
|
||||
// The words, their owners and their folds are the lockstep form's, so the bits are too.
|
||||
//
|
||||
// Shares the wide family's flag/seq/scratch set (halo_ar_wide.h): it publishes in the 2*seq flag
|
||||
// space plus the 2s-1 half-step (with pieces: pieces+1 values from 2s-1 on, after reserving one
|
||||
// step a piece), 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 "halo.h"
|
||||
#include "halo_ar_wide.h"
|
||||
#include "halo_ar_shards.h"
|
||||
#include "halo_chain.h"
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
static_assert(HALO_AR_TL_WORDS >= 4 + 2 * HALO_AR_TS_MAX_PIECES,
|
||||
"a timeline holds the start, a stamp pair a handshake and the end");
|
||||
|
||||
template <int WS>
|
||||
struct HaloArShardOff {
|
||||
int off[WS + 1];
|
||||
int sh_max;
|
||||
};
|
||||
|
||||
// PIECED false fixes pieces at 1, so the unpipelined launch keeps the straight-line kernel.
|
||||
// CHAIN: the chained form's wait (before the sequence take, so a block of the next launch on the
|
||||
// instance never starts ahead of this one's) and add (halo_chain.h); no block returns early.
|
||||
template <typename T, int LANES, int WS, bool PIECED, int FORM, bool CHAIN>
|
||||
__device__ __forceinline__ void halo_ar_twoshot_wide_exact_body(
|
||||
const int4* __restrict__ in4, HaloArWidePeers<int4, WS - 1> peers,
|
||||
const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags,
|
||||
int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, HaloArShardOff<WS> sh,
|
||||
int slot_stride16, int rank, int drain, int acq, int pub,
|
||||
long long* gate, unsigned int* gate_ctr, int pieces_arg, long long* tl_all) {
|
||||
if (CHAIN) halo_chain_wait();
|
||||
constexpr int NPEERS = WS - 1;
|
||||
const int pieces = PIECED ? pieces_arg : 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 = halo_ar_link_word(gate, (unsigned int)tid);
|
||||
// device-resident, replay-safe; `pieces` steps reserve the 2*pieces flag values this launch uses
|
||||
// (the split form publishes 2 * pieces + 1 and reserves one step more)
|
||||
halo_ar_seq_take(seq_ctrs, HALO_AR_WIDE_MAX_BLOCKS, s_seq, s_slot,
|
||||
(unsigned int)(FORM == HALO_AR8_FORM_SPLIT ? pieces + 1 : pieces));
|
||||
const unsigned int v0 = 2u * s_seq - 1u;
|
||||
const int parity = (int)s_slot;
|
||||
// the split form awaits 2 * pieces times, which the timeline holds up to 8 pieces
|
||||
long long* const tl = tl_all && (FORM != HALO_AR8_FORM_SPLIT || 4 * pieces + 2 <= HALO_AR_TL_WORDS)
|
||||
? tl_all + (size_t)b * HALO_AR_TL_WORDS : nullptr;
|
||||
halo_ar_tl_stamp(tl, 0);
|
||||
|
||||
const int sh_max = sh.sh_max;
|
||||
#define HALO_TS_OFF(s) (sh.off[s])
|
||||
#define HALO_TS_LEN(s) (sh.off[(s) + 1] - sh.off[s])
|
||||
|
||||
const int w = (sh_max + nb - 1) / nb; // block b owns words [w0,w1) of the SHARD space
|
||||
const int w0 = b * w;
|
||||
int w1 = w0 + w; if (w1 > sh_max) w1 = sh_max;
|
||||
const int pw = (w + pieces - 1) / pieces; // piece j of the block: [w0 + j*pw, +pw) within w1
|
||||
|
||||
// region A of my slot in every peer's scratch (B sits at +sh_max)
|
||||
int4* pa[NPEERS];
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p)
|
||||
pa[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16;
|
||||
|
||||
const int4* src[WS];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < WS; ++r)
|
||||
src[r] = (r == rank) ? (in4 + (size_t)HALO_TS_OFF(rank))
|
||||
: (my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16);
|
||||
int4* my_out = out4 + (size_t)HALO_TS_OFF(rank);
|
||||
|
||||
// phase 1: my contribution to each peer-owned shard -> owner's region A
|
||||
auto push1 = [&](int j) {
|
||||
const int p0 = w0 + j * pw, p1 = p0 + pw < w1 ? p0 + pw : w1;
|
||||
for (int i = 0; i < NPEERS; ++i) {
|
||||
const int p = FORM == HALO_AR8_FORM_LOCKSTEP ? i : (i + rank) % NPEERS;
|
||||
const int owner = peers.rank[p];
|
||||
const int4* s1 = in4 + (size_t)HALO_TS_OFF(owner);
|
||||
int4* dst = pa[p];
|
||||
const int lim = p1 < HALO_TS_LEN(owner) ? p1 : HALO_TS_LEN(owner);
|
||||
for (int k = p0 + tid; k < lim; k += nt) dst[k] = s1[k];
|
||||
}
|
||||
};
|
||||
// reduce my shard (fp32, ascending rank, own contribution from the input) fused with the phase-2
|
||||
// push: the reduced word goes to my out and every peer's region B in the same pass
|
||||
auto reduce2 = [&](int j) {
|
||||
const int p0 = w0 + j * pw, p1 = p0 + pw < w1 ? p0 + pw : w1;
|
||||
const int my_lim = p1 < HALO_TS_LEN(rank) ? p1 : HALO_TS_LEN(rank);
|
||||
for (int k = p0 + tid; k < my_lim; k += nt) {
|
||||
float acc[LANES];
|
||||
#pragma unroll
|
||||
for (int l = 0; l < LANES; ++l) acc[l] = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < WS; ++r) {
|
||||
const int4 v = src[r][k];
|
||||
const T* pv = reinterpret_cast<const T*>(&v);
|
||||
#pragma unroll
|
||||
for (int l = 0; l < LANES; ++l) acc[l] += halo_ar_to_f(pv[l]);
|
||||
}
|
||||
int4 o;
|
||||
T* po = reinterpret_cast<T*>(&o);
|
||||
#pragma unroll
|
||||
for (int l = 0; l < LANES; ++l) halo_ar_from_f(acc[l], po[l]);
|
||||
my_out[k] = o;
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p) pa[p][sh_max + k] = o; // region B
|
||||
}
|
||||
};
|
||||
// every peer-owned shard from my region B copies
|
||||
auto assemble = [&](int j) {
|
||||
const int p0 = w0 + j * pw, p1 = p0 + pw < w1 ? p0 + pw : w1;
|
||||
for (int p = 0; p < NPEERS; ++p) {
|
||||
const int owner = peers.rank[p];
|
||||
const int4* srcB = my_base + ((size_t)parity * WS + owner) * (size_t)slot_stride16 + sh_max;
|
||||
int4* dst = out4 + (size_t)HALO_TS_OFF(owner);
|
||||
const int lim = p1 < HALO_TS_LEN(owner) ? p1 : HALO_TS_LEN(owner);
|
||||
for (int k = p0 + tid; k < lim; k += nt) dst[k] = srcB[k];
|
||||
}
|
||||
};
|
||||
|
||||
/* Pieces run as a pipeline so both directions of a link carry bytes at once: step j pushes
|
||||
* piece j+1's phase 1 and piece j's phase 2. One flag word per (block, source) is a monotone
|
||||
* counter, so a step's single handshake (v0 + 1 + j) also vouches for every earlier one. A rank
|
||||
* owning little sends nearly all its bytes in phase 1 and receives them in phase 2; without the
|
||||
* overlap one direction idles in each phase. With one piece the sequence is push, flag 2s-1,
|
||||
* reduce, flag 2s, assemble. A word is touched by the same thread in all three steps, which keeps
|
||||
* the in-place form safe. */
|
||||
if constexpr (FORM != HALO_AR8_FORM_SPLIT) {
|
||||
push1(0);
|
||||
halo_ar_handshake<WS>(peers, my_flags, b, rank, v0, drain, acq, pub, tl ? tl + 1 : nullptr);
|
||||
for (int j = 0; j < pieces; ++j) {
|
||||
if (j + 1 < pieces) push1(j + 1);
|
||||
reduce2(j);
|
||||
if (j > 0) assemble(j - 1);
|
||||
halo_ar_handshake<WS>(peers, my_flags, b, rank, v0 + 1u + (unsigned int)j, drain, acq, pub,
|
||||
tl ? tl + 3 + 2 * j : nullptr);
|
||||
}
|
||||
/* The hold ends after the last handshake, not the first: the reduce is fused with the phase-2
|
||||
* push (every reduced word goes to each peer's region B), so until then 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 of the last piece is left (halo_ar_seq.h). */
|
||||
halo_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
assemble(pieces - 1);
|
||||
if (tl) {
|
||||
__syncthreads();
|
||||
halo_ar_tl_stamp(tl, 3 + 2 * pieces);
|
||||
}
|
||||
} else {
|
||||
/* The same steps with a flag after each half. Published in program order on one monotone
|
||||
* word: first hop of piece 0 at v0, of piece j + 1 at v0 + 2j + 1, the reduce of piece j at
|
||||
* v0 + 2j + 2; so "peer's first hop of j done" is the word at v0 (j = 0) or v0 + 2j - 1, and
|
||||
* "peer's reduce of j done" at v0 + 2j + 2. A launch completes only after every peer has
|
||||
* published its last reduce, which it does inside this launch, so the slot parity argument
|
||||
* of the lockstep form holds unchanged (halo_ar_seq.h). */
|
||||
int n = 0;
|
||||
auto tlp = [&]() { long long* p = tl ? tl + 1 + 2 * n : nullptr; ++n; return p; };
|
||||
push1(0);
|
||||
halo_ar_publish<WS>(peers, b, rank, v0, drain, pub);
|
||||
for (int j = 0; j < pieces; ++j) {
|
||||
if (j + 1 < pieces) {
|
||||
push1(j + 1);
|
||||
halo_ar_publish<WS>(peers, b, rank, v0 + 2u * (unsigned int)j + 1u, drain, pub);
|
||||
}
|
||||
halo_ar_await<WS>(peers, my_flags, b, j == 0 ? v0 : v0 + 2u * (unsigned int)j - 1u, acq,
|
||||
tlp());
|
||||
reduce2(j);
|
||||
halo_ar_publish<WS>(peers, b, rank, v0 + 2u * (unsigned int)j + 2u, drain, pub);
|
||||
if (j > 0) {
|
||||
halo_ar_await<WS>(peers, my_flags, b, v0 + 2u * (unsigned int)j, acq, tlp());
|
||||
assemble(j - 1);
|
||||
}
|
||||
}
|
||||
halo_ar_await<WS>(peers, my_flags, b, v0 + 2u * (unsigned int)pieces, acq, tlp());
|
||||
halo_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
assemble(pieces - 1);
|
||||
if (tl) {
|
||||
__syncthreads();
|
||||
halo_ar_tl_stamp(tl, 1 + 2 * n);
|
||||
}
|
||||
}
|
||||
#undef HALO_TS_OFF
|
||||
#undef HALO_TS_LEN
|
||||
if (CHAIN) halo_chain_done();
|
||||
}
|
||||
|
||||
// ---- the coded form: both pushes carry ~12.2 bits a bf16 value instead of 16, losslessly
|
||||
//
|
||||
// The prefill overlap's reductions are link-bound, and a residual stream's bf16 words have few
|
||||
// distinct exponents: on the 31B (4x R9700, 64 groups of 512 x 5376 values from a 9.9k-token
|
||||
// prefill) 2.5-3.2 bits of exponent entropy against 8 stored. A chunk is one int4 word (8
|
||||
// values); 8 consecutive chunks (64 values) form a group that shares a base exponent, and each
|
||||
// value keeps its sign, its 7 mantissa bits and a 4-bit exponent offset (0 = an exact zero, 1..15 =
|
||||
// base .. base + 14), 8 values to 3 dwords. A group holding a subnormal, an inf or NaN, or an
|
||||
// exponent range past 14 (0.02% of groups there) is stored raw in a shadow area, its base byte
|
||||
// 0xFF. A region (one source's shard in an owner's scratch) is [3 dwords a chunk][a base byte a
|
||||
// group][the shadow, 16 bytes a chunk]; A and B are two regions in a slot. A wave codes 32
|
||||
// consecutive chunks: the group's exponents meet by lane shuffles, and the packed dwords are
|
||||
// redistributed so every store a wave makes is contiguous, keeping the P2P writes coalesced.
|
||||
//
|
||||
// Decoding gives back the same bf16 values, so the reduce folds the same numbers in the same rank
|
||||
// order: the bytes are the plain kernel's. Four-card microbenchmark (the real payload above, the
|
||||
// two-shot of a 1024-row slice beside the w4a8 prefill GEMM): byte-identical; the reduction 1383
|
||||
// us at the plain lane launch (2 x 256) against 996 us coded at 4 x 1024, with the GEMM beside it
|
||||
// 746 -> 724 us. Below 1024 threads a launch codes too slowly (2 x 256: 2492 us).
|
||||
__device__ __forceinline__ unsigned halo_arc_shfl(unsigned v, int src) {
|
||||
return (unsigned)__builtin_amdgcn_ds_bpermute(src << 2, (int)v);
|
||||
}
|
||||
struct HaloArcEnc { unsigned w[3]; unsigned base; };
|
||||
// Code this lane's chunk; every lane of the wave calls (a lane past the end with valid false).
|
||||
__device__ __forceinline__ HaloArcEnc halo_arc_enc(int4 v, bool valid) {
|
||||
const unsigned d[4] = {(unsigned)v.x, (unsigned)v.y, (unsigned)v.z, (unsigned)v.w};
|
||||
unsigned emin = 255u, emax = 0u, bad = 0u;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const unsigned u = (d[i >> 1] >> ((i & 1) * 16)) & 0xffffu;
|
||||
const unsigned e = (u >> 7) & 0xffu, m = u & 0x7fu;
|
||||
if (e) { emin = e < emin ? e : emin; emax = e > emax ? e : emax; }
|
||||
bad |= (unsigned)(e == 0u && m != 0u) | (unsigned)(e == 255u);
|
||||
}
|
||||
if (!valid) { emin = 255u; emax = 0u; bad = 0u; }
|
||||
const int lane = (int)(threadIdx.x & 31u);
|
||||
#pragma unroll
|
||||
for (int s = 1; s < 8; s <<= 1) {
|
||||
const unsigned a = halo_arc_shfl(emin, lane ^ s), b = halo_arc_shfl(emax, lane ^ s);
|
||||
const unsigned c = halo_arc_shfl(bad, lane ^ s);
|
||||
emin = a < emin ? a : emin; emax = b > emax ? b : emax; bad |= c;
|
||||
}
|
||||
HaloArcEnc r;
|
||||
const unsigned base = emin == 255u ? 1u : emin;
|
||||
r.base = (bad || emax > base + 14u) ? 0xFFu : base;
|
||||
unsigned c[8];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const unsigned u = (d[i >> 1] >> ((i & 1) * 16)) & 0xffffu;
|
||||
const unsigned e = (u >> 7) & 0xffu, m = u & 0x7fu, sg = u >> 15;
|
||||
c[i] = (sg << 11) | (m << 4) | (e ? (e - base + 1u) & 15u : 0u);
|
||||
}
|
||||
r.w[0] = c[0] | (c[1] << 12) | (c[2] << 24);
|
||||
r.w[1] = (c[2] >> 8) | (c[3] << 4) | (c[4] << 16) | (c[5] << 28);
|
||||
r.w[2] = (c[5] >> 4) | (c[6] << 8) | (c[7] << 20);
|
||||
return r;
|
||||
}
|
||||
__device__ __forceinline__ int4 halo_arc_dec(const unsigned (&w)[3], unsigned base) {
|
||||
unsigned c[8];
|
||||
c[0] = w[0] & 0xfffu; c[1] = (w[0] >> 12) & 0xfffu; c[2] = (w[0] >> 24) | ((w[1] & 0xfu) << 8);
|
||||
c[3] = (w[1] >> 4) & 0xfffu; c[4] = (w[1] >> 16) & 0xfffu; c[5] = (w[1] >> 28) | ((w[2] & 0xffu) << 4);
|
||||
c[6] = (w[2] >> 8) & 0xfffu; c[7] = w[2] >> 20;
|
||||
unsigned u[8];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const unsigned off = c[i] & 15u;
|
||||
u[i] = ((c[i] >> 11) << 15) | ((off ? base + off - 1u : 0u) << 7) | ((c[i] >> 4) & 0x7fu);
|
||||
}
|
||||
int4 v;
|
||||
v.x = (int)(u[0] | (u[1] << 16)); v.y = (int)(u[2] | (u[3] << 16));
|
||||
v.z = (int)(u[4] | (u[5] << 16)); v.w = (int)(u[6] | (u[7] << 16));
|
||||
return v;
|
||||
}
|
||||
struct HaloArcRegion { unsigned* packed; unsigned* bases; int4* shadow; };
|
||||
__host__ __device__ constexpr size_t halo_arc_shadow_off(long SL) {
|
||||
return ((size_t)12 * SL + (size_t)SL / 8 + 15) & ~(size_t)15;
|
||||
}
|
||||
__host__ __device__ constexpr size_t halo_arc_region_bytes(long SL) {
|
||||
return (halo_arc_shadow_off(SL) + (size_t)16 * SL + 255) & ~(size_t)255;
|
||||
}
|
||||
__device__ __forceinline__ HaloArcRegion halo_arc_region(const void* p, int SL) {
|
||||
char* b = (char*)p;
|
||||
return HaloArcRegion{(unsigned*)b, (unsigned*)(b + (size_t)12 * SL), (int4*)(b + halo_arc_shadow_off(SL))};
|
||||
}
|
||||
// A wave's coded chunks [k0, k0 + 32) (k0 a multiple of 32) into ND regions, every store contiguous.
|
||||
template <int ND>
|
||||
__device__ __forceinline__ void halo_arc_put(HaloArcRegion (&dst)[ND], int k0, const HaloArcEnc& e,
|
||||
int4 raw, bool valid) {
|
||||
const int lane = (int)(threadIdx.x & 31u);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 3; ++j) {
|
||||
const int p = 32 * j + lane, sl = p / 3, wi = p - sl * 3;
|
||||
const unsigned a0 = halo_arc_shfl(e.w[0], sl), a1 = halo_arc_shfl(e.w[1], sl);
|
||||
const unsigned a2 = halo_arc_shfl(e.w[2], sl), vs = halo_arc_shfl(valid ? 1u : 0u, sl);
|
||||
const unsigned val = wi == 0 ? a0 : wi == 1 ? a1 : a2;
|
||||
if (vs) {
|
||||
#pragma unroll
|
||||
for (int q = 0; q < ND; ++q) dst[q].packed[(size_t)k0 * 3 + p] = val;
|
||||
}
|
||||
}
|
||||
const unsigned b0 = halo_arc_shfl(e.base, 0), b1 = halo_arc_shfl(e.base, 8);
|
||||
const unsigned b2 = halo_arc_shfl(e.base, 16), b3 = halo_arc_shfl(e.base, 24);
|
||||
if (lane == 0 && valid) {
|
||||
#pragma unroll
|
||||
for (int q = 0; q < ND; ++q) dst[q].bases[k0 / 32] = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
|
||||
}
|
||||
if (valid && e.base == 0xFFu) {
|
||||
#pragma unroll
|
||||
for (int q = 0; q < ND; ++q) dst[q].shadow[k0 + lane] = raw;
|
||||
}
|
||||
}
|
||||
// A wave's chunks [k0, k0 + 32) back from a region; every lane calls.
|
||||
__device__ __forceinline__ int4 halo_arc_get(const HaloArcRegion& src, int k0, bool valid) {
|
||||
const int lane = (int)(threadIdx.x & 31u);
|
||||
unsigned ld[3];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 3; ++j) ld[j] = valid ? src.packed[(size_t)k0 * 3 + 32 * j + lane] : 0u;
|
||||
unsigned w[3];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
const int q = 3 * lane + i, sl = q & 31, j = q >> 5;
|
||||
const unsigned a0 = halo_arc_shfl(ld[0], sl), a1 = halo_arc_shfl(ld[1], sl);
|
||||
const unsigned a2 = halo_arc_shfl(ld[2], sl);
|
||||
w[i] = j == 0 ? a0 : j == 1 ? a1 : a2;
|
||||
}
|
||||
const unsigned base = ((valid ? src.bases[k0 / 32] : 0u) >> ((lane >> 3) * 8)) & 0xffu;
|
||||
if (base == 0xFFu) return valid ? src.shadow[k0 + lane] : make_int4(0, 0, 0, 0);
|
||||
return halo_arc_dec(w, base);
|
||||
}
|
||||
|
||||
// The coded two-shot, bf16 only; the launcher checks that each shard is a whole number of waves'
|
||||
// 32 chunks and that a slot holds two regions.
|
||||
template <int WS, bool CHAIN>
|
||||
__device__ __forceinline__ void halo_ar_twoshot_coded_body(
|
||||
const int4* __restrict__ in4, HaloArWidePeers<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,
|
||||
long long* gate, unsigned int* gate_ctr) {
|
||||
if (CHAIN) halo_chain_wait();
|
||||
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 = halo_ar_link_word(gate, (unsigned int)tid);
|
||||
halo_ar_seq_take(seq_ctrs, HALO_AR_WIDE_MAX_BLOCKS, s_seq, s_slot);
|
||||
const unsigned int s = s_seq;
|
||||
const int parity = (int)s_slot;
|
||||
const int SL = n16 / WS; /* every shard: a multiple of 32 chunks */
|
||||
int w = (SL + nb - 1) / nb;
|
||||
w = (w + 31) & ~31;
|
||||
const int w0 = b * w;
|
||||
int w1 = w0 + w; if (w1 > SL) w1 = SL;
|
||||
const size_t RB = halo_arc_region_bytes(SL);
|
||||
const int lane = tid & 31;
|
||||
|
||||
// phase 1: my contribution to each peer-owned shard, coded, into the owner's region A for me
|
||||
for (int p = 0; p < NPEERS; ++p) {
|
||||
const int owner = peers.rank[p];
|
||||
const int4* src = in4 + (size_t)owner * SL;
|
||||
HaloArcRegion dst[1] = {halo_arc_region(peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16, SL)};
|
||||
for (int k = w0 + tid; k - lane < w1; k += nt) {
|
||||
const bool valid = k < w1;
|
||||
const int4 v = valid ? src[k] : make_int4(0, 0, 0, 0);
|
||||
halo_arc_put<1>(dst, k - lane, halo_arc_enc(v, valid), v, valid);
|
||||
}
|
||||
}
|
||||
halo_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s - 1u, drain, acq, pub);
|
||||
|
||||
// reduce my shard (fp32, ascending rank, my own contribution raw from the input), code it once,
|
||||
// and push it to every peer's region B
|
||||
HaloArcRegion srcA[WS], dstB[NPEERS];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < WS; ++r)
|
||||
srcA[r] = halo_arc_region(my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16, SL);
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p)
|
||||
dstB[p] = halo_arc_region((const char*)(peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16) + RB, SL);
|
||||
const int4* own = in4 + (size_t)rank * SL;
|
||||
int4* my_out = out4 + (size_t)rank * SL;
|
||||
for (int k = w0 + tid; k - lane < w1; k += nt) {
|
||||
const bool valid = k < w1;
|
||||
const int k0 = k - lane;
|
||||
float acc[8];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) acc[j] = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < WS; ++r) {
|
||||
const int4 v = (r == rank) ? (valid ? own[k] : make_int4(0, 0, 0, 0)) : halo_arc_get(srcA[r], k0, valid);
|
||||
const __hip_bfloat16* pv = reinterpret_cast<const __hip_bfloat16*>(&v);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) acc[j] += (float)pv[j];
|
||||
}
|
||||
int4 o;
|
||||
__hip_bfloat16* po = reinterpret_cast<__hip_bfloat16*>(&o);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) po[j] = (__hip_bfloat16)acc[j];
|
||||
if (valid) my_out[k] = o;
|
||||
halo_arc_put<NPEERS>(dstB, k0, halo_arc_enc(o, valid), o, valid);
|
||||
}
|
||||
halo_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s, drain, acq, pub);
|
||||
halo_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
// assemble: every peer-owned shard from my region B
|
||||
for (int p = 0; p < NPEERS; ++p) {
|
||||
const int owner = peers.rank[p];
|
||||
const HaloArcRegion src = halo_arc_region((const char*)(my_base + ((size_t)parity * WS + owner) * (size_t)slot_stride16) + RB, SL);
|
||||
int4* dst = out4 + (size_t)owner * SL;
|
||||
for (int k = w0 + tid; k - lane < w1; k += nt) {
|
||||
const bool valid = k < w1;
|
||||
const int4 v = halo_arc_get(src, k - lane, valid);
|
||||
if (valid) dst[k] = v;
|
||||
}
|
||||
}
|
||||
if (CHAIN) halo_chain_done();
|
||||
}
|
||||
|
||||
#define HALO_ARTS_PARAMS const int4* __restrict__ in4, HaloArWidePeers<int4, WS - 1> peers, \
|
||||
const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, \
|
||||
int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, HaloArShardOff<WS> sh, \
|
||||
int slot_stride16, int rank, int drain, int acq, int pub, long long* gate, \
|
||||
unsigned int* gate_ctr, int pieces_arg, long long* tl_all
|
||||
#define HALO_ARTS_ARGS in4, peers, my_base, my_flags, out4, seq_ctrs, sh, slot_stride16, rank, \
|
||||
drain, acq, pub, gate, gate_ctr, pieces_arg, tl_all
|
||||
template <typename T, int LANES, int WS, bool PIECED, int FORM>
|
||||
__global__ void halo_ar_twoshot_wide_exact_kernel(HALO_ARTS_PARAMS) {
|
||||
halo_ar_twoshot_wide_exact_body<T, LANES, WS, PIECED, FORM, false>(HALO_ARTS_ARGS);
|
||||
}
|
||||
template <typename T, int LANES, int WS, bool PIECED, int FORM>
|
||||
__global__ void halo_r4dchain_ar_twoshot_wide_exact(HALO_ARTS_PARAMS) {
|
||||
halo_ar_twoshot_wide_exact_body<T, LANES, WS, PIECED, FORM, true>(HALO_ARTS_ARGS);
|
||||
}
|
||||
#undef HALO_ARTS_ARGS
|
||||
#undef HALO_ARTS_PARAMS
|
||||
// The coded form keeps the even split (its launcher checks every shard is whole waves' chunks), so
|
||||
// it takes the message length, not the plain form's shard table and pieces.
|
||||
#define HALO_ARTC_PARAMS const int4* __restrict__ in4, HaloArWidePeers<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, long long* gate, unsigned int* gate_ctr
|
||||
#define HALO_ARTC_ARGS in4, peers, my_base, my_flags, out4, seq_ctrs, n16, slot_stride16, rank, \
|
||||
drain, acq, pub, gate, gate_ctr
|
||||
template <int WS>
|
||||
__global__ void halo_ar_twoshot_coded_kernel(HALO_ARTC_PARAMS) {
|
||||
halo_ar_twoshot_coded_body<WS, false>(HALO_ARTC_ARGS);
|
||||
}
|
||||
template <int WS>
|
||||
__global__ void halo_r4dchain_ar_twoshot_coded(HALO_ARTC_PARAMS) {
|
||||
halo_ar_twoshot_coded_body<WS, true>(HALO_ARTC_ARGS);
|
||||
}
|
||||
#undef HALO_ARTC_ARGS
|
||||
#undef HALO_ARTC_PARAMS
|
||||
|
||||
// --- host side ---
|
||||
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 gate, long gate_ctr, const int* shard_weights,
|
||||
long pieces, long timeline, long form, bool chain = false) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
if (rank < 0 || rank >= WS)
|
||||
throw std::runtime_error("all_reduce: rank " + std::to_string(rank) +
|
||||
" out of range for the " + std::to_string(WS) +
|
||||
" ranks this entry point is compiled for");
|
||||
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 (n_elem > HALO_AR_TWOSHOT_WIDE_MAX_ELEMS)
|
||||
throw std::runtime_error("all_reduce: n_elem " + std::to_string(n_elem) +
|
||||
" exceeds the twoshot band (" +
|
||||
std::to_string(HALO_AR_TWOSHOT_WIDE_MAX_ELEMS) +
|
||||
" elems); use the fallback path");
|
||||
const long n16 = nbytes / 16;
|
||||
if (!shard_weights && n16 < WS)
|
||||
throw std::runtime_error("all_reduce: message (" + std::to_string(n16) +
|
||||
" 16B words) is shorter than one word a rank");
|
||||
if (n16 < 1) throw std::runtime_error("all_reduce: empty message");
|
||||
if (shard_weights) {
|
||||
long wsum = 0;
|
||||
for (int s = 0; s < WS; ++s) {
|
||||
if (shard_weights[s] < 0 || shard_weights[s] > HALO_AR_SHARD_WEIGHT_MAX)
|
||||
throw std::runtime_error("all_reduce: shard weight out of range");
|
||||
wsum += shard_weights[s];
|
||||
}
|
||||
if (wsum <= 0) throw std::runtime_error("all_reduce: shard weights sum to zero");
|
||||
}
|
||||
long off[WS + 1];
|
||||
const long sh_max = halo_ar_shard_table(n16, WS, shard_weights, off);
|
||||
HaloArShardOff<WS> sh{};
|
||||
for (int s = 0; s <= WS; ++s) sh.off[s] = (int)off[s];
|
||||
sh.sh_max = (int)sh_max;
|
||||
// regions A and B each hold the longest shard
|
||||
if (2 * sh_max > (long)slot_stride16)
|
||||
throw std::runtime_error("all_reduce: shard (" + std::to_string(sh_max) +
|
||||
" 16B words) needs 2x inside the per-source slot stride (" +
|
||||
std::to_string(slot_stride16) + ")");
|
||||
|
||||
int nb = (int)nblocks;
|
||||
if (nb < 1) nb = HALO_AR_NB_DESIGN;
|
||||
if (nb > sh_max) nb = (int)sh_max;
|
||||
if (nb > HALO_AR_WIDE_MAX_BLOCKS) nb = HALO_AR_WIDE_MAX_BLOCKS;
|
||||
int nt = (int)nthreads;
|
||||
if (nt < 64) nt = 64;
|
||||
if (nt > 1024) nt = 1024;
|
||||
if (pieces < 1 || pieces > HALO_AR_TS_MAX_PIECES)
|
||||
throw std::runtime_error("all_reduce: pieces " + std::to_string(pieces) + " outside 1.." +
|
||||
std::to_string((int)HALO_AR_TS_MAX_PIECES));
|
||||
if (form < HALO_AR8_FORM_LOCKSTEP || form > HALO_AR8_FORM_SPLIT ||
|
||||
(WS != 8 && form != HALO_AR8_FORM_LOCKSTEP))
|
||||
throw std::runtime_error("all_reduce: form " + std::to_string(form) + " at " +
|
||||
std::to_string(WS) + " ranks (ring and split are eight-rank forms)");
|
||||
// a block's share of the longest shard bounds the pieces worth a handshake each
|
||||
const long words_a_block = (sh_max + nb - 1) / nb;
|
||||
const int np = (int)(pieces < words_a_block ? pieces : words_a_block);
|
||||
|
||||
HaloArWidePeers<int4, NPEERS> peers{};
|
||||
for (int i = 0; i < NPEERS; ++i) {
|
||||
if (!peer_scratch[i] || !peer_flags[i])
|
||||
throw std::runtime_error("all_reduce: null peer scratch/flag pointer at index " +
|
||||
std::to_string(i));
|
||||
peers.scratch[i] = (int4*)peer_scratch[i];
|
||||
peers.flags[i] = (unsigned int*)peer_flags[i];
|
||||
peers.rank[i] = (i < (int)rank) ? i : i + 1;
|
||||
}
|
||||
|
||||
// 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 (halo_ar_seq.h).
|
||||
const long slot_bytes = 2L * WS * (long)slot_stride16 * 16;
|
||||
const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int);
|
||||
halo_ar_check_extent(my_scratch, slot_bytes, "all_reduce", "my_scratch");
|
||||
halo_ar_check_extent(my_flags, flag_bytes, "all_reduce", "my_flags");
|
||||
halo_ar_check_extent(seq_ctrs, 2L * HALO_AR_WIDE_MAX_BLOCKS * (long)sizeof(unsigned int),
|
||||
"all_reduce", "seq_ctrs");
|
||||
for (int i = 0; i < NPEERS; ++i) {
|
||||
halo_ar_check_extent(peer_scratch[i], slot_bytes, "all_reduce", "peer scratch");
|
||||
halo_ar_check_extent(peer_flags[i], flag_bytes, "all_reduce", "peer flags");
|
||||
}
|
||||
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
#define HALO_AR_TS_LAUNCH_F(T, LN, P, F) \
|
||||
(chain ? halo_r4dchain_ar_twoshot_wide_exact<T, LN, WS, P, F> \
|
||||
: halo_ar_twoshot_wide_exact_kernel<T, LN, WS, P, F>)<<<nb, nt, 0, st>>>( \
|
||||
(const int4*)inp, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \
|
||||
(int4*)out, (unsigned int*)seq_ctrs, sh, (int)slot_stride16, \
|
||||
(int)rank, (int)drain, (int)acq, (int)pub, (long long*)gate, \
|
||||
(unsigned int*)gate_ctr, np, (long long*)timeline)
|
||||
#define HALO_AR_TS_LAUNCH_P(T, LN, P) \
|
||||
do { \
|
||||
if constexpr (WS == 8) { \
|
||||
if (form == HALO_AR8_FORM_RING) \
|
||||
HALO_AR_TS_LAUNCH_F(T, LN, P, HALO_AR8_FORM_RING); \
|
||||
else if (form == HALO_AR8_FORM_SPLIT) \
|
||||
HALO_AR_TS_LAUNCH_F(T, LN, P, HALO_AR8_FORM_SPLIT); \
|
||||
else \
|
||||
HALO_AR_TS_LAUNCH_F(T, LN, P, HALO_AR8_FORM_LOCKSTEP); \
|
||||
} else { \
|
||||
HALO_AR_TS_LAUNCH_F(T, LN, P, HALO_AR8_FORM_LOCKSTEP); \
|
||||
} \
|
||||
} while (0)
|
||||
#define HALO_AR_TS_LAUNCH(T, LN) \
|
||||
do { \
|
||||
if (np > 1) HALO_AR_TS_LAUNCH_P(T, LN, true); \
|
||||
else HALO_AR_TS_LAUNCH_P(T, LN, false); \
|
||||
} while (0)
|
||||
if (dtype == 0) HALO_AR_TS_LAUNCH(__hip_bfloat16, 8);
|
||||
else if (dtype == 1) HALO_AR_TS_LAUNCH(__half, 8);
|
||||
else if (dtype == 2) HALO_AR_TS_LAUNCH(float, 4);
|
||||
else throw std::runtime_error("all_reduce: bad dtype");
|
||||
#undef HALO_AR_TS_LAUNCH
|
||||
#undef HALO_AR_TS_LAUNCH_P
|
||||
#undef HALO_AR_TS_LAUNCH_F
|
||||
}
|
||||
|
||||
void halo_ar_twoshot_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, long inp, long out, long n_elem, long dtype,
|
||||
long rank, long stream, 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_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, 0L, 0L, nullptr,
|
||||
1L, 0L, 0L);
|
||||
}
|
||||
|
||||
void halo_ar_twoshot_4rank_exact(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 stream, long nblocks, long nthreads, long drain,
|
||||
long acq, long pub, long gate, long gate_ctr, long chain) {
|
||||
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, gate, gate_ctr,
|
||||
nullptr, 1L, 0L, 0L, chain != 0);
|
||||
}
|
||||
|
||||
/* The coded form's conditions: bf16, a message that shards evenly into whole waves' 32 chunks
|
||||
* (256 values) a rank, and a slot that holds two coded regions. */
|
||||
int halo_ar_twoshot_coded_ok(long n_elem, long dtype, long world, long slot_stride16) {
|
||||
if (dtype != 0 || world <= 0 || n_elem % (world * 256) != 0) return 0;
|
||||
const long SL = n_elem / 8 / world;
|
||||
return 2 * halo_arc_region_bytes(SL) <= (size_t)slot_stride16 * 16 ? 1 : 0;
|
||||
}
|
||||
|
||||
void halo_ar_twoshot_4rank_exact_coded(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 rank, long stream, long nblocks, long nthreads,
|
||||
long drain, long acq, long pub, long gate, long gate_ctr,
|
||||
long chain) {
|
||||
constexpr int WS = 4;
|
||||
if (!halo_ar_twoshot_coded_ok(n_elem, 0, WS, slot_stride16))
|
||||
throw std::runtime_error("all_reduce (coded): message or slot outside the coded form");
|
||||
if (rank < 0 || rank >= WS) throw std::runtime_error("all_reduce (coded): rank out of range");
|
||||
const long n16 = n_elem / 8, SL = n16 / WS;
|
||||
int nb = (int)nblocks;
|
||||
if (nb < 1) nb = 4;
|
||||
if (nb > HALO_AR_WIDE_MAX_BLOCKS) nb = HALO_AR_WIDE_MAX_BLOCKS;
|
||||
if (nb > SL / 32) nb = (int)(SL / 32);
|
||||
int nt = (int)nthreads;
|
||||
if (nt < 256) nt = 256;
|
||||
if (nt > 1024) nt = 1024;
|
||||
nt &= ~31;
|
||||
HaloArWidePeers<int4, WS - 1> peers{};
|
||||
const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2};
|
||||
const long pf[3] = {peer_flags0, peer_flags1, peer_flags2};
|
||||
for (int i = 0; i < WS - 1; ++i) {
|
||||
if (!ps[i] || !pf[i]) throw std::runtime_error("all_reduce (coded): null peer pointer");
|
||||
peers.scratch[i] = (int4*)ps[i];
|
||||
peers.flags[i] = (unsigned int*)pf[i];
|
||||
peers.rank[i] = (i < (int)rank) ? i : i + 1;
|
||||
}
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
(chain ? halo_r4dchain_ar_twoshot_coded<WS> : halo_ar_twoshot_coded_kernel<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, (long long*)gate, (unsigned int*)gate_ctr);
|
||||
}
|
||||
|
||||
void halo_ar_twoshot_8rank_exact(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,
|
||||
long peer_flags2, long peer_flags3, long peer_flags4,
|
||||
long peer_flags5, long peer_flags6, 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,
|
||||
const int* shard_weights, long pieces, long timeline,
|
||||
long form) {
|
||||
const long ps[7] = {peer_scratch0, peer_scratch1, peer_scratch2, peer_scratch3,
|
||||
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, 0L, 0L,
|
||||
shard_weights, pieces, timeline, form);
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
/* Derived from libr4d/r4d_ar_twoshot_Nrank_ti8.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_ar_twoshot_Nrank_ti8.hip: halo_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 halo_ar_ti8.h,
|
||||
// transport from halo_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, 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 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 "halo.h"
|
||||
#include "halo_ar_ti8.h"
|
||||
#include "halo_ar_wide.h"
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
template <typename T, int WS>
|
||||
__global__ void halo_ar_twoshot_wide_ti8_kernel(
|
||||
const T* __restrict__ in, HaloArWidePeers<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 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 = halo_ar_link_word(gate, (unsigned int)tid);
|
||||
halo_ar_seq_take(seq_ctrs, HALO_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe
|
||||
const unsigned int s = s_seq;
|
||||
const int parity = (int)s_slot;
|
||||
|
||||
// shard s = groups [s*gbase + min(s, grem), +gbase + (s < grem)); sg is the longest
|
||||
const int gbase = n_groups / WS, grem = n_groups % WS;
|
||||
const int sg = gbase + (grem ? 1 : 0);
|
||||
#define HALO_TI8_OFF(s) ((size_t)((s) * gbase + ((s) < grem ? (s) : grem)) * TI8_GROUP)
|
||||
#define HALO_TI8_LEN(s) (gbase + ((s) < grem ? 1 : 0))
|
||||
const int rec_off = TI8_REC_OFF * sg, sc_off = TI8_SC_OFF * sg; // wire layout: codes | rec | scales
|
||||
const int gpb = (sg + nb - 1) / nb; // block b owns shard groups [gA, gB)
|
||||
const int gA = b * gpb;
|
||||
const int gB = (gA + gpb < sg) ? gA + gpb : sg;
|
||||
|
||||
char* pslot[NPEERS];
|
||||
#pragma unroll
|
||||
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.
|
||||
for (int p = 0; p < NPEERS; ++p) {
|
||||
const T* src = in + HALO_TI8_OFF(peers.rank[p]);
|
||||
const int gE = gB < HALO_TI8_LEN(peers.rank[p]) ? gB : HALO_TI8_LEN(peers.rank[p]);
|
||||
for (int k = 4 * gA + tid; k < 4 * gE; k += nt) {
|
||||
const int lig = k & 3;
|
||||
const int g = k >> 2;
|
||||
uint2 codes;
|
||||
unsigned int rec;
|
||||
__half scale;
|
||||
ti8_encode_group<T>(src + k * TI8_EPL, lig, &codes, &rec, &scale);
|
||||
((uint2*)pslot[p])[k] = codes;
|
||||
if (lig == 0) {
|
||||
((unsigned int*)(pslot[p] + rec_off))[g] = rec;
|
||||
((__half*)(pslot[p] + sc_off))[g] = scale;
|
||||
}
|
||||
}
|
||||
}
|
||||
halo_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s - 1u, drain, acq, pub);
|
||||
|
||||
// ---- 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 + HALO_TI8_OFF(rank);
|
||||
T* my_out = out + HALO_TI8_OFF(rank);
|
||||
const int gM = gB < HALO_TI8_LEN(rank) ? gB : HALO_TI8_LEN(rank);
|
||||
for (int k = 4 * gA + tid; k < 4 * gM; k += nt) {
|
||||
const int lig = k & 3;
|
||||
const int g = k >> 2;
|
||||
float acc[TI8_EPL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TI8_EPL; ++i) acc[i] = 0.f;
|
||||
for (int r = 0; r < WS; ++r) { // ascending source order, own exact from the input
|
||||
float v[TI8_EPL];
|
||||
if (r == rank) {
|
||||
ti8_load8(my_in + k * TI8_EPL, v);
|
||||
} else {
|
||||
const char* base =
|
||||
my_base + ((size_t)parity * WS + r) * (size_t)slot_stride_bytes;
|
||||
const uint2 c = ((const uint2*)base)[k];
|
||||
const unsigned int rc = ((const unsigned int*)(base + rec_off))[g];
|
||||
const float scl = __half2float(((const __half*)(base + sc_off))[g]);
|
||||
ti8_decode_group<T>(c, rc, scl, lig, v);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TI8_EPL; ++i) acc[i] += v[i];
|
||||
}
|
||||
uint2 codes;
|
||||
unsigned int rc2;
|
||||
__half scl2;
|
||||
ti8_encode_group_v<T>(acc, lig, &codes, &rc2, &scl2);
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p) {
|
||||
char* bB = pslot[p] + b_off_bytes;
|
||||
((uint2*)bB)[k] = codes;
|
||||
if (lig == 0) {
|
||||
((unsigned int*)(bB + rec_off))[g] = rc2;
|
||||
((__half*)(bB + sc_off))[g] = scl2;
|
||||
}
|
||||
}
|
||||
float v2[TI8_EPL];
|
||||
ti8_decode_group<T>(codes, rc2, __half2float(scl2), lig, v2);
|
||||
ti8_store8(my_out + k * TI8_EPL, v2);
|
||||
}
|
||||
halo_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 (halo_ar_seq.h). */
|
||||
halo_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
|
||||
|
||||
// ---- 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 +
|
||||
((size_t)parity * WS + owner) * (size_t)slot_stride_bytes + b_off_bytes;
|
||||
T* dst = out + HALO_TI8_OFF(owner);
|
||||
const int gE = gB < HALO_TI8_LEN(owner) ? gB : HALO_TI8_LEN(owner);
|
||||
for (int k = 4 * gA + tid; k < 4 * gE; k += nt) {
|
||||
const int lig = k & 3;
|
||||
const int g = k >> 2;
|
||||
const uint2 c = ((const uint2*)baseB)[k];
|
||||
const unsigned int rc2 = ((const unsigned int*)(baseB + rec_off))[g];
|
||||
const float scl = __half2float(((const __half*)(baseB + sc_off))[g]);
|
||||
float v[TI8_EPL];
|
||||
ti8_decode_group<T>(c, rc2, scl, lig, v);
|
||||
ti8_store8(dst + k * TI8_EPL, v);
|
||||
}
|
||||
}
|
||||
#undef HALO_TI8_OFF
|
||||
#undef HALO_TI8_LEN
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------- host side
|
||||
template <int WS>
|
||||
static void ar_twoshot_ti8_launch(const long* peer_scratch, const long* peer_flags,
|
||||
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 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) +
|
||||
" out of range for the " + std::to_string(WS) +
|
||||
" ranks this entry point is compiled for");
|
||||
if (dtype != 0 && dtype != 1) throw std::runtime_error("ti8 ar: only bf16/fp16 payloads");
|
||||
if (n_elem % TI8_GROUP != 0)
|
||||
throw std::runtime_error("ti8 ar: n_elem must be whole " + std::to_string(TI8_GROUP) +
|
||||
"-elem groups");
|
||||
const long n_groups = n_elem / TI8_GROUP;
|
||||
if (n_groups < WS)
|
||||
throw std::runtime_error("ti8 ar: fewer groups than ranks");
|
||||
const int sg = (int)((n_groups + WS - 1) / WS); // the longest shard, the slot layout's size
|
||||
const long b_off = ((long)TI8_GROUP_BYTES * sg + 15) / 16 * 16; // one wire image, 16B-aligned
|
||||
if (2 * b_off > slot_stride_bytes)
|
||||
throw std::runtime_error("ti8 ar: slot stride " + std::to_string(slot_stride_bytes) +
|
||||
" too small for two wire images (needs " +
|
||||
std::to_string(2 * b_off) + " bytes)");
|
||||
|
||||
int nb = (int)nblocks;
|
||||
if (nb < 1) nb = HALO_AR_NB_DESIGN;
|
||||
if (nb > sg) nb = sg;
|
||||
if (nb > HALO_AR_WIDE_MAX_BLOCKS) nb = HALO_AR_WIDE_MAX_BLOCKS;
|
||||
int nt = (int)nthreads;
|
||||
if (nt < 64) nt = 64;
|
||||
if (nt > 1024) nt = 1024;
|
||||
// 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 "
|
||||
"adjacent lanes); got " + std::to_string(nt));
|
||||
|
||||
HaloArWidePeers<char, NPEERS> peers{};
|
||||
for (int i = 0; i < NPEERS; ++i) {
|
||||
if (!peer_scratch[i] || !peer_flags[i])
|
||||
throw std::runtime_error("ti8 ar: null peer scratch/flag pointer at index " +
|
||||
std::to_string(i));
|
||||
peers.scratch[i] = (char*)peer_scratch[i];
|
||||
peers.flags[i] = (unsigned int*)peer_flags[i];
|
||||
peers.rank[i] = (i < (int)rank) ? i : i + 1;
|
||||
}
|
||||
|
||||
// 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 (halo_ar_seq.h).
|
||||
const long slot_bytes = 2L * WS * slot_stride_bytes;
|
||||
const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int);
|
||||
halo_ar_check_extent(my_scratch, slot_bytes, "ti8 ar", "my_scratch");
|
||||
halo_ar_check_extent(my_flags, flag_bytes, "ti8 ar", "my_flags");
|
||||
halo_ar_check_extent(seq_ctrs, 2L * HALO_AR_WIDE_MAX_BLOCKS * (long)sizeof(unsigned int),
|
||||
"ti8 ar", "seq_ctrs");
|
||||
for (int i = 0; i < NPEERS; ++i) {
|
||||
halo_ar_check_extent(peer_scratch[i], slot_bytes, "ti8 ar", "peer scratch");
|
||||
halo_ar_check_extent(peer_flags[i], flag_bytes, "ti8 ar", "peer flags");
|
||||
}
|
||||
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
#define HALO_AR_TS8_LAUNCH(T) \
|
||||
halo_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, (long long*)gate, (unsigned int*)gate_ctr)
|
||||
if (dtype == 0) HALO_AR_TS8_LAUNCH(__hip_bfloat16);
|
||||
else HALO_AR_TS8_LAUNCH(__half);
|
||||
#undef HALO_AR_TS8_LAUNCH
|
||||
}
|
||||
|
||||
void halo_ar_twoshot_3rank_ti8(long peer_scratch0, long peer_scratch1, long peer_flags0,
|
||||
long peer_flags1, 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) {
|
||||
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, 0L, 0L);
|
||||
}
|
||||
|
||||
void halo_ar_twoshot_4rank_ti8(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_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 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, gate, gate_ctr);
|
||||
}
|
||||
|
||||
// Tiered-int8 wire format dimensions, for sizing the caller's packed scratch.
|
||||
void halo_ar_ti8_dims(int* group, int* group_bytes) {
|
||||
if (group) *group = TI8_GROUP;
|
||||
if (group_bytes) *group_bytes = TI8_GROUP_BYTES;
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/* Derived from libr4d/r4d_ar_wide.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
#pragma once
|
||||
// halo_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 (a two-shot in pieces by its piece
|
||||
// count, reserving the extra flag values it publishes), 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
|
||||
// halo_ar_seq.h, so seq_ctrs is 2 * HALO_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 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>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include "halo_ar_seq.h"
|
||||
#include "halo_ar_shards.h"
|
||||
|
||||
#define HALO_AR_SPIN_MAX 4000000000ULL
|
||||
#define HALO_AR_WIDE_MAX_BLOCKS 64
|
||||
#define HALO_AR_NB_DESIGN 16
|
||||
#define HALO_AR_WIDE_MAX_PEERS 7
|
||||
|
||||
// Ascending peer rank throughout; rank[] maps a spin lane to its global source rank. The
|
||||
// scratch word type is the one per-family difference (int4 exact wire, char ti8 wire).
|
||||
template <typename S, int NPEERS>
|
||||
struct HaloArWidePeers {
|
||||
S* scratch[NPEERS];
|
||||
unsigned int* flags[NPEERS];
|
||||
int rank[NPEERS];
|
||||
};
|
||||
|
||||
__device__ __forceinline__ void halo_ar_store_sys_rel(unsigned int* p, unsigned int v) {
|
||||
__hip_atomic_store(p, v, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
__device__ __forceinline__ void halo_ar_store_sys_rlx(unsigned int* p, unsigned int v) {
|
||||
__hip_atomic_store(p, v, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
__device__ __forceinline__ unsigned int halo_ar_load_sys_rlx(const unsigned int* p) {
|
||||
return __hip_atomic_load(p, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
}
|
||||
__device__ __forceinline__ float halo_ar_to_f(const float& x) { return x; }
|
||||
__device__ __forceinline__ float halo_ar_to_f(const __half& x) { return __half2float(x); }
|
||||
__device__ __forceinline__ float halo_ar_to_f(const __hip_bfloat16& x) { return (float)x; }
|
||||
__device__ __forceinline__ void halo_ar_from_f(float v, float& o) { o = v; }
|
||||
__device__ __forceinline__ void halo_ar_from_f(float v, __half& o) { o = __float2half(v); }
|
||||
__device__ __forceinline__ void halo_ar_from_f(float v, __hip_bfloat16& o) { o = (__hip_bfloat16)v; }
|
||||
|
||||
// drain: 0 none, 1 all-thread threadfence_system, 2 single-thread (applied by the publisher
|
||||
// inside the handshake), 3 s_wait_storecnt 0.
|
||||
__device__ __forceinline__ void halo_ar_drain(int drain) {
|
||||
if (drain == 1) __threadfence_system();
|
||||
else if (drain == 3) asm volatile("s_waitcnt vmcnt(0)" ::: "memory"); // pre-gfx12 store wait
|
||||
}
|
||||
// acq: 0 acquire-only fence (global_inv, no writeback half), 1 full threadfence_system,
|
||||
// 2 none -- fine-grained scratch only.
|
||||
__device__ __forceinline__ void halo_ar_acquire(int acq) {
|
||||
if (acq == 1) __threadfence_system();
|
||||
else if (acq != 2) __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "");
|
||||
}
|
||||
|
||||
// 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.
|
||||
//
|
||||
// `tl`, when not null, takes two wall-clock stamps: when the whole block has issued and drained
|
||||
// its stores, and when every peer's flag has been seen. A diagnostic: the eight-rank two-shot
|
||||
// passes it only for a launch asking for its timeline (halo_ar_tl_stamp).
|
||||
template <int WS, typename S, int NPEERS>
|
||||
__device__ __forceinline__ void halo_ar_handshake(const HaloArWidePeers<S, NPEERS>& peers,
|
||||
unsigned int* __restrict__ my_flags, int b,
|
||||
int rank, unsigned int val, int drain, int acq,
|
||||
int pub, long long* tl = nullptr) {
|
||||
halo_ar_drain(drain);
|
||||
__syncthreads();
|
||||
const int tid = threadIdx.x;
|
||||
if (tl && tid == 0) tl[0] = (long long)wall_clock64();
|
||||
if (tid == 0) {
|
||||
if (drain == 2) __threadfence_system();
|
||||
if (pub) {
|
||||
// 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)
|
||||
halo_ar_store_sys_rlx(&peers.flags[p][(size_t)b * WS + rank], val);
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p)
|
||||
halo_ar_store_sys_rel(&peers.flags[p][(size_t)b * WS + rank], val);
|
||||
}
|
||||
}
|
||||
if (tid < NPEERS) {
|
||||
const unsigned int* f = &my_flags[(size_t)b * WS + peers.rank[tid]];
|
||||
unsigned long long z = 0;
|
||||
while ((int)(halo_ar_load_sys_rlx(f) - val) < 0) {
|
||||
__builtin_amdgcn_s_sleep(2);
|
||||
if (++z > HALO_AR_SPIN_MAX) __builtin_trap(); // lockstep violation
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (tl && tid == 0) tl[1] = (long long)wall_clock64();
|
||||
halo_ar_acquire(acq);
|
||||
}
|
||||
|
||||
// The two halves of halo_ar_handshake, for a kernel that tells its peers how far it has come before
|
||||
// it needs to know how far they have (the eight-rank two-shot's split form). Publish: once this
|
||||
// block's stores have drained, every peer's word [b][rank] takes `val`.
|
||||
template <int WS, typename S, int NPEERS>
|
||||
__device__ __forceinline__ void halo_ar_publish(const HaloArWidePeers<S, NPEERS>& peers, int b,
|
||||
int rank, unsigned int val, int drain, int pub) {
|
||||
halo_ar_drain(drain);
|
||||
__syncthreads();
|
||||
if (threadIdx.x == 0) {
|
||||
if (drain == 2) __threadfence_system();
|
||||
if (pub) {
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "");
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p)
|
||||
halo_ar_store_sys_rlx(&peers.flags[p][(size_t)b * WS + rank], val);
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int p = 0; p < NPEERS; ++p)
|
||||
halo_ar_store_sys_rel(&peers.flags[p][(size_t)b * WS + rank], val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Await: wait until each of this block's words from every peer has reached `val`, then acquire
|
||||
// what they published before it. `tl` as halo_ar_handshake's, stamped on entry and on release.
|
||||
template <int WS, typename S, int NPEERS>
|
||||
__device__ __forceinline__ void halo_ar_await(const HaloArWidePeers<S, NPEERS>& peers,
|
||||
unsigned int* __restrict__ my_flags, int b,
|
||||
unsigned int val, int acq, long long* tl = nullptr) {
|
||||
const int tid = threadIdx.x;
|
||||
if (tl && tid == 0) tl[0] = (long long)wall_clock64();
|
||||
if (tid < NPEERS) {
|
||||
const unsigned int* f = &my_flags[(size_t)b * WS + peers.rank[tid]];
|
||||
unsigned long long z = 0;
|
||||
while ((int)(halo_ar_load_sys_rlx(f) - val) < 0) {
|
||||
__builtin_amdgcn_s_sleep(2);
|
||||
if (++z > HALO_AR_SPIN_MAX) __builtin_trap(); // lockstep violation
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (tl && tid == 0) tl[1] = (long long)wall_clock64();
|
||||
halo_ar_acquire(acq);
|
||||
}
|
||||
|
||||
// The two-shot timeline (layout in halo_ar_shards.h), one stamp of the device wall clock.
|
||||
static_assert(HALO_AR_TL_BLOCKS == HALO_AR_WIDE_MAX_BLOCKS, "halo_ar_shards.h restates the ceiling");
|
||||
__device__ __forceinline__ void halo_ar_tl_stamp(long long* tl, int i) {
|
||||
if (tl && threadIdx.x == 0) tl[i] = (long long)wall_clock64();
|
||||
}
|
||||
|
||||
// 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 halo_ar_check_extent(long p, long need, const char* prefix, const char* what) {
|
||||
hipDeviceptr_t base = nullptr;
|
||||
size_t sz = 0;
|
||||
hipError_t e = hipMemGetAddressRange(&base, &sz, (hipDeviceptr_t)(uintptr_t)p);
|
||||
if (e != hipSuccess)
|
||||
throw std::runtime_error(std::string(prefix) + ": " + what +
|
||||
" is not an allocation the runtime can size (" +
|
||||
hipGetErrorString(e) + ")");
|
||||
const long avail = (long)(((char*)base + sz) - (char*)(uintptr_t)p);
|
||||
if (avail < need)
|
||||
throw std::runtime_error(std::string(prefix) + ": " + what + " backs " +
|
||||
std::to_string(avail) + " bytes from the given pointer, needs " +
|
||||
std::to_string(need));
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
/* Derived from libr4d/r4d_args.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
/* halo_args.h -- how a libhalo entry point reads its arguments.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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 halo.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 HALO_ARGS_H
|
||||
#define HALO_ARGS_H
|
||||
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
/* ================================================================== parameter access
|
||||
*
|
||||
* Forwards to rad_abi.h's static inline helpers, the ones a third-party plugin gets, keeping
|
||||
* libhalo's spelling at its call sites. */
|
||||
static inline int halo_geti(const RadArgs* a, const char* k, long long* out) {
|
||||
return rad_args_geti(a, k, out);
|
||||
}
|
||||
|
||||
static inline long long halo_geti_or(const RadArgs* a, const char* k, long long dflt) {
|
||||
return rad_args_geti_or(a, k, dflt);
|
||||
}
|
||||
|
||||
static inline const char* halo_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` 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 halo_getf(const RadArgs* a, const char* k, double dflt) {
|
||||
if (!a || !k) return dflt;
|
||||
for (int i = 0; i < a->n_p; ++i) {
|
||||
if (!a->p[i].key || std::strcmp(a->p[i].key, k) != 0) continue;
|
||||
if (a->p[i].kind == RAD_P_F64) return a->p[i].dval;
|
||||
if (a->p[i].kind == RAD_P_INT) return (double)a->p[i].ival;
|
||||
if (a->p[i].kind == RAD_P_STR && a->p[i].sval && a->p[i].sval[0]) {
|
||||
char* end = nullptr;
|
||||
const double v = std::strtod(a->p[i].sval, &end);
|
||||
return (end && end != a->p[i].sval) ? v : dflt;
|
||||
}
|
||||
return dflt;
|
||||
}
|
||||
return dflt;
|
||||
}
|
||||
|
||||
/* An enumerated parameter: `act` is "silu" or "sigmoid", not 0 or 1, so a --debug-graph dump says
|
||||
* what runs; the mapping to libhalo's integer lives in the shim. Returns -1 for an unknown name,
|
||||
* which every caller turns into RAD_E_INVAL. `alt` is libhalo's own integer spelling of the same
|
||||
* key (`mode` on gated_had_quant_i8), consulted only when the name is absent. */
|
||||
static inline int halo_act_code(const RadArgs* a, const char* key, const char* alt, int dflt) {
|
||||
if (const char* s = halo_gets(a, key)) {
|
||||
if (!std::strcmp(s, "silu") || !std::strcmp(s, "swish")) return 0;
|
||||
if (!std::strcmp(s, "sigmoid")) return 1;
|
||||
return -1;
|
||||
}
|
||||
long long v = 0;
|
||||
if (alt && halo_geti(a, alt, &v)) return (v == 0 || v == 1) ? (int)v : -1;
|
||||
return dflt;
|
||||
}
|
||||
|
||||
/* Same, off a bare RadParam list (init() and the layout hooks); forwards to rad_plugin.h's
|
||||
* rad_param_*. */
|
||||
static inline long long halo_pgeti_or(const RadParam* p, int n_p, const char* k, long long dflt) {
|
||||
return rad_param_geti(p, n_p, k, dflt);
|
||||
}
|
||||
|
||||
static inline const char* halo_pgets(const RadParam* p, int n_p, const char* k) {
|
||||
return rad_param_gets(p, n_p, k, nullptr);
|
||||
}
|
||||
|
||||
/* ================================================================== operand access
|
||||
*
|
||||
* An absent optional operand is a null RadTensor.data (rad_abi.h). halo_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* halo_opt(const RadArgs* a, int i) { return rad_arg_in(a, i); }
|
||||
|
||||
static inline const void* halo_p(const RadTensor* t) { return t ? t->data : nullptr; }
|
||||
|
||||
/* 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* halo_wp(const RadTensor* t) { return t ? t->data : nullptr; }
|
||||
static inline long halo_addr(const RadTensor* t) { return t ? (long)(uintptr_t)t->data : 0L; }
|
||||
|
||||
static inline long long halo_dim(const RadTensor* t, int i) {
|
||||
if (!t || i < 0 || (uint32_t)i >= t->rank) return 0;
|
||||
return t->shape[i];
|
||||
}
|
||||
|
||||
static inline long long halo_stride(const RadTensor* t, int i) {
|
||||
if (!t || i < 0 || (uint32_t)i >= t->rank) return 0;
|
||||
return t->stride[i];
|
||||
}
|
||||
|
||||
static inline long long halo_numel(const RadTensor* t) { return rad_tensor_numel(t); }
|
||||
|
||||
/* [rows..., K] flattened to (M, K). Every per-row kernel in libhalo 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 halo_rows_of(const RadTensor* t, long long* M, long long* K) {
|
||||
if (!t || t->rank < 1) return RAD_E_SHAPE;
|
||||
*K = t->shape[t->rank - 1];
|
||||
*M = 1;
|
||||
for (uint32_t i = 0; i + 1 < t->rank; ++i) *M *= t->shape[i];
|
||||
return (*M >= 1 && *K >= 1) ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
/* Dense row-major over the whole tensor. libhalo'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 halo_contig(const RadTensor* t) { return rad_tensor_is_contiguous(t); }
|
||||
|
||||
/* Contiguous in every axis but the leading one, whose stride is the row pitch libhalo takes as an
|
||||
* explicit argument (`xpitch`, `a_stride`, `xrow`, ...). Returns the pitch in elements, or -1. */
|
||||
static inline long long halo_row_pitch(const RadTensor* t) {
|
||||
if (!t || t->rank == 0) return -1;
|
||||
if (t->rank == 1) return 1;
|
||||
long long acc = 1;
|
||||
for (int i = (int)t->rank - 1; i >= 1; --i) {
|
||||
if (t->shape[i] != 1 && t->stride[i] != acc) return -1;
|
||||
acc *= t->shape[i];
|
||||
}
|
||||
return t->stride[0];
|
||||
}
|
||||
|
||||
/* [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.
|
||||
*
|
||||
* 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 halo_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);
|
||||
if (nel % n) return -1;
|
||||
*rows = nel / n;
|
||||
if (t->rank == 1) return n;
|
||||
if (t->shape[t->rank - 1] == n) {
|
||||
if (t->stride[t->rank - 1] != 1) return -1;
|
||||
return t->rank >= 2 ? t->stride[t->rank - 2] : n;
|
||||
}
|
||||
if (rad_tensor_is_contiguous(t)) return n;
|
||||
long long trail = 1;
|
||||
for (int i = 1; i < (int)t->rank; ++i) trail *= t->shape[i];
|
||||
return trail == n ? halo_row_pitch(t) : -1;
|
||||
}
|
||||
|
||||
/* 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 halo_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 = halo_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 halo_aligned(const void* p, unsigned bytes) {
|
||||
return p ? (((uintptr_t)p & (uintptr_t)(bytes - 1)) == 0) : 1;
|
||||
}
|
||||
|
||||
/* ================================================================== which check refused
|
||||
*
|
||||
* 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. HALO_NO() wraps a refusal and prints its own line
|
||||
* when RAD_HALO_TRACE is set; otherwise it is the bare return plus one cached-flag load on a path
|
||||
* that is failing anyway. */
|
||||
static inline int halo_trace_on(void) {
|
||||
static int on = -1;
|
||||
if (on < 0) { const char* e = std::getenv("RAD_HALO_TRACE"); on = (e && *e && *e != '0'); }
|
||||
return on;
|
||||
}
|
||||
static inline int halo_refused(int code, const char* file, int line) {
|
||||
if (halo_trace_on()) std::fprintf(stderr, "[r4d] %s:%d refused -> %d\n", file, line, code);
|
||||
return code;
|
||||
}
|
||||
#define HALO_NO(code) halo_refused((code), __FILE__, __LINE__)
|
||||
|
||||
/* ================================================================== dtype helpers */
|
||||
/* Widest world any libhalo all-reduce serves, fixed by the 8-rank entry points' argument lists
|
||||
* (seven explicit peers). */
|
||||
enum { HALO_MAX_RANKS = 8, HALO_MAX_PEERS = 7 };
|
||||
|
||||
/* libhalo's all-reduce dtype code: 0 bf16, 1 fp16, 2 fp32. Returns -1 for anything else. */
|
||||
static inline int halo_ar_dtype_code(const char* s) {
|
||||
if (!s) return -1;
|
||||
if (!std::strcmp(s, "bf16")) return 0;
|
||||
if (!std::strcmp(s, "fp16") || !std::strcmp(s, "f16")) return 1;
|
||||
if (!std::strcmp(s, "fp32") || !std::strcmp(s, "f32")) return 2;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static inline int halo_ar_esize(int code) { return code == 2 ? 4 : 2; }
|
||||
|
||||
|
||||
/* ================================================================== weight layout constants
|
||||
*
|
||||
* libhalo's compile-time constants, restated because halo_layout.cpp is host code built without
|
||||
* ROCm and cannot include halo.h, and because the .rad container records them in the layout tag.
|
||||
* halo_gemm_args.h static_asserts the group constants against libhalo's macros.
|
||||
*/
|
||||
enum {
|
||||
HALO_W4_GROUP = 128, /* K per (scale, zero) dword; libhalo HALO_GEMM_W4_GROUP */
|
||||
HALO_W4_KPB = 64, /* K per packed block: 4 k steps, 16 bytes per lane */
|
||||
HALO_W8_GROUP = 128, /* libhalo HALO_GEMM_W8_GROUP and HALO_GEMM_W8A8_GROUP */
|
||||
HALO_W8_KPB = 32, /* K per packed block: 2 k steps, 16 bytes per lane */
|
||||
HALO_W2_GROUP = 128, /* libhalo HALO_GEMM_W2A8_GROUP */
|
||||
HALO_MXFP4_GROUP = 32, /* K per E8M0 exponent, fixed by the OCP MX format */
|
||||
/* 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 `halo_gemm_fp8a8_block()` (a function, not a macro), so
|
||||
* halo_gemm_fp8a8.hip checks it at launch. */
|
||||
HALO_FP8_BLOCK = 128,
|
||||
HALO_WAVE = 32,
|
||||
HALO_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 this, and the layout hook sizes them. */
|
||||
enum {
|
||||
HALO_DT_W4_FRAG = RAD_DT_PLUGIN_BASE + 0, /* 4-bit codes in WMMA fragment order */
|
||||
HALO_DT_W4_SZ = RAD_DT_PLUGIN_BASE + 1, /* (f16 scale, f16 -(1024+zero)) dwords */
|
||||
HALO_DT_W8_FRAG = RAD_DT_PLUGIN_BASE + 2, /* 8-bit codes in the same fragment order */
|
||||
HALO_DT_W8_S = RAD_DT_PLUGIN_BASE + 3, /* f16-only scale plane (w8a8) */
|
||||
HALO_DT_W2_FRAG = RAD_DT_PLUGIN_BASE + 4,
|
||||
HALO_DT_MXFP4_FRAG = RAD_DT_PLUGIN_BASE + 5,
|
||||
HALO_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 HALO_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 halo_layout.cpp. */
|
||||
HALO_DT_MOEW4 = RAD_DT_PLUGIN_BASE + 7,
|
||||
/* The same GEMM's 5-bit expert weight: per row, HALO_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 (halo_layout.cpp, moew5_row). A row is 5K/8 bytes. */
|
||||
HALO_DT_MOEW5 = RAD_DT_PLUGIN_BASE + 8
|
||||
};
|
||||
|
||||
/* The grouped MoE GEMM's code tables, as the four dwords w4_e4m3's byte permutes read
|
||||
* (halo_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, 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,
|
||||
14.0f, 16.0f, 18.0f, 20.0f, 22.0f, 24.0f, 26.0f, 30.0f,
|
||||
-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 };
|
||||
|
||||
/* 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
|
||||
*
|
||||
* libhalo'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". 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, halo_gemm_args.h:pick_sk.
|
||||
*/
|
||||
struct HaloGemmCfg { int wv, sk, mb, npw, nt; };
|
||||
|
||||
/* The tiled and prefill GEMMs take one opaque variant index into libhalo's own switch of compiled
|
||||
* tile arms; the row's tunable lists the arms a tuner may pick (halo_rows.cpp, kTileArms). */
|
||||
struct HaloTileCfg { 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. The crossover depends on M (see halo_gemm_mxfp4a8_tiled.hip), so 0, the
|
||||
* default, decides at issue; a fixed value is for a tuner. */
|
||||
struct HaloMxTileCfg { int tn; };
|
||||
|
||||
/* The MXFP4 decode GEMM's split-K width, K slab and weight-load hint. 0 on each is the rule in
|
||||
* halo_gemm_mxfp4a8_decode.hip (it needs M and the shape, which exist only at issue); `nt` 1 streams
|
||||
* the weight past L2/MALL, 2 loads it plainly. */
|
||||
struct HaloMxDecCfg { int ks; int bk; int nt; };
|
||||
|
||||
/* Split-KV segment count for the paged decode kernels. 0 is libhalo's split law (table in
|
||||
* halo_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 HaloSplitCfg { int splits; };
|
||||
|
||||
/* The all-reduce launch geometry, passed to libhalo 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 HaloArCfg { 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 (libhalo
|
||||
* rounds it up to a multiple of eight columns, so the scratch hook asks halo_rowtopk_bf16_chunks()
|
||||
* for the real one), PT1 the stage-1 thread count. */
|
||||
struct HaloTopkCfg { int rc; int nch; int pt1; };
|
||||
|
||||
/* 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 HaloMvCfg { int rb; };
|
||||
|
||||
|
||||
|
||||
extern "C" {
|
||||
/* -- the tuned configuration (halo_rows.cpp) --
|
||||
*
|
||||
* 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 halo_cfg_gemm (const RadArgs*, struct HaloGemmCfg*);
|
||||
void halo_cfg_tiled (const RadArgs*, struct HaloTileCfg*);
|
||||
void halo_cfg_prefill(const RadArgs*, struct HaloTileCfg*);
|
||||
void halo_cfg_mxfp4_tiled(const RadArgs*, struct HaloMxTileCfg*);
|
||||
void halo_cfg_mxfp4_decode(const RadArgs*, struct HaloMxDecCfg*);
|
||||
void halo_cfg_split (const RadArgs*, struct HaloSplitCfg*);
|
||||
void halo_cfg_ar (const RadArgs*, struct HaloArCfg*);
|
||||
/* Whether the four-rank fused junction takes its tail form from 5 rows (the row's `tail` axis). */
|
||||
int halo_cfg_ar_tail(const RadArgs*);
|
||||
/* The four-rank exact one-shot's size, in elements, from which it takes the exact two-shot instead
|
||||
* (0: never); the all-reduce rows' `ts_min` axis. */
|
||||
long halo_cfg_ar_ts_min(const RadArgs*);
|
||||
/* The prefetch's workgroup count (the row's `nb` axis). */
|
||||
int halo_cfg_prefetch_nb(const RadArgs*);
|
||||
void halo_cfg_topk (const RadArgs*, struct HaloTopkCfg*);
|
||||
void halo_cfg_mv (const RadArgs*, struct HaloMvCfg*);
|
||||
/* rmsnorm_quant_i8's decode form: 1 the row's operands in registers before the reductions, 0 the
|
||||
* pass-per-read kernel; the row's `reg` axis. */
|
||||
int halo_cfg_rmsq8_reg(const RadArgs*);
|
||||
|
||||
} /* extern "C" */
|
||||
|
||||
#endif /* HALO_ARGS_H */
|
||||
@@ -0,0 +1,178 @@
|
||||
/* Derived from libr4d/r4d_attn_args.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
/* halo_attn_args.h -- the paged-attention operand reader shared by every paged kernel geometry.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* HaloArgs 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.
|
||||
*
|
||||
* 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 HALO_ATTN_ARGS_H
|
||||
#define HALO_ATTN_ARGS_H
|
||||
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
/* Checks libhalo's compiled-in geometry against the row table, so a libhalo 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;
|
||||
halo_attn_dims(&hd, &gqa, &bs, &rows);
|
||||
return (hd == 256 && gqa == 6 && bs == 16 && rows == 64) ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
/* Operand indices, from oAttnPaged in halo_rows.cpp. */
|
||||
enum { AP_Q = 0, AP_KV, AP_BT, AP_SEQ, AP_KDS, AP_VDS, AP_CU, AP_OUT };
|
||||
|
||||
/* Fill HaloArgs from a RadArgs. Returns RAD_OK, or the negative code naming what is wrong.
|
||||
*
|
||||
* 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).
|
||||
*
|
||||
* `q_pitched`: q may be a column slice of a wider row (attn_paged_qrow), its pitch in r->q_ld. Only
|
||||
* the split-KV decode kernel reads q_ld; every other caller leaves this off.
|
||||
*/
|
||||
/* `row` is a token's bytes (elements for a 16-bit cache) in a (block, head) page: 2 * head_dim,
|
||||
* or 25 * head_dim / 16 for the fp8_v4 cache (E4M3 K, int4 V, f16 group scales). */
|
||||
static inline int fill_paged_row(const RadArgs* a, HaloArgs* r, int expect_head_dim, long long row,
|
||||
bool q_pitched = false) {
|
||||
const RadTensor* q = halo_opt(a, AP_Q);
|
||||
const RadTensor* kv = halo_opt(a, AP_KV);
|
||||
const RadTensor* bt = halo_opt(a, AP_BT);
|
||||
const RadTensor* su = halo_opt(a, AP_SEQ);
|
||||
const RadTensor* cu = halo_opt(a, AP_CU);
|
||||
const RadTensor* o = halo_opt(a, AP_OUT);
|
||||
if (!q || !kv || !bt || !su || !o) return HALO_NO(RAD_E_INVAL);
|
||||
|
||||
if (q->rank < 2 || o->rank < 2 || bt->rank != 2 || su->rank < 1) return HALO_NO(RAD_E_SHAPE);
|
||||
if (kv->rank != 4) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
/* 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];
|
||||
if (num_seqs <= 0 || total_q <= 0 || head_dim <= 0) return HALO_NO(RAD_E_SHAPE);
|
||||
if (halo_numel(q) % (total_q * head_dim)) return HALO_NO(RAD_E_SHAPE);
|
||||
const long long q_heads = halo_numel(q) / (total_q * head_dim);
|
||||
if (q_heads <= 0) return HALO_NO(RAD_E_SHAPE);
|
||||
/* 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 HALO_NO(RAD_E_SHAPE);
|
||||
if (!halo_contig(cu)) return HALO_NO(RAD_E_STRIDE);
|
||||
} else if (total_q % num_seqs) {
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* q and out are indexed as one dense [total_q, q_heads, head_dim] block; the kernel has no
|
||||
* pitch argument for either -- except q under q_pitched, whose rows may be apart: dense inside
|
||||
* a row, a pitch in whole 8-byte loads (the kernel reads q four elements at a time). */
|
||||
long long q_ld = 0;
|
||||
if (q_pitched && !halo_contig(q)) {
|
||||
q_ld = halo_row_pitch(q);
|
||||
if (q_ld < q_heads * head_dim || q_ld % 4) return HALO_NO(RAD_E_STRIDE);
|
||||
} else if (!halo_contig(q)) {
|
||||
return HALO_NO(RAD_E_STRIDE);
|
||||
}
|
||||
if (!halo_contig(o)) return HALO_NO(RAD_E_STRIDE);
|
||||
if (o->shape[0] != total_q || halo_numel(o) != total_q * q_heads * head_dim)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
if (su->shape[0] != num_seqs) return HALO_NO(RAD_E_SHAPE);
|
||||
if (!halo_contig(bt) || !halo_contig(su)) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
/* 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 HALO_NO(RAD_E_STRIDE);
|
||||
if (kv->stride[2] != row) return HALO_NO(RAD_E_STRIDE);
|
||||
if (kv->shape[3] != row) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
/* 16-byte alignment for 128-bit loads. */
|
||||
if (!halo_aligned(q->data, 16) || !halo_aligned(o->data, 16) || !halo_aligned(kv->data, 16))
|
||||
return HALO_NO(RAD_E_ALIGN);
|
||||
|
||||
const RadTensor* kds = halo_opt(a, AP_KDS);
|
||||
const RadTensor* vds = halo_opt(a, AP_VDS);
|
||||
|
||||
std::memset(r, 0, sizeof(*r));
|
||||
r->q = q->data;
|
||||
r->kv = kv->data;
|
||||
r->block_table = (const int*)bt->data;
|
||||
r->seqused_k = (const int*)su->data;
|
||||
r->out = o->data;
|
||||
r->k_descale = kds ? (const float*)kds->data : nullptr;
|
||||
r->v_descale = vds ? (const float*)vds->data : nullptr;
|
||||
r->q_descale = nullptr; /* the query is bf16 in every variant */
|
||||
r->q_ld = (long)q_ld; /* 0: dense */
|
||||
r->scratch = a->scratch;
|
||||
r->num_seqs = (int)num_seqs;
|
||||
r->cu_q = ragged ? (const int*)cu->data : nullptr;
|
||||
r->total_q = (int)total_q;
|
||||
/* 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 = halo_geti_or(a, "q_len", total_q);
|
||||
r->q_len = (int)(band > 0 && band < total_q ? band : total_q);
|
||||
}
|
||||
r->q_heads = (int)q_heads;
|
||||
r->kv_heads = (int)kv->shape[1];
|
||||
r->head_dim = (int)head_dim;
|
||||
r->block_size = (int)block_size;
|
||||
r->max_blocks = (int)bt->shape[1];
|
||||
r->kv_block_stride = (long)kv->stride[0];
|
||||
r->kv_head_stride = (long)kv->stride[1];
|
||||
r->window = (int)halo_geti_or(a, "window", 0);
|
||||
r->causal = (int)halo_geti_or(a, "causal", 1);
|
||||
r->causal_seq = nullptr;
|
||||
|
||||
/* Softmax scale; defaults to 1/sqrt(head_dim). */
|
||||
r->scale = (float)halo_getf(a, "scale", 1.0 / std::sqrt((double)head_dim));
|
||||
|
||||
/* 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 = halo_geti_or(a, "max_ctx", 0);
|
||||
if (mc <= 0) mc = (long long)r->max_blocks * block_size;
|
||||
r->max_ctx = (int)mc;
|
||||
|
||||
/* Set by the caller from the tuned `splits`; 0 means libhalo's own split law. */
|
||||
r->splits = 0;
|
||||
r->chain = halo_geti_or(a, "chain", 0) != 0 ? 1 : 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The decode rows declare a `splits` axis; its default is 0, which is that same law. */
|
||||
static inline int split_of(const RadArgs* a) {
|
||||
HaloSplitCfg c;
|
||||
halo_cfg_split(a, &c);
|
||||
return c.splits;
|
||||
}
|
||||
|
||||
|
||||
static inline int fill_paged(const RadArgs* a, HaloArgs* r, int expect_head_dim,
|
||||
bool q_pitched = false) {
|
||||
return fill_paged_row(a, r, expect_head_dim, 2LL * expect_head_dim, q_pitched);
|
||||
}
|
||||
|
||||
#endif /* HALO_ATTN_ARGS_H */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,441 @@
|
||||
/* Derived from libr4d/r4d_attn_dense_bf16.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// Halo dense attention, varlen over cu_seqlens segments, grouped-query: an encoder's, non-causal with
|
||||
// an optional two-sided window, i - j < window behind and j - i < wright ahead (wright is
|
||||
// `window_right`, or `window` for the symmetric |i - j| < window), or causal with an optional
|
||||
// window behind (a codec's sliding layers, a text encoder's prompt). bf16 in and out, f16
|
||||
// operands, f32 accumulate. Head widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair
|
||||
// is a row.
|
||||
//
|
||||
// Core from the vision kernel (halo_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 all query heads reading it, so each
|
||||
// staged K/V tile feeds GQA times as many WMMAs. Grid is (query blocks, kv heads, segments).
|
||||
//
|
||||
// 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).
|
||||
//
|
||||
// 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.
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_dt16.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
template<int HD, int GQA, int NQB, int DSPLIT, int TILE>
|
||||
__global__ __launch_bounds__(NQB * GQA * DSPLIT * 32)
|
||||
void halo_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 wright,
|
||||
int block, int cdiv, int causal, int q_ld, int k_ld, int v_ld, int o_ld,
|
||||
int krep)
|
||||
{
|
||||
typedef DT16<1> D;
|
||||
typedef D::frag frag16;
|
||||
|
||||
constexpr int NWARPS = NQB * GQA * DSPLIT;
|
||||
constexpr int NTHR = NWARPS * 32;
|
||||
constexpr int BQ = NQB * 16; // query rows per head per workgroup
|
||||
constexpr int HDP = HD / DSPLIT; // the head dims one wave owns
|
||||
constexpr int NKS = HDP / 16; // its 16-wide k-tiles
|
||||
constexpr int MT = TILE / 16;
|
||||
// Row strides padded by 8 shorts: 16-byte aligned, and off the bank period.
|
||||
constexpr int KSTR = HD + 8;
|
||||
constexpr int VSTR = TILE + 8;
|
||||
constexpr int DG = HD / 8; // eight-element dim groups in a row
|
||||
constexpr int KGRP = TILE / 8; // eight-key groups in a tile
|
||||
constexpr int KITEMS = TILE * DG; // 16-byte K fetches a tile
|
||||
constexpr int KP = (KITEMS + NTHR - 1) / NTHR;
|
||||
constexpr int NTR = KGRP * DG; // transposed V units, eight lanes each
|
||||
constexpr int LGRP = NTHR / 8;
|
||||
constexpr int VP = (NTR + LGRP - 1) / LGRP;
|
||||
constexpr float GROW = D::GROW;
|
||||
static_assert(HD % (16 * DSPLIT) == 0 && TILE % 16 == 0, "geometry");
|
||||
static_assert(DSPLIT == 1 || DSPLIT == 2, "a head is split across at most two waves");
|
||||
|
||||
__shared__ __align__(16) uint16_t sK[TILE * KSTR];
|
||||
__shared__ __align__(16) uint16_t sV[HD * VSTR];
|
||||
__shared__ __align__(16) float sX[DSPLIT > 1 ? NWARPS * 32 * 8 : 4];
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
const int c = lane & 15, h = lane >> 4;
|
||||
const int dp = warp % DSPLIT;
|
||||
const int g = (warp / DSPLIT) % GQA;
|
||||
const int qbi = warp / (DSPLIT * GQA);
|
||||
// blockIdx.y is a group of GQA query heads; krep groups read one KV head.
|
||||
const int kvh = blockIdx.y / krep, seq = blockIdx.z;
|
||||
const int hq = blockIdx.y * GQA + g;
|
||||
|
||||
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;
|
||||
|
||||
// The keys any query of this workgroup can see: none past its last query when causal.
|
||||
int kb = 0, ke = slen;
|
||||
if (window > 0) {
|
||||
kb = max(0, q0 - (window - 1));
|
||||
if (!causal) ke = min(slen, qlast + wright);
|
||||
}
|
||||
if (causal) ke = min(ke, qlast + 1);
|
||||
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;
|
||||
const bool live = qpos < slen;
|
||||
|
||||
// ---- this wave's half (or whole) of its 16 query rows, scaled once -------------------------
|
||||
frag16 qf[NKS];
|
||||
{
|
||||
const int qrow = live ? qpos : slen - 1;
|
||||
const uint16_t* qp = gq + (long)(s0 + qrow) * q_ld + (long)hq * HD + dp * HDP;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NKS; ++t) {
|
||||
const uint4 u0 = *(const uint4*)(qp + 16 * t);
|
||||
const uint4 u1 = *(const uint4*)(qp + 16 * t + 8);
|
||||
auto cv = [&](uint32_t w) {
|
||||
return D::pk(__builtin_bit_cast(float, w << 16) * mul,
|
||||
__builtin_bit_cast(float, w & 0xffff0000u) * mul);
|
||||
};
|
||||
const uint32_t w8[8] = { cv(u0.x), cv(u0.y), cv(u0.z), cv(u0.w),
|
||||
cv(u1.x), cv(u1.y), cv(u1.z), cv(u1.w) };
|
||||
qf[t] = D::mk(w8);
|
||||
}
|
||||
}
|
||||
|
||||
float m_ref = -3.0e38f, soff = 3.0e38f, l_i = 0.0f;
|
||||
v8f acc[NKS];
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NKS; ++t) acc[t] = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
|
||||
const int vj = tid & 7, lgi = tid >> 3;
|
||||
const uint16_t* kbase = gk + (long)kvh * HD;
|
||||
const uint16_t* vbase = gv + (long)kvh * HD;
|
||||
|
||||
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.
|
||||
// Workgroup-uniform, so interior tiles skip the test.
|
||||
const bool mask = (k0 + TILE > ke) ||
|
||||
(causal && k0 + TILE - 1 > q0) ||
|
||||
(window > 0 && (k0 < qlast - (window - 1) ||
|
||||
k0 + TILE - 1 > q0 + (wright - 1))) ||
|
||||
(blocks && (q_straddle || k0 / block != (k0 + TILE - 1) / block ||
|
||||
k0 / block != q0 / block));
|
||||
|
||||
uint4 kr[KP], vr[VP];
|
||||
#pragma unroll
|
||||
for (int p = 0; p < KP; ++p) {
|
||||
const int i = tid + p * NTHR;
|
||||
if (KITEMS % NTHR == 0 || i < KITEMS) {
|
||||
const int key = i / DG, gg = i % DG;
|
||||
const int kk = (k0 + key < ke) ? k0 + key : ke - 1;
|
||||
kr[p] = *(const uint4*)(kbase + (long)(s0 + kk) * k_ld + gg * 8);
|
||||
}
|
||||
}
|
||||
// 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;
|
||||
if (NTR % LGRP == 0 || u < NTR) {
|
||||
const int kg = u % KGRP, dg = u / KGRP;
|
||||
const int kk0 = k0 + kg * 8 + vj;
|
||||
const int kk = (kk0 < ke) ? kk0 : ke - 1;
|
||||
vr[r] = __builtin_bit_cast(uint4, load_tr_b128(vbase + (long)(s0 + kk) * v_ld +
|
||||
dg * 8));
|
||||
}
|
||||
}
|
||||
|
||||
lds_barrier(); // the previous tile's readers are done
|
||||
#pragma unroll
|
||||
for (int r = 0; r < VP; ++r) {
|
||||
const int u = lgi + r * LGRP;
|
||||
if (NTR % LGRP == 0 || u < NTR) {
|
||||
const int kg = u % KGRP, dg = u / KGRP;
|
||||
const uint4 w = vr[r];
|
||||
*(uint4*)&sV[(dg * 8 + vj) * VSTR + kg * 8] =
|
||||
make_uint4(D::from_bf16w(w.x), D::from_bf16w(w.y),
|
||||
D::from_bf16w(w.z), D::from_bf16w(w.w));
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int p = 0; p < KP; ++p) {
|
||||
const int i = tid + p * NTHR;
|
||||
if (KITEMS % NTHR == 0 || i < KITEMS) {
|
||||
const uint4 w = kr[p];
|
||||
*(uint4*)&sK[(i / DG) * KSTR + (i % DG) * 8] =
|
||||
make_uint4(D::from_bf16w(w.x), D::from_bf16w(w.y),
|
||||
D::from_bf16w(w.z), D::from_bf16w(w.w));
|
||||
}
|
||||
}
|
||||
lds_barrier();
|
||||
|
||||
#pragma unroll 1
|
||||
for (int mt = 0; mt < MT; ++mt) {
|
||||
v8f s = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
{
|
||||
const uint16_t* krow = &sK[(mt * 16 + c) * KSTR + dp * HDP];
|
||||
#pragma unroll
|
||||
for (int t0 = 0; t0 < NKS; t0 += 4) {
|
||||
frag16 kf[4];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j)
|
||||
if (t0 + j < NKS) {
|
||||
const uint4 u0 = *(const uint4*)(krow + 16 * (t0 + j));
|
||||
const uint4 u1 = *(const uint4*)(krow + 16 * (t0 + j) + 8);
|
||||
const uint32_t w8[8] = { u0.x, u0.y, u0.z, u0.w,
|
||||
u1.x, u1.y, u1.z, u1.w };
|
||||
kf[j] = D::mk(w8);
|
||||
}
|
||||
sched_barrier();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j)
|
||||
if (t0 + j < NKS) s = D::wmma(kf[j], qf[t0 + j], s);
|
||||
}
|
||||
}
|
||||
if (DSPLIT > 1) {
|
||||
// The other half of q.k, from the wave that owns it.
|
||||
float* mine = &sX[(warp * 32 + lane) * 8];
|
||||
const float* theirs = &sX[((warp ^ 1) * 32 + lane) * 8];
|
||||
*(float4*)mine = make_float4(s[0], s[1], s[2], s[3]);
|
||||
*(float4*)(mine + 4) = make_float4(s[4], s[5], s[6], s[7]);
|
||||
lds_barrier();
|
||||
const float4 a = *(const float4*)theirs, b = *(const float4*)(theirs + 4);
|
||||
s[0] += a.x; s[1] += a.y; s[2] += a.z; s[3] += a.w;
|
||||
s[4] += b.x; s[5] += b.y; s[6] += b.z; s[7] += b.w;
|
||||
lds_barrier();
|
||||
}
|
||||
|
||||
float sc[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) sc[e] = s[e];
|
||||
if (mask) {
|
||||
const int kq = k0 + mt * 16;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int key = kq + 2 * e + h;
|
||||
const int d = qpos - key;
|
||||
const bool ok = key < ke && (!causal || d >= 0) &&
|
||||
(window <= 0 || (d < window && -d < wright)) &&
|
||||
(!blocks || key / block == qpos / block);
|
||||
sc[e] = ok ? sc[e] : -INFINITY;
|
||||
}
|
||||
}
|
||||
|
||||
// Softmax against a reference max, rescaled only when the row max outgrows the f16
|
||||
// P range (halo_dt16.h).
|
||||
float smax = sc[0];
|
||||
#pragma unroll
|
||||
for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]);
|
||||
if (wave_any(smax > m_ref + GROW)) {
|
||||
const float rmax = fmaxf(smax, swap16(smax));
|
||||
const float mnew = fmaxf(fmaxf(m_ref, rmax), -3.0e38f);
|
||||
const float alpha = ex2(m_ref - mnew);
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NKS; ++t)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) acc[t][e] *= alpha;
|
||||
l_i *= alpha;
|
||||
m_ref = mnew;
|
||||
soff = -mnew;
|
||||
}
|
||||
|
||||
uint32_t pw[4];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e += 2)
|
||||
pw[e >> 1] = D::pk(ex2(sc[e] + soff), ex2(sc[e + 1] + soff));
|
||||
// Row sum from the packed P, so the denominator matches the values P.V used.
|
||||
const v2hf_dt one = {(__fp16)1.0f, (__fp16)1.0f};
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 4; ++e)
|
||||
l_i = __builtin_amdgcn_fdot2(__builtin_bit_cast(v2hf_dt, pw[e]), one, l_i, false);
|
||||
uint32_t pw16[8];
|
||||
p16w<D>(pw, pw16);
|
||||
const frag16 p16 = D::mk(pw16);
|
||||
|
||||
{
|
||||
const uint16_t* vrow = &sV[(dp * HDP + c) * VSTR + mt * 16];
|
||||
#pragma unroll
|
||||
for (int t0 = 0; t0 < NKS; t0 += 4) {
|
||||
frag16 vf[4];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j)
|
||||
if (t0 + j < NKS) {
|
||||
const uint4 u0 = *(const uint4*)(vrow + (t0 + j) * 16 * VSTR);
|
||||
const uint4 u1 = *(const uint4*)(vrow + (t0 + j) * 16 * VSTR + 8);
|
||||
const uint32_t w8[8] = { u0.x, u0.y, u0.z, u0.w,
|
||||
u1.x, u1.y, u1.z, u1.w };
|
||||
vf[j] = D::mk(w8);
|
||||
}
|
||||
sched_barrier();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j)
|
||||
if (t0 + j < NKS) acc[t0 + j] = D::wmma(vf[j], p16, acc[t0 + j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!live) return;
|
||||
const float ls = l_i + swap16(l_i);
|
||||
const float inv = (ls > 0.0f) ? (1.0f / ls) : 0.0f;
|
||||
uint16_t* op = go + (long)(s0 + qpos) * o_ld + (long)hq * HD + dp * HDP;
|
||||
// gfx1151: element e of the accumulator is head dim 2*e + (lane>>4), one value a lane, so
|
||||
// the store is a scatter of eight 16-bit values rather than one 16-byte write.
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NKS; ++t)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e)
|
||||
((uint16_t*)op)[t * 16 + 2 * e + h] = f32_to_bf16(acc[t][e] * inv);
|
||||
}
|
||||
|
||||
// ---- launch ----------------------------------------------------------------------------------
|
||||
// One instantiation per (head_dim, gqa), at a workgroup shape picked for it:
|
||||
// h64 gqa1: 8 query blocks of 16, K/V tiles of 64 keys (the vision towers' heads)
|
||||
// h256 gqa1: 8 query blocks of 16, tiles of 32 (LDS: 37 KiB)
|
||||
// h256 gqa2, 4, 8: 8, 4, 2 query blocks x the heads, tiles of 32 (LDS: 37 KiB)
|
||||
// h512 gqa2, 4, 8: 4, 2, 1 query blocks x the heads x 2 head halves, tiles of 16 (LDS: 57 KiB)
|
||||
// The LDS holds one K/V tile, so the query heads a workgroup carries change its waves, not it.
|
||||
// A wider group (16 query heads a KV head and up, any multiple of 8) runs as krep workgroups of
|
||||
// eight heads each over the same KV head: 16 heads in one would need 32 waves and, at h512, more
|
||||
// than 64 KiB of LDS.
|
||||
template<int HD, int GQA, int NQB, int DSPLIT, int TILE>
|
||||
static int halo_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 wright, int block, int cdiv,
|
||||
int causal, int q_ld, int k_ld, int v_ld, int o_ld, hipStream_t s,
|
||||
int krep = 1)
|
||||
{
|
||||
constexpr int BQ = NQB * 16;
|
||||
dim3 grid((max_seqlen + BQ - 1) / BQ, n_head_kv * krep, num_seqs);
|
||||
hipLaunchKernelGGL((halo_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, wright,
|
||||
block, cdiv, causal, q_ld, k_ld, v_ld, o_ld, krep);
|
||||
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, in rows, and sizes the grid. window 0 is the whole segment (with
|
||||
// causal, every earlier key), wright 0 the window's own right side, block 0 no blocks; cu_seqlens
|
||||
// counts in units cdiv rows apart.
|
||||
extern "C" int halo_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 block, int cdiv, int q_ld, int k_ld, int v_ld,
|
||||
int o_ld, void* stream, int wright = 0, int causal = 0)
|
||||
{
|
||||
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 || wright < 0 || block < 0 || cdiv <= 0 ||
|
||||
(wright > 0 && (window == 0 || causal)))
|
||||
return -4;
|
||||
if (num_seqs <= 0 || max_seqlen <= 0) return 0;
|
||||
if (wright == 0) wright = window;
|
||||
int gqa = n_head / n_head_kv, krep = 1;
|
||||
if (gqa > 8 && gqa % 8 == 0) krep = gqa / 8, gqa = 8;
|
||||
hipStream_t s = (hipStream_t)stream;
|
||||
if (head_dim == 64 && gqa == 1)
|
||||
return halo_attn_dense_launch<64, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen,
|
||||
n_head_kv, scale, window, wright, block,
|
||||
cdiv, causal, q_ld, k_ld, v_ld, o_ld, s);
|
||||
#define HALO_DENSE(HD, G, NQB, DS, T) \
|
||||
return halo_attn_dense_launch<HD, G, NQB, DS, T>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen, \
|
||||
n_head_kv, scale, window, wright, block, \
|
||||
cdiv, causal, q_ld, k_ld, v_ld, o_ld, s, krep)
|
||||
if (head_dim == 256) {
|
||||
switch (gqa) {
|
||||
case 1: HALO_DENSE(256, 1, 8, 1, 32);
|
||||
case 2: HALO_DENSE(256, 2, 8, 1, 32);
|
||||
case 4: HALO_DENSE(256, 4, 4, 1, 32);
|
||||
case 8: HALO_DENSE(256, 8, 2, 1, 32);
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
if (head_dim == 512) {
|
||||
switch (gqa) {
|
||||
case 2: HALO_DENSE(512, 2, 4, 2, 16);
|
||||
case 4: HALO_DENSE(512, 4, 2, 2, 16);
|
||||
case 8: HALO_DENSE(512, 8, 1, 2, 16);
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
#undef HALO_DENSE
|
||||
return -1;
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
|
||||
enum { DN_Q = 0, DN_K, DN_V, DN_CU, DN_OUT };
|
||||
|
||||
extern "C" int halo_rad_attn_dense(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* q = halo_opt(a, DN_Q);
|
||||
const RadTensor* k = halo_opt(a, DN_K);
|
||||
const RadTensor* v = halo_opt(a, DN_V);
|
||||
const RadTensor* cu = halo_opt(a, DN_CU);
|
||||
const RadTensor* o = halo_opt(a, DN_OUT);
|
||||
if (!q || !k || !v || !cu || !o) return HALO_NO(RAD_E_INVAL);
|
||||
if (!halo_contig(cu)) return HALO_NO(RAD_E_STRIDE);
|
||||
const long long causal = halo_geti_or(a, "causal", 0);
|
||||
if (causal < 0 || causal > 1) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
const long long head_dim = halo_geti_or(a, "head_dim", 0);
|
||||
const long long gqa = halo_geti_or(a, "gqa", 1);
|
||||
if (head_dim <= 0 || gqa <= 0) return HALO_NO(RAD_E_SHAPE);
|
||||
/* [tokens, heads * head_dim] (or [tokens, heads, head_dim]) at the operand's own row pitch. */
|
||||
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 (!halo_head_rows(q, head_dim, &total, &nh, &q_ld) ||
|
||||
!halo_head_rows(k, head_dim, &tk, &hk, &k_ld) ||
|
||||
!halo_head_rows(v, head_dim, &tv, &hv, &v_ld) ||
|
||||
!halo_head_rows(o, head_dim, &to, &ho, &o_ld))
|
||||
return HALO_NO(RAD_E_STRIDE);
|
||||
if (hk != hv || ho != nh || hk * gqa != nh) return HALO_NO(RAD_E_SHAPE);
|
||||
if (tk < total || tv < total || to < total) return HALO_NO(RAD_E_SHAPE);
|
||||
if (cu->rank != 1 || cu->shape[0] < 2) return HALO_NO(RAD_E_SHAPE);
|
||||
const int num_seqs = (int)(cu->shape[0] - 1);
|
||||
|
||||
/* max_seqlen is a grid-sizing bound (the kernel reads device-side cu_seqlens); defaults to
|
||||
* the total token count. */
|
||||
long long msl = halo_geti_or(a, "max_seqlen", 0);
|
||||
if (msl <= 0 || msl > total) msl = total;
|
||||
const float scale = (float)halo_getf(a, "scale", 1.0 / std::sqrt((double)head_dim));
|
||||
const long long window = halo_geti_or(a, "window", 0);
|
||||
const long long wright = halo_geti_or(a, "window_right", 0);
|
||||
const long long block = halo_geti_or(a, "block", 0);
|
||||
const long long cdiv = halo_geti_or(a, "cu_div", 1);
|
||||
/* A right side needs a non-causal window to be the right side of (libref refuses it alike). */
|
||||
if (wright < 0 || (wright > 0 && (window == 0 || causal))) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
const int e = halo_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)block, (int)cdiv, (int)q_ld, (int)k_ld,
|
||||
(int)v_ld, (int)o_ld, s, (int)wright, (int)causal);
|
||||
if (e == 0) return RAD_OK;
|
||||
return HALO_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,587 @@
|
||||
/* Derived from libr4d/r4d_attn_paged_gqa8.hip by the libhalo rename transform (2026-10-26), then
|
||||
* ported to gfx1151; see libhalo/README.md. */
|
||||
// Halo paged attention dispatch at eight queries per KV head, head_dim 256 and 128.
|
||||
//
|
||||
// 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
|
||||
// MiniCPM5-2B 16 query heads over 2 KV heads, head_dim 128
|
||||
//
|
||||
// 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).
|
||||
//
|
||||
// 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.
|
||||
// All other option bits are as defined in halo_attn_prefill_h256_gqa6.hip.
|
||||
//
|
||||
// gfx1151: both bands. The split-KV decode kernel is a body of its own
|
||||
// (halo_attn_decode_h256_gqa6.hip); this unit includes it, instantiates it at this ratio and defines
|
||||
// the ratio's decode entry points, plain and gated.
|
||||
//
|
||||
// No halo_attn_dims here: that entry point 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 "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_attn_args.h"
|
||||
#include "halo_common.h"
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
using std::max;
|
||||
#include "halo_attn_prefill_h256_gqa6.hip"
|
||||
// The split-KV decode body. Both bands of a geometry belong to its unit, and this one is the unit
|
||||
// for every ratio that does not have a file of its own (this one, and the wrappers that define
|
||||
// HALO_ATTN_GQA before including it).
|
||||
#include "halo_attn_decode_h256_gqa6.hip"
|
||||
|
||||
#define CHK8() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0)
|
||||
|
||||
/* Queries per KV head, and the symbol names built from it.
|
||||
*
|
||||
* Another ratio reuses this file: it defines these macros and includes this one (e.g.
|
||||
* halo_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 and prefill block 384/gqa query positions.
|
||||
* Both must divide, and both are stated in the row so the selector bands on them. */
|
||||
#ifndef HALO_ATTN_GQA
|
||||
#define HALO_ATTN_GQA 8
|
||||
#define HALO_ATTN_H128 1 /* this ratio also serves head_dim 128 -- MiniCPM5-2B is 16 over 2 */
|
||||
#endif
|
||||
/* Head_dim 64 prefill leg, off unless the including unit enables it (LFM2: 32 query heads over 8,
|
||||
* halo_attn_paged_h256_gqa4.hip). Uses the h128 option set (no O_KWIDE). */
|
||||
#ifndef HALO_ATTN_H64
|
||||
#define HALO_ATTN_H64 0
|
||||
#endif
|
||||
/* Head_dim 256 leg, on unless the including unit serves only head_dim 128. */
|
||||
#ifndef HALO_ATTN_H256
|
||||
#define HALO_ATTN_H256 1
|
||||
#endif
|
||||
/* The fp8_v4 and k6_v4 caches at head_dim 256, off unless the including unit serves a model whose
|
||||
* plugin offers them: Qwen3.8-Flash-Next's QSA layers (gqa12, and gqa6 at four ranks). */
|
||||
#ifndef HALO_ATTN_V4
|
||||
#define HALO_ATTN_V4 0
|
||||
#endif
|
||||
/* The fused attn_paged_gate_quant rows on the decode leg (gate, codes and scales as the merge's
|
||||
* epilogue), off unless the including unit's model declares them beside its unfused pair: the QSA
|
||||
* layers above, at both ratios. */
|
||||
#ifndef HALO_ATTN_GQ
|
||||
#define HALO_ATTN_GQ 0
|
||||
#endif
|
||||
/* The union form of the gated decode rows at prefill (g8_union_launch below), off unless the
|
||||
* including unit serves the QSA sparse attention (gqa12 over 4-token pages). */
|
||||
#ifndef G8_UNION
|
||||
#define G8_UNION 0
|
||||
#endif
|
||||
#define GQ_JOIN_(a, b, c) a##b##c
|
||||
#define GQ_JOIN(a, b, c) GQ_JOIN_(a, b, c)
|
||||
#define GQ_SYM(pre, suf) GQ_JOIN(pre, HALO_ATTN_GQA, suf)
|
||||
|
||||
#define G8_GQA HALO_ATTN_GQA
|
||||
/* 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
|
||||
|
||||
#define G8_P_NWARPS 24
|
||||
#define G8_P_TILE 48
|
||||
// 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, prefetch 4
|
||||
#define G8_P_OPT_64 G8_P_OPT_128
|
||||
|
||||
// ---- prefill -----------------------------------------------------------------------------------
|
||||
template <int HEAD_DIM, int OPT, int KVP>
|
||||
static int g8_prefill_launch(const HaloArgs* a, hipStream_t s) {
|
||||
if (a->head_dim != HEAD_DIM || a->block_size != G8_BLOCK_SIZE) return -1;
|
||||
if (a->q_heads / a->kv_heads != G8_GQA) return -2;
|
||||
// Split-KV when the caller set a->splits > 1 with scratch (halo_prefill_split_setup).
|
||||
return halo_prefill_launch<G8_P_NWARPS, G8_P_TILE, HEAD_DIM, G8_GQA, G8_BLOCK_SIZE, KVP, OPT>(
|
||||
a, s);
|
||||
}
|
||||
#define G8_SPLIT(HD, a, r) halo_prefill_split_setup<G8_P_NWARPS, G8_P_TILE, HD, G8_GQA>((a), (r))
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
|
||||
/* The split-KV partials of the prefill rows (halo_prefill_scratch in the body). */
|
||||
#if HALO_ATTN_H256
|
||||
extern "C" int64_t GQ_SYM(halo_rad_attn_prefill_h256_gqa, _scratch)(const RadArgs* a) {
|
||||
return halo_prefill_scratch<G8_P_NWARPS, G8_P_TILE, 256, G8_GQA>(a);
|
||||
}
|
||||
#endif
|
||||
#if HALO_ATTN_H128
|
||||
extern "C" int64_t GQ_SYM(halo_rad_attn_prefill_h128_gqa, _scratch)(const RadArgs* a) {
|
||||
return halo_prefill_scratch<G8_P_NWARPS, G8_P_TILE, 128, G8_GQA>(a);
|
||||
}
|
||||
#endif
|
||||
#if HALO_ATTN_H64
|
||||
extern "C" int64_t GQ_SYM(halo_rad_attn_prefill_h64_gqa, _scratch)(const RadArgs* a) {
|
||||
return halo_prefill_scratch<G8_P_NWARPS, G8_P_TILE, 64, G8_GQA>(a);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if HALO_ATTN_H256
|
||||
extern "C" int GQ_SYM(halo_rad_attn_prefill_h256_gqa, _fp8)(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
const int rc = fill_paged(a, &r, 256);
|
||||
if (rc != RAD_OK) return rc;
|
||||
G8_SPLIT(256, a, &r);
|
||||
/* 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(halo_rad_attn_prefill_h256_gqa, _bf16)(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
const int rc = fill_paged(a, &r, 256);
|
||||
if (rc != RAD_OK) return rc;
|
||||
G8_SPLIT(256, a, &r);
|
||||
return g8_prefill_launch<256, G8_P_OPT_256, 1>(&r, (hipStream_t)s);
|
||||
}
|
||||
#endif
|
||||
#if HALO_ATTN_H128
|
||||
extern "C" int GQ_SYM(halo_rad_attn_prefill_h128_gqa, _fp8)(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
const int rc = fill_paged(a, &r, 128);
|
||||
if (rc != RAD_OK) return rc;
|
||||
G8_SPLIT(128, a, &r);
|
||||
return g8_prefill_launch<128, G8_P_OPT_128, 0>(&r, (hipStream_t)s);
|
||||
}
|
||||
extern "C" int GQ_SYM(halo_rad_attn_prefill_h128_gqa, _bf16)(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
const int rc = fill_paged(a, &r, 128);
|
||||
if (rc != RAD_OK) return rc;
|
||||
G8_SPLIT(128, a, &r);
|
||||
return g8_prefill_launch<128, G8_P_OPT_128, 1>(&r, (hipStream_t)s);
|
||||
}
|
||||
#endif
|
||||
#if HALO_ATTN_H64
|
||||
extern "C" int GQ_SYM(halo_rad_attn_prefill_h64_gqa, _fp8)(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
const int rc = fill_paged(a, &r, 64);
|
||||
if (rc != RAD_OK) return rc;
|
||||
G8_SPLIT(64, a, &r);
|
||||
return g8_prefill_launch<64, G8_P_OPT_64, 0>(&r, (hipStream_t)s);
|
||||
}
|
||||
extern "C" int GQ_SYM(halo_rad_attn_prefill_h64_gqa, _bf16)(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
const int rc = fill_paged(a, &r, 64);
|
||||
if (rc != RAD_OK) return rc;
|
||||
G8_SPLIT(64, a, &r);
|
||||
return g8_prefill_launch<64, G8_P_OPT_64, 1>(&r, (hipStream_t)s);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if HALO_ATTN_H256 && HALO_ATTN_V4
|
||||
/* ---- the fp8_v4 cache (a token's row 25 * 256 / 16 = 400 bytes: E4M3 K, int4 V, f16 scales) and
|
||||
* the k6_v4 cache (352 bytes: int6 K, int4 V), prefill. */
|
||||
#define G8_V4_ENTRIES(TAG, ROWB, XOPT) \
|
||||
extern "C" int GQ_SYM(halo_rad_attn_prefill_h256_gqa, _##TAG)(const RadArgs* a, RadStream s) { \
|
||||
HaloArgs r; \
|
||||
const int rc = fill_paged_row(a, &r, 256, ROWB); \
|
||||
if (rc != RAD_OK) return rc; \
|
||||
G8_SPLIT(256, a, &r); \
|
||||
return g8_prefill_launch<256, G8_P_OPT_256 | (XOPT), 0>(&r, (hipStream_t)s); \
|
||||
} \
|
||||
extern "C" int64_t GQ_SYM(halo_rad_attn_prefill_h256_gqa, _##TAG##_scratch)(const RadArgs* a) {\
|
||||
return halo_prefill_scratch<G8_P_NWARPS, G8_P_TILE, 256, G8_GQA>(a, ROWB); \
|
||||
}
|
||||
G8_V4_ENTRIES(fp8v4, 400, O_V4)
|
||||
G8_V4_ENTRIES(k6v4, 352, O_V4 | O_K6)
|
||||
#undef G8_V4_ENTRIES
|
||||
#endif
|
||||
|
||||
// ============================================================== the split-KV decode leg
|
||||
//
|
||||
// The h256/gqa6 split law and its merge constants (halo_attn_decode_h256_gqa6.hip). Gqa changes two
|
||||
// things here: the decode verify width (64 / gqa query rows a workgroup) and the ratio the launch
|
||||
// gates on. The option set is the h256 decode set for every geometry: libr4d's h128 decode set adds
|
||||
// O_KRAW, a gfx12 K round the port does not instantiate, and its GPREV turns itself off at head_dim
|
||||
// 128 anyway (a V prefetch there is past the three registers it fits in).
|
||||
#define G8_D_OPT HALO_D_OPT
|
||||
#define G8_MAX_DECODE_ROWS 64 // q_len * gqa a single decode workgroup can hold
|
||||
|
||||
template <int HEAD_DIM, int KVP, int XOPT = 0>
|
||||
/* The attention kernel and the merge; `gq` non-null adds the output gate and the quantiser to the
|
||||
* merge's epilogue (attn_paged_gate_quant). XOPT adds the cache-layout bits (O_V4, O_K6). */
|
||||
static int g8_decode_launch(const HaloArgs* a, RadStream stream,
|
||||
const HaloGateQuant* gq = nullptr) {
|
||||
return decode_launch<HEAD_DIM, G8_GQA, G8_BLOCK_SIZE, G8_D_OPT | XOPT, KVP, 0>(
|
||||
a, (hipStream_t)stream, gq);
|
||||
}
|
||||
|
||||
/* Split-KV partial buffer size at declare time, from the band's upper bound (decode_scratch in the
|
||||
* body): parameters first, tensors the fallback. */
|
||||
#if G8_UNION
|
||||
static int64_t g8_union_scratch(const RadArgs* a);
|
||||
#endif
|
||||
static int64_t g8_decode_scratch(const RadArgs* a, int head_dim, long long row = 0) {
|
||||
#if G8_UNION
|
||||
{
|
||||
const int64_t base = decode_scratch<256, G8_GQA, G8_BLOCK_SIZE, G8_D_OPT>(a, row);
|
||||
if (base < 0 || head_dim != 256) return base;
|
||||
return std::max<int64_t>(base, g8_union_scratch(a));
|
||||
}
|
||||
#endif
|
||||
#if HALO_ATTN_H256 && HALO_ATTN_H128
|
||||
return head_dim == 256 ? decode_scratch<256, G8_GQA, G8_BLOCK_SIZE, G8_D_OPT>(a, row)
|
||||
: decode_scratch<128, G8_GQA, G8_BLOCK_SIZE, G8_D_OPT>(a, row);
|
||||
#elif HALO_ATTN_H256
|
||||
(void)head_dim;
|
||||
return decode_scratch<256, G8_GQA, G8_BLOCK_SIZE, G8_D_OPT>(a, row);
|
||||
#else
|
||||
(void)head_dim;
|
||||
return decode_scratch<128, G8_GQA, G8_BLOCK_SIZE, G8_D_OPT>(a, row);
|
||||
#endif
|
||||
}
|
||||
|
||||
static int g8_decode_common(const RadArgs* a, HaloArgs* r, int head_dim, long long row = 0) {
|
||||
#if HALO_ATTN_H256 && HALO_ATTN_H128
|
||||
return head_dim == 256 ? decode_common<256, G8_GQA, G8_BLOCK_SIZE, G8_D_OPT>(a, r, row)
|
||||
: decode_common<128, G8_GQA, G8_BLOCK_SIZE, G8_D_OPT>(a, r, row);
|
||||
#elif HALO_ATTN_H256
|
||||
(void)head_dim;
|
||||
return decode_common<256, G8_GQA, G8_BLOCK_SIZE, G8_D_OPT>(a, r, row);
|
||||
#else
|
||||
(void)head_dim;
|
||||
return decode_common<128, G8_GQA, G8_BLOCK_SIZE, G8_D_OPT>(a, r, row);
|
||||
#endif
|
||||
}
|
||||
|
||||
#if HALO_ATTN_GQ && HALO_ATTN_H256
|
||||
/* ---- attn_paged_gate_quant: attn_paged's eight operands, then the gate, the codes and their
|
||||
* per-128-column scales. A gated row's merge row is one (token, head) pair, so the gate is a
|
||||
* [T, n_head, head_dim] view of the [q|gate] projection whose (token, head) rows are one pitch
|
||||
* apart when the view narrowed the last axis alone (gate_quant_fp8's test, repeated here because
|
||||
* this unit cannot link that unit). */
|
||||
enum { AP_GQ_G = AP_OUT + 1, AP_GQ_Q, AP_GQ_S };
|
||||
|
||||
static long long g8_gq_row_pitch(const RadTensor* t, long long width) {
|
||||
if (!t || t->rank < 1) return -1;
|
||||
if (t->shape[t->rank - 1] != width) return halo_contig(t) ? width : -1;
|
||||
if (t->stride[t->rank - 1] != 1) return -1;
|
||||
if (t->rank == 1) return width;
|
||||
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 gate/codes/scales operands, validated as gate_quant_fp8 validates them: a bf16 gate, E4M3 (or
|
||||
* int8, for an int8 out projection) codes, f32 scales, act sigmoid, a scale group of 128. */
|
||||
static int g8_gate_quant_args(const RadArgs* a, const HaloArgs& r, HaloGateQuant* gq) {
|
||||
const RadTensor* g = halo_opt(a, AP_GQ_G);
|
||||
const RadTensor* q = halo_opt(a, AP_GQ_Q);
|
||||
const RadTensor* s = halo_opt(a, AP_GQ_S);
|
||||
if (!g || !q || !s) return HALO_NO(RAD_E_INVAL);
|
||||
if (g->dtype != RAD_BF16 || (q->dtype != RAD_F8E4M3 && q->dtype != RAD_I8) ||
|
||||
s->dtype != RAD_F32)
|
||||
return HALO_NO(RAD_E_DTYPE);
|
||||
const char* act = halo_gets(a, "act");
|
||||
if (!act || std::strcmp(act, "sigmoid")) return HALO_NO(RAD_E_UNSUPPORTED);
|
||||
if (halo_geti_or(a, "group", kHaloGqGroup) != kHaloGqGroup) return HALO_NO(RAD_E_SHAPE);
|
||||
const long long n = r.head_dim;
|
||||
if (n % kHaloGqGroup) return HALO_NO(RAD_E_SHAPE);
|
||||
const long long nkb = n / kHaloGqGroup;
|
||||
const long long rows = (long long)halo_q_total(r) * r.q_heads;
|
||||
if (halo_numel(g) < rows * n || halo_numel(q) < rows * n || halo_numel(s) < rows * nkb)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
const long long gp = g8_gq_row_pitch(g, n), qp = g8_gq_row_pitch(q, n),
|
||||
sp = g8_gq_row_pitch(s, nkb);
|
||||
if (gp < 0 || qp < 0 || sp < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
/* The vector merge reads a lane's gate in one 16-byte access and stores its codes in one 8-byte
|
||||
* access. */
|
||||
if ((halo_addr(g) & 15) || (gp % 8) || (halo_addr(q) & 7) || (qp % 8))
|
||||
return HALO_NO(RAD_E_STRIDE);
|
||||
gq->g = (const uint16_t*)halo_addr(g);
|
||||
gq->q = (uint8_t*)halo_addr(q);
|
||||
gq->s = (float*)halo_addr(s);
|
||||
gq->g_ld = (unsigned)gp;
|
||||
gq->q_ld = (unsigned)qp;
|
||||
gq->s_ld = (unsigned)sp;
|
||||
gq->i8 = q->dtype == RAD_I8 ? 1 : 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
#endif /* HALO_ATTN_GQ && HALO_ATTN_H256 */
|
||||
|
||||
|
||||
#if G8_UNION && HALO_ATTN_GQ && HALO_ATTN_H256
|
||||
/* ---- the QSA prefill form: query rows in groups, each group's pages read once -------------------
|
||||
*
|
||||
* At prefill the sparse attention is issued one row per query (docs/QSA.md), each row with its own
|
||||
* 513-entry selection, and the decode kernel serves a row alone: 12 live rows of a 32-row tile pair
|
||||
* and every selected page widened for them, so a 2048-row launch moved ~4.3 GB of K/V through the
|
||||
* caches for 103 GFLOP. Consecutive queries select mostly the same pages (on Flash-Next prose, five
|
||||
* consecutive rows' selections have ~1.5x one row's pages in their union), so here five rows are
|
||||
* one workgroup's "sequence" (60 of the kernel's 64 rows) over the union of their pages:
|
||||
*
|
||||
* 1. g8_union_plan_kernel, a block a group: the union in a fixed order (the rows in turn, each
|
||||
* row's pages not yet in it in that row's table order; an LDS hash maps page -> union index)
|
||||
* and a word a union page, four bits a row: the tokens of the page the row attends to (4, the
|
||||
* row's own count of its last, partial page, or 0 when it did not select the page).
|
||||
* 2. halo_attn_decode_kernel under O_UNION over (group, kv head), one split: the mask replaces
|
||||
* the causal limit. 13.6 -> 6.5 ms a 2048-row call on an 8.9K prompt.
|
||||
* 3. the gated merge, per row, unchanged (each row's one partial).
|
||||
*
|
||||
* A row's softmax runs over its selected keys in union order rather than table order, so the bits
|
||||
* differ from the per-row form within rounding; the set, the scale and the epilogue are the same.
|
||||
* The page ids need not be ordered (a pool's free list need not be): the union is by lookup. */
|
||||
constexpr int kG8UnionR = 5; /* rows a group: 60 of the 64-row workgroup at gqa 12 */
|
||||
constexpr int kG8UnionMinRows = 64; /* below this the per-row form (decode) */
|
||||
constexpr int kG8UnionMaxSp = 520; /* the selection's pitch it plans for (topk + 1 = 513) */
|
||||
constexpr int kG8UnionHash = 4096; /* LDS hash slots: >= 1.5x the largest union */
|
||||
/* Keys a staging round: 32 ran ~1% faster end to end than 16 (8.9K prefill, 1590 against 1580
|
||||
* tok/s); in isolation the two are within 2%. */
|
||||
#ifndef G8_UNION_TILE
|
||||
#define G8_UNION_TILE 32
|
||||
#endif
|
||||
constexpr int kG8UnionTile = G8_UNION_TILE;
|
||||
constexpr int kG8UnionUp = (kG8UnionR * kG8UnionMaxSp + 7) & ~7;
|
||||
|
||||
struct G8UnionPlan {
|
||||
int* u; uint32_t* m; int* gctx; int* cu; int* fs;
|
||||
long long bytes;
|
||||
};
|
||||
static G8UnionPlan g8_union_plan(void* base, long long rows, int up) {
|
||||
const long long G = (rows + kG8UnionR - 1) / kG8UnionR;
|
||||
G8UnionPlan p;
|
||||
int* w = (int*)base;
|
||||
p.u = w; w += G * up;
|
||||
p.m = (uint32_t*)w; w += G * up;
|
||||
p.gctx = w; w += G;
|
||||
p.cu = w; w += G + 1;
|
||||
p.fs = w; w += rows;
|
||||
p.bytes = (long long)((char*)w - (char*)base);
|
||||
return p;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ uint32_t g8_union_hash(int pg) {
|
||||
return ((uint32_t)pg * 2654435761u) >> (32 - 12);
|
||||
}
|
||||
static_assert(kG8UnionHash == 4096, "g8_union_hash keeps 12 bits");
|
||||
|
||||
__global__ __launch_bounds__(256) void g8_union_plan_kernel(
|
||||
const int* __restrict__ sel, int sp, const int* __restrict__ su, int rows, int up,
|
||||
int* __restrict__ U, uint32_t* __restrict__ M, int* __restrict__ gctx, int* __restrict__ cu,
|
||||
int* __restrict__ fs, int fsv) {
|
||||
__shared__ int hk[kG8UnionHash], hv[kG8UnionHash];
|
||||
__shared__ uint32_t sm[kG8UnionUp];
|
||||
__shared__ int wcnt[8];
|
||||
__shared__ int s_base;
|
||||
const int g = blockIdx.x, tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
for (int i = tid; i < kG8UnionHash; i += 256) hk[i] = -1;
|
||||
for (int i = tid; i < up; i += 256) sm[i] = 0u;
|
||||
if (tid == 0) s_base = 0;
|
||||
__syncthreads();
|
||||
auto lookup = [&](int pg) {
|
||||
uint32_t h = g8_union_hash(pg);
|
||||
for (;;) {
|
||||
const int k = hk[h];
|
||||
if (k == pg) return hv[h];
|
||||
if (k == -1) return -1;
|
||||
h = (h + 1) & (kG8UnionHash - 1);
|
||||
}
|
||||
};
|
||||
/* The union, row by row: a chunk's new pages are numbered by a block scan in table order. */
|
||||
for (int r = 0; r < kG8UnionR; ++r) {
|
||||
const int row = g * kG8UnionR + r;
|
||||
if (row >= rows) break;
|
||||
const int c = su[row];
|
||||
const int n = c > 0 ? min((c + 3) / 4, sp) : 0;
|
||||
for (int j0 = 0; j0 < n; j0 += 256) {
|
||||
const int j = j0 + tid;
|
||||
const int pg = j < n ? sel[(size_t)row * sp + j] : -1;
|
||||
const bool isnew = pg >= 0 && lookup(pg) < 0;
|
||||
const unsigned bal = (unsigned)__ballot(isnew);
|
||||
if (lane == 0) wcnt[wave] = __popc(bal);
|
||||
__syncthreads();
|
||||
int pre = 0, tot = 0;
|
||||
#pragma unroll
|
||||
for (int w = 0; w < 8; ++w) { pre += w < wave ? wcnt[w] : 0; tot += wcnt[w]; }
|
||||
if (isnew) {
|
||||
const int idx = s_base + pre + __popc(bal & ((1u << lane) - 1u));
|
||||
U[(size_t)g * up + idx] = pg;
|
||||
uint32_t h = g8_union_hash(pg);
|
||||
for (;;) {
|
||||
const int prev = atomicCAS(&hk[h], -1, pg);
|
||||
if (prev == -1) { hv[h] = idx; break; }
|
||||
h = (h + 1) & (kG8UnionHash - 1);
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (tid == 0) s_base += tot;
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
const int cnt = s_base;
|
||||
/* Each row's tokens of each of its pages, four bits a row. */
|
||||
for (int r = 0; r < kG8UnionR; ++r) {
|
||||
const int row = g * kG8UnionR + r;
|
||||
if (row >= rows) break;
|
||||
const int c = su[row];
|
||||
const int n = c > 0 ? min((c + 3) / 4, sp) : 0;
|
||||
for (int j = tid; j < n; j += 256) {
|
||||
const int pg = sel[(size_t)row * sp + j];
|
||||
if (pg < 0) continue;
|
||||
const int u = lookup(pg);
|
||||
const int tk = j == n - 1 ? min(c - 4 * j, 4) : 4;
|
||||
atomicOr(&sm[u], (uint32_t)tk << (4 * r));
|
||||
}
|
||||
if (tid == 0) fs[row] = c > 0 ? fsv : 0;
|
||||
}
|
||||
__syncthreads();
|
||||
const int padded = (cnt + kG8UnionTile / 4 - 1) & ~(kG8UnionTile / 4 - 1);
|
||||
for (int i = tid; i < padded; i += 256) M[(size_t)g * up + i] = i < cnt ? sm[i] : 0u;
|
||||
if (tid == 0) {
|
||||
gctx[g] = 4 * cnt;
|
||||
cu[g] = g * kG8UnionR;
|
||||
if (g == (int)gridDim.x - 1) cu[g + 1] = rows;
|
||||
}
|
||||
}
|
||||
|
||||
/* Declare-time bytes: the per-row partials at one split for max_seqs rows, the plan after them. */
|
||||
static int64_t g8_union_scratch(const RadArgs* a) {
|
||||
const long long n_head = halo_geti_or(a, "n_head", 0), rows = halo_geti_or(a, "max_seqs", 0);
|
||||
if (n_head <= 0 || rows < kG8UnionMinRows) return 0;
|
||||
const long long part = rows * n_head * (256 * 2 + 8);
|
||||
return (int64_t)(((part + 255) & ~255LL) + g8_union_plan(nullptr, rows, kG8UnionUp).bytes);
|
||||
}
|
||||
|
||||
/* 1 when the launch is not the union form's (the per-row form takes it), else 0 or the error. */
|
||||
static int g8_union_launch(const HaloArgs* a, long long scratch_bytes, RadStream stream,
|
||||
const HaloGateQuant* gq) {
|
||||
if (a->cu_q || a->q_len != 1 || a->num_seqs < kG8UnionMinRows || a->k_descale ||
|
||||
a->v_descale || a->window != 0 || a->kv_rep > 1 || a->q_ld != 0 || a->chain ||
|
||||
a->head_dim != 256 || a->block_size != 4 || a->kv_heads <= 0 ||
|
||||
a->q_heads / a->kv_heads != G8_GQA || a->max_blocks > kG8UnionMaxSp || a->splits > 1)
|
||||
return 1;
|
||||
constexpr int TILE = HALO_D_TILE, JPB = HALO_D_JPB;
|
||||
constexpr int PF16 = (G8_D_OPT & O_PF16) ? 1 : 0;
|
||||
static_assert(PF16, "the partials are f16");
|
||||
const long long rows = a->num_seqs, G = (rows + kG8UnionR - 1) / kG8UnionR;
|
||||
const int up = (kG8UnionR * a->max_blocks + 7) & ~7;
|
||||
const long long part = rows * a->q_heads * (256 * 2 + 8);
|
||||
const long long off = (part + 255) & ~255LL;
|
||||
G8UnionPlan pl = g8_union_plan((char*)a->scratch + off, rows, up);
|
||||
if (!a->scratch || off + pl.bytes > scratch_bytes) return 1;
|
||||
hipStream_t s = (hipStream_t)stream;
|
||||
|
||||
hipLaunchKernelGGL(g8_union_plan_kernel, dim3((unsigned)G), dim3(256), 0, s, a->block_table,
|
||||
a->max_blocks, a->seqused_k, (int)rows, up, pl.u, pl.m, pl.gctx, pl.cu, pl.fs,
|
||||
TILE);
|
||||
CHK8();
|
||||
HaloArgs u = *a;
|
||||
u.num_seqs = (int)G;
|
||||
u.q_len = kG8UnionR;
|
||||
u.cu_q = pl.cu;
|
||||
u.total_q = (int)rows;
|
||||
u.block_table = pl.u;
|
||||
u.max_blocks = up;
|
||||
u.seqused_k = pl.gctx;
|
||||
u.umask = pl.m;
|
||||
u.splits = 1;
|
||||
hipLaunchKernelGGL((halo_attn_decode_kernel<4, kG8UnionTile, 256, G8_GQA, 4, 0, G8_D_OPT | O_UNION>),
|
||||
dim3(1, a->kv_heads, (unsigned)G), dim3(4 * halo_dec_ds(256) * 32), 0, s, u, 1);
|
||||
CHK8();
|
||||
/* The merge reads one partial a row: `fs` gives a live row one tile of context. */
|
||||
HaloArgs m = *a;
|
||||
m.seqused_k = pl.fs;
|
||||
const int jobs = (int)rows * a->q_heads, blocks = (jobs + JPB - 1) / JPB;
|
||||
if (gq->i8)
|
||||
hipLaunchKernelGGL((halo_attn_splitkv_combine_vec_gq_kernel<256, 4, PF16, JPB, 0, 2>),
|
||||
dim3(blocks), dim3(32 * JPB), 0, s, m, 1, TILE, *gq);
|
||||
else
|
||||
hipLaunchKernelGGL((halo_attn_splitkv_combine_vec_gq_kernel<256, 4, PF16, JPB, 0, 1>),
|
||||
dim3(blocks), dim3(32 * JPB), 0, s, m, 1, TILE, *gq);
|
||||
CHK8();
|
||||
return 0;
|
||||
}
|
||||
#endif /* G8_UNION && HALO_ATTN_GQ && HALO_ATTN_H256 */
|
||||
|
||||
// ---- decode entry points ------------------------------------------------------------------------
|
||||
#if HALO_ATTN_H256
|
||||
extern "C" int64_t GQ_SYM(halo_rad_attn_decode_h256_gqa, _scratch)(const RadArgs* a) {
|
||||
return g8_decode_scratch(a, 256);
|
||||
}
|
||||
extern "C" int GQ_SYM(halo_rad_attn_decode_h256_gqa, _fp8)(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
const int rc = g8_decode_common(a, &r, 256);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return g8_decode_launch<256, 0>(&r, s);
|
||||
}
|
||||
extern "C" int GQ_SYM(halo_rad_attn_decode_h256_gqa, _bf16)(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
const int rc = g8_decode_common(a, &r, 256);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return g8_decode_launch<256, 1>(&r, s);
|
||||
}
|
||||
#if HALO_ATTN_GQ
|
||||
/* Gated: the merge's epilogue carries the gate and the quantiser. */
|
||||
extern "C" int GQ_SYM(halo_rad_attn_decode_gq_h256_gqa, _fp8)(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
const int rc = g8_decode_common(a, &r, 256);
|
||||
if (rc != RAD_OK) return rc;
|
||||
HaloGateQuant gq{};
|
||||
const int gc = g8_gate_quant_args(a, r, &gq);
|
||||
if (gc != RAD_OK) return gc;
|
||||
#if G8_UNION
|
||||
const int uc = g8_union_launch(&r, (long long)a->scratch_bytes, s, &gq);
|
||||
if (uc <= 0) return uc;
|
||||
#endif
|
||||
return g8_decode_launch<256, 0>(&r, s, &gq);
|
||||
}
|
||||
extern "C" int GQ_SYM(halo_rad_attn_decode_gq_h256_gqa, _bf16)(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
const int rc = g8_decode_common(a, &r, 256);
|
||||
if (rc != RAD_OK) return rc;
|
||||
HaloGateQuant gq{};
|
||||
const int gc = g8_gate_quant_args(a, r, &gq);
|
||||
if (gc != RAD_OK) return gc;
|
||||
return g8_decode_launch<256, 1>(&r, s, &gq);
|
||||
}
|
||||
#endif /* HALO_ATTN_GQ */
|
||||
#endif /* HALO_ATTN_H256 */
|
||||
|
||||
#if HALO_ATTN_H128
|
||||
extern "C" int64_t GQ_SYM(halo_rad_attn_decode_h128_gqa, _scratch)(const RadArgs* a) {
|
||||
return g8_decode_scratch(a, 128);
|
||||
}
|
||||
extern "C" int GQ_SYM(halo_rad_attn_decode_h128_gqa, _fp8)(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
const int rc = g8_decode_common(a, &r, 128);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return g8_decode_launch<128, 0>(&r, s);
|
||||
}
|
||||
extern "C" int GQ_SYM(halo_rad_attn_decode_h128_gqa, _bf16)(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
const int rc = g8_decode_common(a, &r, 128);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return g8_decode_launch<128, 1>(&r, s);
|
||||
}
|
||||
#endif /* HALO_ATTN_H128 */
|
||||
|
||||
#if HALO_ATTN_H256 && HALO_ATTN_V4
|
||||
/* The fp8_v4 (a token's row 400 bytes: E4M3 K, int4 V, f16 scales) and k6_v4 (352 bytes: int6 K,
|
||||
* int4 V) caches on the decode leg, plain and gated. */
|
||||
#define G8_V4_DECODE(TAG, ROWB, XOPT) \
|
||||
extern "C" int64_t GQ_SYM(halo_rad_attn_decode_h256_gqa, _##TAG##_scratch)(const RadArgs* a) { \
|
||||
return g8_decode_scratch(a, 256, ROWB); \
|
||||
} \
|
||||
extern "C" int GQ_SYM(halo_rad_attn_decode_h256_gqa, _##TAG)(const RadArgs* a, RadStream s) { \
|
||||
HaloArgs r; \
|
||||
const int rc = g8_decode_common(a, &r, 256, ROWB); \
|
||||
if (rc != RAD_OK) return rc; \
|
||||
return g8_decode_launch<256, 0, (XOPT)>(&r, s); \
|
||||
} \
|
||||
extern "C" int GQ_SYM(halo_rad_attn_decode_gq_h256_gqa, _##TAG)(const RadArgs* a, RadStream s) { \
|
||||
HaloArgs r; \
|
||||
const int rc = g8_decode_common(a, &r, 256, ROWB); \
|
||||
if (rc != RAD_OK) return rc; \
|
||||
HaloGateQuant gq{}; \
|
||||
const int gc = g8_gate_quant_args(a, r, &gq); \
|
||||
if (gc != RAD_OK) return gc; \
|
||||
return g8_decode_launch<256, 0, (XOPT)>(&r, s, &gq); \
|
||||
}
|
||||
G8_V4_DECODE(fp8v4, 400, O_V4)
|
||||
G8_V4_DECODE(k6v4, 352, O_V4 | O_K6)
|
||||
#undef G8_V4_DECODE
|
||||
#endif /* HALO_ATTN_H256 && HALO_ATTN_V4 */
|
||||
@@ -0,0 +1,20 @@
|
||||
/* Derived from libr4d/r4d_attn_paged_h128_gqa1.hip by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. */
|
||||
/* halo_attn_paged_h128_gqa1.hip -- head_dim 128 with ONE query head per KV head: plain MHA.
|
||||
*
|
||||
* Everything else in this library pages attention through a grouped ratio (2, 4, 6, 8 or 12
|
||||
* queries per KV head). The Unlimited-OCR decoder has 10 query heads over 10 KV heads at 128 wide,
|
||||
* so the ratio is 1 and none of the existing legs matches it; the engine reports every band of that
|
||||
* geometry as having no kernel rather than serving it on the host.
|
||||
*
|
||||
* The device code is the generic body (halo_attn_paged_gqa8.hip, which is parameterised by
|
||||
* HALO_ATTN_GQA rather than fixed at 8) instantiated at ratio 1: the same templated prefill
|
||||
* kernel, with GQA=1 substituted. No new kernel, no new masking path.
|
||||
*
|
||||
* The prefill option set is the h128 set (G8_P_OPT_128), which is the one compiled for this head
|
||||
* width. gfx1151: both bands -- the split-KV decode leg is the generic body's, included below. */
|
||||
#define HALO_ATTN_GQA 1
|
||||
#define HALO_ATTN_H128 1
|
||||
#define HALO_ATTN_H256 0
|
||||
|
||||
#include "halo_attn_paged_gqa8.hip"
|
||||
@@ -0,0 +1,14 @@
|
||||
/* Derived from libr4d/r4d_attn_paged_h128_gqa2.hip by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. */
|
||||
/* halo_attn_paged_h128_gqa2.hip -- head_dim 128, two queries per KV head, paged block 16, no
|
||||
* window: the windowless h128/gqa2 rows. Gemma 3's sliding layers take their own unit
|
||||
* (halo_attn_paged_h128_gqa2w.hip) with the window bit on, so the global layers stay on the tuned
|
||||
* full-attention legs.
|
||||
*
|
||||
* The device code is the generic body (halo_attn_paged_gqa8.hip) at ratio 2, h128 option set, both
|
||||
* bands: the split-KV decode leg comes from the same body. */
|
||||
#define HALO_ATTN_GQA 2
|
||||
#define HALO_ATTN_H128 1
|
||||
#define HALO_ATTN_H256 0
|
||||
|
||||
#include "halo_attn_paged_gqa8.hip"
|
||||
@@ -0,0 +1,111 @@
|
||||
/* Derived from libr4d/r4d_attn_paged_h128_gqa2w.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// Halo attention dispatch for Gemma 3's sliding-window layers (arch/gemma3, TranslateGemma 27B):
|
||||
// head_dim 128, 2 queries per KV head (32 over 16, 16 over 8 at TP2), paged block 16, window 1024
|
||||
// (52 of 62 layers). Instantiations of the h128 prefill kernel template with WIN = 1, as
|
||||
// halo_attn_paged_h256_gqa2.hip does at head_dim 256 for Gemma 4.
|
||||
//
|
||||
// Both bands: decode (q_len * gqa <= 64, so q_len <= 32) and the query-tiled prefill kernel. The
|
||||
// windowless h128/gqa2 rows (halo_attn_paged_h128_gqa2.hip) keep window == 0; these rows take
|
||||
// window >= 1 only, so the global layers stay on the tuned full-attention legs.
|
||||
//
|
||||
// gfx1151: both bands. The split-KV decode kernel is a body of its own
|
||||
// (halo_attn_decode_h256_gqa6.hip); this unit instantiates it at the end, window bit on.
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_attn_args.h"
|
||||
#include "halo_common.h"
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
using std::max;
|
||||
#include "halo_attn_prefill_h256_gqa6.hip"
|
||||
|
||||
#define CHK4() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0)
|
||||
|
||||
#define B_HEAD_DIM 128
|
||||
#define B_GQA 2
|
||||
#define B_BLOCK_SIZE 16
|
||||
|
||||
// ---- prefill ---------------------------------------------------------------------------------
|
||||
// The windowless h128 prefill option set (halo_attn_paged_gqa8.hip, G8_P_OPT_128: no O_KWIDE, which
|
||||
// is a head_dim 256 fetch, K prefetch 4) with WIN on. At gqa 2 a block covers NWARPS * 16 / 2 = 192
|
||||
// query positions. window <= 0 would give full attention, but the rows never send one here.
|
||||
#define P_NWARPS 24
|
||||
#define P_TILE 48
|
||||
#define P_OPT 3430923
|
||||
|
||||
template <int KVP>
|
||||
static int prefill_launch_h128_gqa2w(const HaloArgs* a, hipStream_t s) {
|
||||
if (a->head_dim != B_HEAD_DIM || a->block_size != B_BLOCK_SIZE) return -1;
|
||||
if (a->q_heads / a->kv_heads != B_GQA) return -2;
|
||||
constexpr int BQ = (P_NWARPS * 16) / B_GQA;
|
||||
dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs);
|
||||
hipLaunchKernelGGL((halo_attn_prefill_kernel<P_NWARPS, P_TILE, B_HEAD_DIM, B_GQA,
|
||||
B_BLOCK_SIZE, KVP, P_OPT, 1>),
|
||||
grid, dim3(P_NWARPS * 32), 0, s, *a);
|
||||
CHK4();
|
||||
return 0;
|
||||
}
|
||||
|
||||
extern "C" int halo_attn_prefill_h128_gqa2w_fp8kv(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_launch_h128_gqa2w<0>(a, s);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h128_gqa2w_bf16kv(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_launch_h128_gqa2w<1>(a, s);
|
||||
}
|
||||
|
||||
/* Prefill RadArgs wrappers. Absent descales mean 1.0 (fill_paged leaves them null). */
|
||||
extern "C" int halo_rad_attn_prefill_h128_gqa2w_fp8(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = fill_paged(a, &r, B_HEAD_DIM);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_prefill_h128_gqa2w_fp8kv(&r, (hipStream_t)s);
|
||||
}
|
||||
extern "C" int halo_rad_attn_prefill_h128_gqa2w_bf16(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = fill_paged(a, &r, B_HEAD_DIM);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_prefill_h128_gqa2w_bf16kv(&r, (hipStream_t)s);
|
||||
}
|
||||
|
||||
// ============================================================== the split-KV decode leg
|
||||
//
|
||||
// Same geometry, the decode band (q_len * gqa <= 64, so q_len <= 32), with the window bit on: the
|
||||
// body halo_attn_decode_h256_gqa6.hip instantiated at h128/gqa2 with WIN = 1. The rows carry
|
||||
// window >= 1, so a global (windowless) layer stays on the tuned full-attention legs.
|
||||
#include "halo_attn_decode_h256_gqa6.hip"
|
||||
|
||||
#define B_TILE HALO_D_TILE
|
||||
// The h256/gqa6 decode option set. libr4d's h128 windowed set adds O_KRAW, a gfx12 shape this port
|
||||
// does not instantiate; the set's GPREV turns itself off at head_dim 128 (a V prefetch no longer
|
||||
// fits in three registers).
|
||||
#define B_OPT HALO_D_OPT
|
||||
|
||||
extern "C" long halo_attn_decode_h128_gqa2w_scratch_bytes(const HaloArgs* a) {
|
||||
return decode_scratch_bytes<B_OPT, 1>(a);
|
||||
}
|
||||
|
||||
extern "C" int halo_attn_decode_h128_gqa2w_fp8kv(const HaloArgs* a, hipStream_t s) {
|
||||
return decode_launch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 0, 1>(a, s);
|
||||
}
|
||||
extern "C" int halo_attn_decode_h128_gqa2w_bf16kv(const HaloArgs* a, hipStream_t s) {
|
||||
return decode_launch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1, 1>(a, s);
|
||||
}
|
||||
|
||||
/* ---- the plugin ABI entry points of the decode band */
|
||||
|
||||
extern "C" int64_t halo_rad_attn_decode_h128_gqa2w_scratch(const RadArgs* a) {
|
||||
return decode_scratch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a);
|
||||
}
|
||||
extern "C" int halo_rad_attn_decode_h128_gqa2w_fp8(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = decode_common<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a, &r);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_decode_h128_gqa2w_fp8kv(&r, (hipStream_t)s);
|
||||
}
|
||||
extern "C" int halo_rad_attn_decode_h128_gqa2w_bf16(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = decode_common<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a, &r);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_decode_h128_gqa2w_bf16kv(&r, (hipStream_t)s);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/* Derived from libr4d/r4d_attn_paged_h128_gqa4.hip by the libhalo rename transform (2026-10-27),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// Halo attention dispatch for the DFlash2 drafter: head_dim 128, 4 queries per KV head, paged
|
||||
// block 16, sliding window. Instantiations of the split-KV decode body
|
||||
// (halo_attn_decode_h256_gqa6.hip) with WIN = 1, as the Gemma 4 and Gemma 3 legs do at h256/gqa2
|
||||
// and h128/gqa2w.
|
||||
//
|
||||
// Decode only. Queries long enough for the query-tiled prefill kernel occur on a drafter only in
|
||||
// prefill steps; the decode rows declare the decode band (q_len * gqa <= 64), so those steps
|
||||
// resolve to the prefill kernel of another geometry's unit.
|
||||
//
|
||||
// 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. halo 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.
|
||||
//
|
||||
// The same geometry serves attn_paged_qrow: the gqa-4 kernel with each kv head mapped onto two
|
||||
// query groups (HaloArgs::kv_rep = 2) is the 31B drafter's gqa 8 over a cache that holds each kv
|
||||
// head once, and q read at its own row pitch (HaloArgs::q_ld). The workgroup then holds q_len * 4
|
||||
// rows, so a draft block of 16 fits where gqa 8's own decode (q_len <= 8) does not.
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_attn_args.h"
|
||||
#include "halo_common.h"
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
using std::max;
|
||||
#include "halo_attn_decode_h256_gqa6.hip"
|
||||
|
||||
#define B_HEAD_DIM 128
|
||||
#define B_GQA 4
|
||||
#define B_BLOCK_SIZE 16
|
||||
|
||||
// The h256/gqa6 decode option set (HALO_D_OPT). libr4d's h128 set adds O_KRAW, one-round raw K,
|
||||
// which is a gfx12 shape the port does not instantiate (halo_attn_decode_h256_gqa6.hip asserts it
|
||||
// off), and the set's GPREV turns itself off here: at head_dim 128 a V prefetch is 4 registers more
|
||||
// than the three it fits in.
|
||||
#define B_OPT HALO_D_OPT
|
||||
|
||||
extern "C" long halo_attn_decode_h128_gqa4_scratch_bytes(const HaloArgs* a) {
|
||||
return decode_scratch_bytes<B_OPT, 1>(a);
|
||||
}
|
||||
|
||||
extern "C" int halo_attn_decode_h128_gqa4_fp8kv(const HaloArgs* a, hipStream_t s) {
|
||||
return decode_launch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 0, 1>(a, s);
|
||||
}
|
||||
extern "C" int halo_attn_decode_h128_gqa4_bf16kv(const HaloArgs* a, hipStream_t s) {
|
||||
return decode_launch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1, 1>(a, s);
|
||||
}
|
||||
// The same over a cache holding each kv head once for kv_rep query groups (O_KVREP), q at
|
||||
// HaloArgs::q_ld (O_QLD): gqa 8 on this gqa-4 kernel, under attn_paged_qrow.
|
||||
extern "C" int halo_attn_decode_h128_gqa4_rep_fp8kv(const HaloArgs* a, hipStream_t s) {
|
||||
return decode_launch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT | O_QLD | O_KVREP, 0, 1>(a, s);
|
||||
}
|
||||
extern "C" int halo_attn_decode_h128_gqa4_rep_bf16kv(const HaloArgs* a, hipStream_t s) {
|
||||
return decode_launch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT | O_QLD | O_KVREP, 1, 1>(a, s);
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
|
||||
extern "C" int64_t halo_rad_attn_decode_h128_scratch(const RadArgs* a) {
|
||||
return decode_scratch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a);
|
||||
}
|
||||
extern "C" int halo_rad_attn_decode_h128_fp8(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = decode_common<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a, &r);
|
||||
if (rc != RAD_OK) return rc;
|
||||
/* Absent descales mean 1.0; see the prefill twins. */
|
||||
return halo_attn_decode_h128_gqa4_fp8kv(&r, (hipStream_t)s);
|
||||
}
|
||||
extern "C" int halo_rad_attn_decode_h128_bf16(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = decode_common<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a, &r);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_decode_h128_gqa4_bf16kv(&r, (hipStream_t)s);
|
||||
}
|
||||
|
||||
/* Head_dim 128 at 8 queries per kv head under attn_paged_qrow: the gqa-4 kernel, each kv head
|
||||
* mapped onto two query groups (kv_rep 2), q at its own row pitch. */
|
||||
extern "C" int64_t halo_rad_attn_qrow_h128_gqa8_scratch(const RadArgs* a) {
|
||||
return decode_scratch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a, 0, 2, true);
|
||||
}
|
||||
extern "C" int halo_rad_attn_qrow_h128_gqa8_fp8(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = decode_common<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a, &r, 0, 2, true);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_decode_h128_gqa4_rep_fp8kv(&r, (hipStream_t)s);
|
||||
}
|
||||
extern "C" int halo_rad_attn_qrow_h128_gqa8_bf16(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = decode_common<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a, &r, 0, 2, true);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_decode_h128_gqa4_rep_bf16kv(&r, (hipStream_t)s);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/* Derived from libr4d/r4d_attn_paged_h256_gqa12.hip by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. */
|
||||
// Halo 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; halo_attn_paged_gqa8.hip is the body. The ratio
|
||||
// changes two bounds, both stated in the row table:
|
||||
//
|
||||
// decode verify width 64 / gqa = 5. A wider speculative verify takes the prefill kernel.
|
||||
// prefill block width 384 / gqa = 32 query positions.
|
||||
//
|
||||
// No head_dim 128 leg: nothing in scope is gqa 12 at 128, so those entry points are not built.
|
||||
#define HALO_ATTN_GQA 12
|
||||
#define HALO_ATTN_H128 0
|
||||
// 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.
|
||||
//
|
||||
// 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).
|
||||
#define G8_BLOCK_SIZE 4
|
||||
// The fp8_v4 and k6_v4 caches (--kv-cache-dtype), which qwen4exp_fp8 offers for these layers.
|
||||
// The fused gate+quantise rows beside its unfused pair (attn_paged_gate_quant).
|
||||
#define HALO_ATTN_V4 1
|
||||
#define HALO_ATTN_GQ 1
|
||||
// The gated rows' prefill form over groups of query rows (g8_union_launch): the QSA attention.
|
||||
#define G8_UNION 1
|
||||
|
||||
#include "halo_attn_paged_gqa8.hip"
|
||||
@@ -0,0 +1,132 @@
|
||||
/* Derived from libr4d/r4d_attn_paged_h256_gqa2.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// Halo paged 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 prefill
|
||||
// kernel template with WIN = 1, as the DFlash2 drafter leg does at head_dim 128.
|
||||
//
|
||||
// Both bands: decode (q_len * gqa <= 64, so q_len <= 32) and the query-tiled prefill kernel. The
|
||||
// split-KV decode kernel is a body of its own (halo_attn_decode_h256_gqa6.hip) and this unit
|
||||
// instantiates it at the end, window bit on.
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_attn_args.h"
|
||||
#include "halo_common.h"
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
using std::max;
|
||||
#include "halo_attn_prefill_h256_gqa6.hip"
|
||||
|
||||
#define CHK4() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0)
|
||||
|
||||
#define B_HEAD_DIM 256
|
||||
#define B_GQA 2
|
||||
#define B_BLOCK_SIZE 16
|
||||
|
||||
// ---- prefill ---------------------------------------------------------------------------------
|
||||
// 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
|
||||
|
||||
template <int KVP>
|
||||
static int prefill_launch_h256_gqa2(const HaloArgs* a, hipStream_t s) {
|
||||
if (a->head_dim != B_HEAD_DIM || a->block_size != B_BLOCK_SIZE) return -1;
|
||||
if (a->q_heads / a->kv_heads != B_GQA) return -2;
|
||||
constexpr int BQ = (P_NWARPS * 16) / B_GQA;
|
||||
dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs);
|
||||
hipLaunchKernelGGL((halo_attn_prefill_kernel<P_NWARPS, P_TILE, B_HEAD_DIM, B_GQA,
|
||||
B_BLOCK_SIZE, KVP, P_OPT, 1>),
|
||||
grid, dim3(P_NWARPS * 32), 0, s, *a);
|
||||
CHK4();
|
||||
return 0;
|
||||
}
|
||||
|
||||
extern "C" int halo_attn_prefill_h256_gqa2_fp8kv(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_launch_h256_gqa2<0>(a, s);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h256_gqa2_bf16kv(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_launch_h256_gqa2<1>(a, s);
|
||||
}
|
||||
|
||||
/* Prefill RadArgs wrappers, defined in this unit rather than the h256 dispatch. Absent descales
|
||||
* mean 1.0 (fill_paged leaves them null). */
|
||||
extern "C" int halo_rad_attn_prefill_h256_gqa2_fp8(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = fill_paged(a, &r, B_HEAD_DIM);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_prefill_h256_gqa2_fp8kv(&r, (hipStream_t)s);
|
||||
}
|
||||
extern "C" int halo_rad_attn_prefill_h256_gqa2_bf16(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = fill_paged(a, &r, B_HEAD_DIM);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_prefill_h256_gqa2_bf16kv(&r, (hipStream_t)s);
|
||||
}
|
||||
|
||||
// ============================================================== the split-KV decode leg
|
||||
//
|
||||
// Same geometry, the decode band (q_len * gqa <= 64, so q_len <= 32), with the window bit on: the
|
||||
// body halo_attn_decode_h256_gqa6.hip instantiated at h256/gqa2 with WIN = 1, which picks the
|
||||
// windowed split law and compiles the window walk in. window <= 0 is full attention.
|
||||
//
|
||||
// attn_paged_qrow reads the same geometry with q at HaloArgs::q_ld (O_QLD), its own instances so the
|
||||
// dense pair above keeps its registers.
|
||||
#include "halo_attn_decode_h256_gqa6.hip"
|
||||
|
||||
#define B_TILE HALO_D_TILE
|
||||
#define B_OPT HALO_D_OPT
|
||||
|
||||
extern "C" long halo_attn_decode_h256_gqa2_scratch_bytes(const HaloArgs* a) {
|
||||
return decode_scratch_bytes<B_OPT, 1>(a);
|
||||
}
|
||||
|
||||
extern "C" int halo_attn_decode_h256_gqa2_fp8kv(const HaloArgs* a, hipStream_t s) {
|
||||
return decode_launch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 0, 1>(a, s);
|
||||
}
|
||||
extern "C" int halo_attn_decode_h256_gqa2_bf16kv(const HaloArgs* a, hipStream_t s) {
|
||||
return decode_launch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1, 1>(a, s);
|
||||
}
|
||||
extern "C" int halo_attn_decode_h256_gqa2_qld_fp8kv(const HaloArgs* a, hipStream_t s) {
|
||||
return decode_launch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT | O_QLD, 0, 1>(a, s);
|
||||
}
|
||||
extern "C" int halo_attn_decode_h256_gqa2_qld_bf16kv(const HaloArgs* a, hipStream_t s) {
|
||||
return decode_launch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT | O_QLD, 1, 1>(a, s);
|
||||
}
|
||||
|
||||
/* ---- the plugin ABI entry points of the decode band */
|
||||
|
||||
extern "C" int64_t halo_rad_attn_decode_h256_gqa2_scratch(const RadArgs* a) {
|
||||
return decode_scratch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a);
|
||||
}
|
||||
extern "C" int halo_rad_attn_decode_h256_gqa2_fp8(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = decode_common<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a, &r);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_decode_h256_gqa2_fp8kv(&r, (hipStream_t)s);
|
||||
}
|
||||
extern "C" int halo_rad_attn_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = decode_common<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a, &r);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_decode_h256_gqa2_bf16kv(&r, (hipStream_t)s);
|
||||
}
|
||||
|
||||
/* The same decode under attn_paged_qrow: q read at its own row pitch (HaloArgs::q_ld), the sliding
|
||||
* layers' q where a fused q|k|v projection left it. Same kernel, same arithmetic. */
|
||||
extern "C" int64_t halo_rad_attn_qrow_decode_h256_gqa2_scratch(const RadArgs* a) {
|
||||
return decode_scratch<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a, 0, 1, true);
|
||||
}
|
||||
extern "C" int halo_rad_attn_qrow_decode_h256_gqa2_fp8(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = decode_common<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a, &r, 0, 1, true);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_decode_h256_gqa2_qld_fp8kv(&r, (hipStream_t)s);
|
||||
}
|
||||
extern "C" int halo_rad_attn_qrow_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) {
|
||||
HaloArgs r;
|
||||
int rc = decode_common<B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, B_OPT, 1>(a, &r, 0, 1, true);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_decode_h256_gqa2_qld_bf16kv(&r, (hipStream_t)s);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/* Derived from libr4d/r4d_attn_paged_h256_gqa4.hip by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. */
|
||||
// Halo 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; halo_attn_paged_gqa8.hip is the body. The ratio changes
|
||||
// two bounds, both stated in the row table:
|
||||
//
|
||||
// decode verify width 64 / gqa = 16.
|
||||
// prefill block width 384 / gqa = 96 query positions.
|
||||
//
|
||||
// No head_dim 128 leg: gqa 4 at 128 is the DFlash2 drafter's windowed geometry. 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.
|
||||
//
|
||||
// gfx1151: both bands -- the split-KV decode leg comes from the generic body too.
|
||||
#define HALO_ATTN_GQA 4
|
||||
#define HALO_ATTN_H128 0
|
||||
#define HALO_ATTN_H64 1
|
||||
|
||||
#include "halo_attn_paged_gqa8.hip"
|
||||
@@ -0,0 +1,285 @@
|
||||
/* Derived from libr4d/r4d_attn_paged_h256_gqa6.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// Halo 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 exact variant. Two families differ in KV dtype: bf16 and 8-bit (fp8,
|
||||
// the production configuration, and the fp8_v4 and k6_v4 caches). The e4m3-product rows (QK8, PV8)
|
||||
// run the same body with their operands rounded to e4m3 first: gfx1151 has no fp8 matrix
|
||||
// instruction, so the legs are emulated on the f16 WMMA (see halo_attn_prefill_h256_gqa6.hip).
|
||||
//
|
||||
// This unit is the gfx1151 counterpart of libr4d's and ships both bands. libhalo keeps the split-KV
|
||||
// decode kernel in a body of its own (halo_attn_decode_h256_gqa6.hip, text shared by every paged
|
||||
// geometry); this unit includes it at the end and defines this geometry's decode entry points.
|
||||
//
|
||||
// `opt` is a bitmask of optimisation steps, defined in halo_attn_prefill_h256_gqa6.hip:
|
||||
// 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. Not O_KLATE (8-bit K fetched a tile ahead): on gfx1151 its live
|
||||
// K registers took the fp8 and k6_v4 kernels from ~90 to ~300 spilled VGPRs,
|
||||
// and those two ran 2.3x slower than fp8_v4 and bf16 (q_len 512 at 16K:
|
||||
// 11.8 -> 4.3 ms without it).
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_attn_args.h"
|
||||
#include "halo_common.h"
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
using std::max;
|
||||
#include "halo_attn_prefill_h256_gqa6.hip"
|
||||
|
||||
#define CHK() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0)
|
||||
|
||||
// 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
|
||||
#define A_MAX_DECODE_ROWS 64 // q_len * gqa a single decode workgroup can hold
|
||||
|
||||
extern "C" void halo_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows) {
|
||||
if (head_dim) *head_dim = A_HEAD_DIM;
|
||||
if (gqa) *gqa = A_GQA;
|
||||
if (block_size) *block_size = A_BLOCK_SIZE;
|
||||
if (max_decode_rows) *max_decode_rows = A_MAX_DECODE_ROWS;
|
||||
}
|
||||
|
||||
// ---- prefill ---------------------------------------------------------------------------------
|
||||
// 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 make the m-tile loop spill at six waves per SIMD.
|
||||
#define P_OPT 3954187
|
||||
|
||||
// KVP: 0 = an 8-bit cache (XOPT names fp8_v4 or k6_v4), 1 = bf16 cache.
|
||||
template <int KVP, int XOPT = 0>
|
||||
static int prefill_launch(const HaloArgs* a, hipStream_t s) {
|
||||
if (a->head_dim != A_HEAD_DIM || a->block_size != A_BLOCK_SIZE) return -1;
|
||||
if (a->q_heads / a->kv_heads != A_GQA) return -2;
|
||||
// Split-KV when the caller set a->splits > 1 with scratch for the partials
|
||||
// (halo_prefill_split_setup); otherwise the query-tiled grid as before.
|
||||
return halo_prefill_launch<P_NWARPS, P_TILE, A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, KVP,
|
||||
P_OPT | XOPT>(a, s);
|
||||
}
|
||||
|
||||
/* The split-KV partials (halo_prefill_scratch in the body), one hook per cache row width. */
|
||||
extern "C" int64_t halo_rad_attn_prefill_h256_scratch(const RadArgs* a) {
|
||||
return halo_prefill_scratch<P_NWARPS, P_TILE, A_HEAD_DIM, A_GQA>(a);
|
||||
}
|
||||
extern "C" int64_t halo_rad_attn_prefill_h256_v4_scratch(const RadArgs* a) {
|
||||
return halo_prefill_scratch<P_NWARPS, P_TILE, A_HEAD_DIM, A_GQA>(a, 400);
|
||||
}
|
||||
extern "C" int64_t halo_rad_attn_prefill_h256_k6_scratch(const RadArgs* a) {
|
||||
return halo_prefill_scratch<P_NWARPS, P_TILE, A_HEAD_DIM, A_GQA>(a, 352);
|
||||
}
|
||||
#define P_SPLIT(a, r) halo_prefill_split_setup<P_NWARPS, P_TILE, A_HEAD_DIM, A_GQA>((a), (r))
|
||||
|
||||
extern "C" int halo_attn_prefill_h256_gqa6_fp8kv(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_launch<0>(a, s);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h256_gqa6_bf16kv(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_launch<1>(a, s);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h256_gqa6_fp8v4kv(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_launch<0, O_V4>(a, s);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h256_gqa6_k6v4kv(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_launch<0, O_V4 | O_K6>(a, s);
|
||||
}
|
||||
|
||||
// The e4m3 legs over an 8-bit cache: `legs` 1 Q.K^T, 2 P.V, 3 both. XOPT names the cache.
|
||||
template <int XOPT>
|
||||
static int prefill_legs_launch(const HaloArgs* a, hipStream_t s, int legs) {
|
||||
if (legs == 1) return prefill_launch<0, XOPT | O_QK8>(a, s);
|
||||
if (legs == 2) return prefill_launch<0, XOPT | O_PV8>(a, s);
|
||||
return prefill_launch<0, XOPT | O_QK8 | O_PV8>(a, s);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h256_gqa6_fp8kv_qk8(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_legs_launch<0>(a, s, 1);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h256_gqa6_fp8kv_pv8(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_legs_launch<0>(a, s, 2);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h256_gqa6_fp8kv_qk8pv8(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_legs_launch<0>(a, s, 3);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h256_gqa6_fp8v4kv_qk8(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_legs_launch<O_V4>(a, s, 1);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h256_gqa6_fp8v4kv_pv8(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_legs_launch<O_V4>(a, s, 2);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h256_gqa6_fp8v4kv_qk8pv8(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_legs_launch<O_V4>(a, s, 3);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h256_gqa6_k6v4kv_qk8(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_legs_launch<O_V4 | O_K6>(a, s, 1);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h256_gqa6_k6v4kv_pv8(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_legs_launch<O_V4 | O_K6>(a, s, 2);
|
||||
}
|
||||
extern "C" int halo_attn_prefill_h256_gqa6_k6v4kv_qk8pv8(const HaloArgs* a, hipStream_t s) {
|
||||
return prefill_legs_launch<O_V4 | O_K6>(a, s, 3);
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader is halo_attn_args.h, shared by every paged geometry.
|
||||
/* ------------------------------------------------------------------ paged prefill */
|
||||
|
||||
extern "C" int halo_rad_attn_prefill_h256_fp8(const RadArgs* a, RadStream s) {
|
||||
if (check_dims_once() != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
HaloArgs r;
|
||||
int rc = fill_paged(a, &r, 256);
|
||||
if (rc != RAD_OK) return rc;
|
||||
P_SPLIT(a, &r);
|
||||
/* Absent descales mean 1.0, not an error: the kernels read them that way, vLLM defaults both
|
||||
* scales to 1.0, and kv_store_fp8 at its default scale needs no descale plane. */
|
||||
return halo_attn_prefill_h256_gqa6_fp8kv(&r, (hipStream_t)s);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_attn_prefill_h256_bf16(const RadArgs* a, RadStream s) {
|
||||
if (check_dims_once() != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
HaloArgs r;
|
||||
int rc = fill_paged(a, &r, 256);
|
||||
if (rc != RAD_OK) return rc;
|
||||
P_SPLIT(a, &r);
|
||||
return halo_attn_prefill_h256_gqa6_bf16kv(&r, (hipStream_t)s);
|
||||
}
|
||||
|
||||
/* The fp8_v4 cache: a token's row is 25 * 256 / 16 = 400 bytes (E4M3 K, int4 V, f16 scales). */
|
||||
extern "C" int halo_rad_attn_prefill_h256_fp8v4(const RadArgs* a, RadStream s) {
|
||||
if (check_dims_once() != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
HaloArgs r;
|
||||
int rc = fill_paged_row(a, &r, 256, 400);
|
||||
if (rc != RAD_OK) return rc;
|
||||
P_SPLIT(a, &r);
|
||||
return halo_attn_prefill_h256_gqa6_fp8v4kv(&r, (hipStream_t)s);
|
||||
}
|
||||
|
||||
/* The k6_v4 cache: a token's row is 22 * 256 / 16 = 352 bytes (int6 K, int4 V, f16 scales). */
|
||||
extern "C" int halo_rad_attn_prefill_h256_k6v4(const RadArgs* a, RadStream s) {
|
||||
if (check_dims_once() != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
HaloArgs r;
|
||||
int rc = fill_paged_row(a, &r, 256, 352);
|
||||
if (rc != RAD_OK) return rc;
|
||||
P_SPLIT(a, &r);
|
||||
return halo_attn_prefill_h256_gqa6_k6v4kv(&r, (hipStream_t)s);
|
||||
}
|
||||
|
||||
/* The 8-bit caches with e4m3 products. `legs` is the row's `prefill_fp8`, which its constraint has
|
||||
* matched: 1 Q.K^T, 2 P.V, 3 both. `row` is a token's bytes in a (block, head) page: 512 for fp8,
|
||||
* 400 for fp8_v4, 352 for k6_v4. */
|
||||
template <int XOPT>
|
||||
static int prefill_h256_legs(const RadArgs* a, RadStream s, long long row, int legs) {
|
||||
if (check_dims_once() != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
HaloArgs r;
|
||||
int rc = fill_paged_row(a, &r, 256, row);
|
||||
if (rc != RAD_OK) return rc;
|
||||
P_SPLIT(a, &r);
|
||||
return prefill_legs_launch<XOPT>(&r, (hipStream_t)s, legs);
|
||||
}
|
||||
extern "C" int halo_rad_attn_prefill_h256_fp8_qk8(const RadArgs* a, RadStream s) {
|
||||
return prefill_h256_legs<0>(a, s, 512, 1);
|
||||
}
|
||||
extern "C" int halo_rad_attn_prefill_h256_fp8_pv8(const RadArgs* a, RadStream s) {
|
||||
return prefill_h256_legs<0>(a, s, 512, 2);
|
||||
}
|
||||
extern "C" int halo_rad_attn_prefill_h256_fp8_qk8pv8(const RadArgs* a, RadStream s) {
|
||||
return prefill_h256_legs<0>(a, s, 512, 3);
|
||||
}
|
||||
extern "C" int halo_rad_attn_prefill_h256_fp8v4_qk8(const RadArgs* a, RadStream s) {
|
||||
return prefill_h256_legs<O_V4>(a, s, 400, 1);
|
||||
}
|
||||
extern "C" int halo_rad_attn_prefill_h256_fp8v4_pv8(const RadArgs* a, RadStream s) {
|
||||
return prefill_h256_legs<O_V4>(a, s, 400, 2);
|
||||
}
|
||||
extern "C" int halo_rad_attn_prefill_h256_fp8v4_qk8pv8(const RadArgs* a, RadStream s) {
|
||||
return prefill_h256_legs<O_V4>(a, s, 400, 3);
|
||||
}
|
||||
extern "C" int halo_rad_attn_prefill_h256_k6v4_qk8(const RadArgs* a, RadStream s) {
|
||||
return prefill_h256_legs<O_V4 | O_K6>(a, s, 352, 1);
|
||||
}
|
||||
extern "C" int halo_rad_attn_prefill_h256_k6v4_pv8(const RadArgs* a, RadStream s) {
|
||||
return prefill_h256_legs<O_V4 | O_K6>(a, s, 352, 2);
|
||||
}
|
||||
extern "C" int halo_rad_attn_prefill_h256_k6v4_qk8pv8(const RadArgs* a, RadStream s) {
|
||||
return prefill_h256_legs<O_V4 | O_K6>(a, s, 352, 3);
|
||||
}
|
||||
|
||||
// ============================================================== the split-KV decode leg
|
||||
//
|
||||
// Same geometry, the decode band: the body (halo_attn_decode_h256_gqa6.hip) is text shared by every
|
||||
// paged geometry, so this unit instantiates it at the geometry it owns and defines that geometry's
|
||||
// entry points -- the internal `<geom>_*kv` forms the engine dlsyms and the plugin rows the table
|
||||
// points at. An entry point added to the body itself would be defined by every unit that includes
|
||||
// it, which does not link.
|
||||
#include "halo_attn_decode_h256_gqa6.hip"
|
||||
|
||||
extern "C" long halo_attn_decode_h256_gqa6_scratch_bytes(const HaloArgs* a) {
|
||||
return decode_scratch_bytes<HALO_D_OPT>(a);
|
||||
}
|
||||
|
||||
extern "C" int halo_attn_decode_h256_gqa6_fp8kv(const HaloArgs* a, hipStream_t stream) {
|
||||
return decode_launch<A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, HALO_D_OPT, 0>(a, stream);
|
||||
}
|
||||
extern "C" int halo_attn_decode_h256_gqa6_bf16kv(const HaloArgs* a, hipStream_t stream) {
|
||||
return decode_launch<A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, HALO_D_OPT, 1>(a, stream);
|
||||
}
|
||||
extern "C" int halo_attn_decode_h256_gqa6_fp8v4kv(const HaloArgs* a, hipStream_t stream) {
|
||||
return decode_launch<A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, HALO_D_OPT | O_V4, 0>(a, stream);
|
||||
}
|
||||
extern "C" int halo_attn_decode_h256_gqa6_k6v4kv(const HaloArgs* a, hipStream_t stream) {
|
||||
return decode_launch<A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, HALO_D_OPT | O_V4 | O_K6, 0>(a, stream);
|
||||
}
|
||||
|
||||
/* ---- the plugin ABI entry points of the decode band */
|
||||
|
||||
extern "C" int64_t halo_rad_attn_decode_h256_scratch(const RadArgs* a) {
|
||||
return decode_scratch<A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, HALO_D_OPT>(a);
|
||||
}
|
||||
/* The fp8_v4 cache: a token's row is 25 * 256 / 16 = 400 bytes (E4M3 K, int4 V, f16 scales). */
|
||||
extern "C" int64_t halo_rad_attn_decode_h256_v4_scratch(const RadArgs* a) {
|
||||
return decode_scratch<A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, HALO_D_OPT>(a, 400);
|
||||
}
|
||||
/* The k6_v4 cache: a token's row is 22 * 256 / 16 = 352 bytes (int6 K, int4 V, f16 scales). */
|
||||
extern "C" int64_t halo_rad_attn_decode_h256_k6_scratch(const RadArgs* a) {
|
||||
return decode_scratch<A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, HALO_D_OPT>(a, 352);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_attn_decode_h256_fp8(const RadArgs* a, RadStream s) {
|
||||
if (check_dims_once() != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
HaloArgs r;
|
||||
int rc = decode_common<A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, HALO_D_OPT>(a, &r);
|
||||
if (rc != RAD_OK) return rc;
|
||||
/* Absent descales mean 1.0, not an error: the kernels read them that way and kv_store_fp8 at
|
||||
* its default scale needs no descale plane. */
|
||||
return halo_attn_decode_h256_gqa6_fp8kv(&r, (hipStream_t)s);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_attn_decode_h256_bf16(const RadArgs* a, RadStream s) {
|
||||
if (check_dims_once() != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
HaloArgs r;
|
||||
int rc = decode_common<A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, HALO_D_OPT>(a, &r);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_decode_h256_gqa6_bf16kv(&r, (hipStream_t)s);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_attn_decode_h256_fp8v4(const RadArgs* a, RadStream s) {
|
||||
if (check_dims_once() != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
HaloArgs r;
|
||||
int rc = decode_common<A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, HALO_D_OPT>(a, &r, 400);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_decode_h256_gqa6_fp8v4kv(&r, (hipStream_t)s);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_attn_decode_h256_k6v4(const RadArgs* a, RadStream s) {
|
||||
if (check_dims_once() != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
HaloArgs r;
|
||||
int rc = decode_common<A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, HALO_D_OPT>(a, &r, 352);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return halo_attn_decode_h256_gqa6_k6v4kv(&r, (hipStream_t)s);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/* Derived from libr4d/r4d_attn_paged_h256_gqa6_bs4.hip by the libhalo rename transform
|
||||
* (2026-10-26); see libhalo/README.md. */
|
||||
// Halo attention at six queries per KV head, head_dim 256, KV page of FOUR tokens: the TP4 leg of
|
||||
// Qwen3.8-Flash-Next's sparse (QSA) attention, where a four-rank world gives a rank the gqa12
|
||||
// geometry's ratio halved (12 query heads over 2 KV heads). Geometry only;
|
||||
// halo_attn_paged_gqa8.hip is the body. Everything but the page size is the gqa12 unit's, and the
|
||||
// rows state block_size 4.
|
||||
//
|
||||
// gfx1151: both bands -- the split-KV decode leg comes from the generic body too.
|
||||
#define HALO_ATTN_GQA 6
|
||||
#define HALO_ATTN_H128 0
|
||||
#define G8_BLOCK_SIZE 4
|
||||
#define HALO_ATTN_V4 1
|
||||
// The fused gate+quantise rows beside its unfused pair (attn_paged_gate_quant).
|
||||
#define HALO_ATTN_GQ 1
|
||||
|
||||
#include "halo_attn_paged_gqa8.hip"
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,934 @@
|
||||
/* Derived from libr4d/r4d_attn_prefill_h256_gqa6.hip by the libhalo rename transform
|
||||
* (2026-10-26), then ported to gfx1151; see libhalo/README.md and libhalo/halo_dt16.h. */
|
||||
// Halo prefill. Transposed core: S^T = K.Q^T, one lane owns one query row, ROWS = 16*NWARPS,
|
||||
// 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 halo_dt16.h for why).
|
||||
//
|
||||
// gfx1151 port of libr4d's body. The score fragment keeps its COLUMN on (lane & 15) -- the query --
|
||||
// exactly as on gfx1201, so the softmax state, the swap16 row reductions and the whole control flow
|
||||
// are unchanged. What moves is the ROW: on gfx12 a lane's accumulator element e is key
|
||||
// 8*half + e of the sixteen-key tile, on gfx11 it is key 2*e + half. Four sites change:
|
||||
//
|
||||
// gather one 32-byte read of the whole sixteen-value k run, with no 8*half term (both the
|
||||
// O_CONTIG and the split map collapse into this one form);
|
||||
// mask key = kbase + 2e + half;
|
||||
// P the WMMA's A operand wants the sixteen keys in order, so the two parities are
|
||||
// assembled across the half-pair (halo_dt16.h's p16w);
|
||||
// store element e is head dim 2e + half, so each lane scatters its eight values.
|
||||
//
|
||||
// Two gfx1151 facts the gfx12 body had no use for, both probed on the part (a 16x16x16 WMMA with
|
||||
// garbage planted in chosen lanes): the low half-wave computes D's even rows from its own lanes'
|
||||
// A and B, the high half the odd rows from theirs. So B must be replicated in both halves, but A
|
||||
// row r is read only from lane r (r even) or 16 + r (r odd). Two uses:
|
||||
//
|
||||
// QX at head_dim 256 the query is held once, not twice (see QX below): the query and the
|
||||
// accumulator no longer fill the whole register file, and the m-tile loop stops
|
||||
// re-reading ~70 spilled query VGPRs from scratch every sixteen keys.
|
||||
// arow a lane reads A's row (c & ~1) | half, the row its lane pair's target needs: the pair
|
||||
// reads one address (an LDS broadcast), so a fragment costs 512 bytes of LDS bandwidth
|
||||
// rather than 1 KB (QX's per-half dims would otherwise make the halves' reads distinct).
|
||||
//
|
||||
// O_QK8 and O_PV8 run Q.K^T and P.V over e4m3 operands, which gfx1201 does as an fp8 WMMA and
|
||||
// gfx1151 has no instruction for (halo_fp8_wmma.h). They are EMULATED here instead of dropped:
|
||||
// every operand is rounded to e4m3 exactly as the gfx12 leg rounds it, then widened back to the
|
||||
// f16 the WMMA takes. e4m3 has 3 mantissa bits, so the widening is exact and each product is
|
||||
// representable in f16 (<= 8 significand bits), which makes this the same arithmetic the fp8 WMMA
|
||||
// did -- the same loss, to the last rounding, and no loss of its own.
|
||||
//
|
||||
// QK8 Q rounded to e4m3 once at load, after the folded scale (the gfx12 site, moved from the
|
||||
// pk_fp8x4 there to halo_qcvt's E8 path here). K needs no rounding over the fp8 and fp8_v4
|
||||
// caches, whose K bytes ARE e4m3 and whose exact staging already holds those values; over
|
||||
// k6_v4, whose K is int6, the widen-then-round-once the byte staging does is applied at
|
||||
// the f16 staging instead (storeK).
|
||||
// PV8 P rounded to e4m3 from the f32 the softmax produced (pk_fp8x4's rounding), and V rounded
|
||||
// to e4m3 where the staging widens it with a scale (fp8_v4/k6_v4's int4 -> f16 * group
|
||||
// scale -> e4m3); the fp8 cache's V bytes are already e4m3. GROW is 8 octaves (e4m3's
|
||||
// largest value is 448 = 2^8.8) and DOT2 is off, both as in libr4d.
|
||||
//
|
||||
// The cost against the exact row is the rounding (the row's own accuracy, measured by the
|
||||
// selftest) and one e4m3 encode + decode per operand value; the WMMA count is unchanged, so the
|
||||
// leg buys no speed on this part, where the exact row already runs the same 16-bit WMMA.
|
||||
//
|
||||
// Each option below can be turned off on its own after a geometry change:
|
||||
//
|
||||
// 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. gfx1151 has no bf16 convert either; 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. On
|
||||
// gfx1151 the gather reads the lane's whole sixteen-value run either way; the bit is kept
|
||||
// in the option masks because the launchers still carry it, and it selects the padded row
|
||||
// stride (the 32-byte reads want it).
|
||||
// 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/KLATE tile staging; see each define.
|
||||
// QK8/PV8 Lossy e4m3 legs, emulated on the f16 WMMA (see the header).
|
||||
#include "halo.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_dt16.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
#define O_F16 1
|
||||
#define O_MSKIP 2
|
||||
#define O_QK8 32
|
||||
#define O_PV8 64
|
||||
#define O_FOLDQ 8
|
||||
#define O_CONTIG 512
|
||||
#define O_PF2 1024
|
||||
#define O_PF4 2048
|
||||
#define O_PF8 3072
|
||||
#define O_SGB 4096
|
||||
#define O_DOT2 16384
|
||||
// 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 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 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() (lds_barrier() in halo_common.h). The
|
||||
// default fence invalidates the vector cache twice per tile, though only LDS needs ordering.
|
||||
#define O_LDSB 2097152
|
||||
// KLATE: on the fp8 and k6_v4 caches (the wide K fetch), tile ti+1's K is fetched once tile ti's
|
||||
// last m-tile has its scores (its K fragments are dead there, so kreg adds no live range across the
|
||||
// WMMAs), and the staging between the barriers only widens and stores. Otherwise every wave of the
|
||||
// workgroup (the only one on its WGP) waits out a global round trip each tile.
|
||||
#define O_KLATE 4194304
|
||||
// O_V4: the fp8_v4 cache, O_V4 | O_K6 the k6_v4 cache (they share the int4 V layout; K6 adds the
|
||||
// int6 K one).
|
||||
#define O_V4 33554432
|
||||
#define O_K6 67108864
|
||||
|
||||
// One f32 through an e4m3 round trip: the value an e4m3 code holds after pk_fp8x4's rounding.
|
||||
__device__ __forceinline__ float halo_e4m3_rt(float x) {
|
||||
return halo_fp8::e4m3(halo_fp8::f32_to_e4m3(x));
|
||||
}
|
||||
|
||||
// Four f16 dwords (eight values) through the same round trip in place -- the lossy legs' rounding
|
||||
// of an operand the staging has already widened into f16.
|
||||
template<class D>
|
||||
__device__ __forceinline__ void halo_e4m3_rt4(uint32_t w4[4]) {
|
||||
typedef _Float16 h2 __attribute__((ext_vector_type(2)));
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
const h2 v = __builtin_bit_cast(h2, w4[q]);
|
||||
w4[q] = D::pk(halo_e4m3_rt((float)v[0]), halo_e4m3_rt((float)v[1]));
|
||||
}
|
||||
}
|
||||
|
||||
// Eight e4m3 bytes to four 16-bit dwords in element order: fp8x8_to_16x4w's result, cheaper in
|
||||
// the f16 format. A byte's magnitude bits moved to f16 bits 14..7 read as 2^-8 times the e4m3 value
|
||||
// (exponent bias 15 against 7; e4m3 subnormals land on f16 subnormals of the same mantissa), the
|
||||
// sign goes to bit 15, and one packed multiply by 256 scales both values exactly. About 2.5 VALU a
|
||||
// value against ~12 for the f32 route, and bit-identical to it on all 256 codes (checked on the
|
||||
// part), the NaN codes included (+-480, as halo_fp8::e4m3 decodes them).
|
||||
template<class D, int F16>
|
||||
__device__ __forceinline__ void halo_fp8x8_w4(uint2 raw, uint32_t w4[4]) {
|
||||
if constexpr (!F16) {
|
||||
fp8x8_to_16x4w<D>(raw, w4);
|
||||
} else {
|
||||
typedef _Float16 h2 __attribute__((ext_vector_type(2)));
|
||||
const h2 k256 = { (_Float16)256.0f, (_Float16)256.0f };
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
const uint32_t w = q ? raw.y : raw.x;
|
||||
const uint32_t m = w & 0x7F7F7F7Fu, sg = w & 0x80808080u;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 2; ++j) {
|
||||
// Bytes 2j and 2j+1: magnitudes to bits 0-7 and 16-23, signs to bytes 1 and 3
|
||||
// (perm selector 0x0c is a zero byte).
|
||||
const uint32_t lo = 0x0c000c00u | (uint32_t)(2 * j) | ((uint32_t)(2 * j + 1) << 16);
|
||||
const uint32_t hi = 0x000c000cu | ((uint32_t)(2 * j) << 8) | ((uint32_t)(2 * j + 1) << 24);
|
||||
const uint32_t n = (__builtin_amdgcn_perm(0u, m, lo) << 7) |
|
||||
__builtin_amdgcn_perm(0u, sg, hi);
|
||||
w4[2 * q + j] = __builtin_bit_cast(uint32_t, __builtin_bit_cast(h2, n) * k256);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A fragment with its two half-waves exchanged: lane L takes lane L ^ 16's eight dwords.
|
||||
template<class D>
|
||||
__device__ __forceinline__ typename D::frag halo_swap16_frag(typename D::frag f) {
|
||||
union { typename D::frag f; uint32_t u[8]; } x;
|
||||
x.f = f;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
// v_permlanex16 with identity selectors, as swap16. Its `old` operand is never read (every
|
||||
// lane is active and has a partner). Left undefined, the destination needs no prior copy of
|
||||
// the source, which passing the source as `old` costs (one v_mov a dword); a defined value
|
||||
// (even __builtin_nondeterministic_value) is materialised the same way.
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wuninitialized"
|
||||
int old;
|
||||
x.u[i] = (uint32_t)__builtin_amdgcn_permlanex16(old, (int)x.u[i], 0x76543210u,
|
||||
0xFEDCBA98u, false, false);
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
return x.f;
|
||||
}
|
||||
|
||||
// bf16 dword -> 16-bit dword in the target format, optionally scaled. Used once per kernel on Q.
|
||||
// E8 rounds each value once to e4m3 first (the QK8 leg's query operand).
|
||||
template<class D, int FOLDQ, int F16, int E8 = 0>
|
||||
__device__ __forceinline__ uint32_t halo_qcvt(uint32_t w, float s) {
|
||||
const float lo = __builtin_bit_cast(float, w << 16);
|
||||
const float hi = __builtin_bit_cast(float, w & 0xffff0000u);
|
||||
if (E8) return D::pk(halo_e4m3_rt(FOLDQ ? lo * s : lo), halo_e4m3_rt(FOLDQ ? hi * s : hi));
|
||||
if (!FOLDQ) return F16 ? D::from_bf16w(w) : w;
|
||||
return D::pk(lo * s, hi * s);
|
||||
}
|
||||
|
||||
// ---- the split-KV law (the launch side is at the end of this file) ----------------------------
|
||||
#define HALO_P_SLOTS 20 // workgroups resident at once: one 24-wave workgroup a WGP
|
||||
#define HALO_P_UNITS_MAX 160 // grids this large lose < 1/8 to the last round: never split
|
||||
#define HALO_P_MIN_TILES 4 // tiles a split walks at least
|
||||
#define HALO_P_MAX_SPLIT 64
|
||||
#define HALO_P_OVH_TILES 4 // a split's fixed cost (query load, partial, merge), in tiles
|
||||
#define HALO_P_SCRATCH_MAX (64LL << 20)
|
||||
|
||||
// Bytes of one split's partials: f32 O plus (m, l) per (token, q head).
|
||||
static inline long long halo_prefill_split_bytes(long long q_total, long long q_heads, int head_dim) {
|
||||
return q_total * q_heads * (long long)(head_dim + 2) * 4LL;
|
||||
}
|
||||
|
||||
// The split law: the count that minimises (rounds of HALO_P_SLOTS workgroups) x (tiles a
|
||||
// workgroup walks + its fixed cost), taking a larger count only for a 3 % gain, and keeping the
|
||||
// partials under HALO_P_SCRATCH_MAX.
|
||||
// The kernel reruns it per workgroup on the tile count it really walks (the host knows only
|
||||
// max_ctx), so a short context does not pay for partials it does not need.
|
||||
__host__ __device__ inline int halo_prefill_splits(int units, int tiles, long long per_split) {
|
||||
if (units <= 0 || units >= HALO_P_UNITS_MAX || tiles < 2 * HALO_P_MIN_TILES) return 1;
|
||||
int smax = tiles / HALO_P_MIN_TILES;
|
||||
if (smax > HALO_P_MAX_SPLIT) smax = HALO_P_MAX_SPLIT;
|
||||
if (per_split > 0 && HALO_P_SCRATCH_MAX / per_split < smax) smax = (int)(HALO_P_SCRATCH_MAX / per_split);
|
||||
int best = 1;
|
||||
float best_cost = (float)((units + HALO_P_SLOTS - 1) / HALO_P_SLOTS) *
|
||||
(float)(tiles + HALO_P_OVH_TILES);
|
||||
for (int s = 2; s <= smax; ++s) {
|
||||
const float rounds = (float)((units * s + HALO_P_SLOTS - 1) / HALO_P_SLOTS);
|
||||
const float cost = rounds * ((float)tiles / (float)s + (float)HALO_P_OVH_TILES);
|
||||
if (cost < 0.97f * best_cost) { best_cost = cost; best = s; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// 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 halo_attn_prefill_kernel(const HaloArgs a)
|
||||
{
|
||||
constexpr int F16 = (OPT & O_F16) ? 1 : 0;
|
||||
constexpr int MSKIP = (OPT & O_MSKIP) ? 1 : 0;
|
||||
constexpr int FOLDQ = (OPT & O_FOLDQ) ? 1 : 0;
|
||||
constexpr int CTG = (OPT & O_CONTIG) ? 1 : 0;
|
||||
constexpr int PF = 1 << ((OPT >> 10) & 3);
|
||||
constexpr int SGB = (OPT & O_SGB) ? 1 : 0;
|
||||
constexpr int QK8 = ((OPT & O_QK8) && !KVP) ? 1 : 0;
|
||||
constexpr int PV8 = ((OPT & O_PV8) && !KVP) ? 1 : 0;
|
||||
static_assert(!(OPT & (O_QK8 | O_PV8)) || !KVP,
|
||||
"the e4m3 legs need an 8-bit cache, or they compile to the exact form");
|
||||
static_assert(!(QK8 || PV8) || F16, "the e4m3 legs emulate on the f16 operand format");
|
||||
// PV8 keeps the denominator on the f32 p values the softmax formed (libr4d's choice): with
|
||||
// DOT2 on it would sum the rounded e4m3 ones.
|
||||
constexpr int DOT2 = ((OPT & O_DOT2) && (OPT & O_F16) && !PV8) ? 1 : 0;
|
||||
constexpr int BTS = (OPT & O_BTS) ? 1 : 0;
|
||||
constexpr int V4 = ((OPT & O_V4) && !KVP) ? 1 : 0;
|
||||
constexpr int K6 = ((OPT & O_K6) && V4) ? 1 : 0;
|
||||
// A token's row in a page, and where in it V's codes, V's scales and K's scales start.
|
||||
constexpr int ROWB = K6 ? HEAD_DIM * 22 / 16 : V4 ? HEAD_DIM * 25 / 16 : 2 * HEAD_DIM;
|
||||
constexpr int VOFF = K6 ? HEAD_DIM * 3 / 4 : HEAD_DIM;
|
||||
constexpr int VSOFF = K6 ? HEAD_DIM * 21 / 16 : HEAD_DIM * 3 / 2;
|
||||
constexpr int KSOFF = HEAD_DIM * 5 / 4;
|
||||
constexpr int GPREV = (OPT & O_GPREV) ? 1 : 0;
|
||||
constexpr int LDSB = (OPT & O_LDSB) ? 1 : 0;
|
||||
constexpr int KWIDE = (OPT & O_KWIDE) ? 1 : 0;
|
||||
// fp8_v4 takes none of the three (KLATE, the assume, the scale pack): they gain at 100k but lose
|
||||
// 3-7 % at 25k and 50k.
|
||||
constexpr int OLDV4 = V4 && !K6;
|
||||
constexpr int KLATE = ((OPT & O_KLATE) && KWIDE && !KVP && !OLDV4) ? 1 : 0;
|
||||
typedef DT16<F16> D;
|
||||
typedef typename D::frag frag16;
|
||||
|
||||
// QX (head_dim 256): the query is held once, not twice. A B operand is replicated in both
|
||||
// half-waves, but each half only multiplies its own copy (header), so register i carries
|
||||
// fragment 2i in the low half and 2i+1 in the high one: one WMMA contracts each half against
|
||||
// its own fragment, a second against the half-swapped copy (eight v_permlanex16), with K read
|
||||
// at the matching dims per half. Q drops from 128 to 64 VGPRs; beside the 128-VGPR accumulator
|
||||
// the full query left ~90 spill slots, re-read from scratch every m-tile. The Q.K^T loop takes
|
||||
// its K fragments a pair at a time here; PF still sets the P.V loop's.
|
||||
constexpr int QX = (HEAD_DIM >= 256) ? 1 : 0;
|
||||
constexpr int NQF = QX ? HEAD_DIM / 32 : HEAD_DIM / 16; // query registers
|
||||
|
||||
constexpr int ROWS = NWARPS * 16;
|
||||
constexpr int BLOCK_Q = ROWS / GQA;
|
||||
constexpr int NKS = HEAD_DIM / 16;
|
||||
constexpr int MT = TILE / 16;
|
||||
// Row strides padded by 8 shorts: 32-byte-aligned enough for the 16-byte gather pairs, and off
|
||||
// the bank period.
|
||||
constexpr int KSTR = HEAD_DIM + 8;
|
||||
constexpr int VSTR = TILE + 8;
|
||||
constexpr int NTHR = NWARPS * 32;
|
||||
constexpr int NB = TILE / BS; // block-table entries per tile
|
||||
constexpr int KEL = KWIDE ? 16 : 8; // K elements fetched per thread-pass
|
||||
constexpr int KITEMS = TILE * (HEAD_DIM / KEL); // K passes needed for one tile
|
||||
constexpr int KPASS = (KITEMS + NTHR - 1) / NTHR; // passes per thread
|
||||
constexpr int KREGS = KPASS * (KVP ? 2 : 1); // uint4 of raw K per thread
|
||||
constexpr int NTR = (TILE / 8) * (HEAD_DIM / (KVP ? 32 : 64));
|
||||
constexpr int VREGS = (NTR + NWARPS - 1) / NWARPS; // uint4 of raw V per thread
|
||||
constexpr float PSHIFT = D::SHIFT;
|
||||
constexpr float PGROW = PV8 ? 8.0f : D::GROW; // e4m3 max is 448 = 2^8.8
|
||||
static_assert(!KWIDE || KPASS == 1, "the wide K fetch is one straight-line pass");
|
||||
static_assert(!K6 || KWIDE, "k6_v4 K is staged sixteen dims a thread");
|
||||
|
||||
__shared__ __align__(16) uint16_t sK[TILE * KSTR];
|
||||
__shared__ __align__(16) uint16_t sV16[HEAD_DIM * VSTR];
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
// The launch is NTHR threads. Stated, so the wide K fetch's `key >= TILE` test (never true:
|
||||
// KITEMS == NTHR) folds: as a branch its join made the compiler wait on every load in flight right
|
||||
// after the K fetch, the V stores' cover included.
|
||||
if constexpr (!OLDV4) __builtin_assume(tid < NTHR);
|
||||
const int c = lane & 15, h = lane >> 4;
|
||||
// The A-operand row this lane reads: its lane pair's target row (header), so both lanes of the
|
||||
// pair read one address.
|
||||
const int arow = (c & ~1) | h;
|
||||
|
||||
// Split-KV (a.splits > 1, partials in a.scratch): grid.z is sequence-major over the splits, and
|
||||
// split sp walks its share of the workgroup's tile range, then writes its unnormalised O and its
|
||||
// (m, l) for halo_attn_prefill_merge to combine. One split is the plain kernel.
|
||||
const int nsplit = (a.splits > 1 && a.scratch) ? a.splits : 1;
|
||||
const int qb = blockIdx.x, kvh = blockIdx.y;
|
||||
const int seq = (int)blockIdx.z / nsplit, sp = (int)blockIdx.z - seq * nsplit;
|
||||
const int ctx = a.seqused_k[seq];
|
||||
|
||||
// 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 = halo_q_off(a.cu_q, seq, a.q_len);
|
||||
const int qlen = halo_q_len(a.cu_q, seq, a.q_len);
|
||||
if (qb * BLOCK_Q >= qlen) return;
|
||||
|
||||
const int row = warp * 16 + c;
|
||||
const int qi = row / GQA, hi = row - qi * GQA;
|
||||
const int qpos = qb * BLOCK_Q + qi;
|
||||
const bool live = (qpos < qlen);
|
||||
const int qrow = live ? qpos : (qlen - 1);
|
||||
const int qhead = kvh * GQA + hi;
|
||||
const size_t qtot = (size_t)halo_q_total(a);
|
||||
// Where this split's partial row lives: O as f32 [split][token][q_head][HEAD_DIM], then (m, l)
|
||||
// as f32 pairs [split][token][q_head].
|
||||
float* const pO = (float*)a.scratch
|
||||
+ (((size_t)sp * qtot + qoff + qpos) * a.q_heads + qhead) * HEAD_DIM;
|
||||
float* const pML = (float*)a.scratch + (size_t)nsplit * qtot * a.q_heads * HEAD_DIM
|
||||
+ (((size_t)sp * qtot + qoff + qpos) * a.q_heads + qhead) * 2;
|
||||
if (ctx <= 0) {
|
||||
// The plain kernel leaves these rows untouched; a negative l tells the merge to as well.
|
||||
if (nsplit > 1 && sp == 0 && live && h == 0) pML[1] = -1.0f;
|
||||
return;
|
||||
}
|
||||
// Warps whose sixteen rows are all past the sequence's queries only stage tiles (their rows
|
||||
// are never stored): at a short q_len most of the workgroup's WMMAs were for nothing.
|
||||
const bool wdead = __builtin_amdgcn_readfirstlane(qb * BLOCK_Q + (warp * 16) / GQA) >= qlen;
|
||||
|
||||
const int* __restrict__ bt = a.block_table + (size_t)seq * a.max_blocks;
|
||||
|
||||
const float kdesc = a.k_descale ? a.k_descale[seq * a.kv_heads + kvh] : 1.0f;
|
||||
const float vdesc = a.v_descale ? a.v_descale[seq * a.kv_heads + kvh] : 1.0f;
|
||||
const float mul = a.scale * kdesc * 1.44269504089f;
|
||||
|
||||
// gfx1151: a lane holds the whole sixteen-value k run of its query row, so the fragment is one
|
||||
// 32-byte read with no lane-half term (the O_CONTIG and split gathers are the same read here).
|
||||
frag16 qf[NQF];
|
||||
{
|
||||
const uint16_t* qp = (const uint16_t*)a.q
|
||||
+ ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NQF; ++i) {
|
||||
const int t = QX ? 2 * i + h : i; // QX: fragment 2i + h in this half
|
||||
const uint4 u0 = *(const uint4*)(qp + 16 * t);
|
||||
const uint4 u1 = *(const uint4*)(qp + 16 * t + 8);
|
||||
const uint32_t w8[8] = { halo_qcvt<D, FOLDQ, F16, QK8>(u0.x, mul),
|
||||
halo_qcvt<D, FOLDQ, F16, QK8>(u0.y, mul),
|
||||
halo_qcvt<D, FOLDQ, F16, QK8>(u0.z, mul),
|
||||
halo_qcvt<D, FOLDQ, F16, QK8>(u0.w, mul),
|
||||
halo_qcvt<D, FOLDQ, F16, QK8>(u1.x, mul),
|
||||
halo_qcvt<D, FOLDQ, F16, QK8>(u1.y, mul),
|
||||
halo_qcvt<D, FOLDQ, F16, QK8>(u1.z, mul),
|
||||
halo_qcvt<D, FOLDQ, F16, QK8>(u1.w, mul) };
|
||||
qf[i] = D::mk(w8);
|
||||
}
|
||||
}
|
||||
|
||||
const int klimit = ctx - qlen + qpos;
|
||||
// First key in this row's window, floored at zero. Same formula as the decode unit's window
|
||||
// floor.
|
||||
int wlo = (WIN && a.window > 0) ? (ctx - qlen + qpos - a.window + 1) : 0;
|
||||
if (WIN && a.window > 0 && wlo < 0) wlo = 0;
|
||||
|
||||
float m_ref = -3.0e38f;
|
||||
float off = PSHIFT + 3.0e38f;
|
||||
float l_i = 0.0f;
|
||||
v8f acc[NKS];
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NKS; ++t) acc[t] = (v8f){0,0,0,0,0,0,0,0};
|
||||
|
||||
const int qmax_cta = min(qb * BLOCK_Q + BLOCK_Q - 1, qlen - 1);
|
||||
const int klimit_cta = ctx - qlen + qmax_cta;
|
||||
const int ntiles_cta = (min(klimit_cta + 1, ctx) + TILE - 1) / TILE;
|
||||
// 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_cta = (WIN && a.window > 0 && wlo0 > 0) ? (wlo0 / TILE) : 0;
|
||||
// The host sized the split from max_ctx, a bound; the walk this workgroup really has decides
|
||||
// how many splits it uses: ne, the split law at its real tile count. Splits past ne only
|
||||
// say they are empty (m at its floor, l = 0, which the merge skips without reading O); with
|
||||
// ne == 1 split 0 stores the output itself and tells the merge to leave the row (l < 0).
|
||||
// Split sp walks its contiguous share of [tstart_cta, ntiles_cta).
|
||||
const int nt_cta = max(ntiles_cta - tstart_cta, 0);
|
||||
const int ne = (nsplit > 1)
|
||||
? min(nsplit, halo_prefill_splits((int)(gridDim.x * gridDim.y) * a.num_seqs, nt_cta, 0)) : 1;
|
||||
if (sp >= ne) {
|
||||
if (ne > 1 && live && h == 0) { pML[0] = -3.0e38f; pML[1] = 0.0f; }
|
||||
return;
|
||||
}
|
||||
const int tstart = tstart_cta + (int)(((long)nt_cta * sp) / ne);
|
||||
const int ntiles = tstart_cta + (int)(((long)nt_cta * (sp + 1)) / ne);
|
||||
|
||||
// ---- 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];
|
||||
|
||||
// ---- fp8_v4 / k6_v4: V is int4 in groups of 32 with an f16 scale (absmax / 7): 16 bytes of
|
||||
// codes a group at VOFF (dim d at bits 4*(d%8) of word d/8), the group scales at VSOFF. A thread
|
||||
// stages one key pair's 8 dims: two code words and the pair's scale, fetched a tile ahead like
|
||||
// GPREV's V, so the loads are in flight across the m-tile loop. They widen into sV16 ([dim][key])
|
||||
// as a dword per dim holding both keys: with u = code ^ 8 (offset binary), 0x6400 | u is the f16
|
||||
// 1024 + u, so (x - 1032) * s is the value times s, rounded once. Key pairs run fastest across
|
||||
// lanes, which keeps the dword stores of one dim row in distinct banks.
|
||||
static_assert(!V4 || F16, "fp8_v4 widens V to f16");
|
||||
constexpr int NP4 = (TILE / 2) * (HEAD_DIM / 8);
|
||||
constexpr int U4 = V4 ? (NP4 + NTHR - 1) / NTHR : 1;
|
||||
// The pair's two scales stay apart until storeV4 packs them: packed here, the prefetch a tile
|
||||
// ahead would be waited on right after it is issued (fp8_v4 packs here, see KLATE).
|
||||
uint32_t v4c[U4][2], v4s[U4][2];
|
||||
auto fetchV4 = [&](int k0, const int* blks) {
|
||||
#pragma unroll
|
||||
for (int r = 0; r < U4; ++r) {
|
||||
const int u = tid + r * NTHR;
|
||||
if (NP4 % NTHR == 0 || u < NP4) {
|
||||
const int kp = u % (TILE / 2), o = u / (TILE / 2);
|
||||
uint32_t sc[2];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 2; ++j) {
|
||||
const int kk = min(k0 + 2 * kp + j, ctx - 1);
|
||||
const int bk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS];
|
||||
const uint8_t* base = (const uint8_t*)a.kv + (size_t)bk * a.kv_block_stride
|
||||
+ (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB;
|
||||
v4c[r][j] = *(const uint32_t*)(base + VOFF + o * 4);
|
||||
sc[j] = *(const uint16_t*)(base + VSOFF + (o >> 2) * 2);
|
||||
}
|
||||
if constexpr (OLDV4) { v4s[r][0] = sc[0] | (sc[1] << 16); v4s[r][1] = 0; }
|
||||
else { v4s[r][0] = sc[0]; v4s[r][1] = sc[1]; }
|
||||
}
|
||||
}
|
||||
};
|
||||
auto storeV4 = [&]() {
|
||||
typedef _Float16 h2 __attribute__((ext_vector_type(2)));
|
||||
#pragma unroll
|
||||
for (int r = 0; r < U4; ++r) {
|
||||
const int u = tid + r * NTHR;
|
||||
if (NP4 % NTHR == 0 || u < NP4) {
|
||||
const int kp = u % (TILE / 2), o = u / (TILE / 2);
|
||||
// Codes are two's complement nibbles; ^ 8 makes them offset binary (value + 8).
|
||||
const uint32_t n0 = (v4c[r][0] & 0x0F0F0F0Fu) ^ 0x08080808u;
|
||||
const uint32_t m0 = ((v4c[r][0] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
|
||||
const uint32_t n1 = (v4c[r][1] & 0x0F0F0F0Fu) ^ 0x08080808u;
|
||||
const uint32_t m1 = ((v4c[r][1] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
|
||||
const h2 s2 = __builtin_bit_cast(h2, OLDV4 ? v4s[r][0] : (v4s[r][0] | (v4s[r][1] << 16)));
|
||||
const h2 bias = { (_Float16)1032.0f, (_Float16)1032.0f };
|
||||
uint16_t* dst = &sV16[(o * 8) * VSTR + 2 * kp];
|
||||
#pragma unroll
|
||||
for (int b = 0; b < 4; ++b) {
|
||||
// Byte b of the first key's word low, of the second key's word in the high half:
|
||||
// perm selects source bytes 0-3 from its second operand, 4-7 from its first,
|
||||
// and 0x0c is a zero byte.
|
||||
const uint32_t sel = (uint32_t)b | 0x0c00u | ((uint32_t)(4 + b) << 16) | 0x0c000000u;
|
||||
const uint32_t lo = __builtin_amdgcn_perm(n1, n0, sel) | 0x64006400u; // dim 2b
|
||||
const uint32_t hi = __builtin_amdgcn_perm(m1, m0, sel) | 0x64006400u; // dim 2b+1
|
||||
const h2 vl = (__builtin_bit_cast(h2, lo) - bias) * s2;
|
||||
const h2 vh = (__builtin_bit_cast(h2, hi) - bias) * s2;
|
||||
if constexpr (PV8) {
|
||||
// V as e4m3 bytes on gfx12: the widened value, rounded once
|
||||
*(uint32_t*)(dst + (2 * b) * VSTR) =
|
||||
D::pk(halo_e4m3_rt((float)vl[0]), halo_e4m3_rt((float)vl[1]));
|
||||
*(uint32_t*)(dst + (2 * b + 1) * VSTR) =
|
||||
D::pk(halo_e4m3_rt((float)vh[0]), halo_e4m3_rt((float)vh[1]));
|
||||
} else {
|
||||
*(uint32_t*)(dst + (2 * b) * VSTR) = __builtin_bit_cast(uint32_t, vl);
|
||||
*(uint32_t*)(dst + (2 * b + 1) * VSTR) = __builtin_bit_cast(uint32_t, vh);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
auto fetchK = [&](int k0, const int* blks) {
|
||||
#pragma unroll
|
||||
for (int p = 0; p < KPASS; ++p) {
|
||||
const int i = tid + p * NTHR;
|
||||
if (KITEMS % NTHR == 0 || i < KITEMS) {
|
||||
const int key = KWIDE ? (2 * (i >> 5) + (i & 1)) : (i / (HEAD_DIM / KEL));
|
||||
const int ch = KWIDE ? ((i & 31) >> 1) : (i - key * (HEAD_DIM / KEL));
|
||||
if (KWIDE && key >= TILE) continue;
|
||||
const int kk = min(k0 + key, ctx - 1);
|
||||
const int blk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS];
|
||||
const size_t o = (size_t)blk * a.kv_block_stride
|
||||
+ (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB;
|
||||
if (KVP) {
|
||||
const uint16_t* g = (const uint16_t*)a.kv + o + ch * KEL;
|
||||
#pragma unroll
|
||||
for (int q = 0; q < (KVP ? (KEL / 8) : 1); ++q)
|
||||
kreg[p * (KEL / 8) + q] = *(const uint4*)(g + 8 * q);
|
||||
} else if (K6) {
|
||||
// k6_v4: the chunk's sixteen low nibbles, its high-bit word, its group's scale.
|
||||
const uint8_t* rp = (const uint8_t*)a.kv + o;
|
||||
const uint2 lo = *(const uint2*)(rp + ch * 8);
|
||||
kreg[p] = make_uint4(lo.x, lo.y, *(const uint32_t*)(rp + HEAD_DIM / 2 + ch * 4),
|
||||
*(const uint16_t*)(rp + KSOFF + (ch >> 1) * 2));
|
||||
} else if (KWIDE) {
|
||||
kreg[p] = *(const uint4*)((const uint8_t*)a.kv + o + ch * 16);
|
||||
} else {
|
||||
const uint2 r = *(const uint2*)((const uint8_t*)a.kv + o + ch * 8);
|
||||
kreg[p] = make_uint4(r.x, r.y, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
auto fetchV = [&](int k0, const int* blks) {
|
||||
#pragma unroll
|
||||
for (int r = 0; r < VREGS; ++r) {
|
||||
const int idx = warp + r * NWARPS;
|
||||
if (NTR % NWARPS == 0 || idx < NTR) {
|
||||
constexpr int DG = HEAD_DIM / (KVP ? 32 : 64);
|
||||
const int kg = idx / DG, dg = idx - kg * DG;
|
||||
const int kk = min(k0 + kg * 8 + vj, ctx - 1);
|
||||
const int d0 = dg * (KVP ? 32 : 64) + vg * (KVP ? 8 : 16);
|
||||
const int blk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS];
|
||||
const size_t o = (size_t)blk * a.kv_block_stride
|
||||
+ (size_t)kvh * a.kv_head_stride
|
||||
+ (size_t)(kk % BS) * ROWB + HEAD_DIM + d0;
|
||||
const void* p = KVP ? (const void*)((const uint16_t*)a.kv + o)
|
||||
: (const void*)((const uint8_t*)a.kv + o);
|
||||
vreg[r] = __builtin_bit_cast(uint4, load_tr_b128(p));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
auto storeK = [&]() {
|
||||
#pragma unroll
|
||||
for (int p = 0; p < KPASS; ++p) {
|
||||
const int i = tid + p * NTHR;
|
||||
if (KITEMS % NTHR == 0 || i < KITEMS) {
|
||||
const int key = KWIDE ? (2 * (i >> 5) + (i & 1)) : (i / (HEAD_DIM / KEL));
|
||||
const int ch = KWIDE ? ((i & 31) >> 1) : (i - key * (HEAD_DIM / KEL));
|
||||
if (KWIDE && key >= TILE) continue;
|
||||
uint16_t* kd = &sK[key * KSTR + ch * KEL];
|
||||
#pragma unroll
|
||||
for (int q = 0; q < KEL / 8; ++q) {
|
||||
uint32_t w4[4];
|
||||
if (KVP) {
|
||||
const uint4 r = kreg[p * (KEL / 8) + q];
|
||||
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 {
|
||||
const uint4 r = kreg[p];
|
||||
if constexpr (K6) {
|
||||
k6x8_to_f16x4w(q ? r.y : r.x, r.z, q, r.w | (r.w << 16), w4);
|
||||
// QK8 over k6_v4: the byte staging rounds the widened int6 to e4m3
|
||||
if constexpr (QK8) halo_e4m3_rt4<D>(w4);
|
||||
} else halo_fp8x8_w4<D, F16>(q ? make_uint2(r.z, r.w) : make_uint2(r.x, r.y), w4);
|
||||
}
|
||||
*(uint2*)(kd + 8 * q) = make_uint2(w4[0], w4[1]);
|
||||
*(uint2*)(kd + 8 * q + 4) = make_uint2(w4[2], w4[3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
auto storeV = [&]() {
|
||||
#pragma unroll
|
||||
for (int r = 0; r < VREGS; ++r) {
|
||||
const int idx = warp + r * NWARPS;
|
||||
if (NTR % NWARPS == 0 || idx < NTR) {
|
||||
constexpr int DG = HEAD_DIM / (KVP ? 32 : 64);
|
||||
const int kg = idx / DG, dg = idx - kg * DG;
|
||||
const int d0 = dg * (KVP ? 32 : 64) + vg * (KVP ? 8 : 16);
|
||||
const uint4 v = vreg[r];
|
||||
if (KVP) {
|
||||
uint16_t* dst = &sV16[(d0 + vj) * VSTR + kg * 8];
|
||||
*(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 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];
|
||||
halo_fp8x8_w4<D, F16>(make_uint2(lo0, lo1), wl);
|
||||
halo_fp8x8_w4<D, F16>(make_uint2(hi0, hi1), wh);
|
||||
uint16_t* a0 = &sV16[(d0 + 2 * vj) * VSTR + kg * 8];
|
||||
uint16_t* a1 = &sV16[(d0 + 2 * vj + 1) * VSTR + kg * 8];
|
||||
*(uint2*)(a0) = make_uint2(wl[0], wl[1]);
|
||||
*(uint2*)(a0 + 4) = make_uint2(wl[2], wl[3]);
|
||||
*(uint2*)(a1) = make_uint2(wh[0], wh[1]);
|
||||
*(uint2*)(a1 + 4) = make_uint2(wh[2], wh[3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 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) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NB; ++i) out[i] = bt[min(t0 + i, lastb)];
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NB; ++i) out[i] = bt[t0 + i];
|
||||
}
|
||||
};
|
||||
int blk[NB];
|
||||
// An empty split's tstart can lie past the context, where the clamped key would index blk
|
||||
// below its start: it fetches nothing.
|
||||
if (tstart < ntiles) {
|
||||
if (BTS) load_bt(tstart * NB, blk);
|
||||
if (GPREV) fetchV(tstart * TILE, blk);
|
||||
if (V4) fetchV4(tstart * TILE, blk);
|
||||
if (KLATE) fetchK(tstart * TILE, blk);
|
||||
}
|
||||
|
||||
for (int ti = tstart; ti < ntiles; ++ti) {
|
||||
const int k0 = ti * TILE;
|
||||
int blkn[NB];
|
||||
if (BTS && ti + 1 < ntiles) {
|
||||
load_bt((ti + 1) * NB, blkn);
|
||||
}
|
||||
if (LDSB) lds_barrier(); else __syncthreads();
|
||||
if (!KLATE) fetchK(k0, blk);
|
||||
// V first: already in registers.
|
||||
if constexpr (V4) { storeV4(); } else { if (!GPREV) fetchV(k0, blk); storeV(); }
|
||||
storeK();
|
||||
if (LDSB) lds_barrier(); else __syncthreads();
|
||||
// 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);
|
||||
if (V4 && ti + 1 < ntiles) fetchV4(k0 + TILE, blkn);
|
||||
|
||||
if (wdead && KLATE && ti + 1 < ntiles) fetchK(k0 + TILE, blkn);
|
||||
#pragma unroll 1
|
||||
for (int mt = 0; mt < (wdead ? 0 : MT); ++mt) {
|
||||
v8f s = (v8f){0,0,0,0,0,0,0,0};
|
||||
{
|
||||
// gfx1151: the A operand's row is the key and its element e is k = e, so this lane
|
||||
// reads the whole sixteen-dim run of key row arow -- no lane-half term.
|
||||
const uint16_t* krow = &sK[(mt * 16 + arow) * KSTR];
|
||||
if constexpr (QX) {
|
||||
// Register i is fragment 2i + h here and 2i + 1 - h in its swapped copy, and
|
||||
// each half reads its keys at the same dims, so the pair of WMMAs contracts all
|
||||
// 32 dims in both halves (the low half in order 2i, 2i+1, the high 2i+1, 2i).
|
||||
const uint16_t* kp0 = krow + 16 * h;
|
||||
const uint16_t* kp1 = krow + 16 * (1 - h);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NQF; ++i) {
|
||||
frag16 kb[2];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 2; ++j) {
|
||||
const uint16_t* kp = (j ? kp1 : kp0) + 32 * i;
|
||||
const uint4 u0 = *(const uint4*)kp;
|
||||
const uint4 u1 = *((const uint4*)kp + 1);
|
||||
const uint32_t w8[8] = { u0.x, u0.y, u0.z, u0.w,
|
||||
u1.x, u1.y, u1.z, u1.w };
|
||||
kb[j] = D::mk(w8);
|
||||
}
|
||||
const frag16 qs = halo_swap16_frag<D>(qf[i]);
|
||||
if (SGB) sched_barrier();
|
||||
s = D::wmma(kb[0], qf[i], s);
|
||||
s = D::wmma(kb[1], qs, s);
|
||||
}
|
||||
} else
|
||||
#pragma unroll
|
||||
for (int g = 0; g < NKS; g += PF) {
|
||||
frag16 kb[PF];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PF; ++j) {
|
||||
const uint16_t* kp = krow + 16 * (g + j);
|
||||
const uint4 u0 = *(const uint4*)kp;
|
||||
const uint4 u1 = *((const uint4*)kp + 1);
|
||||
const uint32_t w8[8] = { u0.x, u0.y, u0.z, u0.w,
|
||||
u1.x, u1.y, u1.z, u1.w };
|
||||
kb[j] = D::mk(w8);
|
||||
}
|
||||
if (SGB) sched_barrier();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PF; ++j) s = D::wmma(kb[j], qf[g + j], s);
|
||||
}
|
||||
}
|
||||
if (KLATE && mt == MT - 1 && ti + 1 < ntiles) fetchK(k0 + TILE, blkn);
|
||||
float sc[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) sc[e] = FOLDQ ? s[e] : s[e] * mul;
|
||||
|
||||
// gfx1151: element e of the score fragment is key 2e + (lane >> 4) of the tile.
|
||||
const int kbase = k0 + mt * 16;
|
||||
// Mask keys past klimit and, with WIN, before wlo. MSKIP skips tiles straddling neither.
|
||||
if (!MSKIP || wave_any(kbase + 15 > klimit) || (WIN && wave_any(kbase < wlo))) {
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int key = kbase + 2 * e + h;
|
||||
sc[e] = ((key <= klimit) && (!WIN || key >= wlo)) ? sc[e] : -INFINITY;
|
||||
}
|
||||
}
|
||||
|
||||
float smax = sc[0];
|
||||
#pragma unroll
|
||||
for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]);
|
||||
if (wave_any(smax > m_ref + PGROW)) {
|
||||
const float rmax = fmaxf(smax, swap16(smax));
|
||||
const float mnew = fmaxf(fmaxf(m_ref, rmax), -3.0e38f);
|
||||
const float alpha = ex2(m_ref - mnew);
|
||||
#pragma unroll
|
||||
for (int dt = 0; dt < NKS; ++dt)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) acc[dt][e] *= alpha;
|
||||
l_i *= alpha;
|
||||
m_ref = mnew;
|
||||
off = PSHIFT - mnew;
|
||||
}
|
||||
|
||||
float pf[8], lsum = 0.0f;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const float p = ex2(sc[e] + off);
|
||||
pf[e] = PV8 ? halo_e4m3_rt(p) : p;
|
||||
if (!DOT2) lsum += p;
|
||||
}
|
||||
if (!DOT2) l_i += lsum;
|
||||
|
||||
{
|
||||
uint32_t pw[4];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e += 2) pw[e >> 1] = D::pk(pf[e], pf[e + 1]);
|
||||
if (DOT2) {
|
||||
typedef __fp16 v2hf_attn __attribute__((ext_vector_type(2)));
|
||||
const v2hf_attn one = {(__fp16)1.0f, (__fp16)1.0f};
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 4; ++e)
|
||||
l_i = __builtin_amdgcn_fdot2(__builtin_bit_cast(v2hf_attn, pw[e]), one, l_i, false);
|
||||
}
|
||||
// The P fragment's element e is key e, but this lane's eight values are keys
|
||||
// 2e + (lane >> 4): interleave the half-pair's copies into key order.
|
||||
uint32_t pw16[8];
|
||||
p16w<D>(pw, pw16);
|
||||
const frag16 p16 = D::mk(pw16);
|
||||
// V^T is the A operand: its row is the head dim and element e is k = e, so each lane
|
||||
// reads the whole sixteen-key run of dim row arow.
|
||||
const uint16_t* vbase = &sV16[arow * VSTR + mt * 16];
|
||||
#pragma unroll
|
||||
for (int g = 0; g < NKS; g += PF) {
|
||||
frag16 vb[PF];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PF; ++j) {
|
||||
const uint16_t* vp = vbase + (g + j) * 16 * VSTR;
|
||||
const uint4 u0 = *(const uint4*)vp;
|
||||
const uint4 u1 = *((const uint4*)vp + 1);
|
||||
const uint32_t w8[8] = { u0.x, u0.y, u0.z, u0.w,
|
||||
u1.x, u1.y, u1.z, u1.w };
|
||||
vb[j] = D::mk(w8);
|
||||
}
|
||||
if (SGB) sched_barrier();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PF; ++j) acc[g + j] = D::wmma(vb[j], p16, acc[g + j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (BTS) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NB; ++i) blk[i] = blkn[i];
|
||||
}
|
||||
}
|
||||
|
||||
if (!live) return;
|
||||
l_i += swap16(l_i);
|
||||
if (nsplit > 1 && ne == 1 && h == 0) pML[1] = -1.0f; // stored below, merge skips it
|
||||
if (ne > 1) {
|
||||
// The partial: O times the V descale, unnormalised; m_ref is the reference both O and l
|
||||
// are exponentiated against (each carries the same 2^PSHIFT, which the merge cancels).
|
||||
#pragma unroll
|
||||
for (int dt = 0; dt < NKS; ++dt)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e)
|
||||
pO[dt * 16 + 2 * e + h] = acc[dt][e] * vdesc;
|
||||
if (h == 0) { pML[0] = m_ref; pML[1] = l_i; }
|
||||
return;
|
||||
}
|
||||
const float inv = (l_i > 0.0f) ? (vdesc / l_i) : 0.0f;
|
||||
uint16_t* op = (uint16_t*)a.out
|
||||
+ ((size_t)(qoff + qpos) * a.q_heads + qhead) * HEAD_DIM;
|
||||
// gfx1151: accumulator element e is head dim 2*e + (lane >> 4), one value a lane, so the store
|
||||
// is a scatter of eight 16-bit values rather than one 16-byte write.
|
||||
#pragma unroll
|
||||
for (int dt = 0; dt < NKS; ++dt)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e)
|
||||
op[dt * 16 + 2 * e + h] = f32_to_bf16(acc[dt][e] * inv);
|
||||
}
|
||||
|
||||
// ================================================================== split-KV prefill
|
||||
//
|
||||
// The query-tiled grid is q tiles x KV heads x sequences. A short chunk over a long context -- a
|
||||
// q_len of 11 at 16K tokens, four KV heads -- is four workgroups, each walking the whole context
|
||||
// alone on one of the 20 WGPs (one 768-thread workgroup fills a WGP), so it ran at the speed of a
|
||||
// q_len-64 chunk: 6.4 ms where reading the cache once is ~0.2. Splitting the tile range across
|
||||
// workgroups (flash-decoding) fills the part; halo_attn_prefill_merge combines the partials. The
|
||||
// partial buffer is the row's scratch, sized by its hook; without it (or with too little) the
|
||||
// launch runs unsplit, the kernel as before.
|
||||
|
||||
// The count a launch of these args takes, before the scratch check.
|
||||
template <int BQ, int TILE>
|
||||
static inline int halo_prefill_splits_for(const HaloArgs& a) {
|
||||
const int qtiles = (a.q_len + BQ - 1) / BQ;
|
||||
const int units = qtiles * a.kv_heads * a.num_seqs;
|
||||
const int tiles = (a.max_ctx + TILE - 1) / TILE;
|
||||
return halo_prefill_splits(units, tiles,
|
||||
halo_prefill_split_bytes(halo_q_total(a), a.q_heads, a.head_dim));
|
||||
}
|
||||
|
||||
// Picks r->splits for a launch: the law's count when the caller's scratch holds its partials,
|
||||
// else as many as fit, else 1 (unsplit, no scratch read). Call after fill_paged*.
|
||||
template <int NWARPS, int TILE, int HEAD_DIM, int GQA>
|
||||
static inline void halo_prefill_split_setup(const RadArgs* ra, HaloArgs* r) {
|
||||
constexpr int BQ = (NWARPS * 16) / GQA;
|
||||
r->splits = 1;
|
||||
const int s = halo_prefill_splits_for<BQ, TILE>(*r);
|
||||
if (s <= 1 || !ra->scratch || ra->scratch_bytes <= 0) return;
|
||||
const long long per = halo_prefill_split_bytes(halo_q_total(*r), r->q_heads, HEAD_DIM);
|
||||
const long long fit = per > 0 ? ra->scratch_bytes / per : 0;
|
||||
const int n = (int)std::min<long long>(s, fit);
|
||||
if (n > 1) { r->splits = n; r->scratch = ra->scratch; }
|
||||
}
|
||||
|
||||
// The scratch hook: the largest partial buffer the law asks for over every q_len up to the band's
|
||||
// bound and every sequence count up to max_seqs (parameters at declare time); from the tensors
|
||||
// when the parameters are absent. 0 when no launch in the band splits.
|
||||
template <int NWARPS, int TILE, int HEAD_DIM, int GQA>
|
||||
static inline int64_t halo_prefill_scratch(const RadArgs* a, long long row = 0) {
|
||||
constexpr int BQ = (NWARPS * 16) / GQA;
|
||||
const long long n_head = halo_geti_or(a, "n_head", 0);
|
||||
const long long max_seqs = halo_geti_or(a, "max_seqs", 0);
|
||||
const long long max_ctx = halo_geti_or(a, "max_ctx", 0);
|
||||
const long long band = halo_geti_or(a, "q_len", 0);
|
||||
if (n_head > 0 && max_seqs > 0 && max_ctx > 0 && band > 0) {
|
||||
const long long gqa = halo_geti_or(a, "gqa", GQA);
|
||||
const long long kvh = gqa > 0 ? n_head / gqa : n_head;
|
||||
const int tiles = (int)((max_ctx + TILE - 1) / TILE);
|
||||
int64_t worst = 0;
|
||||
for (long long n = 1; n <= max_seqs; ++n)
|
||||
for (long long qt = 1; (qt - 1) * BQ < band; ++qt) {
|
||||
const long long units = qt * kvh * n;
|
||||
if (units >= HALO_P_UNITS_MAX) break;
|
||||
const long long q = std::min<long long>(qt * BQ, band);
|
||||
const long long per = halo_prefill_split_bytes(n * q, n_head, HEAD_DIM);
|
||||
const int s = halo_prefill_splits((int)units, tiles, per);
|
||||
if (s > 1 && s * per > worst) worst = s * per;
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
HaloArgs r;
|
||||
const int rc = fill_paged_row(a, &r, HEAD_DIM, row > 0 ? row : 2LL * HEAD_DIM);
|
||||
if (rc != RAD_OK) return 0; // no tensors either: the launch runs unsplit
|
||||
const int s = halo_prefill_splits_for<BQ, TILE>(r);
|
||||
return s > 1 ? (int64_t)s * halo_prefill_split_bytes(halo_q_total(r), r.q_heads, HEAD_DIM) : 0;
|
||||
}
|
||||
|
||||
// Combine the splits' partials into bf16 out: one wave a (token, q head) row, HEAD_DIM / 32 dims a
|
||||
// lane. A row whose split 0 says l < 0 belongs to an empty sequence and is left as the plain kernel
|
||||
// leaves it.
|
||||
template <int HEAD_DIM>
|
||||
__global__ __launch_bounds__(256)
|
||||
void halo_attn_prefill_merge(const float* __restrict__ part, uint16_t* __restrict__ out,
|
||||
int rows, int nsplit)
|
||||
{
|
||||
constexpr int DPL = HEAD_DIM / 32;
|
||||
const int row = (int)blockIdx.x * 8 + (int)(threadIdx.x >> 5);
|
||||
const int lane = threadIdx.x & 31;
|
||||
if (row >= rows) return;
|
||||
const float* ml = part + (size_t)nsplit * rows * HEAD_DIM;
|
||||
if (ml[(size_t)row * 2 + 1] < 0.0f) return;
|
||||
float mx = -3.0e38f;
|
||||
for (int s = 0; s < nsplit; ++s) mx = fmaxf(mx, ml[((size_t)s * rows + row) * 2]);
|
||||
float o[DPL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DPL; ++i) o[i] = 0.0f;
|
||||
float l = 0.0f;
|
||||
for (int s = 0; s < nsplit; ++s) {
|
||||
const float m_s = ml[((size_t)s * rows + row) * 2];
|
||||
const float l_s = ml[((size_t)s * rows + row) * 2 + 1];
|
||||
if (!(l_s > 0.0f)) continue; // an empty split: O was never written
|
||||
const float w = exp2f(m_s - mx);
|
||||
l += w * l_s;
|
||||
const float* src = part + ((size_t)s * rows + row) * HEAD_DIM + lane * DPL;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DPL; ++i) o[i] += w * src[i];
|
||||
}
|
||||
const float inv = (l > 0.0f) ? 1.0f / l : 0.0f;
|
||||
uint16_t* dst = out + (size_t)row * HEAD_DIM + lane * DPL;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DPL; ++i) dst[i] = f32_to_bf16(o[i] * inv);
|
||||
}
|
||||
|
||||
// The launch every prefill geometry shares: the attention kernel over q tiles x KV heads x
|
||||
// (sequences x splits), then the merge when it split. Returns 0 or -100 - hipError_t.
|
||||
template <int NWARPS, int TILE, int HEAD_DIM, int GQA, int BS, int KVP, int OPT, int WIN = 0>
|
||||
static int halo_prefill_launch(const HaloArgs* a, hipStream_t s) {
|
||||
constexpr int BQ = (NWARPS * 16) / GQA;
|
||||
HaloArgs r = *a;
|
||||
if (!(r.splits > 1 && r.scratch)) r.splits = 1;
|
||||
dim3 grid((r.q_len + BQ - 1) / BQ, r.kv_heads, r.num_seqs * r.splits);
|
||||
hipLaunchKernelGGL((halo_attn_prefill_kernel<NWARPS, TILE, HEAD_DIM, GQA, BS, KVP, OPT, WIN>),
|
||||
grid, dim3(NWARPS * 32), 0, s, r);
|
||||
hipError_t e = hipGetLastError();
|
||||
if (e != hipSuccess) return -100 - (int)e;
|
||||
if (r.splits > 1) {
|
||||
const int rows = halo_q_total(r) * r.q_heads;
|
||||
hipLaunchKernelGGL((halo_attn_prefill_merge<HEAD_DIM>), dim3((rows + 7) / 8), dim3(256),
|
||||
0, s, (const float*)r.scratch, (uint16_t*)r.out, rows, r.splits);
|
||||
e = hipGetLastError();
|
||||
if (e != hipSuccess) return -100 - (int)e;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
/* Derived from libr4d/r4d_attn_vit_h72_bf16.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// Halo vision-encoder attention: dense, non-causal, head_dim 72, bf16 in and out.
|
||||
//
|
||||
// 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, its keys) is the B fragment of P.V (P^T), so P never goes
|
||||
// through LDS.
|
||||
//
|
||||
// head_dim 72 runs as 5 k-tiles of 16 = 80, with dims 72..79 zero: the last Q tile's upper eight
|
||||
// values are zeroed, the last 8 columns of every staged K row are zeroed once, and only head dims
|
||||
// 0..71 are stored. 11% padded WMMA work. gfx1151 gives a lane the whole 16-wide k run of its
|
||||
// fragment (halo_dt16.h), so on this part the padding sits inside the *lane* rather than in the
|
||||
// h==1 half of the wave: the Q gather reads 16 bytes for the last tile and leaves the upper eight
|
||||
// values zero, the K and V gathers read 32 bytes at the un-split offset, and the output store is a
|
||||
// scatter at head dim 2*e + (lane>>4) that skips dims 72..79.
|
||||
//
|
||||
// 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 (global_load_tr_b128 on gfx12,
|
||||
// halo_common.h's emulation here).
|
||||
// * 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).
|
||||
//
|
||||
// Operands are f16: packing P costs 1 instruction per pair instead of bf16's ~6.
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_dt16.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
// Optimisation steps, each separable so any one can be turned off after a geometry change.
|
||||
#define V_O_F16 1 // f16 rather than bf16 as the 16-bit operand format
|
||||
#define V_O_FOLDQ 8 // scale * log2(e) folded into the query once at load
|
||||
#define V_O_PF2 1024 // fragment prefetch depth: 2
|
||||
#define V_O_PF4 2048 // 4
|
||||
#define V_O_SGB 4096 // hard scheduling barrier between the prefetch group and its WMMAs
|
||||
#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: register prefetch for K too. The K fetch is three uint4 and this kernel runs at ~130
|
||||
// VGPRs; without it the K load sits between the barriers with only the V LDS stores to cover it.
|
||||
#define V_O_GPREK 4194304
|
||||
// MIXFMT is off: same speed on gfx12, and one operand format is simpler.
|
||||
#define V_O_MIXFMT 8388608
|
||||
|
||||
|
||||
// bf16 dword -> 16-bit dword in the target format, with the query scale folded in.
|
||||
template<class D, int FOLDQ, int F16>
|
||||
__device__ __forceinline__ uint32_t halo_vit_qcvt(uint32_t w, float s) {
|
||||
if (!FOLDQ) return F16 ? D::from_bf16w(w) : w;
|
||||
return D::pk(__builtin_bit_cast(float, w << 16) * s,
|
||||
__builtin_bit_cast(float, w & 0xffff0000u) * s);
|
||||
}
|
||||
|
||||
template<int NWARPS, int TILE, int QB, int OPT>
|
||||
__global__ __launch_bounds__(NWARPS * 32)
|
||||
void halo_attn_vit_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
|
||||
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
|
||||
const int* __restrict__ cu, int heads, float scale,
|
||||
int q_ld, int k_ld, int v_ld, int o_ld)
|
||||
{
|
||||
constexpr int F16 = (OPT & V_O_F16) ? 1 : 0;
|
||||
constexpr int FOLDQ = (OPT & V_O_FOLDQ) ? 1 : 0;
|
||||
constexpr int PF = (OPT & V_O_PF4) ? 4 : ((OPT & V_O_PF2) ? 2 : 1);
|
||||
constexpr int SGB = (OPT & V_O_SGB) ? 1 : 0;
|
||||
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 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
|
||||
typedef DT16<MIXF ? 0 : F16> DK; // K and Q: bf16 under MIXFMT, else the same
|
||||
typedef typename D::frag frag16;
|
||||
typedef typename DK::frag fragK;
|
||||
|
||||
constexpr int HD = 72; // the real head dim
|
||||
constexpr int HDP = 80; // padded to whole 16-wide WMMA k-tiles
|
||||
constexpr int NKS = HDP / 16; // 5
|
||||
constexpr int DGRP = HD / 8; // 9 eight-element dim groups spanning the real dims
|
||||
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 (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
|
||||
constexpr int NTR = KGRP * DGRP; // transposed V units, one per 8 lanes
|
||||
constexpr int LGRP = NTHR / 8;
|
||||
constexpr int VPASS = (NTR + LGRP - 1) / LGRP;
|
||||
constexpr int KIA = TILE * 8; // K fetch items, dims 0..63 (16 B each)
|
||||
constexpr int KIB = TILE; // K fetch items, dims 64..71
|
||||
constexpr int KPA = (KIA + NTHR - 1) / NTHR;
|
||||
constexpr int KPB = (KIB + NTHR - 1) / NTHR;
|
||||
constexpr float PSHIFT = D::SHIFT;
|
||||
constexpr float PGROW = D::GROW;
|
||||
static_assert((TILE & (TILE - 1)) == 0 && TILE >= 16, "TILE must be a power of two >= 16");
|
||||
|
||||
__shared__ __align__(16) uint16_t sK[TILE * KSTR];
|
||||
__shared__ __align__(16) uint16_t sV[HDP * VSTR];
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
const int c = lane & 15, h = lane >> 4;
|
||||
const int qb = blockIdx.x, hd = blockIdx.y, seq = blockIdx.z;
|
||||
|
||||
const int s0 = cu[seq], slen = cu[seq + 1] - s0;
|
||||
if (slen <= 0 || qb * ROWS >= slen) return;
|
||||
|
||||
// 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 -----------------------------
|
||||
int qpos[QB];
|
||||
bool live[QB];
|
||||
fragK qf[QB][NKS];
|
||||
#pragma unroll
|
||||
for (int b = 0; b < QB; ++b) {
|
||||
qpos[b] = qb * ROWS + (warp * QB + b) * 16 + c;
|
||||
live[b] = qpos[b] < slen;
|
||||
const int qrow = live[b] ? qpos[b] : slen - 1;
|
||||
const uint16_t* qp = gq + (long)(s0 + qrow) * q_ld + (long)hd * HD;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NKS; ++t) {
|
||||
uint32_t w8[8];
|
||||
if (t == NKS - 1) {
|
||||
// Dims 64..71 are real, 72..79 are padding. On gfx1151 a lane holds all sixteen,
|
||||
// so the upper eight are zeroed here for EVERY lane (gfx12 zeroed only the h==1
|
||||
// half), and the gather is 16 bytes: reading the 32 that a full tile reads would
|
||||
// run past the 72-element row at the tensor's last token. K's padding is zeroed
|
||||
// too: the WMMA contracts, so a NaN * 0 there would poison the whole score row.
|
||||
const uint4 u = *(const uint4*)(qp + 16 * t);
|
||||
w8[0] = halo_vit_qcvt<DK, FOLDQ, MIXF ? 0 : F16>(u.x, mul);
|
||||
w8[1] = halo_vit_qcvt<DK, FOLDQ, MIXF ? 0 : F16>(u.y, mul);
|
||||
w8[2] = halo_vit_qcvt<DK, FOLDQ, MIXF ? 0 : F16>(u.z, mul);
|
||||
w8[3] = halo_vit_qcvt<DK, FOLDQ, MIXF ? 0 : F16>(u.w, mul);
|
||||
w8[4] = w8[5] = w8[6] = w8[7] = 0u;
|
||||
} else {
|
||||
const uint4 u0 = *(const uint4*)(qp + 16 * t);
|
||||
const uint4 u1 = *(const uint4*)(qp + 16 * t + 8);
|
||||
w8[0] = halo_vit_qcvt<DK, FOLDQ, MIXF ? 0 : F16>(u0.x, mul);
|
||||
w8[1] = halo_vit_qcvt<DK, FOLDQ, MIXF ? 0 : F16>(u0.y, mul);
|
||||
w8[2] = halo_vit_qcvt<DK, FOLDQ, MIXF ? 0 : F16>(u0.z, mul);
|
||||
w8[3] = halo_vit_qcvt<DK, FOLDQ, MIXF ? 0 : F16>(u0.w, mul);
|
||||
w8[4] = halo_vit_qcvt<DK, FOLDQ, MIXF ? 0 : F16>(u1.x, mul);
|
||||
w8[5] = halo_vit_qcvt<DK, FOLDQ, MIXF ? 0 : F16>(u1.y, mul);
|
||||
w8[6] = halo_vit_qcvt<DK, FOLDQ, MIXF ? 0 : F16>(u1.z, mul);
|
||||
w8[7] = halo_vit_qcvt<DK, FOLDQ, MIXF ? 0 : F16>(u1.w, mul);
|
||||
}
|
||||
qf[b][t] = DK::mk(w8);
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
for (int i = tid; i < (HDP - HD) * VSTR; i += NTHR) sV[HD * VSTR + i] = 0;
|
||||
|
||||
float m_ref[QB], soff[QB], l_i[QB];
|
||||
v8f acc[QB][NKS];
|
||||
#pragma unroll
|
||||
for (int b = 0; b < QB; ++b) {
|
||||
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 -------------------
|
||||
const int vj = tid & 7, lgi = tid >> 3;
|
||||
uint4 kregA[KPA], kregB[KPB], vreg[VPASS];
|
||||
|
||||
auto fetchK = [&](int k0) {
|
||||
#pragma unroll
|
||||
for (int p = 0; p < KPA; ++p) {
|
||||
const int i = tid + p * NTHR;
|
||||
if (KIA % NTHR == 0 || i < KIA) {
|
||||
const int key = i >> 3, g = i & 7;
|
||||
const int kk = (k0 + key < slen) ? (k0 + key) : (slen - 1);
|
||||
kregA[p] = *(const uint4*)(gk + (long)(s0 + kk) * k_ld + (long)hd * HD + g * 8);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int p = 0; p < KPB; ++p) {
|
||||
const int i = tid + p * NTHR;
|
||||
if (KIB % NTHR == 0 || i < KIB) {
|
||||
const int kk = (k0 + i < slen) ? (k0 + i) : (slen - 1);
|
||||
kregB[p] = *(const uint4*)(gk + (long)(s0 + kk) * k_ld + (long)hd * HD + 64);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
auto storeK = [&]() {
|
||||
#pragma unroll
|
||||
for (int p = 0; p < KPA; ++p) {
|
||||
const int i = tid + p * NTHR;
|
||||
if (KIA % NTHR == 0 || i < KIA) {
|
||||
const uint4 r = kregA[p];
|
||||
*(uint4*)&sK[(i >> 3) * KSTR + (i & 7) * 8] =
|
||||
make_uint4(DK::from_bf16w(r.x), DK::from_bf16w(r.y),
|
||||
DK::from_bf16w(r.z), DK::from_bf16w(r.w));
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int p = 0; p < KPB; ++p) {
|
||||
const int i = tid + p * NTHR;
|
||||
if (KIB % NTHR == 0 || i < KIB) {
|
||||
const uint4 r = kregB[p];
|
||||
*(uint4*)&sK[i * KSTR + 64] =
|
||||
make_uint4(DK::from_bf16w(r.x), DK::from_bf16w(r.y),
|
||||
DK::from_bf16w(r.z), DK::from_bf16w(r.w));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// V is read transposed from global: a group's eight lanes name eight key rows at the same 8
|
||||
// dims, and the transposing load gives lane j dim d0+j across all eight, one 16-byte row of
|
||||
// V^T. (gfx1151 has no global_load_tr_b128; halo_common.h emulates it in registers.)
|
||||
auto fetchV = [&](int k0) {
|
||||
#pragma unroll
|
||||
for (int r = 0; r < VPASS; ++r) {
|
||||
const int u = lgi + r * LGRP;
|
||||
if (NTR % LGRP == 0 || u < NTR) {
|
||||
const int kg = u & (KGRP - 1), dg = u / KGRP;
|
||||
const int kk0 = k0 + kg * 8 + vj;
|
||||
const int kk = (kk0 < slen) ? kk0 : (slen - 1);
|
||||
vreg[r] = __builtin_bit_cast(uint4, load_tr_b128(
|
||||
gv + (long)(s0 + kk) * v_ld + (long)hd * HD + dg * 8));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
auto storeV = [&]() {
|
||||
#pragma unroll
|
||||
for (int r = 0; r < VPASS; ++r) {
|
||||
const int u = lgi + r * LGRP;
|
||||
if (NTR % LGRP == 0 || u < NTR) {
|
||||
const int kg = u & (KGRP - 1), dg = u / KGRP;
|
||||
const uint4 v = vreg[r];
|
||||
*(uint4*)&sV[(dg * 8 + vj) * VSTR + kg * 8] =
|
||||
make_uint4(D::from_bf16w(v.x), D::from_bf16w(v.y),
|
||||
D::from_bf16w(v.z), D::from_bf16w(v.w));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const int ntiles = (slen + TILE - 1) / TILE;
|
||||
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 (!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 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) {
|
||||
v8f s[QB];
|
||||
#pragma unroll
|
||||
for (int b = 0; b < QB; ++b) s[b] = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
{
|
||||
// The lane's K fragment row is key mt*16 + c and its sixteen values are the whole
|
||||
// k-tile of dims (halo_wmma.h): no half-wave term in the address, 32 bytes.
|
||||
const uint16_t* krow = &sK[(mt * 16 + c) * KSTR];
|
||||
#pragma unroll
|
||||
for (int g = 0; g < NKS; g += PF) {
|
||||
fragK kb[PF];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PF; ++j) {
|
||||
if (g + j < NKS) {
|
||||
const uint4 u0 = *(const uint4*)(krow + 16 * (g + j));
|
||||
const uint4 u1 = *(const uint4*)(krow + 16 * (g + j) + 8);
|
||||
const uint32_t w8[8] = { u0.x, u0.y, u0.z, u0.w,
|
||||
u1.x, u1.y, u1.z, u1.w };
|
||||
kb[j] = DK::mk(w8);
|
||||
}
|
||||
}
|
||||
if (SGB) sched_barrier();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PF; ++j)
|
||||
if (g + j < NKS)
|
||||
#pragma unroll
|
||||
for (int b = 0; b < QB; ++b) s[b] = DK::wmma(kb[j], qf[b][g + j], s[b]);
|
||||
}
|
||||
}
|
||||
|
||||
frag16 p16[QB];
|
||||
#pragma unroll
|
||||
for (int b = 0; b < QB; ++b) {
|
||||
float sc[8];
|
||||
#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 segment end. Element e is
|
||||
// key mt*16 + 2*e + h of the tile on gfx1151 (halo_dt16.h).
|
||||
if (tail) {
|
||||
const int kbase = k0 + mt * 16;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e)
|
||||
sc[e] = (kbase + 2 * e + h < slen) ? sc[e] : -INFINITY;
|
||||
}
|
||||
|
||||
float smax = sc[0];
|
||||
#pragma unroll
|
||||
for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]);
|
||||
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);
|
||||
#pragma unroll
|
||||
for (int dt = 0; dt < NKS; ++dt)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) acc[b][dt][e] *= alpha;
|
||||
l_i[b] *= alpha;
|
||||
m_ref[b] = mnew;
|
||||
soff[b] = PSHIFT - mnew;
|
||||
}
|
||||
|
||||
float pv[8], lsum = 0.0f;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const float p = ex2(sc[e] + soff[b]);
|
||||
pv[e] = p;
|
||||
if (!DOT2) lsum += p;
|
||||
}
|
||||
if (!DOT2) l_i[b] += lsum;
|
||||
|
||||
uint32_t pw[4];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e += 2) pw[e >> 1] = D::pk(pv[e], pv[e + 1]);
|
||||
if (DOT2) {
|
||||
const v2hf_dt one = {(__fp16)1.0f, (__fp16)1.0f};
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 4; ++e)
|
||||
l_i[b] = __builtin_amdgcn_fdot2(__builtin_bit_cast(v2hf_dt, pw[e]), one,
|
||||
l_i[b], false);
|
||||
}
|
||||
// Lane (c,h) holds keys 2e+h of query c: the sixteen-consecutive-key P fragment is
|
||||
// assembled across the half-pair (halo_dt16.h's p16w).
|
||||
uint32_t pw16[8];
|
||||
p16w<D>(pw, pw16);
|
||||
p16[b] = D::mk(pw16);
|
||||
}
|
||||
|
||||
{
|
||||
// A's row is the head dim (lane & 15) and its k run is the tile's sixteen keys:
|
||||
// 32 bytes at the un-split offset, as for K.
|
||||
const uint16_t* vbase = &sV[c * VSTR + mt * 16];
|
||||
#pragma unroll
|
||||
for (int g = 0; g < NKS; g += PF) {
|
||||
frag16 vb[PF];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PF; ++j) {
|
||||
if (g + j < NKS) {
|
||||
const uint4 u0 = *(const uint4*)(vbase + (g + j) * 16 * VSTR);
|
||||
const uint4 u1 = *(const uint4*)(vbase + (g + j) * 16 * VSTR + 8);
|
||||
const uint32_t w8[8] = { u0.x, u0.y, u0.z, u0.w,
|
||||
u1.x, u1.y, u1.z, u1.w };
|
||||
vb[j] = D::mk(w8);
|
||||
}
|
||||
}
|
||||
if (SGB) sched_barrier();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PF; ++j)
|
||||
if (g + j < NKS)
|
||||
#pragma unroll
|
||||
for (int b = 0; b < QB; ++b)
|
||||
acc[b][g + j] = D::wmma(vb[j], p16[b], acc[b][g + j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int b = 0; b < QB; ++b) {
|
||||
if (!live[b]) continue;
|
||||
const float ls = l_i[b] + swap16(l_i[b]);
|
||||
const float inv = (ls > 0.0f) ? (1.0f / ls) : 0.0f;
|
||||
uint16_t* op = go + (long)(s0 + qpos[b]) * o_ld + (long)hd * HD;
|
||||
#pragma unroll
|
||||
for (int dt = 0; dt < NKS; ++dt) {
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
// Element e of the accumulator is head dim dt*16 + 2*e + h (halo_wmma.h): one
|
||||
// 16-bit value a lane, so the store is a scatter rather than one 16-byte write.
|
||||
// The last tile's dims 72..79 are padding and would store past the row.
|
||||
const int d = 2 * e + h;
|
||||
if (dt == NKS - 1 && d >= HDP - HD) continue;
|
||||
op[dt * 16 + d] = f32_to_bf16(acc[b][dt][e] * inv);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- entry point -----------------------------------------------------------------------------
|
||||
// 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), so the crossover is between 576 and 1024; V_SPLIT 768 is the
|
||||
// midpoint. The same split is kept here; it is a launch-geometry choice, not an arch one.
|
||||
#define V_NWARPS 16 // large instantiation: ROWS = 256
|
||||
#define V_TILE 128
|
||||
#define V_QB 1
|
||||
#define V_SNWARPS 8 // small instantiation: ROWS = 128
|
||||
#define V_STILE 64
|
||||
#define V_SQB 1
|
||||
#define V_SPLIT 768
|
||||
// F16 | FOLDQ | PF4 | SGB | DOT2 | GPREV | LDSB | GPREK.
|
||||
#define V_OPT 7362569
|
||||
|
||||
// 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 halo_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)
|
||||
{
|
||||
const int ld = heads * 72;
|
||||
return halo_attn_vit_h72_strided_bf16(q, k, v, o, cu_seqlens, num_seqs, max_seqlen, heads,
|
||||
head_dim, scale, ld, ld, ld, ld, stream);
|
||||
}
|
||||
|
||||
// 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 halo_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,
|
||||
int k_ld, int v_ld, int o_ld, void* stream)
|
||||
{
|
||||
if (head_dim != 72) return -1;
|
||||
if (heads <= 0) return -2;
|
||||
if ((q_ld | k_ld | v_ld | o_ld) & 7) return -3;
|
||||
if (num_seqs <= 0 || max_seqlen <= 0) return 0;
|
||||
|
||||
#define V_LAUNCH(NW, TL, QBS) \
|
||||
do { \
|
||||
constexpr int ROWS = (NW) * 16 * (QBS); \
|
||||
dim3 grid((max_seqlen + ROWS - 1) / ROWS, heads, num_seqs); \
|
||||
hipLaunchKernelGGL((halo_attn_vit_kernel<(NW), (TL), (QBS), V_OPT>), grid, \
|
||||
dim3((NW) * 32), 0, (hipStream_t)stream, (const uint16_t*)q, \
|
||||
(const uint16_t*)k, (const uint16_t*)v, (uint16_t*)o, \
|
||||
(const int*)cu_seqlens, heads, scale, q_ld, k_ld, v_ld, o_ld); \
|
||||
} while (0)
|
||||
|
||||
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();
|
||||
if (e != hipSuccess) return -100 - (int)e;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Compiled geometry: head_dim, the two query-block heights, and the switch length.
|
||||
extern "C" void halo_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;
|
||||
if (rows_small) *rows_small = V_SNWARPS * 16 * V_SQB;
|
||||
if (split) *split = V_SPLIT;
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
|
||||
enum { AD_Q = 0, AD_K, AD_V, AD_CU, AD_OUT };
|
||||
|
||||
extern "C" int halo_rad_attn_vit(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* q = halo_opt(a, AD_Q);
|
||||
const RadTensor* k = halo_opt(a, AD_K);
|
||||
const RadTensor* v = halo_opt(a, AD_V);
|
||||
const RadTensor* cu = halo_opt(a, AD_CU);
|
||||
const RadTensor* o = halo_opt(a, AD_OUT);
|
||||
if (!q || !k || !v || !cu || !o) return HALO_NO(RAD_E_INVAL);
|
||||
if (!halo_contig(cu)) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
/* [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 = halo_geti_or(a, "head_dim", q->rank == 3 ? q->shape[2] : 72);
|
||||
if (head_dim != 72) return HALO_NO(RAD_E_SHAPE);
|
||||
/* 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 (halo_geti_or(a, "window", 0) != 0 || halo_geti_or(a, "block", 0) != 0 ||
|
||||
halo_geti_or(a, "cu_div", 1) != 1)
|
||||
return HALO_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 (!halo_head_rows(q, head_dim, &total, &heads, &q_ld) ||
|
||||
!halo_head_rows(k, head_dim, &tk, &hk, &k_ld) ||
|
||||
!halo_head_rows(v, head_dim, &tv, &hv, &v_ld) ||
|
||||
!halo_head_rows(o, head_dim, &to, &ho, &o_ld))
|
||||
return HALO_NO(RAD_E_STRIDE);
|
||||
if (hk != heads || hv != heads || ho != heads) return HALO_NO(RAD_E_SHAPE);
|
||||
if (tk < total || tv < total || to < total) return HALO_NO(RAD_E_SHAPE);
|
||||
if (cu->rank != 1 || cu->shape[0] < 2) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
const int num_seqs = (int)(cu->shape[0] - 1);
|
||||
|
||||
/* 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 = halo_geti_or(a, "max_seqlen", 0);
|
||||
if (msl <= 0) msl = total;
|
||||
|
||||
const float scale = (float)halo_getf(a, "scale", 1.0 / std::sqrt((double)head_dim));
|
||||
|
||||
const int e = halo_attn_vit_h72_strided_bf16(q->data, k->data, v->data, o->data, cu->data,
|
||||
num_seqs, (int)msl, (int)heads, (int)head_dim,
|
||||
scale, (int)q_ld, (int)k_ld, (int)v_ld,
|
||||
(int)o_ld, s);
|
||||
if (e == 0) return RAD_OK;
|
||||
return HALO_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,89 @@
|
||||
/* Derived from libr4d/r4d_chain.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
// halo_chain.h -- a chained launch's wait and completion (RadKernelChainFn, abi/rad_abi.h).
|
||||
//
|
||||
// Between two dependent kernels on one queue the packet processor waits for the first to finish
|
||||
// before it launches the second (the AQL barrier bit): on 4x R9700, ~1.3 ms of a 14 ms DFlash2 step
|
||||
// on the 31B. A chained launch drops the bit. The engine writes a record into the
|
||||
// kernel's argument slot, and the kernel waits for its queue's completion counter to reach the
|
||||
// blocks issued before it, then adds its own blocks as they finish. A kernel's chained form
|
||||
// (`CHAIN` true) brackets its body with halo_chain_wait / halo_chain_done; the plain form never reads
|
||||
// the record, so a launch from outside the engine (halo_selftest, rad-kbench) is untouched.
|
||||
//
|
||||
// Every block must reach halo_chain_done exactly once, so a kernel whose blocks return early keeps
|
||||
// its body in a __device__ function called from the chained wrapper.
|
||||
#pragma once
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "rad_abi.h"
|
||||
|
||||
#if !defined(__HIP__)
|
||||
/* The host SIMT emulator (tests/halo_emu) compiles some of these sources as C++: no engine record
|
||||
* ever reaches a launch there, so a chained form is its plain form. */
|
||||
__device__ __forceinline__ void halo_chain_wait() {}
|
||||
__device__ __forceinline__ void halo_chain_done() {}
|
||||
#else
|
||||
|
||||
struct HaloChainRec {
|
||||
unsigned long long magic, target;
|
||||
unsigned long long* ctr;
|
||||
unsigned long long check;
|
||||
};
|
||||
|
||||
// The record, or null where it is not the engine's. Read from the argument segment (scalar loads)
|
||||
// at both ends of the kernel, so nothing is held across the body: a register-heavy body (the
|
||||
// split-KV decode attention) would otherwise pay for the pointer.
|
||||
__device__ __forceinline__ const HaloChainRec* halo_chain_rec() {
|
||||
const HaloChainRec* r = (const HaloChainRec*)((const char*)__builtin_amdgcn_kernarg_segment_ptr() +
|
||||
RAD_CHAIN_KARG_OFF);
|
||||
const unsigned long long magic = r->magic, target = r->target, check = r->check;
|
||||
const unsigned long long* ctr = r->ctr;
|
||||
if (magic != RAD_CHAIN_MAGIC ||
|
||||
check != (magic ^ target ^ (unsigned long long)(uintptr_t)ctr ^ RAD_CHAIN_CHECK))
|
||||
return nullptr;
|
||||
return r;
|
||||
}
|
||||
|
||||
// Before the first read of an operand: one lane waits for the counter to reach the target.
|
||||
// Every resident block polls the same word, so a wide kernel launched behind a long one (a GEMM
|
||||
// behind a junction's all-reduce) would put hundreds of loads into one L2 channel every few dozen
|
||||
// clocks for as long as the wait lasts, slowing whatever else that channel serves. The first
|
||||
// HALO_CHAIN_FAST polls are ~64 clocks apart, the rest HALO_CHAIN_SLOW x 64: a long wait ends at most
|
||||
// that much late and puts 1/HALO_CHAIN_SLOW of the load on the channel.
|
||||
#ifndef HALO_CHAIN_FAST
|
||||
#define HALO_CHAIN_FAST 8
|
||||
#endif
|
||||
#ifndef HALO_CHAIN_SLOW
|
||||
#define HALO_CHAIN_SLOW 16
|
||||
#endif
|
||||
__device__ __forceinline__ void halo_chain_wait() {
|
||||
const HaloChainRec* r = halo_chain_rec();
|
||||
if (!r) return;
|
||||
if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0) {
|
||||
const unsigned long long target = r->target;
|
||||
unsigned long long* ctr = r->ctr;
|
||||
int n = 0;
|
||||
while (__hip_atomic_load(ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < target) {
|
||||
if (n < HALO_CHAIN_FAST) {
|
||||
__builtin_amdgcn_s_sleep(1);
|
||||
++n;
|
||||
} else {
|
||||
__builtin_amdgcn_s_sleep(HALO_CHAIN_SLOW);
|
||||
}
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
|
||||
}
|
||||
|
||||
// After the block's last write: release, then one add a block.
|
||||
__device__ __forceinline__ void halo_chain_done() {
|
||||
const HaloChainRec* r = halo_chain_rec();
|
||||
if (!r) return;
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
|
||||
__syncthreads();
|
||||
if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0)
|
||||
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
|
||||
}
|
||||
#endif /* __HIP__ */
|
||||
@@ -0,0 +1,325 @@
|
||||
/* Derived from libr4d/r4d_common.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
// Shared device-side machinery for Halo. 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 read the same packed weight and
|
||||
// a disagreement would be silently wrong, not a link error. halo_gemm_args.h restates it and checks
|
||||
// it against the layout constant.
|
||||
#define HALO_GEMM_W4A8_GROUP 128 // K per scale
|
||||
|
||||
// ---- ragged query batches ----------------------------------------------------------------------
|
||||
// A paged-attention batch may have a different query length per sequence (HaloArgs::cu_q in halo.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 halo_q_off(const int* cu_q, int seq, int q_len) {
|
||||
return cu_q ? cu_q[seq] : seq * q_len;
|
||||
}
|
||||
__device__ __forceinline__ int halo_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 a few scalar loads, once per block.
|
||||
__device__ __forceinline__ int halo_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]
|
||||
while (hi - lo > 1) {
|
||||
const int mid = (lo + hi) >> 1;
|
||||
if (cu_q[mid] <= tok) lo = mid; else hi = mid;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
// ---- the occupancy a kernel is built for ---------------------------------------------------------
|
||||
// HALO_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 HALO_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 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. halo_dflash_conv_body.h declares the same
|
||||
* type for a source also compiled without this header. */
|
||||
typedef unsigned int halo_u32x4 __attribute__((ext_vector_type(4)));
|
||||
|
||||
// exp2 with the hardware transcendental.
|
||||
|
||||
__device__ __forceinline__ float ex2(float x) {
|
||||
#if __has_builtin(__builtin_amdgcn_exp2f)
|
||||
return __builtin_amdgcn_exp2f(x);
|
||||
#else
|
||||
return exp2f(x);
|
||||
#endif
|
||||
}
|
||||
|
||||
// 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: 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 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, 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);
|
||||
}
|
||||
// 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;
|
||||
return f != f ? q : r;
|
||||
}
|
||||
// Two such words as one bf16 pair, `lo`'s high half in the low half: one byte permute.
|
||||
__device__ __forceinline__ uint32_t bf16_pack_hi(uint32_t lo, uint32_t hi) {
|
||||
return __builtin_amdgcn_perm(hi, lo, 0x07060302u);
|
||||
}
|
||||
// Two floats as a bf16 pair (`lo` in the low half), rounded as f32_to_bf16 rounds.
|
||||
__device__ __forceinline__ uint32_t bf16x2_rne(float lo, float hi) {
|
||||
return bf16_pack_hi(bf16_hi_rne(lo), bf16_hi_rne(hi));
|
||||
}
|
||||
// Two floats as a bf16 pair, rounded as (__hip_bfloat16) rounds.
|
||||
__device__ __forceinline__ uint32_t bf16x2_rne_nan(float lo, float hi) {
|
||||
return bf16_pack_hi(bf16_hi_rne_nan(lo), bf16_hi_rne_nan(hi));
|
||||
}
|
||||
// A bf16 pair word's two values as floats: a shift and a mask, no conversion.
|
||||
__device__ __forceinline__ float bf16w_lo(uint32_t w) { return __uint_as_float(w << 16); }
|
||||
__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).
|
||||
// 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* halo_gu16;
|
||||
__device__ __forceinline__ uint32_t ldg_u16(const uint16_t* p) { return *(halo_gu16)p; }
|
||||
|
||||
// `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 halo_xor_lane_u32(uint32_t v) {
|
||||
static_assert(N >= 1 && N <= 16 && (N & (N - 1)) == 0, "a lane xor within the wave");
|
||||
if constexpr (N < 16)
|
||||
return (uint32_t)__builtin_amdgcn_update_dpp(0, (int)v, 0x160 | N, 0xf, 0xf, true);
|
||||
else
|
||||
return (uint32_t)__builtin_amdgcn_permlanex16((int)v, (int)v, 0x76543210u, 0xFEDCBA98u,
|
||||
false, false);
|
||||
}
|
||||
|
||||
template <int N>
|
||||
__device__ __forceinline__ float halo_xor_lane(float v) {
|
||||
return __uint_as_float(halo_xor_lane_u32<N>(__float_as_uint(v)));
|
||||
}
|
||||
|
||||
// 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 halo_xor_lane_u64(unsigned long long v) {
|
||||
const uint32_t lo = halo_xor_lane_u32<N>((uint32_t)v);
|
||||
const uint32_t hi = halo_xor_lane_u32<N>((uint32_t)(v >> 32));
|
||||
return ((unsigned long long)hi << 32) | lo;
|
||||
}
|
||||
|
||||
// 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 halo_xor_lane<16>(x); }
|
||||
|
||||
// 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).
|
||||
//
|
||||
// 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 halo_dpp_xor_add(float v) {
|
||||
return v + __builtin_bit_cast(float,
|
||||
__builtin_amdgcn_update_dpp(0, __builtin_bit_cast(int, v), CTRL, 0xF, 0xF, true));
|
||||
}
|
||||
|
||||
__device__ __forceinline__ float halo_wave_sum(float v) {
|
||||
v += swap16(v); /* xor 16 -- crosses the two rows of sixteen */
|
||||
v = halo_dpp_xor_add<0x168>(v); /* xor 8 -- row_xmask from here down */
|
||||
v = halo_dpp_xor_add<0x164>(v); /* xor 4 */
|
||||
v = halo_dpp_xor_add<0x162>(v); /* xor 2 */
|
||||
v = halo_dpp_xor_add<0x161>(v); /* xor 1 */
|
||||
return v;
|
||||
}
|
||||
|
||||
// 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 halo_xor_sum(float v) {
|
||||
static_assert(W >= 1 && W <= 32 && (W & (W - 1)) == 0, "a power-of-two group within the wave");
|
||||
if constexpr (W >= 32) v += halo_xor_lane<16>(v);
|
||||
if constexpr (W >= 16) v += halo_xor_lane<8>(v);
|
||||
if constexpr (W >= 8) v += halo_xor_lane<4>(v);
|
||||
if constexpr (W >= 4) v += halo_xor_lane<2>(v);
|
||||
if constexpr (W >= 2) v += halo_xor_lane<1>(v);
|
||||
return v;
|
||||
}
|
||||
|
||||
template <int W>
|
||||
__device__ __forceinline__ float halo_xor_max(float v) {
|
||||
static_assert(W >= 1 && W <= 32 && (W & (W - 1)) == 0, "a power-of-two group within the wave");
|
||||
if constexpr (W >= 32) v = fmaxf(v, halo_xor_lane<16>(v));
|
||||
if constexpr (W >= 16) v = fmaxf(v, halo_xor_lane<8>(v));
|
||||
if constexpr (W >= 8) v = fmaxf(v, halo_xor_lane<4>(v));
|
||||
if constexpr (W >= 4) v = fmaxf(v, halo_xor_lane<2>(v));
|
||||
if constexpr (W >= 2) v = fmaxf(v, halo_xor_lane<1>(v));
|
||||
return v;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ float halo_wave_max(float v) { return halo_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 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 halo_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 */
|
||||
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x114, 0xF, 0xF, true); /* row_shr:4 */
|
||||
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x118, 0xF, 0xF, true); /* row_shr:8 */
|
||||
const uint32_t lo = (uint32_t)__builtin_amdgcn_readlane((int)x, 15);
|
||||
return lane >= 16 ? x + lo : x;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ uint32_t halo_wave_suffix_u32(uint32_t x, int lane) {
|
||||
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x101, 0xF, 0xF, true); /* row_shl:1 */
|
||||
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x102, 0xF, 0xF, true); /* row_shl:2 */
|
||||
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x104, 0xF, 0xF, true); /* row_shl:4 */
|
||||
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x108, 0xF, 0xF, true); /* row_shl:8 */
|
||||
const uint32_t hi = (uint32_t)__builtin_amdgcn_readlane((int)x, 16);
|
||||
return lane < 16 ? x + hi : x;
|
||||
}
|
||||
|
||||
// 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.
|
||||
//
|
||||
// gfx1151 has no global_load_tr_b128, so this loads each lane's 16 B and transposes in registers:
|
||||
// lane (base+i)'s output element j is lane (base+j)'s loaded element i, eight shuffles of the one
|
||||
// dword that holds it. Same result, more instructions; a caller on a hot path should say so in
|
||||
// its header so the transpose can be folded into its addressing instead.
|
||||
__device__ __forceinline__ v8s load_tr_b128(const void* p) {
|
||||
const uint4 v = *(const uint4*)p;
|
||||
const uint32_t w[4] = { v.x, v.y, v.z, v.w };
|
||||
const int lane = (int)(threadIdx.x & 31u);
|
||||
const int base = lane & ~7, i = lane & 7;
|
||||
uint32_t o[4] = { 0, 0, 0, 0 };
|
||||
// A shuffle returns the value the SOURCE lane passed, so a lane cannot ask for "my element i"
|
||||
// in one shuffle: at lane base+j the argument `w[i >> 1]` is evaluated with THAT lane's i (j),
|
||||
// not this one's. Fetch all four of the source lane's dwords and select this lane's element
|
||||
// afterwards -- that is the transpose, and it is 32 shuffles rather than 8.
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const uint32_t d0 = (uint32_t)__shfl((int)w[0], base + j, 32);
|
||||
const uint32_t d1 = (uint32_t)__shfl((int)w[1], base + j, 32);
|
||||
const uint32_t d2 = (uint32_t)__shfl((int)w[2], base + j, 32);
|
||||
const uint32_t d3 = (uint32_t)__shfl((int)w[3], base + j, 32);
|
||||
const int d = i >> 1;
|
||||
const uint32_t wd = d == 0 ? d0 : d == 1 ? d1 : d == 2 ? d2 : d3;
|
||||
const uint32_t e = (i & 1) ? (wd >> 16) : (wd & 0xffffu);
|
||||
o[j >> 1] |= e << (16 * (j & 1));
|
||||
}
|
||||
v8s r;
|
||||
__builtin_memcpy(&r, o, sizeof(o));
|
||||
return r;
|
||||
}
|
||||
|
||||
// Gather the low (sel=0) or high (sel=1) byte of each of four 16-bit lanes of {w0,w1} into one
|
||||
// dword. Written so the compiler can contract each to a single v_perm_b32.
|
||||
__device__ __forceinline__ uint32_t byte_gather(uint32_t w0, uint32_t w1, int sel) {
|
||||
uint32_t s = (uint32_t)sel * 8u;
|
||||
return ((w0 >> s) & 0xffu)
|
||||
| (((w0 >> (16 + s)) & 0xffu) << 8)
|
||||
| (((w1 >> s) & 0xffu) << 16)
|
||||
| (((w1 >> (16 + s)) & 0xffu) << 24);
|
||||
}
|
||||
|
||||
__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, 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();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local");
|
||||
}
|
||||
|
||||
// Two-dword form of swap16.
|
||||
__device__ __forceinline__ uint2 swap16_u2p(uint2 v) {
|
||||
return make_uint2(__builtin_bit_cast(uint32_t, swap16(__builtin_bit_cast(float, v.x))),
|
||||
__builtin_bit_cast(uint32_t, swap16(__builtin_bit_cast(float, v.y))));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Workgroup width for the activation-path kernels
|
||||
//
|
||||
// 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 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 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 halo_act_threads(int M, int K) {
|
||||
if (M <= 32) return 1024;
|
||||
const int lim = K >= 8192 ? (1 << 24) : (K >= 4096 ? 120 : 72);
|
||||
return M <= lim ? 512 : 256;
|
||||
}
|
||||
|
||||
// libr4d's r4d_cliff_rows pads a grid past the R9700's full-card cliff (a launch in the last 32
|
||||
// wavefronts below a multiple of its 2048 wave slots runs ~5x slower). gfx1151 has no such cliff:
|
||||
// measured 2026-10-26 with a fixed 200-iteration kernel at 256-thread workgroups, per-launch time
|
||||
// rises smoothly through both candidate multiples (253..258 blocks: 10.18 -> 10.46 us, against the
|
||||
// R9700's 27.6 vs 5.2), with only the ordinary second-round step at 161 blocks -- 160 blocks x 8
|
||||
// waves = 1280 = 40 CUs x 2 SIMDs x 16 wave slots exactly. So the row count to launch is the row
|
||||
// count asked for, and this stays a function because every launch site already calls it: if a
|
||||
// future part or driver grows a cliff, the pad goes back here and nowhere else.
|
||||
__host__ __device__ __forceinline__ uint32_t halo_cliff_rows(uint32_t rows, uint32_t per_row,
|
||||
uint32_t waves) {
|
||||
(void)per_row;
|
||||
(void)waves;
|
||||
return rows;
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
/* Derived from libr4d/r4d_gen.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_conv2d_nhwc.hip -- the image decoder's convolution, gfx1151: an implicit GEMM over
|
||||
// (tap, channel) with the weight stored tap-major, plus the direct form for an input whose channel
|
||||
// count is not a multiple of eight.
|
||||
//
|
||||
// The implicit GEMM is libr4d's, with the two gfx11 fragment changes halo_gdn_wmma.h states:
|
||||
//
|
||||
// * the fragment pointer loses `4 * (lane >> 4)`: on RDNA 3.5 a lane holds the WHOLE 16-wide k
|
||||
// run (32 bytes), on RDNA4 only its half's 8 values 16 bytes apart. `fragP` is therefore one
|
||||
// dwordx4 pair at the un-split k offset.
|
||||
// * the accumulator's element e is D[2e + (lane>>4)][lane & 15], not D[8*(lane>>4) + e][lane&15].
|
||||
// The blocked store below is unchanged in SHAPE because `accPack` exchanges the two halves'
|
||||
// rows first (four v_permlanex16), putting the tile's sixteen consecutive channels back in one
|
||||
// lane -- so the fail-safe is 16 bytes a lane, as libr4d writes it.
|
||||
//
|
||||
// Arithmetic is untouched: f32 accumulation, one WMMA per 16 K in ascending order, bias added
|
||||
// after the product, RTNE bf16 stores (libref/ref_gen.cpp's conv2d_nhwc).
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kCvT = 256;
|
||||
|
||||
inline int cv_st_of(hipError_t e) { return e == hipSuccess ? RAD_OK : HALO_NO(RAD_E_DEVICE); }
|
||||
inline unsigned cv_blocks_for(int64_t n) { return (unsigned)((n + kCvT - 1) / kCvT); }
|
||||
inline bool cv_is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; }
|
||||
|
||||
// A dense [H, W * c] image operand; `pitched` allows a row pitch wider than the row.
|
||||
inline bool cv_image_of(const RadTensor* t, long long c, long long* H, long long* W,
|
||||
bool pitched = false) {
|
||||
if (!t || t->rank != 2 || c <= 0 || t->shape[1] % c || t->stride[1] != 1 ||
|
||||
(pitched ? t->stride[0] < t->shape[1] : t->stride[0] != t->shape[1]))
|
||||
return false;
|
||||
*H = t->shape[0];
|
||||
*W = t->shape[1] / c;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- 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 is stored tap-major (halo_rows' relayout turns PyTorch's
|
||||
// [cout][cin][k][k] into it 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 halo_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 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 one pixel and sixteen output channels of it.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// Kernel size and upsampling are template parameters (KS, UP; 0 reads the argument): at runtime
|
||||
// they cost two integer divisions per staged chunk, at 3 and 2 a multiply-shift and a shift.
|
||||
#define CV_BK 64
|
||||
#define CV_PITCH (CV_BK + 8)
|
||||
|
||||
template <int TP, int TC, int KS, int UP>
|
||||
__global__ __launch_bounds__(256) void conv_igemm_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
|
||||
const uint16_t* __restrict__ bias, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo,
|
||||
int cout, int k, int stride, int up, int pt, int pl, int x_ld, int y_ld, int Mpx, int K) {
|
||||
constexpr int BP = 2 * TP * 16, BC = 4 * TC * 16;
|
||||
constexpr int CPR = CV_BK / 8;
|
||||
constexpr int AL = BP * CPR / 256, WL = BC * CPR / 256;
|
||||
static_assert(AL >= 1 && WL >= 1, "every thread stages whole chunks");
|
||||
__shared__ __attribute__((aligned(16))) uint16_t sA[BP * CV_PITCH];
|
||||
__shared__ __attribute__((aligned(16))) uint16_t sW[BC * CV_PITCH];
|
||||
|
||||
const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31;
|
||||
const int wp = wave / 4, wc = wave % 4;
|
||||
const int p0 = blockIdx.x * BP, c0 = blockIdx.y * BC;
|
||||
const int kq = KS ? KS : k, kk2 = kq * kq;
|
||||
|
||||
int a_oy[AL], a_ox[AL], a_t[AL], a_ci[AL];
|
||||
bool a_ok[AL];
|
||||
uint16_t* adst[AL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) {
|
||||
const int c = tid + 256 * i, r = c / CPR, e = (c % CPR) * 8;
|
||||
const int m = p0 + r;
|
||||
a_ok[i] = m < Mpx;
|
||||
const int mm = a_ok[i] ? m : 0;
|
||||
a_oy[i] = mm / Wo;
|
||||
a_ox[i] = mm % Wo;
|
||||
a_t[i] = e / cin;
|
||||
a_ci[i] = e % cin;
|
||||
adst[i] = sA + r * CV_PITCH + e;
|
||||
}
|
||||
size_t w_off[WL];
|
||||
int w_e[WL];
|
||||
bool w_ok[WL];
|
||||
uint16_t* wdst[WL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) {
|
||||
const int c = tid + 256 * i, r = c / CPR, e = (c % CPR) * 8;
|
||||
const int co = c0 + r;
|
||||
w_ok[i] = co < cout;
|
||||
w_off[i] = (size_t)(w_ok[i] ? co : 0) * K + e;
|
||||
w_e[i] = e;
|
||||
wdst[i] = sW + r * CV_PITCH + e;
|
||||
}
|
||||
const halo_u32x4 zero = {0u, 0u, 0u, 0u};
|
||||
auto loadA = [&](int i) -> halo_u32x4 {
|
||||
if (!a_ok[i] || a_t[i] >= kk2) return zero;
|
||||
const int kh = a_t[i] / kq, kw = a_t[i] - kh * kq;
|
||||
const int iy = a_oy[i] * stride + kh - pt, ix = a_ox[i] * stride + kw - pl;
|
||||
if (iy < 0 || iy >= Hv || ix < 0 || ix >= Wv) return zero;
|
||||
/* Both are non-negative here, so a halving is a shift. */
|
||||
const int sy = UP == 1 ? iy : UP == 2 ? (iy >> 1) : iy / up;
|
||||
const int sx = UP == 1 ? ix : UP == 2 ? (ix >> 1) : ix / up;
|
||||
return *(const halo_u32x4*)(x + (size_t)sy * x_ld + (size_t)sx * cin + a_ci[i]);
|
||||
};
|
||||
auto loadW = [&](int i, int kt) -> halo_u32x4 {
|
||||
if (!w_ok[i] || kt * CV_BK + w_e[i] >= K) return zero;
|
||||
return *(const halo_u32x4*)(w + w_off[i] + (size_t)kt * CV_BK);
|
||||
};
|
||||
|
||||
/* This lane's fragment row of each tile, at the un-split k offset: gfx11 has no half-wave k
|
||||
* term (halo_gdn_wmma.h's rowP). */
|
||||
const uint16_t* fa = sA + (wp * TP * 16 + (lane & 15)) * CV_PITCH;
|
||||
const uint16_t* fw = sW + (wc * TC * 16 + (lane & 15)) * CV_PITCH;
|
||||
|
||||
v8f acc[TC][TP];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TC; ++j)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TP; ++i) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
halo_u32x4 ra[AL], rw[WL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) ra[i] = loadA(i);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) rw[i] = loadW(i, 0);
|
||||
|
||||
const int nk = (K + CV_BK - 1) / CV_BK;
|
||||
for (int kt = 0; kt < nk; ++kt) {
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) *(halo_u32x4*)adst[i] = ra[i];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) *(halo_u32x4*)wdst[i] = rw[i];
|
||||
__syncthreads();
|
||||
if (kt + 1 < nk) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) {
|
||||
a_ci[i] += CV_BK;
|
||||
while (a_ci[i] >= cin) { a_ci[i] -= cin; ++a_t[i]; }
|
||||
ra[i] = loadA(i);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) rw[i] = loadW(i, kt + 1);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int s = 0; s < CV_BK / 16; ++s) {
|
||||
v16bf af[TP], wf[TC];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TP; ++i) af[i] = fragP(fa + i * 16 * CV_PITCH + s * 16);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TC; ++j) wf[j] = fragP(fw + j * 16 * CV_PITCH + s * 16);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TC; ++j)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TP; ++i) acc[j][i] = mma(wf[j], af[i], acc[j][i]);
|
||||
}
|
||||
}
|
||||
|
||||
/* The store. Lane l's element e is channel cb + accRow(l, e) of pixel accCol(l), so the bias is
|
||||
* added per element and accPack then hands each lane its own eight consecutive channels back. */
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TC; ++j)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TP; ++i) {
|
||||
const int px = p0 + (wp * TP + i) * 16 + accCol(lane);
|
||||
if (px >= Mpx) continue;
|
||||
const int cb = c0 + (wc * TC + j) * 16;
|
||||
const int oy = px / Wo, ox = px % Wo;
|
||||
uint16_t* dst = y + (size_t)oy * y_ld + (size_t)ox * cout;
|
||||
if (cb + 16 <= cout && (cout & 7) == 0) {
|
||||
float f[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e)
|
||||
f[e] = acc[j][i][e] + bf16_to_f32(bias[cb + accRow(lane, e)]);
|
||||
*(uint4*)(dst + cb + accPackRow(lane)) = accPack(f, lane);
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int co = cb + accRow(lane, e);
|
||||
if (co < cout) dst[co] = f32_to_bf16(acc[j][i][e] + bf16_to_f32(bias[co]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The direct form, for an input whose channel count is not a multiple of eight (an RGBA image into
|
||||
// the first layer): a thread an output element, f32 over (tap, cin), the same tap-major weight.
|
||||
__global__ __launch_bounds__(kCvT) void conv_direct_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
|
||||
const uint16_t* __restrict__ bias, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo,
|
||||
int cout, int k, int stride, int up, int pt, int pl, int x_ld, int y_ld, int64_t total) {
|
||||
const int64_t t = (int64_t)blockIdx.x * kCvT + threadIdx.x;
|
||||
if (t >= total) return;
|
||||
const int co = (int)(t % cout);
|
||||
const int64_t px = t / cout;
|
||||
const int oy = (int)(px / Wo), ox = (int)(px % Wo);
|
||||
const int K = k * k * cin;
|
||||
float acc = 0.0f;
|
||||
for (int kh = 0; kh < k; ++kh) {
|
||||
const int iy = oy * stride + kh - pt;
|
||||
if (iy < 0 || iy >= Hv) continue;
|
||||
for (int kw = 0; kw < k; ++kw) {
|
||||
const int ix = ox * stride + kw - pl;
|
||||
if (ix < 0 || ix >= Wv) continue;
|
||||
const uint16_t* xp = x + (size_t)(iy / up) * x_ld + (size_t)(ix / up) * cin;
|
||||
const uint16_t* wp = w + (size_t)co * K + (size_t)(kh * k + kw) * cin;
|
||||
for (int ci = 0; ci < cin; ++ci) acc += bf16_to_f32(wp[ci]) * bf16_to_f32(xp[ci]);
|
||||
}
|
||||
}
|
||||
y[(size_t)oy * y_ld + (size_t)ox * cout + co] = f32_to_bf16(acc + bf16_to_f32(bias[co]));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
extern "C" int halo_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = halo_opt(a, 0), *w = halo_opt(a, 1), *b = halo_opt(a, 2),
|
||||
*y = halo_opt(a, 3);
|
||||
if (!x || !w || !b || !y) return HALO_NO(RAD_E_INVAL);
|
||||
if (!cv_is_bf16(x) || !cv_is_bf16(w) || !cv_is_bf16(b) || !cv_is_bf16(y))
|
||||
return HALO_NO(RAD_E_DTYPE);
|
||||
const long long cin = halo_geti_or(a, "cin", 0), cout = halo_geti_or(a, "cout", 0);
|
||||
const long long k = halo_geti_or(a, "k", 0), stride = halo_geti_or(a, "stride", 1);
|
||||
const long long up = halo_geti_or(a, "up", 1);
|
||||
const char* pad = halo_gets(a, "pad");
|
||||
const bool down = pad && !std::strcmp(pad, "down");
|
||||
const bool causal = pad && !std::strcmp(pad, "causal");
|
||||
if (pad && !down && !causal && std::strcmp(pad, "same")) return HALO_NO(RAD_E_INVAL);
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || stride <= 0 || up <= 0) return HALO_NO(RAD_E_SHAPE);
|
||||
long long Hin = 0, Win = 0, Ho = 0, Wo = 0;
|
||||
/* y may be a column slice of wider rows (a channel written into its own columns): both kernels
|
||||
* store at its row pitch. */
|
||||
if (!cv_image_of(x, cin, &Hin, &Win) || !cv_image_of(y, cout, &Ho, &Wo, true))
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
const long long Hv = Hin * up, Wv = Win * up;
|
||||
/* Rows padded above `pt` and below `pb`, columns `pl` left and `pr` right. */
|
||||
const long long pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2;
|
||||
const long long pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
|
||||
if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pl + pr - k) / stride + 1 != Wo)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
const long long K = k * k * cin;
|
||||
if (halo_numel(w) < cout * K || halo_numel(b) < cout) return HALO_NO(RAD_E_SHAPE);
|
||||
const long long Mpx = Ho * Wo;
|
||||
if (Mpx <= 0 || Mpx >= (1ll << 31) || (long long)Ho * Wo * cout >= (1ll << 40))
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
hipStream_t st = (hipStream_t)s;
|
||||
if (cin % 8 || ((uintptr_t)x->data & 15) || ((uintptr_t)w->data & 15)) {
|
||||
const long long total = Mpx * cout;
|
||||
hipLaunchKernelGGL(conv_direct_kernel, dim3(cv_blocks_for(total)), dim3(kCvT), 0, st,
|
||||
(const uint16_t*)x->data, (const uint16_t*)w->data,
|
||||
(const uint16_t*)b->data, (uint16_t*)y->data, (int)Hv, (int)Wv,
|
||||
(int)cin, (int)Wo, (int)cout, (int)k, (int)stride, (int)up, (int)pt,
|
||||
(int)pl, (int)x->stride[0], (int)y->stride[0], (int64_t)total);
|
||||
return cv_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 two or three times the WMMA per K step for the same
|
||||
// two barriers, which pays even with the last block partly empty. The rule is libr4d's; on
|
||||
// gfx1151 a lane's fragment is twice as wide, so a wave's WMMA count per K step is unchanged
|
||||
// (TP x TC accumulators) and the choice was not re-measured here.
|
||||
auto fits = [cout](long long bc) {
|
||||
const long long padded = (cout + bc - 1) / bc * bc;
|
||||
return (padded - cout) * 3 < padded;
|
||||
};
|
||||
#define HALO_CONV(TP, TC, KS, UP) \
|
||||
hipLaunchKernelGGL((conv_igemm_kernel<TP, TC, KS, UP>), \
|
||||
dim3((unsigned)((Mpx + 2 * TP * 16 - 1) / (2 * TP * 16)), \
|
||||
(unsigned)((cout + 4 * TC * 16 - 1) / (4 * TC * 16))), \
|
||||
dim3(256), 0, st, (const uint16_t*)x->data, (const uint16_t*)w->data, \
|
||||
(const uint16_t*)b->data, (uint16_t*)y->data, (int)Hv, (int)Wv, (int)cin, \
|
||||
(int)Wo, (int)cout, (int)k, (int)stride, (int)up, (int)pt, (int)pl, \
|
||||
(int)x->stride[0], (int)y->stride[0], (int)Mpx, (int)K)
|
||||
/* The decoder's two kernel sizes at its two sampling rates, and the generic form for the rest. */
|
||||
#define HALO_CONV_K(TP, TC) \
|
||||
if (k == 3 && up == 1) HALO_CONV(TP, TC, 3, 1); \
|
||||
else if (k == 3 && up == 2) HALO_CONV(TP, TC, 3, 2); \
|
||||
else if (k == 1 && up == 1) HALO_CONV(TP, TC, 1, 1); \
|
||||
else HALO_CONV(TP, TC, 0, 0)
|
||||
if (fits(192)) { HALO_CONV_K(4, 3); }
|
||||
else if (fits(128)) { HALO_CONV_K(4, 2); }
|
||||
else { HALO_CONV_K(4, 1); }
|
||||
#undef HALO_CONV_K
|
||||
#undef HALO_CONV
|
||||
return cv_st_of(hipGetLastError());
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
/* Derived from libr4d/r4d_audio.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_conv_t1d.hip -- a vocoder's transposed convolution, gfx1151: the bf16 conv_t1d row, which
|
||||
// libr4d keeps inside r4d_audio.hip beside conv1d (libhalo's halo_audio.hip holds the rest of that
|
||||
// unit; this one is extracted so the two lanes' slices stay apart).
|
||||
//
|
||||
// The implicit GEMM is libr4d's, with the two gfx11 fragment changes halo_gdn_wmma.h states:
|
||||
// the fragment pointer loses `4 * (lane >> 4)` (a lane holds the whole 16-wide k run, 32 bytes) and
|
||||
// the accumulator's element e is D[2e + (lane>>4)][lane & 15], so the blocked store goes through
|
||||
// accPack -- four v_permlanex16 -- to hand each lane its own eight consecutive channels back.
|
||||
// Arithmetic is untouched: f32 accumulation, one WMMA per 16 K ascending, bias after the product,
|
||||
// RTNE bf16 stores (libref/ref_audio.cpp's conv_t1d).
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
// libr4d's r4d_gdn_wmma.h carried this name; libhalo's halo_gdn_wmma.h is the RDNA3.5 fragment
|
||||
// layer and does not, so the units that need it define it locally (halo_audio.hip does the same).
|
||||
__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); }
|
||||
|
||||
constexpr int kC1T = 256;
|
||||
|
||||
__device__ __forceinline__ void st8(uint16_t* p, const float* f) {
|
||||
uint4 u;
|
||||
u.x = (uint32_t)f32_to_bf16(f[0]) | ((uint32_t)f32_to_bf16(f[1]) << 16);
|
||||
u.y = (uint32_t)f32_to_bf16(f[2]) | ((uint32_t)f32_to_bf16(f[3]) << 16);
|
||||
u.z = (uint32_t)f32_to_bf16(f[4]) | ((uint32_t)f32_to_bf16(f[5]) << 16);
|
||||
u.w = (uint32_t)f32_to_bf16(f[6]) | ((uint32_t)f32_to_bf16(f[7]) << 16);
|
||||
*(uint4*)p = u;
|
||||
}
|
||||
|
||||
// The sequence that owns row r: linear, because a vocoder pass has two (a stereo pair).
|
||||
__device__ __forceinline__ int seq_of(const int* cu, int n_seq, int r) {
|
||||
int s = 0;
|
||||
while (s + 1 < n_seq && cu[s + 1] <= r) ++s;
|
||||
return s;
|
||||
}
|
||||
|
||||
#define C1_BK 64
|
||||
#define C1_PITCH (C1_BK + 8)
|
||||
|
||||
// ---------------------------------------------------------------------------- conv_t1d
|
||||
// The transposed convolution of kernel `taps` s (two taps or one), stride s, padding P
|
||||
// ((k - s) / 2, or 0 for the causal form) as s convolutions of `taps` taps, one a grid slice
|
||||
// (blockIdx.z is the phase r): output row lo = q s + r - P of a sequence of L input rows reads
|
||||
// x[q - t] for each tap t (PyTorch's tap r + t s). For a phase below P the q that land inside the
|
||||
// sequence are 1..L, otherwise 0..L-1, so each phase has L output rows, one per input row: the M
|
||||
// dimension is the input rows, as for conv1d. The weight is relayouted to [s][cout][taps][cin],
|
||||
// which does not depend on P.
|
||||
template <int TP, int TC>
|
||||
__global__ __launch_bounds__(256) void conv_t1d_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
|
||||
const uint16_t* __restrict__ bias, const int* __restrict__ cu, uint16_t* __restrict__ y,
|
||||
int n_seq, int r_beg, int r_end, int cin, int cout, int s, int P, int taps, int x_ld,
|
||||
int y_ld) {
|
||||
constexpr int BP = 2 * TP * 16, BC = 4 * TC * 16;
|
||||
constexpr int CPR = C1_BK / 8;
|
||||
constexpr int AL = BP * CPR / 256, WL = BC * CPR / 256;
|
||||
static_assert(AL >= 1 && WL >= 1, "every thread stages whole chunks");
|
||||
__shared__ __attribute__((aligned(16))) uint16_t sA[BP * C1_PITCH];
|
||||
__shared__ __attribute__((aligned(16))) uint16_t sW[BC * C1_PITCH];
|
||||
|
||||
const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31;
|
||||
const int wp = wave / 4, wc = wave % 4;
|
||||
const int p0 = r_beg + blockIdx.x * BP, c0 = blockIdx.y * BC;
|
||||
const int ph = blockIdx.z, qoff = ph < P ? 1 : 0;
|
||||
const int K = taps * cin;
|
||||
const uint16_t* wph = w + (size_t)ph * cout * K;
|
||||
|
||||
int a_q[AL], a_t[AL], a_ci[AL], a_s0[AL], a_len[AL];
|
||||
bool a_ok[AL];
|
||||
uint16_t* adst[AL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) {
|
||||
const int c = tid + 256 * i, r = c / CPR, e = (c % CPR) * 8;
|
||||
const int m = p0 + r;
|
||||
a_ok[i] = m < r_end;
|
||||
const int mm = a_ok[i] ? m : r_beg;
|
||||
const int sq = seq_of(cu, n_seq, mm);
|
||||
a_s0[i] = cu[sq];
|
||||
a_len[i] = cu[sq + 1] - cu[sq];
|
||||
a_q[i] = mm - cu[sq] + qoff;
|
||||
a_t[i] = e / cin;
|
||||
a_ci[i] = e % cin;
|
||||
adst[i] = sA + r * C1_PITCH + e;
|
||||
}
|
||||
size_t w_off[WL];
|
||||
int w_e[WL];
|
||||
bool w_ok[WL];
|
||||
uint16_t* wdst[WL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) {
|
||||
const int c = tid + 256 * i, r = c / CPR, e = (c % CPR) * 8;
|
||||
const int co = c0 + r;
|
||||
w_ok[i] = co < cout;
|
||||
w_off[i] = (size_t)(w_ok[i] ? co : 0) * K + e;
|
||||
w_e[i] = e;
|
||||
wdst[i] = sW + r * C1_PITCH + e;
|
||||
}
|
||||
const halo_u32x4 zero = {0u, 0u, 0u, 0u};
|
||||
auto loadA = [&](int i) -> halo_u32x4 {
|
||||
if (!a_ok[i] || a_t[i] >= taps) return zero;
|
||||
const int qi = a_q[i] - a_t[i];
|
||||
if (qi < 0 || qi >= a_len[i]) return zero;
|
||||
return *(const halo_u32x4*)(x + (size_t)(a_s0[i] + qi) * x_ld + a_ci[i]);
|
||||
};
|
||||
auto loadW = [&](int i, int kt) -> halo_u32x4 {
|
||||
if (!w_ok[i] || kt * C1_BK + w_e[i] >= K) return zero;
|
||||
return *(const halo_u32x4*)(wph + w_off[i] + (size_t)kt * C1_BK);
|
||||
};
|
||||
|
||||
/* This lane's fragment row of each tile, at the un-split k offset (halo_gdn_wmma.h's rowP). */
|
||||
const uint16_t* fa = sA + (wp * TP * 16 + (lane & 15)) * C1_PITCH;
|
||||
const uint16_t* fw = sW + (wc * TC * 16 + (lane & 15)) * C1_PITCH;
|
||||
|
||||
v8f acc[TC][TP];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TC; ++j)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TP; ++i) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
halo_u32x4 ra[AL], rw[WL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) ra[i] = loadA(i);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) rw[i] = loadW(i, 0);
|
||||
|
||||
const int nk = (K + C1_BK - 1) / C1_BK;
|
||||
for (int kt = 0; kt < nk; ++kt) {
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) *(halo_u32x4*)adst[i] = ra[i];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) *(halo_u32x4*)wdst[i] = rw[i];
|
||||
__syncthreads();
|
||||
if (kt + 1 < nk) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) {
|
||||
a_ci[i] += C1_BK;
|
||||
while (a_ci[i] >= cin) { a_ci[i] -= cin; ++a_t[i]; }
|
||||
ra[i] = loadA(i);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) rw[i] = loadW(i, kt + 1);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int ss = 0; ss < C1_BK / 16; ++ss) {
|
||||
v16bf af[TP], wf[TC];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TP; ++i) af[i] = fragP(fa + i * 16 * C1_PITCH + ss * 16);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TC; ++j) wf[j] = fragP(fw + j * 16 * C1_PITCH + ss * 16);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TC; ++j)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TP; ++i) acc[j][i] = mma(wf[j], af[i], acc[j][i]);
|
||||
}
|
||||
}
|
||||
|
||||
/* Lane l's element e is channel cb + accRow(l, e) of input row accCol(l), so the bias is added
|
||||
* per element and accPack then reassembles the tile's sixteen consecutive channels. */
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TC; ++j)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TP; ++i) {
|
||||
const int m = p0 + (wp * TP + i) * 16 + accCol(lane);
|
||||
if (m >= r_end) continue;
|
||||
const int cb = c0 + (wc * TC + j) * 16;
|
||||
const int sq = seq_of(cu, n_seq, m);
|
||||
const int q = m - cu[sq] + qoff;
|
||||
const int orow = cu[sq] * s + q * s + ph - P;
|
||||
uint16_t* dst = y + (size_t)orow * y_ld + cb;
|
||||
if (cb + 16 <= cout && (cout & 7) == 0) {
|
||||
float f[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) f[e] = acc[j][i][e] + bf2f(bias[cb + accRow(lane, e)]);
|
||||
*(uint4*)(dst + accPackRow(lane)) = accPack(f, lane);
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int co = cb + accRow(lane, e);
|
||||
if (co < cout) dst[co] = f32_to_bf16(acc[j][i][e] + bf2f(bias[co]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline int c1_st_of(hipError_t e) { return e == hipSuccess ? RAD_OK : HALO_NO(RAD_E_DEVICE); }
|
||||
inline bool c1_is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; }
|
||||
inline bool c1_is_i32(const RadTensor* t) { return t && t->dtype == RAD_I32; }
|
||||
|
||||
} // namespace
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
extern "C" int halo_rad_conv_t1d(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = halo_opt(a, 0), *w = halo_opt(a, 1), *b = halo_opt(a, 2),
|
||||
*cu = halo_opt(a, 3);
|
||||
const RadTensor *y = halo_opt(a, 4);
|
||||
if (!x || !w || !b || !cu || !y) return HALO_NO(RAD_E_INVAL);
|
||||
if (!c1_is_bf16(x) || !c1_is_bf16(w) || !c1_is_bf16(b) || !c1_is_bf16(y) || !c1_is_i32(cu))
|
||||
return HALO_NO(RAD_E_DTYPE);
|
||||
const long long cin = halo_geti_or(a, "cin", 0), cout = halo_geti_or(a, "cout", 0);
|
||||
const long long st = halo_geti_or(a, "stride", 0);
|
||||
/* Kernel 2 stride (two taps) or stride (one); without `pad`, the symmetric (k - stride) / 2,
|
||||
* which needs k - stride even. */
|
||||
const long long kw = halo_geti_or(a, "k", 2 * st), pad = halo_geti_or(a, "pad", -1);
|
||||
const long long P = pad >= 0 ? pad : (kw - st) / 2;
|
||||
if (cin <= 0 || cout <= 0 || st <= 0 || (kw != st && kw != 2 * st) ||
|
||||
(pad < 0 && ((kw - st) & 1)) || P >= st || (cin % 8))
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
const int taps = (int)(kw / st);
|
||||
long long rx = 0, ry = 0;
|
||||
const long long xl = halo_rows_pitch(x, cin, &rx), yl = halo_rows_pitch(y, cout, &ry);
|
||||
if (xl < 0 || yl < 0 || (xl % 8) || ((uintptr_t)x->data & 15) || ((uintptr_t)w->data & 15))
|
||||
return HALO_NO(RAD_E_STRIDE);
|
||||
const long long n_seq = halo_numel(cu) - 1;
|
||||
if (n_seq <= 0 || rx <= 0 || ry < rx * st || halo_numel(w) < cin * cout * kw ||
|
||||
halo_numel(b) < cout)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
if (cout >= 128) {
|
||||
constexpr int TP = 4, TC = 2, BP = 128, BC = 128;
|
||||
hipLaunchKernelGGL((conv_t1d_kernel<TP, TC>),
|
||||
dim3((unsigned)((rx + BP - 1) / BP), (unsigned)((cout + BC - 1) / BC),
|
||||
(unsigned)st),
|
||||
dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data,
|
||||
(const uint16_t*)w->data, (const uint16_t*)b->data, (const int*)cu->data,
|
||||
(uint16_t*)y->data, (int)n_seq, 0, (int)rx, (int)cin, (int)cout, (int)st,
|
||||
(int)P, taps, (int)xl, (int)yl);
|
||||
} else {
|
||||
constexpr int TP = 4, TC = 1, BP = 128, BC = 64;
|
||||
hipLaunchKernelGGL((conv_t1d_kernel<TP, TC>),
|
||||
dim3((unsigned)((rx + BP - 1) / BP), (unsigned)((cout + BC - 1) / BC),
|
||||
(unsigned)st),
|
||||
dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data,
|
||||
(const uint16_t*)w->data, (const uint16_t*)b->data, (const int*)cu->data,
|
||||
(uint16_t*)y->data, (int)n_seq, 0, (int)rx, (int)cin, (int)cout, (int)st,
|
||||
(int)P, taps, (int)xl, (int)yl);
|
||||
}
|
||||
return c1_st_of(hipGetLastError());
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/* Derived from libr4d/r4d_dequant_w4_bf16.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_dequant_w4_bf16.hip - halo_dequant_w4_bf16: the packed 4-bit weight back to a plain row-major
|
||||
// bf16 [N, K].
|
||||
//
|
||||
// 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 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.
|
||||
//
|
||||
// Nearly lossless: a 4-bit code times an f16 scale fits bf16's 8-bit mantissa to within a ULP.
|
||||
//
|
||||
// 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 "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define HALO_DQ_KPB 64
|
||||
#define HALO_DQ_THREADS 256
|
||||
|
||||
__constant__ int halo_dq_koff[8] = {0, 8, 1, 9, 2, 10, 3, 11};
|
||||
|
||||
__global__ __launch_bounds__(HALO_DQ_THREADS) void halo_dequant_w4_bf16_kernel(
|
||||
const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws,
|
||||
__hip_bfloat16* __restrict__ Out, int N, int K, int group, int twos) {
|
||||
const long total = (long)N * K / 8; // one thread per packed dword
|
||||
const int nkb = K / HALO_DQ_KPB, ng = K / group;
|
||||
for (long idx = blockIdx.x * (long)blockDim.x + threadIdx.x; idx < total;
|
||||
idx += (long)gridDim.x * blockDim.x) {
|
||||
// [t][kb][lh][r][s]
|
||||
const int s = (int)(idx & 3);
|
||||
const int r = (int)((idx >> 2) & 15);
|
||||
const int lh = (int)((idx >> 6) & 1);
|
||||
const int kb = (int)((idx >> 7) % nkb);
|
||||
const int t = (int)((idx >> 7) / nkb);
|
||||
const int row_n = t * 16 + r;
|
||||
const unsigned w = Wq[idx];
|
||||
|
||||
const int kbase = kb * HALO_DQ_KPB + s * 16 + 4 * lh;
|
||||
const unsigned sz = Ws[(size_t)(t * ng + kbase / group) * 16 + r];
|
||||
const float sc = __half2float(__ushort_as_half((unsigned short)(sz & 0xFFFFu)));
|
||||
const float nz = __half2float(__ushort_as_half((unsigned short)(sz >> 16)));
|
||||
const float zero = -nz - 1024.f; // exact for zero in 0..15
|
||||
|
||||
#pragma unroll
|
||||
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;
|
||||
// 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 + halo_dq_koff[i];
|
||||
Out[(size_t)row_n * K + k] = __float2bfloat16((q - (twos ? 0.f : zero)) * sc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void halo_dequant_w4_bf16(long wq, long ws, long out, int N, int K, int group, int twos,
|
||||
long stream) {
|
||||
if (N % 16) throw std::runtime_error("r4d dequant_w4_bf16: N must be a multiple of 16");
|
||||
if (K % HALO_DQ_KPB) throw std::runtime_error("r4d dequant_w4_bf16: K must be a multiple of 64");
|
||||
if (group < 1 || K % group) throw std::runtime_error(
|
||||
"r4d dequant_w4_bf16: group must divide K");
|
||||
const long total = (long)N * K / 8;
|
||||
const int blocks = (int)((total + HALO_DQ_THREADS - 1) / HALO_DQ_THREADS);
|
||||
hipLaunchKernelGGL(halo_dequant_w4_bf16_kernel, dim3(blocks < 65535 ? blocks : 65535),
|
||||
dim3(HALO_DQ_THREADS), 0, (hipStream_t)stream, (const unsigned*)wq,
|
||||
(const unsigned*)ws, (__hip_bfloat16*)out, N, K, group, twos);
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in halo_gemm_args.h; see libhalo/halo_args.h.
|
||||
/* ------------------------------------------------------------------ dequant */
|
||||
|
||||
enum { D_WQ = 0, D_WS, D_Y };
|
||||
|
||||
extern "C" int halo_rad_dequant_w4(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* wq = halo_opt(a, D_WQ);
|
||||
const RadTensor* ws = halo_opt(a, D_WS);
|
||||
const RadTensor* y = halo_opt(a, D_Y);
|
||||
if (!wq || !ws || !y) return HALO_NO(RAD_E_INVAL);
|
||||
if (y->rank != 2 || !halo_contig(y)) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
const long long N = y->shape[0];
|
||||
const long long K = y->shape[1];
|
||||
const long long group = halo_geti_or(a, "group", HALO_W4_GROUP);
|
||||
const long long twos = halo_geti_or(a, "twos", 1);
|
||||
if (N % 16 || K % 64) return HALO_NO(RAD_E_SHAPE);
|
||||
if (group < 1 || K % group) return HALO_NO(RAD_E_SHAPE);
|
||||
if (twos != 0 && twos != 1) return HALO_NO(RAD_E_INVAL);
|
||||
|
||||
HALO_TRY("dequant_w4_bf16",
|
||||
halo_dequant_w4_bf16(halo_addr(wq), halo_addr(ws), halo_addr(y),
|
||||
(int)N, (int)K, (int)group, (int)twos, (long)(uintptr_t)s));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
/* Derived from libr4d/r4d_dflash_conv_body.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
// DFlash2 grouped dynamic depthwise convolution -- device math only.
|
||||
//
|
||||
// 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 libhalo.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 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 halo_u32;
|
||||
typedef unsigned short halo_u16;
|
||||
typedef halo_u32 halo_u32x4 __attribute__((ext_vector_type(4)));
|
||||
|
||||
// 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 HaloV8 { halo_u32x4 v; halo_u16 h[8]; };
|
||||
|
||||
// Device functions under hipcc; plain always-inline functions under a standalone amdgcn clang.
|
||||
#ifndef HALO_DEV
|
||||
#ifdef __HIP__
|
||||
#define HALO_DEV __device__ __forceinline__
|
||||
#else
|
||||
#define HALO_DEV static __attribute__((always_inline))
|
||||
#endif
|
||||
#endif
|
||||
|
||||
HALO_DEV float halo_bf2f(halo_u16 v) {
|
||||
return __builtin_bit_cast(float, (halo_u32)v << 16);
|
||||
}
|
||||
|
||||
// f32 -> bf16 RTNE in software: gfx1201 has no bf16 convert instruction.
|
||||
HALO_DEV halo_u16 halo_f2bf(float f) {
|
||||
halo_u32 u = __builtin_bit_cast(halo_u32, f);
|
||||
return (halo_u16)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
|
||||
// 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>
|
||||
HALO_DEV void halo_dflash_conv_body(const halo_u16* __restrict__ x,
|
||||
const halo_u16* __restrict__ delta,
|
||||
const halo_u16* __restrict__ base,
|
||||
halo_u16* __restrict__ out,
|
||||
int H, int dpitch, int NG, int vpr,
|
||||
int blockmask, int t, int hv) {
|
||||
if (hv >= vpr) return;
|
||||
|
||||
// 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;
|
||||
|
||||
const halo_u16* __restrict__ xrow = x + (long)t * H;
|
||||
halo_u16* __restrict__ orow = out + (long)t * H;
|
||||
const halo_u16* __restrict__ drow = delta + (long)t * dpitch;
|
||||
|
||||
HaloV8 x0; x0.v = *(const halo_u32x4*)(xrow + off);
|
||||
HaloV8 b0; b0.v = *(const halo_u32x4*)(base + off);
|
||||
const float d0 = halo_bf2f(drow[g]);
|
||||
|
||||
float acc[8];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j)
|
||||
acc[j] = (halo_bf2f(b0.h[j]) + d0) * halo_bf2f(x0.h[j]);
|
||||
|
||||
// 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 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 halo_u16* __restrict__ xprev = xrow - (long)tap * H;
|
||||
const halo_u16* __restrict__ btap = base + (long)tap * H;
|
||||
const halo_u16* __restrict__ dtap = drow + (long)tap * NG;
|
||||
if ((t & blockmask) >= tap) {
|
||||
HaloV8 xs; xs.v = *(const halo_u32x4*)(xprev + off);
|
||||
HaloV8 bt; bt.v = *(const halo_u32x4*)(btap + off);
|
||||
const float dt = halo_bf2f(dtap[g]);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j)
|
||||
acc[j] += (halo_bf2f(bt.h[j]) + dt) * halo_bf2f(xs.h[j]);
|
||||
}
|
||||
}
|
||||
|
||||
HaloV8 o;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) o.h[j] = halo_f2bf(acc[j]);
|
||||
*(halo_u32x4*)(orow + off) = o.v;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/* Derived from libr4d/r4d_dflash_conv_t2_g16_bf16.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// DFlash2 grouped dynamic depthwise convolution, fused.
|
||||
//
|
||||
// Device math is in halo_dflash_conv_body.h (HIP-header-free for standalone ISA review).
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "halo_gdn_args.h"
|
||||
#include "halo_dflash_conv_body.h"
|
||||
#include "halo_chain.h"
|
||||
|
||||
#define DFC_THREADS 128
|
||||
#define DFC_VEC 8 // bf16 lanes per thread: one dwordx4 in and one out
|
||||
|
||||
template <int TAPS, int GROUP>
|
||||
__global__ __launch_bounds__(DFC_THREADS) void halo_dflash_conv_kernel(
|
||||
const halo_u16* __restrict__ x, const halo_u16* __restrict__ delta,
|
||||
const halo_u16* __restrict__ base, halo_u16* __restrict__ out,
|
||||
int H, int dpitch, int NG, int vpr, int blockmask)
|
||||
{
|
||||
const int hv = blockIdx.x * DFC_THREADS + threadIdx.x;
|
||||
halo_dflash_conv_body<TAPS, GROUP>(x, delta, base, out, H, dpitch, NG, vpr,
|
||||
blockmask, blockIdx.y, hv);
|
||||
}
|
||||
|
||||
// The chained form (halo_chain.h): the body returns for lanes past the row, the block still adds.
|
||||
template <int TAPS, int GROUP>
|
||||
__global__ __launch_bounds__(DFC_THREADS) void halo_r4dchain_dflash_conv(
|
||||
const halo_u16* __restrict__ x, const halo_u16* __restrict__ delta,
|
||||
const halo_u16* __restrict__ base, halo_u16* __restrict__ out,
|
||||
int H, int dpitch, int NG, int vpr, int blockmask)
|
||||
{
|
||||
halo_chain_wait();
|
||||
const int hv = blockIdx.x * DFC_THREADS + threadIdx.x;
|
||||
halo_dflash_conv_body<TAPS, GROUP>(x, delta, base, out, H, dpitch, NG, vpr,
|
||||
blockmask, blockIdx.y, hv);
|
||||
halo_chain_done();
|
||||
}
|
||||
|
||||
// x [T, H] bf16, row pitch H
|
||||
// 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 input row t-1.
|
||||
static int dflash_conv_launch(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, bool chain);
|
||||
extern "C" int halo_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)
|
||||
{
|
||||
return dflash_conv_launch(x, delta, base, out, T, H, dpitch, NG, taps, group, block_size,
|
||||
stream, false);
|
||||
}
|
||||
/* `chain`: the chained form at decode heights (halo_rad_dflash_conv passes the row's parameter). */
|
||||
static int dflash_conv_launch(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, bool chain)
|
||||
{
|
||||
if (taps != 2 || group != 16) return -1;
|
||||
if (H % (group * DFC_VEC) || NG != H / group) return -1;
|
||||
if (block_size < 1 || (block_size & (block_size - 1))) return -1; // body masks: pow2 only
|
||||
if (T <= 0) return 0;
|
||||
|
||||
const int vpr = H / DFC_VEC;
|
||||
dim3 grid((vpr + DFC_THREADS - 1) / DFC_THREADS, T), blk(DFC_THREADS);
|
||||
hipLaunchKernelGGL((chain && T <= 64 ? halo_r4dchain_dflash_conv<2, 16>
|
||||
: halo_dflash_conv_kernel<2, 16>),
|
||||
grid, blk, 0, (hipStream_t)stream,
|
||||
(const halo_u16*)x, (const halo_u16*)delta, (const halo_u16*)base,
|
||||
(halo_u16*)out, H, dpitch, NG, vpr, block_size - 1);
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
// Shared operand helpers: halo_gdn_args.h.
|
||||
/* ------------------------------------------------------------------ dflash conv */
|
||||
|
||||
enum { DC_X = 0, DC_DELTA, DC_BASE, DC_OUT };
|
||||
|
||||
extern "C" int halo_rad_dflash_conv(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* x = halo_opt(a, DC_X);
|
||||
const RadTensor* d = halo_opt(a, DC_DELTA);
|
||||
const RadTensor* bs = halo_opt(a, DC_BASE);
|
||||
const RadTensor* o = halo_opt(a, DC_OUT);
|
||||
if (!x || !d || !bs || !o) return HALO_NO(RAD_E_INVAL);
|
||||
if (x->rank != 2 || o->rank != 2 || d->rank < 2) return HALO_NO(RAD_E_SHAPE);
|
||||
if (!halo_contig(x) || !halo_contig(o) || !halo_contig(bs)) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
/* out must not alias x (the kernel reads x while writing out); nothing downstream checks it. */
|
||||
if (x->data == o->data) return HALO_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 HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
/* 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 = halo_row_pitch(d);
|
||||
if (dpitch < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
const int taps = (int)halo_geti_or(a, "taps", 2);
|
||||
const int group = (int)halo_geti_or(a, "group_size", 16);
|
||||
const int NG = (int)halo_geti_or(a, "NG", 0);
|
||||
const int bsz = (int)halo_geti_or(a, "block_size", 0);
|
||||
if (NG <= 0 || bsz <= 0) return HALO_NO(RAD_E_INVAL);
|
||||
/* 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 HALO_NO(RAD_E_INVAL);
|
||||
if (dpitch != 2LL * taps * NG) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
return HALO_RAW(dflash_conv_launch(x->data, d->data, bs->data, o->data, (int)T,
|
||||
(int)H, (int)dpitch, NG, taps, group, bsz, s,
|
||||
halo_geti_or(a, "chain", 0) != 0));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
/* Derived from libr4d/r4d_dflash_select_bf16.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// 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 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]
|
||||
//
|
||||
// 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; 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, 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 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 "halo_gdn_args.h"
|
||||
#include "halo_dflash_conv_body.h" // halo_bf2f, halo_u16
|
||||
#include "halo_common.h" // halo_wave_sum
|
||||
#include "halo_chain.h"
|
||||
|
||||
#define DSL_THREADS 256
|
||||
#define DSL_WAVE 32
|
||||
#define DSL_WAVES (DSL_THREADS / DSL_WAVE)
|
||||
#define DSL_MAX_K 32 // the entry point rejects more; ssc is sized for it
|
||||
#define DSL_MAX_R 512 // and sa for this
|
||||
|
||||
// cand [rows, cand_ld] i32 global token ids, row = s * steps + l
|
||||
// unary [rows, cand_ld] f32 the draft head's logit for each candidate (row_topk's value plane)
|
||||
// hp [rows, hp_ld] bf16 hidden_projection(x) for the same row
|
||||
// anchor [M * anchor_stride] i32 the last committed token of each sequence, at stride s
|
||||
// pred [vocab, R] bf16 predecessor codebook
|
||||
// succ [vocab, R] bf16 successor codebook
|
||||
// out [M, out_ld] i32 the chosen token per step
|
||||
//
|
||||
// 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.
|
||||
// The body; the plain kernel and its chained form (halo_chain.h) wrap it below.
|
||||
__device__ __forceinline__ void halo_dflash_select_body(
|
||||
const int* __restrict__ cand, const float* __restrict__ unary,
|
||||
const halo_u16* __restrict__ hp, const int* __restrict__ anchor,
|
||||
const halo_u16* __restrict__ pred, const halo_u16* __restrict__ succ,
|
||||
int* __restrict__ out, int steps, int K, int R, int V,
|
||||
int cand_ld, int hp_ld, int out_ld, int anchor_stride)
|
||||
{
|
||||
const int s = blockIdx.x;
|
||||
const int tid = threadIdx.x;
|
||||
const int lane = tid & (DSL_WAVE - 1);
|
||||
const int wave = tid / DSL_WAVE;
|
||||
|
||||
// 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
|
||||
|
||||
// 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;
|
||||
// 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
|
||||
for (int i = 0; i < CPW; ++i) {
|
||||
const int c = wave + i * DSL_WAVES;
|
||||
const long at = row * cand_ld + (c < K ? c : K - 1);
|
||||
cid[i] = cand[at];
|
||||
un[i] = unary[at];
|
||||
}
|
||||
// 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 halo_u16* __restrict__ prow = pred + (long)(pid_ok ? pid : 0) * R;
|
||||
/* 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) {
|
||||
const halo_u16* __restrict__ hrow = hp + row * hp_ld;
|
||||
for (int r = tid; r < R; r += DSL_THREADS)
|
||||
sa[r] = halo_bf2f(prow[r]) * halo_bf2f(hrow[r]);
|
||||
} else {
|
||||
for (int r = tid; r < R; r += DSL_THREADS)
|
||||
sa[r] = halo_bf2f(prow[r]);
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
// 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;
|
||||
if (c < K) {
|
||||
const bool ok = cid[i] >= 0 && cid[i] < V;
|
||||
const halo_u16* __restrict__ srow = succ + (long)(ok ? cid[i] : 0) * R;
|
||||
float acc = 0.0f;
|
||||
#pragma unroll 8
|
||||
for (int r = lane; r < R; r += DSL_WAVE) acc += sa[r] * halo_bf2f(srow[r]);
|
||||
acc = halo_wave_sum(ok ? acc : 0.0f);
|
||||
if (lane == 0) ssc[c] = acc + un[i];
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
// 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;
|
||||
for (int c = 0; c < K; ++c)
|
||||
if (ssc[c] > bv) { bv = ssc[c]; best = c; }
|
||||
const int tok = cand[row * cand_ld + best];
|
||||
spid = tok;
|
||||
out[(long)s * out_ld + l] = tok;
|
||||
}
|
||||
// The next step reads spid and overwrites sa, which other threads may still be reading.
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
__global__ __launch_bounds__(DSL_THREADS) void halo_dflash_select_kernel(
|
||||
const int* __restrict__ cand, const float* __restrict__ unary,
|
||||
const halo_u16* __restrict__ hp, const int* __restrict__ anchor,
|
||||
const halo_u16* __restrict__ pred, const halo_u16* __restrict__ succ,
|
||||
int* __restrict__ out, int steps, int K, int R, int V,
|
||||
int cand_ld, int hp_ld, int out_ld, int anchor_stride) {
|
||||
halo_dflash_select_body(cand, unary, hp, anchor, pred, succ, out, steps, K, R, V, cand_ld, hp_ld,
|
||||
out_ld, anchor_stride);
|
||||
}
|
||||
__global__ __launch_bounds__(DSL_THREADS) void halo_r4dchain_dflash_select(
|
||||
const int* __restrict__ cand, const float* __restrict__ unary,
|
||||
const halo_u16* __restrict__ hp, const int* __restrict__ anchor,
|
||||
const halo_u16* __restrict__ pred, const halo_u16* __restrict__ succ,
|
||||
int* __restrict__ out, int steps, int K, int R, int V,
|
||||
int cand_ld, int hp_ld, int out_ld, int anchor_stride) {
|
||||
halo_chain_wait();
|
||||
halo_dflash_select_body(cand, unary, hp, anchor, pred, succ, out, steps, K, R, V, cand_ld, hp_ld,
|
||||
out_ld, anchor_stride);
|
||||
halo_chain_done();
|
||||
}
|
||||
|
||||
/* `chain`: the chained form (the plugin entry, where the row resolved with `chain`). */
|
||||
static int dflash_select_emit(
|
||||
const void* cand, const void* unary, const void* hp, const void* anchor,
|
||||
const void* pred, const void* succ, void* out,
|
||||
int M, int steps, int K, int R, int V, int cand_ld, int hp_ld, int out_ld,
|
||||
int anchor_stride, void* stream, bool chain);
|
||||
|
||||
extern "C" int halo_dflash_select_bf16(
|
||||
const void* cand, const void* unary, const void* hp, const void* anchor,
|
||||
const void* pred, const void* succ, void* out,
|
||||
int M, int steps, int K, int R, int V, int cand_ld, int hp_ld, int out_ld,
|
||||
int anchor_stride, void* stream)
|
||||
{
|
||||
return dflash_select_emit(cand, unary, hp, anchor, pred, succ, out, M, steps, K, R, V, cand_ld,
|
||||
hp_ld, out_ld, anchor_stride, stream, false);
|
||||
}
|
||||
|
||||
static int dflash_select_emit(
|
||||
const void* cand, const void* unary, const void* hp, const void* anchor,
|
||||
const void* pred, const void* succ, void* out,
|
||||
int M, int steps, int K, int R, int V, int cand_ld, int hp_ld, int out_ld,
|
||||
int anchor_stride, void* stream, bool chain)
|
||||
{
|
||||
if (M <= 0 || steps <= 0) return 0;
|
||||
if (K < 1 || K > DSL_MAX_K) return -1;
|
||||
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); then hp_ld is unused. */
|
||||
if (hp && hp_ld < R) return -1;
|
||||
|
||||
hipLaunchKernelGGL((chain ? halo_r4dchain_dflash_select : halo_dflash_select_kernel), dim3(M),
|
||||
dim3(DSL_THREADS), 0, (hipStream_t)stream,
|
||||
(const int*)cand, (const float*)unary, (const halo_u16*)hp,
|
||||
(const int*)anchor, (const halo_u16*)pred, (const halo_u16*)succ,
|
||||
(int*)out, steps, K, R, V, cand_ld, hp_ld, out_ld, anchor_stride);
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
// Shared operand helpers: halo_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 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;
|
||||
if (t->shape[1] < width || t->shape[0] < rows) return -1;
|
||||
const long long pitch = halo_row_pitch(t);
|
||||
return (pitch >= width) ? pitch : -1;
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_dflash_select(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* cand = halo_opt(a, DS_CAND);
|
||||
const RadTensor* un = halo_opt(a, DS_UNARY);
|
||||
const RadTensor* hp = halo_opt(a, DS_HP);
|
||||
const RadTensor* anc = halo_opt(a, DS_ANCHOR);
|
||||
const RadTensor* pr = halo_opt(a, DS_PRED);
|
||||
const RadTensor* sc = halo_opt(a, DS_SUCC);
|
||||
const RadTensor* out = halo_opt(a, DS_OUT);
|
||||
/* Only hp may be absent. */
|
||||
if (!cand || !un || !anc || !pr || !sc || !out) return HALO_NO(RAD_E_INVAL);
|
||||
|
||||
const long long steps = halo_geti_or(a, "steps", 0);
|
||||
const long long K = halo_geti_or(a, "top_k", 0);
|
||||
const long long R = halo_geti_or(a, "rank", 0);
|
||||
const long long V = halo_geti_or(a, "n_vocab", 0);
|
||||
/* 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 HALO_NO(RAD_E_SHAPE);
|
||||
const long long M = out->shape[0];
|
||||
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || V <= 0) return HALO_NO(RAD_E_INVAL);
|
||||
|
||||
/* 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 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 HALO_NO(RAD_E_SHAPE);
|
||||
/* The kernel indexes cand and unary with one pitch. */
|
||||
if (cand_ld != un_ld) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
/* 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 HALO_NO(RAD_E_DTYPE);
|
||||
if (!halo_contig(pr) || !halo_contig(sc)) return HALO_NO(RAD_E_STRIDE);
|
||||
if (halo_numel(pr) < V * R || halo_numel(sc) < V * R) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
/* 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 = halo_geti_or(a, "anchor_stride", 1);
|
||||
if (anc->dtype != RAD_I32 && anc->dtype != RAD_U32) return HALO_NO(RAD_E_DTYPE);
|
||||
if (astr < 1 || !halo_contig(anc)) return HALO_NO(RAD_E_SHAPE);
|
||||
if (halo_numel(anc) < (M - 1) * astr + 1) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
/* The chained form at decode heights, where the row resolved with `chain`. */
|
||||
const bool ch = halo_geti_or(a, "chain", 0) != 0 && M <= 64;
|
||||
return HALO_RAW(dflash_select_emit(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, ch));
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
/* Derived from libr4d/r4d_dsa.hip by the libhalo rename transform (2026-10-26), then ported to
|
||||
* gfx1151; see libhalo/README.md. */
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "halo_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_emit.h"
|
||||
#include "halo_fwht.h"
|
||||
#include "halo_q8.h"
|
||||
#include "halo_fp8_wmma.h"
|
||||
#include "halo_dt16.h" // fp8x16_to_16x8w, the 16-wide gfx1151 fragment
|
||||
#include "halo_wmma.h"
|
||||
#include <climits>
|
||||
|
||||
namespace {
|
||||
__global__ void dsa_query_kernel(const uint16_t* x, uint8_t* q, float* scale, long xp, long qp,
|
||||
long sp, int rows) {
|
||||
const int lane = threadIdx.x & 31, r = blockIdx.x * 4 + (threadIdx.x >> 5);
|
||||
if (r >= rows) return;
|
||||
float v[4];
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) v[d] = bf16_to_f32(x[(long)r * xp + lane * 4 + d]);
|
||||
halo_fwht_wave<128>(v, lane);
|
||||
float am = 1e-4f;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
v[d] = bf16_to_f32(f32_to_bf16(v[d] * 0.08838834764831845f));
|
||||
am = fmaxf(am, fabsf(v[d]));
|
||||
}
|
||||
#pragma unroll
|
||||
for (int mask = 16; mask; mask >>= 1) am = fmaxf(am, __shfl_xor(am, mask, 32));
|
||||
const uint32_t bits = __float_as_uint(am * (1.0f / 448.0f));
|
||||
const float sc = __uint_as_float((bits & 0x7f800000u) + ((bits & 0x7fffffu) ? 0x800000u : 0));
|
||||
if (!lane) scale[(long)r * sp] = sc;
|
||||
const uint32_t packed = q8_pack4<false>(v[0], v[1], v[2], v[3], 1.0f / sc);
|
||||
uint8_t* dst = q + (long)r * qp + lane * 4;
|
||||
if (((uintptr_t)dst & 3) == 0)
|
||||
*(uint32_t*)dst = packed;
|
||||
else {
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) dst[d] = (uint8_t)(packed >> (8 * d));
|
||||
}
|
||||
}
|
||||
int query_body(const RadArgs* a, RadStream stream) {
|
||||
if (!a || a->n_t < 3) return RAD_E_INVAL;
|
||||
const auto &x = a->t[0], &q = a->t[1], &s = a->t[2];
|
||||
if (x.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32) return RAD_E_DTYPE;
|
||||
if (!x.data || !q.data || !s.data) return RAD_E_INVAL;
|
||||
if (halo_geti_or(a, "n", 0) != 128 || x.rank != 2 || q.rank != 2 || s.rank != 2 ||
|
||||
x.shape[0] < 1 || x.shape[0] > INT_MAX - 3 || x.shape[1] != 128 ||
|
||||
q.shape[0] != x.shape[0] || q.shape[1] != 128 || s.shape[0] != x.shape[0] ||
|
||||
s.shape[1] != 1 || x.stride[1] != 1 || q.stride[1] != 1 || s.stride[1] != 1 ||
|
||||
x.stride[0] < 128 || q.stride[0] < 128 || s.stride[0] < 1)
|
||||
return RAD_E_SHAPE;
|
||||
return HALO_EMIT(stream, dsa_query_kernel, dim3((x.shape[0] + 3) / 4), dim3(128), 0,
|
||||
(const uint16_t*)x.data, (uint8_t*)q.data, (float*)s.data, x.stride[0],
|
||||
q.stride[0], s.stride[0], (int)x.shape[0]);
|
||||
}
|
||||
struct ScoreMeta {
|
||||
long qr, qh, qsr, qsc, gr, gc, kr, ksr, btr, btc, cur, ncr, op;
|
||||
int rows, blocks, seqs, pages, row0;
|
||||
};
|
||||
__device__ uint32_t bytes4(const uint8_t* p) {
|
||||
if (!((uintptr_t)p & 3)) return *(const uint32_t*)p;
|
||||
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
/* The lane's sixteen E4M3 codes at `p` (dims d .. d+15 of one row), widened exactly to the 16-bit
|
||||
* operand of halo_wmma.h. The rows are 136 bytes apart, so an odd row is only 8-byte aligned: two
|
||||
* uint2 loads rather than one uint4. Exact in either format (E4M3 has 3 mantissa bits), so f16's
|
||||
* one-instruction pack is what the score path takes. */
|
||||
typedef DT16<1> DsaD;
|
||||
typedef DsaD::frag dsa_frag16;
|
||||
__device__ __forceinline__ dsa_frag16 dsa_fp8_frag(const uint8_t* __restrict__ p) {
|
||||
const uint2 a = *(const uint2*)p, b = *(const uint2*)(p + 8);
|
||||
uint32_t w8[8];
|
||||
fp8x16_to_16x8w<DsaD>(make_uint4(a.x, a.y, b.x, b.y), w8);
|
||||
return DsaD::mk(w8);
|
||||
}
|
||||
|
||||
/* Two waves cover all 32 heads and reuse the query across `kScoreTiles` 16-key tiles, one up to 32
|
||||
* blocks and two past them. FP8 dot products stay on WMMA; scales and the signed per-head gates
|
||||
* fold only after the per-head ReLU. The query operands start at a part's first row, so only the
|
||||
* sequence lookup sees the step row (`row0 + r`). */
|
||||
template <int kScoreTiles>
|
||||
__global__ void dsa_score_kernel(const uint8_t* q, const float* qs, const float* gate,
|
||||
const uint8_t* k, const float* ks, const int* bt, const int* cu,
|
||||
const int* nc, float* out, ScoreMeta m) {
|
||||
constexpr int kScoreKeys = 16 * kScoreTiles;
|
||||
__shared__ __align__(16) uint8_t qa[32 * 136], kb[kScoreKeys * 136];
|
||||
__shared__ int seq, pages[kScoreKeys];
|
||||
__shared__ float scales[kScoreKeys], coefficients[32], partial[2][kScoreKeys];
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int r = blockIdx.y, b0 = blockIdx.x * kScoreKeys;
|
||||
if (!tid) {
|
||||
seq = -1;
|
||||
for (int s = 0; s < m.seqs; ++s)
|
||||
if (m.row0 + r >= cu[(long)s * m.cur] && m.row0 + r < cu[(long)(s + 1) * m.cur]) {
|
||||
seq = s;
|
||||
break;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
const int live = seq >= 0 ? min(nc[(long)seq * m.ncr], m.blocks) : 0;
|
||||
if (b0 >= live) {
|
||||
for (int i = tid; i < kScoreKeys; i += 64)
|
||||
if (b0 + i < m.blocks) out[(long)r * m.op + b0 + i] = -INFINITY;
|
||||
return;
|
||||
}
|
||||
for (int i = tid; i < kScoreKeys; i += 64) {
|
||||
const int b = b0 + i;
|
||||
int p = seq >= 0 && b < m.blocks && b < nc[(long)seq * m.ncr]
|
||||
? bt[(long)seq * m.btr + b * m.btc]
|
||||
: -1;
|
||||
if (p >= m.pages) p = -1;
|
||||
pages[i] = p;
|
||||
scales[i] = p >= 0 ? ks[(long)p * m.ksr] : 0;
|
||||
}
|
||||
if (tid < 32)
|
||||
coefficients[tid] = qs[(long)r * m.qsr + tid * m.qsc] * gate[(long)r * m.gr + tid * m.gc];
|
||||
for (int j = tid; j < 32 * 32; j += 64) {
|
||||
const int h = j / 32, d = (j % 32) * 4;
|
||||
*(uint32_t*)(qa + h * 136 + d) = bytes4(q + (long)r * m.qr + (long)h * m.qh + d);
|
||||
}
|
||||
__syncthreads();
|
||||
for (int j = tid; j < kScoreKeys * 32; j += 64) {
|
||||
const int b = j / 32, d = (j % 32) * 4, p = pages[b];
|
||||
*(uint32_t*)(kb + b * 136 + d) = p >= 0 ? bytes4(k + (long)p * m.kr + d) : 0;
|
||||
}
|
||||
__syncthreads();
|
||||
// gfx1151: a lane holds the WHOLE 16-wide k run of its fragment row (column), so a gather is
|
||||
// 16 consecutive E4M3 codes widened through halo_dt16.h's fp8x16_to_16x8w, not 8 codes split
|
||||
// across the lane half-pair. The A row is the head, the B column the key; the accumulator's
|
||||
// element e belongs to row 2*e + (lane>>4) (halo_wmma.h), so the gate below indexes the head
|
||||
// by 2*e + h rather than by the gfx12 form's 8*h + e.
|
||||
v8f acc[kScoreTiles];
|
||||
const int aoff = (wave * 16 + (lane & 15)) * 136; // this lane's A row (a head)
|
||||
#pragma unroll
|
||||
for (int tile = 0; tile < kScoreTiles; ++tile) acc[tile] = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 128; d += 16) {
|
||||
const dsa_frag16 a = dsa_fp8_frag(qa + aoff + d);
|
||||
#pragma unroll
|
||||
for (int tile = 0; tile < kScoreTiles; ++tile)
|
||||
acc[tile] = DsaD::wmma(a, dsa_fp8_frag(kb + (tile * 16 + (lane & 15)) * 136 + d), acc[tile]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int tile = 0; tile < kScoreTiles; ++tile) {
|
||||
float value = 0;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e)
|
||||
value += fmaxf(acc[tile][e], 0.0f) * coefficients[wave * 16 + 2 * e + (lane >> 4)];
|
||||
value += __shfl_xor(value, 16, 32);
|
||||
if (lane < 16) partial[wave][tile * 16 + lane] = value;
|
||||
}
|
||||
__syncthreads();
|
||||
for (int i = tid; i < kScoreKeys; i += 64)
|
||||
if (b0 + i < m.blocks)
|
||||
out[(long)r * m.op + b0 + i] =
|
||||
pages[i] >= 0 ? (partial[0][i] + partial[1][i]) * scales[i] * 0.015625f : -INFINITY;
|
||||
}
|
||||
/* The step's cu rebased to a part's first row: an op that reads cu over the part's own rows
|
||||
* (qsa_select) then finds each row's sequence unchanged. */
|
||||
__global__ void dsa_rebase_kernel(const int* cu, int* out, long cs, long os, int n, int row0) {
|
||||
for (int i = threadIdx.x; i < n; i += blockDim.x) out[(long)i * os] = cu[(long)i * cs] - row0;
|
||||
}
|
||||
int score_body(const RadArgs* a, RadStream stream) {
|
||||
if (!a || a->n_t < 9) return RAD_E_INVAL;
|
||||
RadTensor q = a->t[0], qs = a->t[1], g = a->t[2];
|
||||
RadTensor k = a->t[3], ks = a->t[4];
|
||||
const bool packed = k.dtype == RAD_U8;
|
||||
if (packed) {
|
||||
if (ks.data || k.rank != 4 || k.shape[1] != 1 || k.shape[2] != 4 || k.shape[3] != 34 ||
|
||||
k.stride[3] != 1 || k.stride[2] != 34 || k.stride[0] < 136 || k.stride[0] % 4 ||
|
||||
((uintptr_t)k.data & 3))
|
||||
return RAD_E_SHAPE;
|
||||
ks = {};
|
||||
ks.data = k.data ? (uint8_t*)k.data + 128 : nullptr;
|
||||
ks.dtype = RAD_F32;
|
||||
ks.rank = 1;
|
||||
ks.shape[0] = k.shape[0];
|
||||
ks.stride[0] = k.stride[0] / 4;
|
||||
k.dtype = RAD_F8E4M3;
|
||||
k.rank = 2;
|
||||
k.shape[1] = 128;
|
||||
k.stride[1] = 1;
|
||||
}
|
||||
const auto &bt = a->t[5], &cu = a->t[6], &nc = a->t[7], &o = a->t[8];
|
||||
const RadTensor* cu_part = rad_arg_in(a, 9);
|
||||
const long long part = halo_geti_or(a, "row_part", -1);
|
||||
if (q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && g.rank == 2 &&
|
||||
q.shape[0] == g.shape[0] * 32 && qs.shape[0] == q.shape[0]) {
|
||||
q.rank = 3;
|
||||
q.shape[0] = g.shape[0];
|
||||
q.shape[2] = q.shape[1];
|
||||
q.shape[1] = 32;
|
||||
q.stride[2] = q.stride[1];
|
||||
q.stride[1] = q.stride[0];
|
||||
q.stride[0] *= 32;
|
||||
qs.shape[0] = g.shape[0];
|
||||
qs.shape[1] = 32;
|
||||
qs.stride[1] = qs.stride[0];
|
||||
qs.stride[0] *= 32;
|
||||
}
|
||||
/* A part scores o's rows from step row part * rows; the query operands span the step. */
|
||||
const long long rows = o.rank == 2 ? o.shape[0] : 0, row0 = part > 0 ? part * rows : 0;
|
||||
if (part >= 0) {
|
||||
if (q.rank != 3 || qs.rank != 2 || g.rank != 2 || rows < 1 || part > INT_MAX / rows ||
|
||||
q.shape[0] < row0 + rows || qs.shape[0] != q.shape[0] || g.shape[0] != q.shape[0])
|
||||
return RAD_E_SHAPE;
|
||||
if (q.data && qs.data && g.data) {
|
||||
q.data = (uint8_t*)q.data + row0 * q.stride[0];
|
||||
qs.data = (float*)qs.data + row0 * qs.stride[0];
|
||||
g.data = (float*)g.data + row0 * g.stride[0];
|
||||
}
|
||||
q.shape[0] = qs.shape[0] = g.shape[0] = rows;
|
||||
}
|
||||
if (cu_part) {
|
||||
if (part < 0) return RAD_E_INVAL;
|
||||
if (cu_part->dtype != RAD_I32) return RAD_E_DTYPE;
|
||||
if (cu_part->rank != 1 || cu_part->shape[0] != cu.shape[0] || cu_part->stride[0] < 1)
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
if (q.dtype != RAD_F8E4M3 || k.dtype != RAD_F8E4M3 || qs.dtype != RAD_F32 ||
|
||||
g.dtype != RAD_F32 || ks.dtype != RAD_F32 || o.dtype != RAD_F32 || bt.dtype != RAD_I32 ||
|
||||
cu.dtype != RAD_I32 || nc.dtype != RAD_I32)
|
||||
return RAD_E_DTYPE;
|
||||
for (int i = 0; i < 9; ++i)
|
||||
if (!(packed && i == 4) && !a->t[i].data) return RAD_E_INVAL;
|
||||
if (halo_geti_or(a, "n", 0) != 128 || halo_geti_or(a, "heads", 0) != 32 || q.rank != 3 ||
|
||||
q.shape[0] < 1 || q.shape[0] > 65535 || q.shape[1] != 32 || q.shape[2] != 128 ||
|
||||
q.stride[2] != 1 || q.stride[1] < 128 || q.stride[0] < 32 * q.stride[1] || qs.rank != 2 ||
|
||||
g.rank != 2 || qs.shape[0] != q.shape[0] || g.shape[0] != q.shape[0] || qs.shape[1] != 32 ||
|
||||
g.shape[1] != 32 || qs.stride[1] < 1 || g.stride[1] < 1 ||
|
||||
qs.stride[0] < 32 * qs.stride[1] || g.stride[0] < 32 * g.stride[1] || k.rank != 2 ||
|
||||
k.shape[0] < 1 || k.shape[0] > INT_MAX || k.shape[1] != 128 || k.stride[1] != 1 ||
|
||||
k.stride[0] < 128 || ks.rank != 1 || ks.shape[0] != k.shape[0] || ks.stride[0] < 1 ||
|
||||
bt.rank != 2 || bt.shape[0] < 1 || bt.shape[0] > INT_MAX || bt.stride[1] < 1 ||
|
||||
cu.rank != 1 || cu.shape[0] != bt.shape[0] + 1 || nc.rank != 1 ||
|
||||
nc.shape[0] != bt.shape[0] || cu.stride[0] < 1 || nc.stride[0] < 1 || o.rank != 2 ||
|
||||
o.shape[0] != q.shape[0] || o.shape[1] < 1 || o.shape[1] > INT_MAX - 15 ||
|
||||
o.shape[1] > bt.shape[1] || o.stride[1] != 1 || o.stride[0] < o.shape[1] ||
|
||||
bt.stride[0] < bt.shape[1] * bt.stride[1])
|
||||
return RAD_E_SHAPE;
|
||||
ScoreMeta m{ q.stride[0], q.stride[1], qs.stride[0], qs.stride[1], g.stride[0],
|
||||
g.stride[1], k.stride[0], ks.stride[0], bt.stride[0], bt.stride[1],
|
||||
cu.stride[0], nc.stride[0], o.stride[0], (int)q.shape[0], (int)o.shape[1],
|
||||
(int)bt.shape[0], (int)k.shape[0], (int)row0 };
|
||||
if (cu_part) {
|
||||
const int rc = HALO_EMIT(stream, dsa_rebase_kernel, dim3(1), dim3(64), 0,
|
||||
(const int*)cu.data, (int*)cu_part->data, cu.stride[0],
|
||||
cu_part->stride[0], (int)cu.shape[0], (int)row0);
|
||||
if (rc != RAD_OK) return rc;
|
||||
}
|
||||
#define SCORE(NT) \
|
||||
HALO_EMIT(stream, (dsa_score_kernel<NT>), dim3((m.blocks + 16 * NT - 1) / (16 * NT), m.rows), \
|
||||
dim3(64), 0, (const uint8_t*)q.data, (const float*)qs.data, (const float*)g.data, \
|
||||
(const uint8_t*)k.data, (const float*)ks.data, (const int*)bt.data, \
|
||||
(const int*)cu.data, (const int*)nc.data, (float*)o.data, m)
|
||||
if (m.blocks <= 32) return SCORE(1);
|
||||
return SCORE(2);
|
||||
#undef SCORE
|
||||
}
|
||||
/* One wave per pool: all softmax channels and the full Hadamard stay in registers. */
|
||||
__global__ void dsa_pool_kernel(const uint16_t* kg, const float* ape, uint8_t* q, float* scale,
|
||||
const int* page, uint8_t* cache, long kp, long ap, long qp, long sp,
|
||||
long pp, long cp, int rows, int pages) {
|
||||
const int lane = threadIdx.x & 31, r = blockIdx.x * 4 + (threadIdx.x >> 5);
|
||||
if (r >= rows) return;
|
||||
float v[4];
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
const int col = lane * 4 + d;
|
||||
float g[4], mx = -INFINITY;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
g[j] = bf16_to_f32(kg[((long)r * 4 + j) * kp + 128 + col]) + ape[(long)j * ap + col];
|
||||
mx = fmaxf(mx, g[j]);
|
||||
}
|
||||
float num = 0, den = 0;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
const float p = expf(g[j] - mx);
|
||||
num += p * bf16_to_f32(kg[((long)r * 4 + j) * kp + col]);
|
||||
den += p;
|
||||
}
|
||||
v[d] = bf16_to_f32(f32_to_bf16(num / den));
|
||||
}
|
||||
halo_fwht_wave<128>(v, lane);
|
||||
float am = 1e-4f;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
v[d] = bf16_to_f32(f32_to_bf16(v[d] * 0.08838834764831845f));
|
||||
am = fmaxf(am, fabsf(v[d]));
|
||||
}
|
||||
#pragma unroll
|
||||
for (int mask = 16; mask; mask >>= 1) am = fmaxf(am, __shfl_xor(am, mask, 32));
|
||||
const uint32_t bits = __float_as_uint(am * (1.0f / 448.0f));
|
||||
const float sc = __uint_as_float((bits & 0x7f800000u) + ((bits & 0x7fffffu) ? 0x800000u : 0));
|
||||
if (!lane) scale[(long)r * sp] = sc;
|
||||
const uint32_t packed = q8_pack4<false>(v[0], v[1], v[2], v[3], 1.0f / sc);
|
||||
uint8_t* dst = q + (long)r * qp + lane * 4;
|
||||
if (((uintptr_t)dst & 3) == 0)
|
||||
*(uint32_t*)dst = packed;
|
||||
else {
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) dst[d] = (uint8_t)(packed >> (8 * d));
|
||||
}
|
||||
if (cache) {
|
||||
const int p = page[(long)r * pp];
|
||||
if (p >= 0 && p < pages) {
|
||||
uint8_t* out = cache + (long)p * cp;
|
||||
*(uint32_t*)(out + lane * 4) = packed;
|
||||
if (!lane) *(float*)(out + 128) = sc;
|
||||
}
|
||||
}
|
||||
}
|
||||
int pool_body(const RadArgs* a, RadStream stream) {
|
||||
if (halo_geti_or(a, "block_size", 4) != 4) return RAD_E_SHAPE;
|
||||
if (!a || a->n_t < 4) return RAD_E_INVAL;
|
||||
const auto &kg = a->t[0], &ape = a->t[1], &q = a->t[2], &s = a->t[3];
|
||||
const auto *page = rad_arg_in(a, 4), *cache = rad_arg_in(a, 5);
|
||||
if ((page != nullptr) != (cache != nullptr)) return RAD_E_INVAL;
|
||||
if (cache &&
|
||||
(page->dtype != RAD_I32 || page->rank != 1 || page->shape[0] != q.shape[0] ||
|
||||
page->stride[0] < 1 || cache->dtype != RAD_U8 || cache->rank != 4 || cache->shape[0] < 1 ||
|
||||
cache->shape[0] > INT_MAX || cache->shape[1] != 1 || cache->shape[2] != 4 ||
|
||||
cache->shape[3] != 34 || cache->stride[3] != 1 || cache->stride[2] != 34 ||
|
||||
cache->stride[0] < 136 || cache->stride[0] % 4 || ((uintptr_t)cache->data & 3)))
|
||||
return RAD_E_SHAPE;
|
||||
if (kg.dtype != RAD_BF16 || ape.dtype != RAD_F32 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32)
|
||||
return RAD_E_DTYPE;
|
||||
if (halo_geti_or(a, "n", 0) != 128 || halo_geti_or(a, "ratio", 0) != 4 || kg.rank != 2 ||
|
||||
ape.rank != 2 || q.rank != 2 || s.rank != 2 || !kg.data || !ape.data || !q.data ||
|
||||
!s.data || q.shape[0] < 1 || q.shape[0] > INT_MAX / 4 || kg.shape[0] != q.shape[0] * 4 ||
|
||||
kg.shape[1] != 256 || ape.shape[0] != 4 || ape.shape[1] != 128 || q.shape[1] != 128 ||
|
||||
s.shape[0] != q.shape[0] || s.shape[1] != 1 || kg.stride[1] != 1 || ape.stride[1] != 1 ||
|
||||
q.stride[1] != 1 || s.stride[1] != 1 || kg.stride[0] < 256 || ape.stride[0] < 128 ||
|
||||
q.stride[0] < 128 || s.stride[0] < 1)
|
||||
return RAD_E_SHAPE;
|
||||
return HALO_EMIT(
|
||||
stream, dsa_pool_kernel, dim3((q.shape[0] + 3) / 4), dim3(128), 0, (const uint16_t*)kg.data,
|
||||
(const float*)ape.data, (uint8_t*)q.data, (float*)s.data,
|
||||
page ? (const int*)page->data : nullptr, cache ? (uint8_t*)cache->data : nullptr,
|
||||
kg.stride[0], ape.stride[0], q.stride[0], s.stride[0], page ? page->stride[0] : 0,
|
||||
cache ? cache->stride[0] : 0, (int)q.shape[0], cache ? (int)cache->shape[0] : 0);
|
||||
}
|
||||
}
|
||||
extern "C" int halo_rad_dsa_pool(const RadArgs* a, RadStream stream) { return pool_body(a, stream); }
|
||||
extern "C" int halo_rad_dsa_query(const RadArgs* a, RadStream stream) {
|
||||
return query_body(a, stream);
|
||||
}
|
||||
extern "C" int halo_rad_dsa_score(const RadArgs* a, RadStream stream) {
|
||||
return score_body(a, stream);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/* Derived from libr4d/r4d_dt16.h by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_dt16.h -- 16-bit operand traits for the attention kernels, gfx1151.
|
||||
//
|
||||
// This is the gfx11 counterpart of libr4d's DT16 layer, and the difference is the
|
||||
// whole porting story for attention. The two architectures disagree on what one
|
||||
// lane holds (halo_wmma.h states the layouts and how they were measured):
|
||||
//
|
||||
// a lane's A / B fragment the k its element e holds
|
||||
// gfx1201 (RDNA4) 8 x 16-bit (4 dwords) k = 8*(half) + e, half = lane>>4
|
||||
// gfx1151 (RDNA3.5) 16 x 16-bit (8 dwords) k = e (lanes 16-31 replicate)
|
||||
//
|
||||
// libr4d's attention kernels are built around a transposed score matrix
|
||||
// S^T = K.Q^T so that the D column -- the query -- stays (lane & 15) on both
|
||||
// architectures; halo_wmma.h notes that this is why those kernels are portable
|
||||
// at all. What changes is the ROW: on gfx12 a lane's accumulator element e is
|
||||
// key 8*half + e of the 16-key tile, on gfx11 it is key 2*e + (lane>>4). Both
|
||||
// spread the tile's sixteen keys over the half-pair, so the kernels' existing
|
||||
// swap16 (lane ^ 16) row-max / row-sum reductions keep their meaning; a port
|
||||
// changes the key index and the fragment width, not the softmax algebra.
|
||||
//
|
||||
// * mk() takes the lane's EIGHT dwords (16 values) instead of four.
|
||||
// * gather reads 32 bytes at the un-split k offset (no 8*half term).
|
||||
// * P fragments the softmax's eight values are keys 2e+half; a 16-consecutive
|
||||
// key fragment is assembled across the half-pair (see p16w).
|
||||
// * store each lane writes its eight values at head dim 2e+half.
|
||||
//
|
||||
// Both sources are exact in either 16-bit format (an fp8 e4m3 K/V has 3 mantissa
|
||||
// bits, bf16 7, f16 10), so DT16<0> (bf16) and DT16<1> (f16) stay interchangeable
|
||||
// for correctness; they differ in range and in convert cost, as r4d_dt16.h says.
|
||||
// gfx1151 has no v_cvt_pk_bf16_f32 either, so DT16<0>::pk is the software RTNE
|
||||
// halo_wmma.h already uses, and f16 packs two floats in one instruction.
|
||||
#pragma once
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <cstdint>
|
||||
#include "halo_common.h"
|
||||
#include "halo_wmma.h" // v16bf / v16hf / v8f, halo::mma, pk_bf16, pk_f16, f32_to_bf16
|
||||
#include "halo_fp8_wmma.h" // e4m3_pk: the exact e4m3 unpack (no fp8 convert insts on gfx11)
|
||||
|
||||
typedef __fp16 v2hf_dt __attribute__((ext_vector_type(2)));
|
||||
|
||||
// GROW = how many octaves the running row max may exceed the reference max before the
|
||||
// accumulator must be rescaled, exactly as r4d_dt16.h defines it for each format.
|
||||
template <int F16> struct DT16;
|
||||
|
||||
template <> struct DT16<0> { // bf16: exponent range of f32
|
||||
typedef v16bf frag;
|
||||
static constexpr float SHIFT = 0.0f;
|
||||
static constexpr float GROW = 60.0f; // 2^60 * |v| * n stays far under f32 max
|
||||
|
||||
// From the lane's eight dwords, i.e. its full sixteen-value k run in order.
|
||||
__device__ __forceinline__ static frag mk(const uint32_t w[8]) {
|
||||
union { uint32_t u[8]; frag f; } q;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) q.u[i] = w[i];
|
||||
return q.f;
|
||||
}
|
||||
__device__ __forceinline__ static v8f wmma(frag a, frag b, v8f c) { return halo::mma(a, b, c); }
|
||||
__device__ __forceinline__ static uint32_t pk(float x, float y) { return halo::pk_bf16(x, y); }
|
||||
// Two f32 to two bf16 in a dword, element order (no lane-half permutation on gfx11).
|
||||
__device__ __forceinline__ static uint32_t pkv(v2f x) {
|
||||
union { v2f f; float e[2]; } s;
|
||||
s.f = x;
|
||||
return halo::pk_bf16(s.e[0], s.e[1]);
|
||||
}
|
||||
__device__ __forceinline__ static uint32_t from_bf16w(uint32_t w) { return w; } // identity
|
||||
};
|
||||
|
||||
template <> struct DT16<1> { // f16: 3 more mantissa bits, 1 convert instead of 6
|
||||
typedef v16hf frag;
|
||||
static constexpr float SHIFT = 0.0f;
|
||||
static constexpr float GROW = 14.0f; // p <= 2^14 = 16384 < 65504
|
||||
|
||||
__device__ __forceinline__ static frag mk(const uint32_t w[8]) {
|
||||
union { uint32_t u[8]; frag f; } q;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) q.u[i] = w[i];
|
||||
return q.f;
|
||||
}
|
||||
__device__ __forceinline__ static v8f wmma(frag a, frag b, v8f c) { return halo::mma(a, b, c); }
|
||||
__device__ __forceinline__ static uint32_t pk(float x, float y) { return halo::pk_f16(x, y); }
|
||||
__device__ __forceinline__ static uint32_t pkv(v2f x) {
|
||||
union { v2f f; float e[2]; } s;
|
||||
s.f = x;
|
||||
return halo::pk_f16(s.e[0], s.e[1]);
|
||||
}
|
||||
// two bf16 in a dword -> two f16 in a dword (bf16->f32 is a shift, so three VALU).
|
||||
__device__ __forceinline__ static uint32_t from_bf16w(uint32_t w) {
|
||||
return halo::pk_f16(__builtin_bit_cast(float, w << 16),
|
||||
__builtin_bit_cast(float, w & 0xffff0000u));
|
||||
}
|
||||
};
|
||||
|
||||
// Widen sixteen fp8 (four dwords) to the lane's eight 16-bit dwords, in element order.
|
||||
// On gfx12 the same widening is eight values with a lane-half permute; on gfx11 every lane
|
||||
// holds the whole 16-wide run, so this is the four dwords twice over and no permute.
|
||||
template <class D>
|
||||
__device__ __forceinline__ void fp8x16_to_16x8w(uint4 raw, uint32_t w8[8]) {
|
||||
const uint32_t d[4] = { raw.x, raw.y, raw.z, raw.w };
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
w8[q * 2 + 0] = D::pkv(halo_fp8::e4m3_pk<false>(d[q]));
|
||||
w8[q * 2 + 1] = D::pkv(halo_fp8::e4m3_pk<true>(d[q]));
|
||||
}
|
||||
}
|
||||
|
||||
// Widen eight fp8 (two dwords) to four 16-bit dwords in element order -- the narrow form,
|
||||
// kept for the kernels that stage fewer than sixteen k at a time (r4d's fp8x8_to_16x4w).
|
||||
template <class D>
|
||||
__device__ __forceinline__ void fp8x8_to_16x4w(uint2 raw, uint32_t w4[4]) {
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
const int wv = (q == 0) ? (int)raw.x : (int)raw.y;
|
||||
w4[q * 2 + 0] = D::pkv(halo_fp8::e4m3_pk<false>(wv));
|
||||
w4[q * 2 + 1] = D::pkv(halo_fp8::e4m3_pk<true>(wv));
|
||||
}
|
||||
}
|
||||
|
||||
/* Eight k6_v4 codes as four f16 dwords, dims (2i, 2i+1) in dword i -- r4d_dt16.h's
|
||||
* k6x8_to_f16x4w, unchanged: the unpack is exact integer/scale arithmetic and touches no
|
||||
* WMMA layout, so it ports as it stands. `half` selects which eight of the sixteen dims a
|
||||
* caller wants; a gfx1151 16-wide fragment asks for both halves into w8[0..7]. */
|
||||
__device__ __forceinline__ void k6x8_to_f16x4w(uint32_t lo, uint32_t hb, int half, uint32_t s2,
|
||||
uint32_t* w4) {
|
||||
typedef _Float16 h2 __attribute__((ext_vector_type(2)));
|
||||
const uint32_t ev = ((lo & 0x0F0F0F0Fu) | ((half ? hb : hb << 4) & 0x30303030u)) ^ 0x20202020u;
|
||||
const uint32_t od = (((lo >> 4) & 0x0F0F0F0Fu) | ((half ? hb >> 2 : hb << 2) & 0x30303030u))
|
||||
^ 0x20202020u;
|
||||
const h2 s = __builtin_bit_cast(h2, s2);
|
||||
const h2 bias = { (_Float16)1056.0f, (_Float16)1056.0f };
|
||||
#pragma unroll
|
||||
for (int b = 0; b < 4; ++b) {
|
||||
const uint32_t sel = (uint32_t)b | 0x0c00u | ((uint32_t)(4 + b) << 16) | 0x0c000000u;
|
||||
const uint32_t x = __builtin_amdgcn_perm(od, ev, sel) | 0x64006400u;
|
||||
w4[b] = __builtin_bit_cast(uint32_t, (__builtin_bit_cast(h2, x) - bias) * s);
|
||||
}
|
||||
}
|
||||
|
||||
/* Build a 16-consecutive-key P fragment from the lane's eight softmax values.
|
||||
*
|
||||
* On gfx1151 a lane's accumulator element e is key 2*e + (lane>>4) of the tile, so a lane holds
|
||||
* the keys of ONE parity and the other eight live in lane ^ 16 -- the same split the kernels
|
||||
* already reduce across for the row max and row sum. The WMMA's A operand wants the sixteen keys
|
||||
* in order, so the halves are interleaved here: four lane-16 exchanges move the partner's four
|
||||
* dwords across, then key k takes element k>>1 from whichever half owns parity k&1. `w` is the
|
||||
* lane's own four dwords (its eight keys in order); `p16` the assembled eight. */
|
||||
template <class D>
|
||||
__device__ __forceinline__ void p16w(const uint32_t w[4], uint32_t p16[8]) {
|
||||
(void)sizeof(D);
|
||||
const int mine_h = (int)((threadIdx.x >> 4) & 1); // the parity this lane holds
|
||||
uint32_t o[4];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) o[i] = halo_xor_lane_u32<16>(w[i]);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) p16[i] = 0u;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < 16; ++k) {
|
||||
const int e = k >> 1; // accumulator element index
|
||||
const uint32_t src = (((k & 1) == mine_h) ? w : o)[e >> 1];
|
||||
const uint32_t v16 = (e & 1) ? (src >> 16) : (src & 0xFFFFu);
|
||||
p16[k >> 1] |= v16 << ((k & 1) ? 16 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* The store side of the same mapping: project a 16-consecutive-dim accumulator onto the lane's
|
||||
* eight values. O's row is the head dim and its column the query (lane & 15), so a lane's
|
||||
* element e is head dim 2*e + (lane>>4) -- the values it packs are at even (or odd) dims in
|
||||
* order, and each is written at its own offset. Returned as the lane's eight 16-bit values in
|
||||
* element order; a caller stores element e at dim 2*e + (lane>>4). */
|
||||
template <class D>
|
||||
__device__ __forceinline__ void o8w(const float acc[8], float inv, uint32_t w4[4]) {
|
||||
uint32_t v[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) v[e] = D::pk(acc[e] * inv, 0.0f) & 0xFFFFu;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) w4[i] = v[i * 2] | (v[i * 2 + 1] << 16);
|
||||
}
|
||||
|
||||
/* Did any lane of the wave take the branch? The row-max test is wave-wide because the
|
||||
* accumulator rescale it guards must be taken by the whole half-pair together. */
|
||||
__device__ __forceinline__ int wave_any(bool c) {
|
||||
return (int)__builtin_amdgcn_ballot_w32(c);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/* Derived from libr4d/r4d_emit.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
// halo_emit.h -- the one launch path every libhalo kernel goes through.
|
||||
//
|
||||
// `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. halo_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_HALO_TRACE and feeds halo_record_dispatches (halo.h).
|
||||
|
||||
#ifndef HALO_EMIT_H
|
||||
#define HALO_EMIT_H
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <tuple>
|
||||
|
||||
#include "rad_abi.h"
|
||||
#include "halo_args.h"
|
||||
|
||||
/* halo_record_dispatches' log (halo_rows.cpp): while `halo_dispatch_log` is set, each launch appends
|
||||
* its function and counts it in `halo_dispatch_n`, which may run past `halo_dispatch_cap`. */
|
||||
extern const void** halo_dispatch_log;
|
||||
extern int halo_dispatch_cap;
|
||||
extern int halo_dispatch_n;
|
||||
|
||||
/* `func` is the kernel's host stub; for a template, the instantiation's own symbol. */
|
||||
template <class... P, class... A>
|
||||
inline int halo_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;
|
||||
std::tuple<P...> vals(static_cast<P>(args)...);
|
||||
void* params[sizeof...(P) + 1];
|
||||
std::apply([&](P&... v) {
|
||||
int i = 0;
|
||||
((params[i++] = (void*)&v), ...);
|
||||
}, vals);
|
||||
params[sizeof...(P)] = nullptr;
|
||||
|
||||
if (halo_dispatch_log) {
|
||||
if (halo_dispatch_n < halo_dispatch_cap) halo_dispatch_log[halo_dispatch_n] = func;
|
||||
++halo_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 (halo_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, (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, 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, params, shared_bytes,
|
||||
(hipStream_t)stream) == hipSuccess ? RAD_OK : RAD_E_DEVICE;
|
||||
if (halo_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. A test may define HALO_EMIT to drive the same
|
||||
* sources through a host SIMT emulator, as with HALO_KLAUNCH (halo_launch.h). */
|
||||
#ifndef HALO_EMIT
|
||||
#define HALO_EMIT(stream, kernel, grid, block, lds, ...) \
|
||||
halo_emit((stream), (kernel), (grid), (block), (uint32_t)(lds), __VA_ARGS__)
|
||||
#endif
|
||||
|
||||
#endif /* HALO_EMIT_H */
|
||||
@@ -0,0 +1,100 @@
|
||||
/* Derived from libr4d/r4d_enc.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
/* halo_enc.h -- the encoding checks libhalo's relayouts make before rearranging a weight.
|
||||
*
|
||||
* 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"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace halo_enc {
|
||||
|
||||
/* The affine encoding a kernel reads: `codes`, a `scale` of dtype `scale` over [br x bc], an
|
||||
* integer zero of dtype `zero` when `zero` is not RAD_DT_INVALID, `transform` exactly ("" for
|
||||
* none), and no other plane. */
|
||||
inline bool affine(const RadEncoding* e, uint32_t codes, uint32_t scale, int64_t br, int64_t bc,
|
||||
uint32_t zero = RAD_DT_INVALID, const char* transform = "") {
|
||||
if (!e || !rad_enc_is(e, "affine")) return false;
|
||||
if (std::strncmp(e->transform, transform, RAD_ENC_STR) != 0) return false;
|
||||
if (e->n_planes != (zero != RAD_DT_INVALID ? 3 : 2)) return false;
|
||||
if (e->plane[0].dtype != codes || e->plane[0].block[1] != 1) return false;
|
||||
const int s = rad_enc_find(e, "scale");
|
||||
if (s < 0 || e->plane[s].dtype != scale || e->plane[s].kind != RAD_PLANE_TILED ||
|
||||
e->plane[s].block[0] != br || e->plane[s].block[1] != bc) return false;
|
||||
if (zero != RAD_DT_INVALID) {
|
||||
const int z = rad_enc_find(e, "zero");
|
||||
if (z < 0 || e->plane[z].dtype != zero || e->plane[z].block[0] != br ||
|
||||
e->plane[z].block[1] != bc) return false;
|
||||
}
|
||||
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. 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;
|
||||
if (std::strncmp(e->transform, transform, RAD_ENC_STR) != 0) return false;
|
||||
if (e->n_planes != 3) return false;
|
||||
if (e->plane[0].dtype != codes || e->plane[0].block[1] != 1) return false;
|
||||
const int s = rad_enc_find(e, "scale");
|
||||
if (s < 0 || e->plane[s].dtype != scale || e->plane[s].kind != RAD_PLANE_TILED ||
|
||||
e->plane[s].block[0] != br || e->plane[s].block[1] != bc) return false;
|
||||
const int t = rad_enc_find(e, "table");
|
||||
return t >= 0 && e->plane[t].dtype == tab && e->plane[t].kind == RAD_PLANE_TABLE &&
|
||||
e->plane[t].extent[0] == 1 && e->plane[t].extent[1] == entries;
|
||||
}
|
||||
|
||||
/* 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 = "") {
|
||||
if (!e || !rad_enc_is(e, "affine")) return false;
|
||||
if (std::strncmp(e->transform, transform, RAD_ENC_STR) != 0) return false;
|
||||
if (e->n_planes != 4) return false;
|
||||
if (e->plane[0].dtype != codes || e->plane[0].block[1] != 1) return false;
|
||||
const int s = rad_enc_find(e, "scale");
|
||||
if (s < 0 || e->plane[s].dtype != scale || e->plane[s].kind != RAD_PLANE_TILED ||
|
||||
e->plane[s].block[0] != br || e->plane[s].block[1] != bc) return false;
|
||||
const int s2 = rad_enc_find(e, "scale.1");
|
||||
if (s2 < 0 || e->plane[s2].dtype != scale2 || e->plane[s2].kind != RAD_PLANE_TILED ||
|
||||
e->plane[s2].block[0] != 0 || e->plane[s2].block[1] != 0) return false;
|
||||
const int t = rad_enc_find(e, "table");
|
||||
return t >= 0 && e->plane[t].dtype == tab && e->plane[t].kind == RAD_PLANE_TABLE &&
|
||||
e->plane[t].extent[0] == 1 && e->plane[t].extent[1] == entries;
|
||||
}
|
||||
|
||||
/* The role of selected plane i. */
|
||||
inline const char* role(const RadEncoding* e, const int* sel, int i) {
|
||||
return (e && sel && sel[i] >= 0 && sel[i] < e->n_planes) ? e->plane[sel[i]].role : "";
|
||||
}
|
||||
|
||||
/* Does the selection name exactly these roles, in this order? */
|
||||
inline bool selects(const RadEncoding* e, const int* sel, int n, const char* a,
|
||||
const char* b = nullptr) {
|
||||
const int want = b ? 2 : 1;
|
||||
if (n != want) return false;
|
||||
if (std::strncmp(role(e, sel, 0), a, RAD_ENC_STR) != 0) return false;
|
||||
return !b || std::strncmp(role(e, sel, 1), b, RAD_ENC_STR) == 0;
|
||||
}
|
||||
|
||||
/* A selected plane's bytes, row r. */
|
||||
inline const uint8_t* row(const RadTensor& t, int64_t r) {
|
||||
return (const uint8_t*)t.data + r * rad_dtype_bytes(t.dtype, t.shape[1]);
|
||||
}
|
||||
|
||||
/* The planes' extents match [rows, cols]. */
|
||||
inline bool dims(const RadTensor& t, int64_t rows, int64_t cols) {
|
||||
return t.rank == 2 && t.shape[0] == rows && t.shape[1] == cols;
|
||||
}
|
||||
|
||||
} /* namespace halo_enc */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,87 @@
|
||||
/* Derived from libr4d/r4d_expert_scale_bf16.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
/* halo_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, 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]] )
|
||||
*
|
||||
* 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>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "halo_plugin.h"
|
||||
#include "halo_launch.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
namespace halo_escale {
|
||||
|
||||
struct EscaleArgs {
|
||||
const int32_t* ids; long long ids_ld;
|
||||
const uint16_t* sc; /* [n_expert], bf16 */
|
||||
uint16_t* ew; long long ew_ld;
|
||||
long long rows;
|
||||
int k, n_expert;
|
||||
};
|
||||
|
||||
__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((unsigned)h << 16); }
|
||||
__device__ __forceinline__ uint16_t f2bf(float f) {
|
||||
const unsigned u = __float_as_uint(f);
|
||||
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
|
||||
__global__ __launch_bounds__(256) void expert_scale_kernel(EscaleArgs A) {
|
||||
const long long e = (long long)blockIdx.x * 256 + threadIdx.x;
|
||||
if (e >= A.rows * A.k) return;
|
||||
const long long r = e / A.k;
|
||||
const int c = (int)(e - r * A.k);
|
||||
const int id = A.ids[r * A.ids_ld + c];
|
||||
const float s = (id >= 0 && id < A.n_expert) ? bf2f(A.sc[id]) : 0.0f;
|
||||
uint16_t* w = A.ew + r * A.ew_ld + c;
|
||||
*w = f2bf(bf2f(*w) * s);
|
||||
}
|
||||
|
||||
/* [rows, k] with a dense last axis: its rows and row pitch, or false */
|
||||
static bool rows_k(const RadTensor* t, uint32_t dt, int64_t k, int64_t* rows, int64_t* ld) {
|
||||
if (!t || t->dtype != dt || t->rank < 1) return false;
|
||||
if (rad_tensor_lastdim(t) != k || t->stride[t->rank - 1] != 1) return false;
|
||||
*rows = rad_tensor_rows(t);
|
||||
*ld = rad_tensor_row_pitch(t);
|
||||
return *ld >= k || *rows <= 1;
|
||||
}
|
||||
|
||||
} /* namespace halo_escale */
|
||||
|
||||
extern "C" {
|
||||
|
||||
/* operands: ids, w_e (the [n_expert] scale table), ew (inout) */
|
||||
int halo_rad_expert_scale_bf16(const RadArgs* a, RadStream stream) {
|
||||
using namespace halo_escale;
|
||||
if (!a || a->n_t < 3) return RAD_E_INVAL;
|
||||
const int64_t k = rad_args_geti_or(a, "top_k", 0), ne = rad_args_geti_or(a, "n_expert", 0);
|
||||
if (k <= 0 || k > 64 || ne <= 0 || ne > (1 << 20)) return RAD_E_SHAPE;
|
||||
const RadTensor *I = rad_arg_in(a, 0), *S = rad_arg_in(a, 1), *W = rad_arg_in(a, 2);
|
||||
if (!I || !S || !W) return RAD_E_INVAL;
|
||||
if (S->dtype != RAD_BF16 || rad_tensor_numel(S) < ne) return RAD_E_DTYPE;
|
||||
int64_t ri = 0, li = 0, rw = 0, lw = 0;
|
||||
if (!rows_k(I, RAD_I32, k, &ri, &li) || !rows_k(W, RAD_BF16, k, &rw, &lw)) return RAD_E_SHAPE;
|
||||
const int64_t M = rw; /* the step's rows: the stream's view */
|
||||
if (M <= 0) return RAD_OK;
|
||||
if (ri < M || M * k > 0x7fffffff) return RAD_E_SHAPE;
|
||||
EscaleArgs P{};
|
||||
P.ids = (const int32_t*)I->data; P.ids_ld = li;
|
||||
P.sc = (const uint16_t*)S->data;
|
||||
P.ew = (uint16_t*)W->data; P.ew_ld = lw;
|
||||
P.rows = M; P.k = (int)k; P.n_expert = (int)ne;
|
||||
const unsigned blocks = (unsigned)((M * k + 255) / 256);
|
||||
HALO_KLAUNCH(HALO_KNAME(expert_scale_kernel), dim3(blocks), dim3(256), (hipStream_t)stream, P);
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
} /* extern "C" */
|
||||
@@ -0,0 +1,159 @@
|
||||
/* Derived from libr4d/r4d_f32_tile.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
// halo_f32_tile.h -- the register-blocked f32 GEMM tile under libhalo's f32 GEMM (gemm_nt_bias at
|
||||
// f32) and its f32 convolutions (conv1d and conv_t1d as implicit GEMMs, halo_audio.hip).
|
||||
//
|
||||
// One 256-thread workgroup computes a BM x BN block (BM = 16 TM, BN = 16 TN) of C = A . W^T over
|
||||
// K. Both operands are staged through LDS k-major, sixteen K a slab and two slabs of LDS, so the
|
||||
// next slab's global loads are in flight under the current slab's FMAs and one barrier a slab
|
||||
// suffices. A thread owns TM x TN accumulators and reads its operands from LDS as float4 (or
|
||||
// float2) rows; every product is a fused multiply-add in ascending K, one rounding a product and
|
||||
// sum, against libref's separate multiply and add in the same order.
|
||||
//
|
||||
// The operands come from loader policies: a thread stages rows `r0 + 16 j` of A (j < TM) and of W
|
||||
// (j < TN) at one K column a slab, `kk = 16 slab + (tid % 16)`, so a GEMM reads rows in place and
|
||||
// a convolution gathers the input row a tap reads, with its sequence's zero padding, from the same
|
||||
// slot. A row or column past the operand reads zero. The epilogue is the caller's: it receives
|
||||
// each run of contiguous columns a thread owns, in registers.
|
||||
//
|
||||
// Thread (tx, ty) = (tid % 16, tid / 16) owns rows g 16 RW + ty RW + r and columns
|
||||
// g 16 CW + tx CW + c, RW = run_of(TM) and CW = run_of(TN): a wave's sixteen tx read 16 CW
|
||||
// contiguous floats of W's slab row, conflict-free, and the two ty values of a wave read two A
|
||||
// vectors, each broadcast. The LDS pitch is padded by four floats, which spreads the staging
|
||||
// stores (a wave's 16 K columns of one row) over distinct banks.
|
||||
#pragma once
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <cstdint>
|
||||
|
||||
namespace halo_f32 {
|
||||
|
||||
constexpr int kThr = 256;
|
||||
constexpr int kBK = 16; // K a staged slab
|
||||
|
||||
// The run a thread owns along an axis of `t` values: four where `t` is whole fours, else two (a
|
||||
// tile of 6 columns is three runs of two, so a 96-wide output fills its tile exactly).
|
||||
constexpr int run_of(int t) { return t % 4 == 0 ? 4 : 2; }
|
||||
|
||||
// A plain row-major f32 operand: row r, column k at p[r * ld + k], zero past `rows` or `K`. Every
|
||||
// load is issued, at an address clamped into the operand, and the zero selected after it: a load
|
||||
// guarded by a branch serialises the slab's loads behind one another. Offsets are 32-bit, so the
|
||||
// operand spans fewer than 2^32 elements (the shims check).
|
||||
template <int CNT>
|
||||
struct RowsLoader {
|
||||
const float* p;
|
||||
int ld, rows, K;
|
||||
int k = 0;
|
||||
uint32_t off[CNT];
|
||||
bool live[CNT];
|
||||
__device__ void init(int first_row, int kk) {
|
||||
k = kk;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < CNT; ++j) {
|
||||
const int r = first_row + 16 * j;
|
||||
live[j] = r < rows;
|
||||
off[j] = (uint32_t)(r < rows ? r : rows - 1) * (uint32_t)ld;
|
||||
}
|
||||
}
|
||||
__device__ void fetch(float (&v)[CNT]) const {
|
||||
const bool kl = k < K;
|
||||
const uint32_t kc = (uint32_t)(kl ? k : K - 1);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < CNT; ++j) {
|
||||
const float x = p[off[j] + kc];
|
||||
v[j] = (live[j] && kl) ? x : 0.0f;
|
||||
}
|
||||
}
|
||||
__device__ void advance() { k += kBK; }
|
||||
};
|
||||
|
||||
template <int TM, int TN, class LA, class LW, class EP>
|
||||
__device__ __forceinline__ void tile(LA& la, LW& lw, int K, EP& ep) {
|
||||
constexpr int BM = 16 * TM, BN = 16 * TN;
|
||||
constexpr int AP = BM + 4, WP = BN + 4;
|
||||
constexpr int RW = run_of(TM), RG = TM / RW;
|
||||
constexpr int CW = run_of(TN), CG = TN / CW;
|
||||
static_assert(RW * RG == TM && CW * CG == TN && (RW == 2 || RW == 4) && (CW == 2 || CW == 4),
|
||||
"a thread's rows and columns are whole runs of two or four");
|
||||
__shared__ __attribute__((aligned(16))) float sA[2][kBK][AP];
|
||||
__shared__ __attribute__((aligned(16))) float sW[2][kBK][WP];
|
||||
|
||||
const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4;
|
||||
|
||||
float acc[TM][TN];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) acc[i][j] = 0.0f;
|
||||
|
||||
float ra[TM], rw[TN];
|
||||
la.fetch(ra);
|
||||
lw.fetch(rw);
|
||||
const int ns = (K + kBK - 1) / kBK;
|
||||
for (int s = 0; s < ns; ++s) {
|
||||
const int b = s & 1;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TM; ++j) sA[b][tx][ty + 16 * j] = ra[j];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) sW[b][tx][ty + 16 * j] = rw[j];
|
||||
__syncthreads();
|
||||
if (s + 1 < ns) {
|
||||
la.advance();
|
||||
lw.advance();
|
||||
la.fetch(ra);
|
||||
lw.fetch(rw);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kBK; ++k) {
|
||||
float a[TM], w[TN];
|
||||
#pragma unroll
|
||||
for (int g = 0; g < RG; ++g) {
|
||||
const float* src = &sA[b][k][g * 16 * RW + ty * RW];
|
||||
if constexpr (RW == 4) {
|
||||
const float4 q = *(const float4*)src;
|
||||
a[g * 4] = q.x; a[g * 4 + 1] = q.y; a[g * 4 + 2] = q.z; a[g * 4 + 3] = q.w;
|
||||
} else {
|
||||
const float2 q = *(const float2*)src;
|
||||
a[g * 2] = q.x; a[g * 2 + 1] = q.y;
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int g = 0; g < CG; ++g) {
|
||||
const float* src = &sW[b][k][g * 16 * CW + tx * CW];
|
||||
if constexpr (CW == 4) {
|
||||
const float4 q = *(const float4*)src;
|
||||
w[g * 4] = q.x; w[g * 4 + 1] = q.y; w[g * 4 + 2] = q.z; w[g * 4 + 3] = q.w;
|
||||
} else {
|
||||
const float2 q = *(const float2*)src;
|
||||
w[g * 2] = q.x; w[g * 2 + 1] = q.y;
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) acc[i][j] = __builtin_fmaf(a[i], w[j], acc[i][j]);
|
||||
}
|
||||
/* One barrier a slab: the next slab goes to the other buffer, which every thread finished
|
||||
* reading before it passed this slab's barrier. */
|
||||
}
|
||||
|
||||
/* A run of CW columns as one float4 (the last two lanes unused at CW 2), so the accumulators
|
||||
* stay in registers through the caller's store; `gj` says which of the thread's CG runs it
|
||||
* is, for state the caller keeps per run. */
|
||||
#pragma unroll
|
||||
for (int gi = 0; gi < RG; ++gi)
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RW; ++r)
|
||||
#pragma unroll
|
||||
for (int gj = 0; gj < CG; ++gj) {
|
||||
const float* q = acc[gi * RW + r] + gj * CW;
|
||||
float4 v;
|
||||
if constexpr (CW == 4) v = make_float4(q[0], q[1], q[2], q[3]);
|
||||
else v = make_float4(q[0], q[1], 0.0f, 0.0f);
|
||||
ep(gi * 16 * RW + ty * RW + r, gj * 16 * CW + tx * CW, CW, v, gj);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace halo_f32
|
||||
@@ -0,0 +1,101 @@
|
||||
/* Derived from libr4d/r4d_fp8_args.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
/* halo_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) implements the same op at a different M and
|
||||
* takes the same five operands in the same order. See libhalo/halo_args.h.
|
||||
*/
|
||||
#ifndef HALO_FP8_ARGS_H
|
||||
#define HALO_FP8_ARGS_H
|
||||
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
|
||||
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 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 };
|
||||
|
||||
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 */
|
||||
};
|
||||
|
||||
/* Reads this family's operands and pitches. libhalo 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`; refuse rather than
|
||||
* ignore (see gemm_ops). */
|
||||
if (halo_geti_or(a, "pb1", 0) > 0 || halo_geti_or(a, "pb2", 0) > 0) return HALO_NO(RAD_E_UNSUPPORTED);
|
||||
g->a = halo_opt(a, F_A);
|
||||
g->ascale = halo_opt(a, F_ASCALE);
|
||||
g->b = halo_opt(a, F_B);
|
||||
g->bscale = halo_opt(a, F_BSCALE);
|
||||
g->y = halo_opt(a, F_Y);
|
||||
if (!g->a || !g->b || !g->bscale || !g->y) return HALO_NO(RAD_E_INVAL);
|
||||
if (want_ascale && !g->ascale) return HALO_NO(RAD_E_INVAL);
|
||||
|
||||
if (g->b->rank != 2 || g->bscale->rank != 2) return HALO_NO(RAD_E_SHAPE);
|
||||
/* Rows are dim 0 and everything after it is the row, as in halo_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 HALO_NO(RAD_E_SHAPE);
|
||||
g->M = g->y->shape[0];
|
||||
if (g->M < 1 || halo_numel(g->y) % g->M) return HALO_NO(RAD_E_SHAPE);
|
||||
g->N = halo_numel(g->y) / g->M;
|
||||
g->K = g->b->shape[1];
|
||||
if (g->b->shape[0] != g->N) return HALO_NO(RAD_E_SHAPE);
|
||||
if (g->N < 1 || g->K < 1) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
/* The layout hook and the .rad it wrote use HALO_FP8_BLOCK and libhalo compiles its own copy;
|
||||
* a mismatch would be a silently wrong scale grid. */
|
||||
const long long blk = halo_gemm_fp8a8_block();
|
||||
if (blk != HALO_FP8_BLOCK) return HALO_NO(RAD_E_SHAPE);
|
||||
g->nkb = (g->K + blk - 1) / blk;
|
||||
/* 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 HALO_NO(RAD_E_SHAPE);
|
||||
if (g->bscale->shape[1] != g->nkb) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
const long long wp = halo_row_pitch(g->b), sp = halo_row_pitch(g->bscale);
|
||||
const long long yp = halo_row_pitch(g->y);
|
||||
if (wp < 0 || sp < 0 || yp < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
/* The output has no pitch argument -- libhalo writes C[r*N + c]. */
|
||||
if (yp != g->N) return HALO_NO(RAD_E_STRIDE);
|
||||
g->w_ld = wp; /* elements == bytes for E4M3 */
|
||||
g->sw_ld = sp;
|
||||
|
||||
if (g->a->rank < 2) return HALO_NO(RAD_E_SHAPE);
|
||||
if (g->a->shape[0] != g->M || halo_numel(g->a) != g->M * g->K) return HALO_NO(RAD_E_SHAPE);
|
||||
const long long ap = halo_row_pitch(g->a);
|
||||
if (ap < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
g->a_ld = ap;
|
||||
if (g->ascale) {
|
||||
if (g->ascale->rank != 2) return HALO_NO(RAD_E_SHAPE);
|
||||
if (g->ascale->shape[0] != g->M || g->ascale->shape[1] != g->nkb) return HALO_NO(RAD_E_SHAPE);
|
||||
const long long asp = halo_row_pitch(g->ascale);
|
||||
if (asp < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
g->sa_ld = asp;
|
||||
}
|
||||
/* 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 (!halo_aligned(g->a->data, 16) || !halo_aligned(g->b->data, 16)) return HALO_NO(RAD_E_ALIGN);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
#endif /* HALO_FP8_ARGS_H */
|
||||
@@ -0,0 +1,41 @@
|
||||
/* Derived from libr4d/r4d_fp8_frag.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
// halo_fp8_frag.h -- where a byte of a block-scaled FP8 weight lives in WMMA fragment order. Pure
|
||||
// C++ (no HIP, no halo.h) so the host layout hook and the device kernels share one definition.
|
||||
//
|
||||
// Why permute: the fp8a8 GEMMs read operands through halo_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.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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 of 16; the 128 scale block already guarantees both.
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
namespace halo_fp8 {
|
||||
|
||||
enum { kFragRows = 16, kFragK = 16, kSuperK = 64, kTileBytes = 1024, kLaneBytes = 32 };
|
||||
|
||||
// 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 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);
|
||||
*k = ks * (int64_t)kSuperK + t * (int64_t)kFragK + (lane >> 4) * 8 + j;
|
||||
}
|
||||
|
||||
} // namespace halo_fp8
|
||||
@@ -0,0 +1,584 @@
|
||||
/* Derived from libr4d/r4d_fp8_layout.cpp by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
/* halo_fp8_layout.cpp -- the stored form of libhalo'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 halo.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] -- as safetensors stores `X.weight`
|
||||
* scale BF16, [ceil(N/128)][ceil(K/128)] -- as `X.weight_scale_inv`
|
||||
*
|
||||
* 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 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 (halo_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 (halo_hc_fp8.h).
|
||||
*
|
||||
* ================================================================= BF16 scales, not UE8M0
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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 "halo_plugin.h"
|
||||
#include "halo_fp8_frag.h"
|
||||
#include "halo_fp8_lm.h"
|
||||
#include "halo_hc_fp8.h"
|
||||
#include "halo_enc.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
/* Operand indices of `gemm_nt_q`. The schema is positional, so these must follow its order in
|
||||
* halo_rows.cpp. */
|
||||
enum { FL_A = 0, FL_ASCALE = 1, FL_B = 2, FL_BSCALE = 3, FL_Y = 4 };
|
||||
|
||||
/* K span of one fragment-order tile, compiled into libhalo. */
|
||||
enum { HALO_FP8_SUPER_K = halo_fp8::kSuperK };
|
||||
|
||||
namespace {
|
||||
|
||||
/* 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 (halo_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 = halo_fp8::kTileBytes / halo_fp8::kLaneBytes;
|
||||
constexpr int kFrags = halo_fp8::kLaneBytes / 8;
|
||||
const long long ksuper = K / halo_fp8::kSuperK;
|
||||
int64_t at = 0;
|
||||
for (long long rt = 0; rt < N / halo_fp8::kFragRows; ++rt)
|
||||
for (long long ks = 0; ks < ksuper; ++ks)
|
||||
for (int lane = 0; lane < kLanes; ++lane)
|
||||
for (int t = 0; t < kFrags; ++t, at += 8) {
|
||||
int64_t row, k;
|
||||
halo_fp8::frag_src(rt, ks, lane, t, 0, &row, &k);
|
||||
move(at, row * K + k);
|
||||
}
|
||||
}
|
||||
|
||||
struct FGeom { long long N, K, sn, sk; };
|
||||
|
||||
int fgeom(const RadParam* p, int n_p, FGeom* g) {
|
||||
g->N = halo_pgeti_or(p, n_p, "N", 0);
|
||||
g->K = halo_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`. The constraint table already refuses
|
||||
* other groups; this catches a caller that invokes the hook without selection. */
|
||||
if (halo_pgeti_or(p, n_p, "group", HALO_FP8_BLOCK) != HALO_FP8_BLOCK) return RAD_E_SHAPE;
|
||||
g->sn = (g->N + HALO_FP8_BLOCK - 1) / HALO_FP8_BLOCK;
|
||||
g->sk = (g->K + HALO_FP8_BLOCK - 1) / HALO_FP8_BLOCK;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void ffill(RadLayout* out, const char* tag, uint32_t dt, long long d0, long long d1,
|
||||
long long bytes) {
|
||||
std::memset(out, 0, sizeof(*out));
|
||||
out->tag = tag;
|
||||
out->dtype = dt;
|
||||
out->rank = 2;
|
||||
out->shape[0] = d0;
|
||||
out->shape[1] = d1;
|
||||
out->align = 16; /* 16-byte loads; see the padding note in halo_fp8_lm.h */
|
||||
out->bytes = bytes;
|
||||
}
|
||||
|
||||
|
||||
/* `logits_gemm` names its geometry `n_vocab` and `n_embd` where the GEMMs say N and K. */
|
||||
int lgeom(const RadParam* p, int n_p, FGeom* g) {
|
||||
g->N = halo_pgeti_or(p, n_p, "n_vocab", 0);
|
||||
g->K = halo_pgeti_or(p, n_p, "n_embd", 0);
|
||||
if (g->N <= 0 || g->K <= 0) return RAD_E_SHAPE;
|
||||
if (g->K % HALO_FP8_BLOCK) return RAD_E_SHAPE;
|
||||
g->sn = (g->N + HALO_FP8_BLOCK - 1) / HALO_FP8_BLOCK;
|
||||
g->sk = g->K / HALO_FP8_BLOCK;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Operand 1 is the weight; see oLogits in halo_rows.cpp. */
|
||||
enum { LGL_X = 0, LGL_W = 1, LGL_Y = 2 };
|
||||
|
||||
/* Operand indices of hc_read -- see oHcRead in halo_rows.cpp. */
|
||||
enum { HCL_DOWN = 2, HCL_UP = 3 };
|
||||
|
||||
struct HGeom { long long rows, K, G; };
|
||||
|
||||
int hgeom(const RadParam* p, int n_p, int operand, HGeom* g) {
|
||||
const long long n = halo_pgeti_or(p, n_p, "n", 0);
|
||||
const long long hc = halo_pgeti_or(p, n_p, "hc", 0);
|
||||
const long long lr = halo_pgeti_or(p, n_p, "lowrank", 0);
|
||||
if (n <= 0 || hc <= 0 || lr <= 0) return RAD_E_SHAPE;
|
||||
if (operand == HCL_DOWN) { g->rows = lr; g->K = hc * n; g->G = halo_hc8::down_group(g->K); }
|
||||
else if (operand == HCL_UP) { g->rows = hc * n; g->K = lr; g->G = halo_hc8::up_group(g->K); }
|
||||
else return RAD_E_UNSUPPORTED;
|
||||
if (!halo_hc8::group_ok(g->K, g->G)) return RAD_E_SHAPE;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
enum { MTL_FCH = 4, MTL_FCE = 5 }; /* oMtpEnter in halo_rows.cpp */
|
||||
|
||||
int mgeom(const RadParam* p, int n_p, int operand, HGeom* g) {
|
||||
if (operand != MTL_FCH && operand != MTL_FCE) return RAD_E_UNSUPPORTED;
|
||||
const long long n = halo_pgeti_or(p, n_p, "n", 0);
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
g->rows = n; g->K = n; g->G = halo_hc8::kDownGroup;
|
||||
if (!halo_hc8::group_ok(g->K, g->G)) return RAD_E_SHAPE;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ==================================================================== the hooks
|
||||
*
|
||||
* 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 block-fp8 weight: e4m3 codes with a bf16 scale per 128x128 block. */
|
||||
bool fp8_block_enc(const RadEncoding* e) {
|
||||
return halo_enc::affine(e, RAD_F8E4M3, RAD_BF16, HALO_FP8_BLOCK, HALO_FP8_BLOCK);
|
||||
}
|
||||
|
||||
int fp8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const RadTensor* pl, int n, RadLayout* out, bool frag) {
|
||||
if (!out || !pl) return RAD_E_INVAL;
|
||||
FGeom g;
|
||||
const int rc = fgeom(p, n_p, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (operand != FL_B && operand != FL_BSCALE) return RAD_E_UNSUPPORTED;
|
||||
if (!fp8_block_enc(enc)) return RAD_E_DTYPE;
|
||||
if (operand == FL_BSCALE) {
|
||||
if (!halo_enc::selects(enc, sel, n, "scale") || !halo_enc::dims(pl[0], g.sn, g.sk))
|
||||
return RAD_E_SHAPE;
|
||||
return RAD_E_UNSUPPORTED; /* the checkpoint's own bf16 plane */
|
||||
}
|
||||
if (!halo_enc::selects(enc, sel, n, "codes") || !halo_enc::dims(pl[0], g.N, g.K))
|
||||
return RAD_E_SHAPE;
|
||||
if (!frag) return RAD_E_UNSUPPORTED; /* row-major, as the matvec reads it */
|
||||
if (g.K % HALO_FP8_SUPER_K || g.N % halo_fp8::kFragRows) return RAD_E_SHAPE;
|
||||
ffill(out, "r4d.fp8.w.frag64", RAD_F8E4M3, g.N, g.K, halo_fp8::frag_bytes(g.N, g.K));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
extern "C" int halo_rad_layout_fp8_block(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out) {
|
||||
return fp8_enc_layout(p, n_p, operand, enc, sel, pl, n, out, true);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_layout_fp8_rowmajor(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out) {
|
||||
return fp8_enc_layout(p, n_p, operand, enc, sel, pl, n, out, false);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_relayout_fp8_block(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, void* dst,
|
||||
int64_t dst_bytes) {
|
||||
RadLayout L;
|
||||
const int rc = fp8_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, true);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
|
||||
const uint8_t* s = (const uint8_t*)pl[0].data;
|
||||
uint8_t* d = (uint8_t*)dst;
|
||||
frag_walk(pl[0].shape[0], pl[0].shape[1],
|
||||
[&](int64_t at, int64_t from) { std::memcpy(d + at, s + from, 8); });
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_unrelayout_fp8_block(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const void* src, int64_t src_bytes,
|
||||
const RadTensor* pl, int n) {
|
||||
RadLayout L;
|
||||
const int rc = fp8_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, true);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
|
||||
const uint8_t* s = (const uint8_t*)src;
|
||||
uint8_t* d = (uint8_t*)pl[0].data;
|
||||
frag_walk(pl[0].shape[0], pl[0].shape[1],
|
||||
[&](int64_t at, int64_t from) { std::memcpy(d + from, s + at, 8); });
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- the int8 twin: i8 codes in the same fragment order as E4M3, with a bf16 scale per row per
|
||||
* 128 K.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* `i8a8h` is the same planes holding a weight rotated by the unnormalised 128-wide Hadamard along
|
||||
* K, the 1/128 in its scale (libquant's `transform=fwht128`), to be met by had_quant_act_i8g's
|
||||
* activation. The bytes cannot tell the two apart, so each dtype accepts only its own transform
|
||||
* and the rotated codes carry a tag of their own. */
|
||||
namespace {
|
||||
bool i8_rotated(const RadParam* p, int n_p) {
|
||||
const char* d = halo_pgets(p, n_p, "dtype");
|
||||
return d && std::strcmp(d, "i8a8h") == 0;
|
||||
}
|
||||
|
||||
int i8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out) {
|
||||
if (!out || !pl) return RAD_E_INVAL;
|
||||
FGeom g;
|
||||
const int rc = fgeom(p, n_p, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (operand != FL_B && operand != FL_BSCALE) return RAD_E_UNSUPPORTED;
|
||||
const bool rot = i8_rotated(p, n_p);
|
||||
if (!halo_enc::affine(enc, RAD_I8, RAD_BF16, 1, HALO_FP8_BLOCK, RAD_DT_INVALID,
|
||||
rot ? "fwht128" : ""))
|
||||
return RAD_E_DTYPE;
|
||||
if (operand == FL_BSCALE) {
|
||||
if (!halo_enc::selects(enc, sel, n, "scale") || !halo_enc::dims(pl[0], g.N, g.sk))
|
||||
return RAD_E_SHAPE;
|
||||
if (g.N % halo_fp8::kFragRows) return RAD_E_SHAPE;
|
||||
ffill(out, "r4d.i8.s.t16", RAD_BF16, g.N, g.sk, g.N * g.sk * 2);
|
||||
return RAD_OK;
|
||||
}
|
||||
if (!halo_enc::selects(enc, sel, n, "codes") || !halo_enc::dims(pl[0], g.N, g.K))
|
||||
return RAD_E_SHAPE;
|
||||
if (g.K % HALO_FP8_SUPER_K || g.N % halo_fp8::kFragRows) return RAD_E_SHAPE;
|
||||
ffill(out, rot ? "r4d.i8h.w.frag64" : "r4d.i8.w.frag64", RAD_I8, g.N, g.K,
|
||||
halo_fp8::frag_bytes(g.N, g.K));
|
||||
return RAD_OK;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
extern "C" int halo_rad_layout_i8_block(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out) {
|
||||
return i8_enc_layout(p, n_p, operand, enc, sel, pl, n, out);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_relayout_i8_block(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, void* dst,
|
||||
int64_t dst_bytes) {
|
||||
RadLayout L;
|
||||
const int rc = i8_enc_layout(p, n_p, operand, enc, sel, pl, n, &L);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
|
||||
if (operand == FL_BSCALE) {
|
||||
const long long N = pl[0].shape[0], nkb = pl[0].shape[1];
|
||||
const uint16_t* s = (const uint16_t*)pl[0].data;
|
||||
uint16_t* d = (uint16_t*)dst;
|
||||
for (long long r = 0; r < N; ++r)
|
||||
for (long long kb = 0; kb < nkb; ++kb)
|
||||
d[((r / 16) * nkb + kb) * 16 + r % 16] = s[r * nkb + kb];
|
||||
return RAD_OK;
|
||||
}
|
||||
const uint8_t* s = (const uint8_t*)pl[0].data;
|
||||
uint8_t* d = (uint8_t*)dst;
|
||||
frag_walk(pl[0].shape[0], pl[0].shape[1],
|
||||
[&](int64_t at, int64_t from) { std::memcpy(d + at, s + from, 8); });
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_unrelayout_i8_block(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const void* src, int64_t src_bytes,
|
||||
const RadTensor* pl, int n) {
|
||||
RadLayout L;
|
||||
const int rc = i8_enc_layout(p, n_p, operand, enc, sel, pl, n, &L);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
|
||||
if (operand == FL_BSCALE) {
|
||||
const long long N = pl[0].shape[0], nkb = pl[0].shape[1];
|
||||
const uint16_t* s = (const uint16_t*)src;
|
||||
uint16_t* d = (uint16_t*)pl[0].data;
|
||||
for (long long r = 0; r < N; ++r)
|
||||
for (long long kb = 0; kb < nkb; ++kb)
|
||||
d[r * nkb + kb] = s[((r / 16) * nkb + kb) * 16 + r % 16];
|
||||
return RAD_OK;
|
||||
}
|
||||
const uint8_t* s = (const uint8_t*)src;
|
||||
uint8_t* d = (uint8_t*)pl[0].data;
|
||||
frag_walk(pl[0].shape[0], pl[0].shape[1],
|
||||
[&](int64_t at, int64_t from) { std::memcpy(d + from, s + at, 8); });
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- the lm_head: codes and scales in one row, the scales of the row's 128-row block repeated
|
||||
* into its tail. */
|
||||
namespace {
|
||||
/* `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;
|
||||
if (operand != LGL_W) return RAD_E_UNSUPPORTED;
|
||||
FGeom g;
|
||||
const int rc = lgeom(p, n_p, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (i8 ? !halo_enc::affine(enc, RAD_I8, RAD_BF16, 1, HALO_FP8_BLOCK) : !fp8_block_enc(enc))
|
||||
return RAD_E_DTYPE;
|
||||
if (!halo_enc::selects(enc, sel, n, "codes", "scale")) return RAD_E_SHAPE;
|
||||
if (!halo_enc::dims(pl[0], g.N, g.K) || !halo_enc::dims(pl[1], i8 ? g.N : g.sn, g.sk))
|
||||
return RAD_E_SHAPE;
|
||||
const long long stride = halo_fp8::lm_row_bytes(g.K);
|
||||
ffill(out, i8 ? "r4d.i8lm.r128" : "r4d.fp8lm.b128", i8 ? RAD_I8 : RAD_F8E4M3, g.N, stride,
|
||||
g.N * stride);
|
||||
if (gout) *gout = g;
|
||||
return RAD_OK;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
extern "C" int halo_rad_layout_fp8_logits(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out) {
|
||||
return lm_enc_layout(p, n_p, operand, enc, sel, pl, n, out, nullptr);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_relayout_fp8_logits(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, void* dst,
|
||||
int64_t dst_bytes) {
|
||||
RadLayout L;
|
||||
FGeom g;
|
||||
const int rc = lm_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (dst_bytes != L.bytes || !pl[0].data || !pl[1].data) return RAD_E_SHAPE;
|
||||
const long long stride = halo_fp8::lm_row_bytes(g.K);
|
||||
const uint8_t* codes = (const uint8_t*)pl[0].data;
|
||||
const uint16_t* sc = (const uint16_t*)pl[1].data;
|
||||
uint8_t* d = (uint8_t*)dst;
|
||||
std::memset(d, 0, (size_t)dst_bytes);
|
||||
for (long long r = 0; r < g.N; ++r) {
|
||||
uint8_t* row = d + r * stride;
|
||||
std::memcpy(row, codes + r * g.K, (size_t)g.K);
|
||||
std::memcpy(row + g.K, sc + (r / HALO_FP8_BLOCK) * g.sk, (size_t)(2 * g.sk));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_unrelayout_fp8_logits(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const void* src, int64_t src_bytes,
|
||||
const RadTensor* pl, int n) {
|
||||
RadLayout L;
|
||||
FGeom g;
|
||||
const int rc = lm_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (src_bytes != L.bytes || !pl[0].data || !pl[1].data) return RAD_E_SHAPE;
|
||||
const long long stride = halo_fp8::lm_row_bytes(g.K);
|
||||
const uint8_t* s = (const uint8_t*)src;
|
||||
uint8_t* codes = (uint8_t*)pl[0].data;
|
||||
uint16_t* sc = (uint16_t*)pl[1].data;
|
||||
for (long long r = 0; r < g.N; ++r) {
|
||||
std::memcpy(codes + r * g.K, s + r * stride, (size_t)g.K);
|
||||
if (r % HALO_FP8_BLOCK == 0)
|
||||
std::memcpy(sc + (r / HALO_FP8_BLOCK) * g.sk, s + r * stride + g.K, (size_t)(2 * g.sk));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_layout_i8_logits(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out) {
|
||||
return lm_enc_layout(p, n_p, operand, enc, sel, pl, n, out, nullptr, true);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_relayout_i8_logits(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, void* dst,
|
||||
int64_t dst_bytes) {
|
||||
RadLayout L;
|
||||
FGeom g;
|
||||
const int rc = lm_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g, true);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (dst_bytes != L.bytes || !pl[0].data || !pl[1].data) return RAD_E_SHAPE;
|
||||
const long long stride = halo_fp8::lm_row_bytes(g.K);
|
||||
const uint8_t* codes = (const uint8_t*)pl[0].data;
|
||||
const uint16_t* sc = (const uint16_t*)pl[1].data;
|
||||
uint8_t* d = (uint8_t*)dst;
|
||||
std::memset(d, 0, (size_t)dst_bytes);
|
||||
for (long long r = 0; r < g.N; ++r) {
|
||||
uint8_t* row = d + r * stride;
|
||||
std::memcpy(row, codes + r * g.K, (size_t)g.K);
|
||||
std::memcpy(row + g.K, sc + r * g.sk, (size_t)(2 * g.sk));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_unrelayout_i8_logits(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const void* src, int64_t src_bytes,
|
||||
const RadTensor* pl, int n) {
|
||||
RadLayout L;
|
||||
FGeom g;
|
||||
const int rc = lm_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g, true);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (src_bytes != L.bytes || !pl[0].data || !pl[1].data) return RAD_E_SHAPE;
|
||||
const long long stride = halo_fp8::lm_row_bytes(g.K);
|
||||
const uint8_t* s = (const uint8_t*)src;
|
||||
uint8_t* codes = (uint8_t*)pl[0].data;
|
||||
uint16_t* sc = (uint16_t*)pl[1].data;
|
||||
for (long long r = 0; r < g.N; ++r) {
|
||||
std::memcpy(codes + r * g.K, s + r * stride, (size_t)g.K);
|
||||
std::memcpy(sc + r * g.sk, s + r * stride + g.K, (size_t)(2 * g.sk));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- 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) {
|
||||
if (!out || !pl) return RAD_E_INVAL;
|
||||
if (!halo_enc::affine(enc, RAD_F8E4M3, RAD_F32, 1, g.G)) return RAD_E_DTYPE;
|
||||
if (!halo_enc::selects(enc, sel, n, "codes", "scale")) return RAD_E_SHAPE;
|
||||
if (!halo_enc::dims(pl[0], g.rows, g.K) || !halo_enc::dims(pl[1], g.rows, g.K / g.G))
|
||||
return RAD_E_SHAPE;
|
||||
const long long stride = halo_hc8::row_bytes(g.K, g.G);
|
||||
ffill(out, tag, RAD_F8E4M3, g.rows, stride, g.rows * stride);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int hcrows_relayout(const HGeom& g, const RadTensor* pl, void* dst, int64_t dst_bytes) {
|
||||
const long long stride = halo_hc8::row_bytes(g.K, g.G), ng = g.K / g.G;
|
||||
if (dst_bytes != g.rows * stride || !pl[0].data || !pl[1].data) return RAD_E_SHAPE;
|
||||
const uint8_t* codes = (const uint8_t*)pl[0].data;
|
||||
const float* sc = (const float*)pl[1].data;
|
||||
uint8_t* d = (uint8_t*)dst;
|
||||
std::memset(d, 0, (size_t)dst_bytes);
|
||||
for (long long r = 0; r < g.rows; ++r) {
|
||||
std::memcpy(d + r * stride, codes + r * g.K, (size_t)g.K);
|
||||
std::memcpy(d + r * stride + g.K, sc + r * ng, (size_t)(4 * ng));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int hcrows_unrelayout(const HGeom& g, const void* src, int64_t src_bytes, const RadTensor* pl) {
|
||||
const long long stride = halo_hc8::row_bytes(g.K, g.G), ng = g.K / g.G;
|
||||
if (src_bytes != g.rows * stride || !pl[0].data || !pl[1].data) return RAD_E_SHAPE;
|
||||
const uint8_t* s = (const uint8_t*)src;
|
||||
for (long long r = 0; r < g.rows; ++r) {
|
||||
std::memcpy((uint8_t*)pl[0].data + r * g.K, s + r * stride, (size_t)g.K);
|
||||
std::memcpy((float*)pl[1].data + r * ng, s + r * stride + g.K, (size_t)(4 * ng));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
const char* hc_tag(int operand) {
|
||||
return operand == HCL_DOWN ? "halo.hc.e4m3.g128" : "halo.hc.e4m3.q4";
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
extern "C" int halo_rad_layout_hc_e4m3(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out) {
|
||||
HGeom g;
|
||||
const int rc = hgeom(p, n_p, operand, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return hcrows_enc_layout(g, hc_tag(operand), enc, sel, pl, n, out);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_relayout_hc_e4m3(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, void* dst, int64_t dst_bytes) {
|
||||
HGeom g;
|
||||
RadLayout L;
|
||||
int rc = hgeom(p, n_p, operand, &g);
|
||||
if (rc == RAD_OK) rc = hcrows_enc_layout(g, hc_tag(operand), enc, sel, pl, n, &L);
|
||||
return rc != RAD_OK ? rc : hcrows_relayout(g, pl, dst, dst_bytes);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_unrelayout_hc_e4m3(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel, const void* src,
|
||||
int64_t src_bytes, const RadTensor* pl, int n) {
|
||||
HGeom g;
|
||||
RadLayout L;
|
||||
int rc = hgeom(p, n_p, operand, &g);
|
||||
if (rc == RAD_OK) rc = hcrows_enc_layout(g, hc_tag(operand), enc, sel, pl, n, &L);
|
||||
return rc != RAD_OK ? rc : hcrows_unrelayout(g, src, src_bytes, pl);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_layout_mtp_e4m3(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out) {
|
||||
HGeom g;
|
||||
const int rc = mgeom(p, n_p, operand, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return hcrows_enc_layout(g, "r4d.mtp.e4m3.g128", enc, sel, pl, n, out);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_relayout_mtp_e4m3(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, void* dst, int64_t dst_bytes) {
|
||||
HGeom g;
|
||||
RadLayout L;
|
||||
int rc = mgeom(p, n_p, operand, &g);
|
||||
if (rc == RAD_OK) rc = hcrows_enc_layout(g, "r4d.mtp.e4m3.g128", enc, sel, pl, n, &L);
|
||||
return rc != RAD_OK ? rc : hcrows_relayout(g, pl, dst, dst_bytes);
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_unrelayout_mtp_e4m3(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const void* src, int64_t src_bytes,
|
||||
const RadTensor* pl, int n) {
|
||||
HGeom g;
|
||||
RadLayout L;
|
||||
int rc = mgeom(p, n_p, operand, &g);
|
||||
if (rc == RAD_OK) rc = hcrows_enc_layout(g, "r4d.mtp.e4m3.g128", enc, sel, pl, n, &L);
|
||||
return rc != RAD_OK ? rc : hcrows_unrelayout(g, src, src_bytes, pl);
|
||||
}
|
||||
|
||||
/* ================================================================= embed_lookup_q's table
|
||||
*
|
||||
* 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 halo_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) {
|
||||
(void)out;
|
||||
enum { EQ_WTE = 1, EQ_SCALE = 2 };
|
||||
if (operand != EQ_WTE && operand != EQ_SCALE) return RAD_E_UNSUPPORTED;
|
||||
const long long rows = rad_param_geti(p, n_p, "n_vocab", 0);
|
||||
const long long dim = rad_param_geti(p, n_p, "n_embd", 0);
|
||||
if (rows <= 0 || dim <= 0) return RAD_E_SHAPE;
|
||||
if (rad_enc_is(enc, "plain") && enc->n_planes == 1 && enc->plane[0].dtype == RAD_BF16) {
|
||||
if (operand != EQ_WTE) return RAD_E_DTYPE;
|
||||
if (n != 1 || !pl || !halo_enc::dims(pl[0], rows, dim)) return RAD_E_SHAPE;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const RadEncPlane* sc = rad_enc_plane(enc, "scale");
|
||||
if (!rad_enc_is(enc, "affine") || enc->n_planes != 2 || enc->transform[0] ||
|
||||
enc->plane[0].dtype != RAD_F8E4M3 || !sc || sc->dtype != RAD_BF16 || sc->block[0] != 0 ||
|
||||
sc->block[1] != 0)
|
||||
return RAD_E_DTYPE;
|
||||
if (n != 1 || !pl || !sel) return RAD_E_SHAPE;
|
||||
if (!halo_enc::selects(enc, sel, n, operand == EQ_WTE ? "codes" : "scale")) return RAD_E_SHAPE;
|
||||
if (!halo_enc::dims(pl[0], operand == EQ_WTE ? rows : 1, operand == EQ_WTE ? dim : 1))
|
||||
return RAD_E_SHAPE;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/* Derived from libr4d/r4d_fp8_lm.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
// halo_fp8_lm.h -- stored row geometry of the fp8 lm_head. Pure C++ (no HIP, no halo.h) so the
|
||||
// layout hook (halo_fp8_layout.cpp), the entry point (halo_gemm_fp8a16_nt_m1.hip) and the selftest
|
||||
// derive the row width from one definition.
|
||||
//
|
||||
// `logits_gemm` carries one weight operand, so the block scales live in each row's tail (see
|
||||
// halo_rad_layout_fp8_logits); a row-sharded lm_head stays a plain byte range under TP.
|
||||
//
|
||||
// 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
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// This is a 16-byte correctness floor, unrelated to the 128-byte row padding that
|
||||
// halo_gemm_fp8a16_nt_m1.hip's header evaluates and rejects.
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
namespace halo_fp8 {
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
} // namespace halo_fp8
|
||||
@@ -0,0 +1,120 @@
|
||||
/* Derived from libr4d/r4d_fp8_wmma.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
// Shared device code for the block-scaled FP8 family: the E4M3 decoders and the bf16 block-scale
|
||||
// load. libr4d's version of this header also carries the gfx12 fp8 WMMA fragment map and its LDS
|
||||
// staging; gfx1151 has no fp8 matrix instruction, so halo's fp8 GEMMs dequantise to bf16 in
|
||||
// registers and run on halo_wmma.h's bf16 WMMA instead. That machinery lands with the fp8 GEMM
|
||||
// units, in halo_wmma.h's terms; nothing here pretends otherwise.
|
||||
#pragma once
|
||||
#include "halo_common.h"
|
||||
#include "halo_fp8_frag.h"
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <cstdint>
|
||||
|
||||
namespace halo_fp8 {
|
||||
|
||||
/* The fp8 matrix machinery (libr4d's mma/mma8, fragment map and staging) is not
|
||||
* carried over: it names gfx12 instructions and a fragment layout this part does
|
||||
* not have. The fp8 GEMM units bring their own, built on halo_wmma.h. */
|
||||
|
||||
// ---- E4M3 -> f32 -------------------------------------------------------------------------------
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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);
|
||||
#else
|
||||
const uint32_t sign = (b & 0x80u) << 24;
|
||||
const uint32_t ex = (b >> 3) & 0x0Fu;
|
||||
const uint32_t mn = b & 0x07u;
|
||||
const float nrm = __uint_as_float(((ex + 120u) << 23) | (mn << 20));
|
||||
const float sub = (float)mn * (1.0f / 512.0f);
|
||||
return __uint_as_float(__float_as_uint(ex ? nrm : sub) | sign);
|
||||
#endif
|
||||
}
|
||||
|
||||
// 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 halo_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)
|
||||
return __builtin_amdgcn_cvt_pk_f32_fp8(q, HI);
|
||||
#else
|
||||
constexpr uint32_t s = HI ? 16u : 0u;
|
||||
v2f r;
|
||||
r.x = e4m3((q >> s) & 0xFFu);
|
||||
r.y = e4m3((q >> (s + 8u)) & 0xFFu);
|
||||
return r;
|
||||
#endif
|
||||
}
|
||||
|
||||
// ---- f32 -> E4M3 -------------------------------------------------------------------------------
|
||||
//
|
||||
// gfx1151 has no v_cvt_pkfp8_f32 (fp8-conversion-insts), so the encode is software. It is a
|
||||
// transcription of abi/rad_plugin.h's rad_f32_to_fp8e4m3 -- round-to-nearest-even in both the
|
||||
// normal and subnormal branches, saturating at 448, NaN to 0x7f -- because that function is the
|
||||
// reference every fp8 store is checked against; a faster form must first be shown to agree with
|
||||
// it on every input class (the host probe in the unit's bring-up compared 2^31 values).
|
||||
__device__ __forceinline__ uint32_t f32_to_e4m3(float f) {
|
||||
const uint32_t u = __builtin_bit_cast(uint32_t, f);
|
||||
const uint32_t s = (u >> 24) & 0x80u;
|
||||
const uint32_t a = u & 0x7fffffffu;
|
||||
if (a > 0x7f800000u) return s | 0x7fu; /* nan */
|
||||
if (a >= 0x43e00000u) return s | 0x7eu; /* >= 448: clamp to the largest */
|
||||
const int e = (int)(a >> 23) - 127;
|
||||
uint32_t m = a & 0x7fffffu;
|
||||
if (e < -10) return s;
|
||||
if (e < -6) { /* subnormal fp8 */
|
||||
const int sh = -6 - e + 20;
|
||||
m |= 0x800000u;
|
||||
const uint32_t lo = m & ((1u << sh) - 1u);
|
||||
uint32_t q = m >> sh;
|
||||
const uint32_t half = 1u << (sh - 1);
|
||||
if (lo > half || (lo == half && (q & 1u))) ++q;
|
||||
return s | q;
|
||||
}
|
||||
uint32_t q = m >> 20;
|
||||
const uint32_t lo = m & 0xfffffu;
|
||||
if (lo > 0x80000u || (lo == 0x80000u && (q & 1u))) ++q;
|
||||
int ee = e + 7;
|
||||
if (q == 0x8u) { q = 0; ++ee; }
|
||||
if (ee > 15 || (ee == 15 && q >= 7u)) return s | 0x7eu;
|
||||
return s | ((uint32_t)ee << 3) | q;
|
||||
}
|
||||
|
||||
/* __builtin_amdgcn_cvt_pk_fp8_f32's shape (two encodes into one half of `old`), so a call site
|
||||
* moves onto it by name alone. Callers still clamp to +-448 first, as they did for the hardware
|
||||
* instruction, whose out-of-range result is NaN rather than saturation; with the clamp the bytes
|
||||
* are the same ones. */
|
||||
__device__ __forceinline__ int cvt_pk_fp8_f32(float lo_f, float hi_f, int old, bool word_sel) {
|
||||
const uint32_t pair = f32_to_e4m3(lo_f) | (f32_to_e4m3(hi_f) << 8);
|
||||
const uint32_t o = (uint32_t)old;
|
||||
return (int)(word_sel ? (o & 0x0000ffffu) | (pair << 16) : (o & 0xffff0000u) | pair);
|
||||
}
|
||||
|
||||
// ---- block scale --------------------------------------------------------------------------------
|
||||
//
|
||||
// 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 zero-extended in a full register (see u16_load_w in halo_moe.hip). The upper
|
||||
* sixteen bits must be zero. */
|
||||
__device__ __forceinline__ float bscale(uint32_t s) {
|
||||
return __uint_as_float(s << 16);
|
||||
}
|
||||
|
||||
} // namespace halo_fp8
|
||||
@@ -0,0 +1,890 @@
|
||||
/* Derived from libr4d/r4d_fuse.cpp by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
/* halo_fuse.cpp -- the chain of unfused ops each fused kernel computes in one launch.
|
||||
*
|
||||
* `RadKernelInfo::replaces` (rad_abi.h) makes a fused row's claim to be byte-identical to the ops
|
||||
* it replaces executable. Most of libhalo'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 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.
|
||||
*
|
||||
* ============================================================ operand presence
|
||||
*
|
||||
* `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:
|
||||
*
|
||||
* - 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.
|
||||
*
|
||||
* A caller that does not know passes RAD_FUSE_PRESENT_ALL, meaning every operand this plugin's own
|
||||
* description lists; halo_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.
|
||||
*
|
||||
* ============================================================ rows with no hook
|
||||
*
|
||||
* 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
|
||||
* `rmsnorm` + `had_quant_act_i8` is expressible but does not hold.
|
||||
* halo_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. halo_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
|
||||
* Primitive ops, not fusions. A one-step chain naming the op itself would check nothing.
|
||||
*
|
||||
* ar_ln_had_quant_i8
|
||||
* `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
|
||||
* 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 halo_act_threads(M, n) threads,
|
||||
* so the two differ by a ULP.
|
||||
*
|
||||
* sample_chain
|
||||
* 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
|
||||
* 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: 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 halo.h, no HIP), like halo_rows.cpp, halo_layout.cpp and halo_shapes.cpp, so the
|
||||
* tables compile and can be read without ROCm.
|
||||
*/
|
||||
|
||||
#include "halo_plugin.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <initializer_list>
|
||||
|
||||
namespace {
|
||||
|
||||
/* ==================================================================== reading the fused geometry
|
||||
*
|
||||
* Not halo_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) {
|
||||
if (!p[i].key || std::strcmp(p[i].key, k) != 0) continue;
|
||||
if (p[i].kind == RAD_P_INT) return (int64_t)p[i].ival;
|
||||
if (p[i].kind == RAD_P_RANGE) return (int64_t)p[i].ihi;
|
||||
return dflt;
|
||||
}
|
||||
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 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 halo_rows.cpp
|
||||
* (the ABI checks it too).
|
||||
*
|
||||
* `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;
|
||||
bool ok = true;
|
||||
|
||||
Step(RadFuseStep* out, const char* op) : s(out) {
|
||||
*s = RadFuseStep{};
|
||||
s->op = op;
|
||||
}
|
||||
|
||||
/* 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; }
|
||||
s->p[s->n_p++] = *f;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/* 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: 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{};
|
||||
q.key = key;
|
||||
q.kind = RAD_P_INT;
|
||||
q.ival = v;
|
||||
s->p[s->n_p++] = q;
|
||||
return *this;
|
||||
}
|
||||
|
||||
Step& pf64(const char* key, double v) {
|
||||
if (s->n_p >= RAD_MAX_FUSE_PARAMS) { ok = false; return *this; }
|
||||
RadParam q{};
|
||||
q.key = key;
|
||||
q.kind = RAD_P_F64;
|
||||
q.dval = v;
|
||||
s->p[s->n_p++] = q;
|
||||
return *this;
|
||||
}
|
||||
|
||||
Step& pstr(const char* key, const char* v) {
|
||||
if (!v || s->n_p >= RAD_MAX_FUSE_PARAMS) { ok = false; return *this; }
|
||||
RadParam q{};
|
||||
q.key = key;
|
||||
q.kind = RAD_P_STR;
|
||||
q.sval = v;
|
||||
s->p[s->n_p++] = q;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/* 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;
|
||||
for (int v : from) s->from[s->n_from++] = (int16_t)v;
|
||||
return RAD_OK;
|
||||
}
|
||||
};
|
||||
|
||||
/* Whether a gated fold's `act` (vocabulary spelling) is `want`. `act` is optional and the shims
|
||||
* default it differently: halo_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 = halo_pgets(p, n_p, "act");
|
||||
return std::strcmp(a ? a : dflt, want) == 0;
|
||||
}
|
||||
|
||||
/* The fp8 folds quantise only on the checkpoint's scale grid: the shims and the operand
|
||||
* descriptions test `group` against halo_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", HALO_FP8_BLOCK) == HALO_FP8_BLOCK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ==========================================================================================
|
||||
* rmsnorm_quant_fp8 -- the RMS norm and the fp8 activation quantiser in one pass.
|
||||
* (kernel: libhalo/halo_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`, 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: 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, matching vLLM's fused_add_rms_norm). The variance
|
||||
* uses the unrounded f32 sum, half a ULP away on every channel.
|
||||
*
|
||||
* All three steps are libhalo rows (add_bf16, rmsnorm_bf16, quant_act_fp8), so the check stays
|
||||
* within libhalo; `rmsnorm_add` has no libhalo row.
|
||||
*
|
||||
* Byte identity depends on the workgroup width agreeing: both kernels take their thread count from
|
||||
* `halo_act_threads(M, n)`, which decides the columns each thread folds into the sum of squares
|
||||
* (see the launcher in halo_model_bf16.hip). `M` is mirrored verbatim for that reason.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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 halo_fuse_rmsnorm_quant_fp8(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
|
||||
if (!out) return RAD_E_INVAL;
|
||||
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
|
||||
if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED;
|
||||
|
||||
/* `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;
|
||||
const int16_t mid = has_out ? (int16_t)5 : RAD_FUSE_TMP(0);
|
||||
/* 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 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` 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");
|
||||
return st.wire({ has_res ? (int16_t)1 : (int16_t)0, 2, mid }); /* x, w, y */
|
||||
}
|
||||
case 2: {
|
||||
/* The codes, taken over the bf16 the norm wrote. */
|
||||
Step st(out, "quant_act_fp8");
|
||||
st.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "group").mirror(p, n_p, "dtype");
|
||||
return st.wire({ mid, 3, 4 }); /* x, q, scale */
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* gated_quant_fp8 -- an elementwise gated product and the fp8 quantiser in one pass.
|
||||
* (kernel: libhalo/halo_fused_quant_fp8.hip, gated_quant_fp8_kernel)
|
||||
*
|
||||
* Operands: [0] gate_up [1] q [2] scale [3] out_bf16?
|
||||
*
|
||||
* 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`.
|
||||
*
|
||||
* 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]));
|
||||
*
|
||||
* That matches `silu_mul_bf16` in halo_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 halo_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
|
||||
if (!out) return RAD_E_INVAL;
|
||||
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
|
||||
if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED;
|
||||
/* The shim (halo_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) {
|
||||
case 0: {
|
||||
/* silu(gate) * up over the packed [M, 2n] plane, into the bf16 the codes are taken over. */
|
||||
Step s(out, "silu_mul");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "dtype");
|
||||
return s.wire({ 0, 3 }); /* gate_up, y */
|
||||
}
|
||||
case 1: {
|
||||
Step s(out, "quant_act_fp8");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "group").mirror(p, n_p, "dtype");
|
||||
return s.wire({ 3, 1, 2 }); /* x, q, scale */
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* swiglu_clamped_quant_fp8 -- GLM's clipped SwiGLU and the fp8 quantiser in one pass.
|
||||
* (kernel: libhalo/halo_glm.hip, swiglu_clamped_quant_kernel)
|
||||
*
|
||||
* Operands: [0] gate_up [1] q [2] scale [3] out_bf16?
|
||||
*
|
||||
* Each element is `swiglu_clamped_bf16`'s expression, rounded to bf16 once, and the codes are
|
||||
* quant_act_fp8's over that rounded value, so the chain is the two rows with the product between.
|
||||
*/
|
||||
extern "C" int halo_fuse_swiglu_clamped_quant_fp8(const RadParam* p, int n_p, uint64_t present,
|
||||
int step, RadFuseStep* out) {
|
||||
|
||||
if (!out) return RAD_E_INVAL;
|
||||
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
|
||||
if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED;
|
||||
const int16_t mid = RAD_FUSE_HAS(present, 3) ? (int16_t)3 : RAD_FUSE_TMP(0);
|
||||
|
||||
switch (step) {
|
||||
case 0: {
|
||||
Step s(out, "swiglu_clamped");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "limit").mirror(p, n_p, "dtype");
|
||||
return s.wire({ 0, mid }); /* gate_up, y */
|
||||
}
|
||||
case 1: {
|
||||
Step s(out, "quant_act_fp8");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "group").mirror(p, n_p, "dtype");
|
||||
return s.wire({ mid, 1, 2 }); /* x, q, scale */
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* router_sigmoid_topk_scatter -- GLM's selection, the sort over its ids and the shared gate's fill.
|
||||
* (kernel: libhalo/halo_glm.hip, router_sigmoid_scatter_kernel)
|
||||
*
|
||||
* Operands: [0] logits [1] bias [2] ids [3] weights [4] sorted_tok [5] expert_offset
|
||||
* [6] expert_count [7] gate? [8] inverse?
|
||||
*
|
||||
* The sort runs over this rank's slice, so `moe_scatter`'s `n_expert` is the fused op's `n_local`;
|
||||
* with the inverse it is `moe_scatter_inv`. The fill steps in only with the gate.
|
||||
*/
|
||||
extern "C" int halo_fuse_router_sigmoid_topk_scatter(const RadParam* p, int n_p, uint64_t present,
|
||||
int step, RadFuseStep* out) {
|
||||
|
||||
if (!out) return RAD_E_INVAL;
|
||||
const int64_t ne = pi(p, n_p, "n_expert"), nl = pi(p, n_p, "n_local", ne);
|
||||
if (ne <= 0 || nl <= 0 || nl > ne) return RAD_E_UNSUPPORTED;
|
||||
|
||||
switch (step) {
|
||||
case 0: {
|
||||
Step s(out, "router_sigmoid_topk");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "n_expert").mirror(p, n_p, "top_k")
|
||||
.mirror(p, n_p, "norm").mirror(p, n_p, "route_scale").mirror(p, n_p, "dtype");
|
||||
return s.wire({ 0, 1, 2, 3 }); /* logits, bias, ids, weights */
|
||||
}
|
||||
case 1: {
|
||||
const bool inv = RAD_FUSE_HAS(present, 8) != 0;
|
||||
Step s(out, inv ? "moe_scatter_inv" : "moe_scatter");
|
||||
s.mirror(p, n_p, "M").pint("n_expert", nl).mirror(p, n_p, "top_k")
|
||||
.mirror_opt(p, n_p, "expert_base").mirror_opt(p, n_p, "protect");
|
||||
if (inv) return s.wire({ 2, 4, 5, 6, 8 }); /* expert_ids, sorted_tok, offset, count, inverse */
|
||||
return s.wire({ 2, 4, 5, 6 }); /* expert_ids, sorted_tok, offset, count */
|
||||
}
|
||||
case 2: {
|
||||
if (!RAD_FUSE_HAS(present, 7)) return RAD_E_NOTFOUND;
|
||||
Step s(out, "fill");
|
||||
s.mirror(p, n_p, "M").pint("n", 1).pstr("dtype", "bf16").pf64("value", 1.0);
|
||||
return s.wire({ 7 }); /* y */
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* gate_quant_fp8 -- the same epilogue with the gate in its own operand.
|
||||
* (kernel: libhalo/halo_fused_quant_fp8.hip, gate_quant_fp8_kernel)
|
||||
*
|
||||
* Operands: [0] gate [1] x [2] q [3] scale [4] out_bf16?
|
||||
*
|
||||
* 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]));
|
||||
*
|
||||
* `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: 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 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 halo_fuse_gate_quant_fp8(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
|
||||
if (!out) return RAD_E_INVAL;
|
||||
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
|
||||
if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED;
|
||||
/* The shim (halo_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: {
|
||||
/* 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 */
|
||||
}
|
||||
case 1: {
|
||||
Step s(out, "mul");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "dtype");
|
||||
return s.wire({ RAD_FUSE_TMP(0), 1, 4 }); /* a, b, y */
|
||||
}
|
||||
case 2: {
|
||||
Step s(out, "quant_act_fp8");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "group").mirror(p, n_p, "dtype");
|
||||
return s.wire({ 4, 2, 3 }); /* x, q, scale */
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* gemm_nt_q_gated -- the narrow fp8 GEMM with the SwiGLU and the quantiser in its epilogue.
|
||||
* (row: gemm_fp8a8_gated_nt_m16; shim: halo_gemm_fp8a8.hip)
|
||||
*
|
||||
* Operands: [0] a [1] a_scale [2] b [3] b_scale [4] q [5] scale [6] out_bf16?
|
||||
*
|
||||
* Byte-identical to gemm_nt_q followed by gated_quant_fp8: the accumulator is rounded to bf16
|
||||
* before the gate and the multiply, and the amax is an fmaxf reduction, exact under any regrouping
|
||||
* across waves. Both steps are libhalo rows.
|
||||
*
|
||||
* TMP(0) is the [M, N] bf16 plane between the GEMM and the quantiser, which the fusion never
|
||||
* writes. Its extents come from step 0's `opd_shape` (the ABI rule for temporaries):
|
||||
* halo_shape_gemm_nt_q gives [M, N] for operand 4 and halo_shape_gated_quant_fp8 gives [M, 2n] for
|
||||
* operand 0, the same plane since `n` = N/2.
|
||||
*
|
||||
* Two parameters are not copies:
|
||||
*
|
||||
* `n` is N/2. The fused `N` is the weight's rows, gate then up, twice the output width
|
||||
* (hence a schema of its own rather than a flag on `gemm_nt_q`).
|
||||
*
|
||||
* `dtype` is "fp8a8" on the GEMM step and "bf16" on the quantiser step. For a GEMM it names the
|
||||
* operand combination, for an activation op the width of its input: cGemmNtQGatedFp8
|
||||
* has `C_IN("dtype", "fp8a8")`, cGatedQuantFp8 `C_IN("dtype", "bf16")`. Copying the
|
||||
* fused value fails to resolve only because no other row declares that combination.
|
||||
*
|
||||
* `a_sum` (asymmetric integer grids) and `b_ref` (mxfp4) follow `gemm_nt_q`'s `y`; an fp8 grid has
|
||||
* neither, and halo_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 halo_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
|
||||
if (!out) return RAD_E_INVAL;
|
||||
const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K");
|
||||
const char* dt = halo_pgets(p, n_p, "dtype");
|
||||
if (M <= 0 || N <= 0 || K <= 0 || N % 2) return RAD_E_UNSUPPORTED;
|
||||
if (pi(p, n_p, "group", HALO_FP8_BLOCK) != HALO_FP8_BLOCK) return RAD_E_UNSUPPORTED;
|
||||
if (!dt || std::strcmp(dt, "fp8a8")) return RAD_E_UNSUPPORTED;
|
||||
/* Required on this op, unlike on the quantiser, because only silu is compiled; an optional
|
||||
* parameter would let the row resolve for a gate it cannot serve. */
|
||||
if (!act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED;
|
||||
|
||||
switch (step) {
|
||||
case 0: {
|
||||
/* The GEMM over the whole [N, K] gate_up weight, into the temporary plane. */
|
||||
Step s(out, "gemm_nt_q");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "N").mirror(p, n_p, "K")
|
||||
.mirror(p, n_p, "group").mirror(p, n_p, "dtype");
|
||||
/* a, a_scale, b, b_scale, y, a_sum, b_ref */
|
||||
return s.wire({ 0, 1, 2, 3, RAD_FUSE_TMP(0), RAD_FUSE_NONE, RAD_FUSE_NONE });
|
||||
}
|
||||
case 1: {
|
||||
/* Gate, multiply and codes over the accumulator plane, at half its width. */
|
||||
Step s(out, "gated_quant_fp8");
|
||||
s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).mirror(p, n_p, "group")
|
||||
.pstr("dtype", "bf16").mirror(p, n_p, "act");
|
||||
return s.wire({ RAD_FUSE_TMP(0), 4, 5, 6 }); /* gate_up, q, scale, out_bf16 */
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* gemm_nt_q_gated_mx -- the same fold over an OCP-MXFP4 weight.
|
||||
* (row: gemm_mxfp4a8_gated_gemv; kernel: libhalo/halo_gemm_mxfp4a8_gemv.hip, the gated form)
|
||||
*
|
||||
* Operands: [0] a [1] a_scale [2] b [3] b_scale [4] b_ref [5] q [6] scale [7] out_bf16
|
||||
*
|
||||
* The GEMM step is gemm_nt_q at dtype mxfp4a8 with `b_ref` in its last operand. `group` is the
|
||||
* weight's 32 on the GEMM and the activation's 128 on the quantiser, so the quantiser's is set, not
|
||||
* mirrored. At act gelu_tanh the chain is three steps, gelu_mul into a second temporary and
|
||||
* quant_act_fp8 over it; that form refuses `out_bf16` (the shim), so operand 7 is not wired.
|
||||
*/
|
||||
extern "C" int halo_fuse_gemm_nt_q_gated_mx(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K");
|
||||
const char* dt = halo_pgets(p, n_p, "dtype");
|
||||
if (M <= 0 || N <= 0 || K <= 0 || N % 2) return RAD_E_UNSUPPORTED;
|
||||
if (pi(p, n_p, "group", 32) != 32) return RAD_E_UNSUPPORTED;
|
||||
if (!dt || std::strcmp(dt, "mxfp4a8")) return RAD_E_UNSUPPORTED;
|
||||
const bool gelu = act_is(p, n_p, "silu", "gelu_tanh");
|
||||
if (!gelu && !act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED;
|
||||
/* The GeGLU chain leaves its bf16 plane in a temporary, so a caller asking for out_bf16 there
|
||||
* has no chain (the shim refuses the operand too). */
|
||||
if (gelu && RAD_FUSE_HAS(present, 7)) return RAD_E_UNSUPPORTED;
|
||||
|
||||
if (step == 0) {
|
||||
Step s(out, "gemm_nt_q");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "N").mirror(p, n_p, "K")
|
||||
.mirror(p, n_p, "group").mirror(p, n_p, "dtype");
|
||||
/* a, a_scale, b, b_scale, y, a_sum, b_ref */
|
||||
return s.wire({ 0, 1, 2, 3, RAD_FUSE_TMP(0), RAD_FUSE_NONE, 4 });
|
||||
}
|
||||
if (gelu) {
|
||||
if (step == 1) {
|
||||
Step s(out, "gelu_mul");
|
||||
s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pstr("dtype", "bf16");
|
||||
return s.wire({ RAD_FUSE_TMP(0), RAD_FUSE_TMP(1) }); /* gate_up, y */
|
||||
}
|
||||
if (step == 2) {
|
||||
Step s(out, "quant_act_fp8");
|
||||
s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pint("group", 128)
|
||||
.pstr("dtype", "bf16");
|
||||
return s.wire({ RAD_FUSE_TMP(1), 5, 6 }); /* x, q, scale */
|
||||
}
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
switch (step) {
|
||||
case 1: {
|
||||
Step s(out, "gated_quant_fp8");
|
||||
s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pint("group", 128)
|
||||
.pstr("dtype", "bf16").mirror(p, n_p, "act");
|
||||
return s.wire({ RAD_FUSE_TMP(0), 5, 6, 7 }); /* gate_up, q, scale, out_bf16 */
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* gdn_conv_recurrent_update -- the decode convolution folded into the recurrent update's prologue.
|
||||
* (row: gdn_conv_recurrent_update_k128_v128_bf16; kernel: libhalo/
|
||||
* halo_gdn_recurrent_update_k128_v128_bf16_fp32state.hip, halo_gdn_recurrent_update_kernel under CV)
|
||||
*
|
||||
* Operands: [0] x [1] conv_w [2] conv_b [3] conv_state [4] conv_idx [5] a [6] b [7] A_log
|
||||
* [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 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 halo_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 = opt_opd(present, 2), oq = opt_opd(present, 16), os = opt_opd(present, 17);
|
||||
switch (step) {
|
||||
case 0: {
|
||||
Step s(out, "gdn_conv_update");
|
||||
s.mirror(p, n_p, "q_len").mirror(p, n_p, "head_k").mirror(p, n_p, "head_v")
|
||||
.mirror(p, n_p, "conv_width");
|
||||
/* x, w, b, conv_state, state_idx, num_accepted, cu, q, k, v */
|
||||
return s.wire({ 0, 1, cb, 3, 4, 11, 12, RAD_FUSE_TMP(0), RAD_FUSE_TMP(1),
|
||||
RAD_FUSE_TMP(2) });
|
||||
}
|
||||
case 1: {
|
||||
Step s(out, "gdn_recurrent_update");
|
||||
s.mirror(p, n_p, "q_len").mirror(p, n_p, "head_k").mirror(p, n_p, "head_v")
|
||||
.mirror_opt(p, n_p, "n_head_v").mirror_opt(p, n_p, "scale").mirror_opt(p, n_p, "eps")
|
||||
.mirror_opt(p, n_p, "l2_eps").mirror_opt(p, n_p, "softplus_thr")
|
||||
.mirror_opt(p, n_p, "act").mirror_opt(p, n_p, "state_fp16")
|
||||
.mirror_opt(p, n_p, "state_form");
|
||||
/* q, k, v, a, b, A_log, dt_bias, state, state_idx, num_accepted, cu, z, norm_w, o, o_q,
|
||||
* o_scale */
|
||||
return s.wire({ RAD_FUSE_TMP(0), RAD_FUSE_TMP(1), RAD_FUSE_TMP(2), 5, 6, 7, 8, 9, 10, 11,
|
||||
12, 13, 14, 15, oq, os });
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* qk_norm_rope_gate_kv_store -- the gated-attention prologue with the cache store folded on.
|
||||
* (rows: qk_norm_rope_gate_kv_store_fp8 and _bf16; kernel: libhalo/halo_qk_norm_rope_gate.hip,
|
||||
* halo_qk_norm_rope_gate_kernel under KV)
|
||||
*
|
||||
* Operands: [0] q_gate? [1] k [2] cos_sin [3] positions [4] q_w? [5] k_w [6] q_out?
|
||||
* [7] k_out [8] gate_out? [9] v [10] slot_mapping [11] kv_cache
|
||||
*
|
||||
* No temporaries: the store reads the prologue's own `k_out`, which the fold writes as well. */
|
||||
extern "C" int halo_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 = [present](int i) { return opt_opd(present, i); };
|
||||
switch (step) {
|
||||
case 0: {
|
||||
Step s(out, "qk_norm_rope_gate");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head")
|
||||
.mirror(p, n_p, "n_head_kv").mirror(p, n_p, "rot").mirror(p, n_p, "q_dtype")
|
||||
.mirror_opt(p, n_p, "eps").mirror_opt(p, n_p, "wadd").mirror_opt(p, n_p, "cs_f32")
|
||||
.mirror_opt(p, n_p, "pos_i64");
|
||||
return s.wire({ opt(0), 1, 2, 3, opt(4), 5, opt(6), 7, opt(8) });
|
||||
}
|
||||
case 1: {
|
||||
Step s(out, "kv_store");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head_kv")
|
||||
.mirror(p, n_p, "block_size").mirror(p, n_p, "kv_dtype")
|
||||
.mirror_opt(p, n_p, "k_scale").mirror_opt(p, n_p, "v_scale");
|
||||
/* k, v, slot_mapping, kv_cache */
|
||||
return s.wire({ 7, 9, 10, 11 });
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* qk_norm_rope_gate_kv_store_streamed -- the same prologue with the streamed store folded on.
|
||||
* (rows: qk_norm_rope_gate_kv_store_streamed_{fp8,bf16}; kernel: halo_qk_norm_rope_gate.hip under
|
||||
* QK_KV_STREAMED)
|
||||
*
|
||||
* Operands: [0] q_gate? [1] k [2] cos_sin [3] positions [4] q_w? [5] k_w [6] q_out?
|
||||
* [7] k_out [8] gate_out? [9] v [10] slot_mapping [11] kv_cache
|
||||
* [12] res [13] host
|
||||
*
|
||||
* The store is `kv_store_streamed`, whose `k` is the prologue's own `k_out`. */
|
||||
extern "C" int halo_fuse_qk_norm_rope_gate_kv_store_streamed(const RadParam* p, int n_p,
|
||||
uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
auto opt = [present](int i) { return opt_opd(present, i); };
|
||||
switch (step) {
|
||||
case 0: {
|
||||
Step s(out, "qk_norm_rope_gate");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head")
|
||||
.mirror(p, n_p, "n_head_kv").mirror(p, n_p, "rot").mirror(p, n_p, "q_dtype")
|
||||
.mirror_opt(p, n_p, "eps").mirror_opt(p, n_p, "wadd").mirror_opt(p, n_p, "cs_f32")
|
||||
.mirror_opt(p, n_p, "pos_i64");
|
||||
return s.wire({ opt(0), 1, 2, 3, opt(4), 5, opt(6), 7, opt(8) });
|
||||
}
|
||||
case 1: {
|
||||
Step s(out, "kv_store_streamed");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head_kv")
|
||||
.mirror(p, n_p, "block_size").mirror(p, n_p, "kv_dtype")
|
||||
.mirror_opt(p, n_p, "k_scale").mirror_opt(p, n_p, "v_scale");
|
||||
/* k_out, v, slot_mapping, kv_cache, res, host */
|
||||
return s.wire({ 7, 9, 10, 11, 12, 13 });
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* qkv_norm_rope_kv_store -- qkv_norm_rope, then kv_store of its finished k and v.
|
||||
* (rows: qkv_norm_rope_kv_store_fp8 and _bf16; kernel: libhalo/halo_qkv_norm_rope.hip,
|
||||
* qkv_norm_rope_kernel under KV)
|
||||
*
|
||||
* Operands: [0] q [1] k [2] v [3] positions [4] q_w [5] k_w [6] slot_mapping [7] kv_cache
|
||||
*
|
||||
* No temporaries: the prologue rewrites q, k and v in place and the store reads k and v as the
|
||||
* prologue left them, which is what the kernel stores. */
|
||||
extern "C" int halo_fuse_qkv_norm_rope_kv_store(const RadParam* p, int n_p, uint64_t present,
|
||||
int step, RadFuseStep* out) {
|
||||
(void)present;
|
||||
if (!out) return RAD_E_INVAL;
|
||||
switch (step) {
|
||||
case 0: {
|
||||
Step s(out, "qkv_norm_rope");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head")
|
||||
.mirror(p, n_p, "n_head_kv").mirror(p, n_p, "theta").mirror(p, n_p, "eps")
|
||||
.mirror_opt(p, n_p, "scale").mirror_opt(p, n_p, "mode").mirror_opt(p, n_p, "rotary_dim")
|
||||
.mirror_opt(p, n_p, "ladder").mirror_opt(p, n_p, "wadd").mirror_opt(p, n_p, "v_from_k")
|
||||
.mirror(p, n_p, "dtype").mirror_opt(p, n_p, "v_norm");
|
||||
return s.wire({ 0, 1, 2, 3, 4, 5 });
|
||||
}
|
||||
case 1: {
|
||||
Step s(out, "kv_store");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head_kv")
|
||||
.mirror(p, n_p, "block_size").mirror(p, n_p, "kv_dtype")
|
||||
.mirror_opt(p, n_p, "k_scale").mirror_opt(p, n_p, "v_scale");
|
||||
/* k, v, slot_mapping, kv_cache */
|
||||
return s.wire({ 1, 2, 6, 7 });
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* add_rmsnorm -- add (x += a), then rmsnorm of the x it wrote.
|
||||
* (row: add_rmsnorm_bf16; kernel: libhalo/halo_model_bf16.hip, add_rmsnorm_kernel)
|
||||
*
|
||||
* Operands: [0] x [1] a [2] w [3] y
|
||||
*
|
||||
* No temporaries: the add writes x in place and the norm reads it. */
|
||||
extern "C" int halo_fuse_add_rmsnorm(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
(void)present;
|
||||
if (!out) return RAD_E_INVAL;
|
||||
switch (step) {
|
||||
case 0: {
|
||||
Step s(out, "add");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "dtype");
|
||||
/* a = x, b = the addend, y = x */
|
||||
return s.wire({ 0, 1, 0 });
|
||||
}
|
||||
case 1: {
|
||||
Step s(out, "rmsnorm");
|
||||
s.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").mirror_opt(p, n_p, "mult");
|
||||
return s.wire({ 0, 2, 3 });
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* attn_paged_gate_quant -- attn_paged, then gate_quant_fp8 over its output.
|
||||
* (row: attn_decode_gq_h256_gqa12_fp8kv; kernels: libhalo/halo_attn_decode_h256_gqa6.hip, the
|
||||
* `_gq` split-KV merges)
|
||||
*
|
||||
* 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, 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 halo_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 = [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;
|
||||
switch (step) {
|
||||
case 0: {
|
||||
Step s(out, "attn_paged");
|
||||
s.mirror(p, n_p, "q_len").mirror(p, n_p, "head_dim").mirror(p, n_p, "gqa")
|
||||
.mirror(p, n_p, "block_size").mirror(p, n_p, "causal").mirror(p, n_p, "window")
|
||||
.mirror(p, n_p, "q_dtype").mirror(p, n_p, "kv_dtype").mirror_opt(p, n_p, "scale")
|
||||
.mirror_opt(p, n_p, "max_ctx").mirror_opt(p, n_p, "n_head")
|
||||
.mirror_opt(p, n_p, "max_seqs");
|
||||
return s.wire({ 0, 1, 2, 3, opt(4), opt(5), opt(6), 7 });
|
||||
}
|
||||
case 1: {
|
||||
Step s(out, "gate_quant_fp8");
|
||||
s.pint("M", (long long)(seqs * q_len * nh)).pint("n", (long long)hd)
|
||||
.mirror(p, n_p, "group").pstr("dtype", "bf16").mirror(p, n_p, "act");
|
||||
return s.wire({ 8, 7, 9, 10, 7 }); /* gate, x, q, scale, out_bf16 */
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* ar_gather_hc_write -- moe_gather, then ar_hc_write.
|
||||
* (kernel: libhalo/halo_ar_oneshot_2rank_exact.hip, halo_ar_gather_hc_write_kernel, and at four ranks
|
||||
* libhalo/halo_ar_oneshot_Nrank_exact.hip, halo_ar_gather_hc_write_wide_kernel; shim: halo_ar_entry.hip)
|
||||
*
|
||||
* 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 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 halo_fuse_ar_gather_hc_write(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), k = pi(p, n_p, "top_k");
|
||||
if (M <= 0 || n <= 0 || k <= 0) return RAD_E_UNSUPPORTED;
|
||||
switch (step) {
|
||||
case 0: {
|
||||
Step s(out, "moe_gather");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "top_k")
|
||||
.mirror(p, n_p, "dtype").mirror_opt(p, n_p, "act");
|
||||
return s.wire({ 0, 1, 2, 3, 4, 5 }); /* y_expert, expert_w, sorted_tok, shared, gate, y */
|
||||
}
|
||||
case 1: {
|
||||
Step s(out, "ar_hc_write");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "hc")
|
||||
.mirror(p, n_p, "world_size").mirror(p, n_p, "dtype").mirror_opt(p, n_p, "wire");
|
||||
return s.wire({ 5, 6, 7 }); /* y, inj, h */
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* ar_rmsnorm_quant_fp8 -- the two-rank all-reduce with the norm and the quantiser folded on.
|
||||
* (kernel: libhalo/halo_fused_quant_fp8.hip, ar_rmsnorm_quant_fp8_kernel; shim: halo_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 libhalo 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 halo_fuse_ar_rmsnorm_quant_fp8(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
|
||||
if (!out) return RAD_E_INVAL;
|
||||
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
|
||||
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 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) {
|
||||
case 0: {
|
||||
Step s(out, "all_reduce");
|
||||
s.mirror(p, n_p, "world_size").pint("numel", (long long)(M * n))
|
||||
.mirror(p, n_p, "dtype").pint("exact", wire == 0 ? 1 : 0);
|
||||
if (wire != 0) s.pint("min_bytes", 0);
|
||||
return s.wire({ 0, RAD_FUSE_NONE }); /* x (inout), y */
|
||||
}
|
||||
case 1: {
|
||||
Step s(out, "rmsnorm_quant_fp8");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "eps")
|
||||
.mirror(p, n_p, "group").mirror(p, n_p, "dtype").mirror_opt(p, n_p, "wadd");
|
||||
return s.wire({ 0, 1, 2, 3, 4, 5 }); /* x, residual, w, q, scale, out_bf16 */
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,60 @@
|
||||
/* Derived from libr4d/r4d_fwht.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
// halo_fwht.h - a wave-local fast Walsh-Hadamard transform in registers, with no LDS and no barrier.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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 in the same lane -- plain register arithmetic
|
||||
// h >= VPL the partner is lane l + h/VPL -- one lane exchange with mask h/VPL
|
||||
//
|
||||
// HAD/VPL is always 32, so the cross-lane masks are 1, 2, 4, 8, 16 at any HAD: five exchanges per
|
||||
// register (halo_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 "halo_common.h"
|
||||
|
||||
// `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 halo_fwht_xstage(float* v, int lane) {
|
||||
const unsigned int sm = (lane & MASK) ? 0x80000000u : 0u;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPL; j++) {
|
||||
const float o = halo_xor_lane<MASK>(v[j]);
|
||||
v[j] = __int_as_float(__float_as_int(v[j]) ^ sm) + o;
|
||||
}
|
||||
}
|
||||
|
||||
// In-register FWHT of a HAD-wide block held VPL = HAD/32 values per lane, lane-major.
|
||||
// Unnormalised: the caller folds 1/sqrt(HAD) into whatever scale it already applies.
|
||||
template <int HAD>
|
||||
__device__ __forceinline__ void halo_fwht_wave(float* v, int lane) {
|
||||
constexpr int VPL = HAD / 32;
|
||||
// in-lane stages: stride 1 .. VPL/2, entirely within this lane's registers
|
||||
#pragma unroll
|
||||
for (int h = 1; h < VPL; h <<= 1) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPL; j++) {
|
||||
if ((j & h) == 0) {
|
||||
const float a = v[j], b = v[j + h];
|
||||
v[j] = a + b;
|
||||
v[j + h] = a - b;
|
||||
}
|
||||
}
|
||||
}
|
||||
// cross-lane stages: stride VPL*mask for mask = 1, 2, 4, 8, 16
|
||||
halo_fwht_xstage<VPL, 1>(v, lane);
|
||||
halo_fwht_xstage<VPL, 2>(v, lane);
|
||||
halo_fwht_xstage<VPL, 4>(v, lane);
|
||||
halo_fwht_xstage<VPL, 8>(v, lane);
|
||||
halo_fwht_xstage<VPL, 16>(v, lane);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
/* Derived from libr4d/r4d_gated_had_quant_i8.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gated_had_quant_i8.hip - halo_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 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
|
||||
// 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.
|
||||
//
|
||||
// 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 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 (halo_fwht.h), so this is one pass: read gate and up, multiply,
|
||||
// rotate inside the wave, stage once for the row absmax.
|
||||
//
|
||||
// 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 "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_fwht.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <cmath>
|
||||
|
||||
template <int HAD, int MODE, int THR>
|
||||
__global__ __launch_bounds__(THR) void halo_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) {
|
||||
constexpr int VPL = HAD / 32, NW = THR / 32;
|
||||
extern __shared__ float lds[];
|
||||
float* red = lds + K;
|
||||
const int row = blockIdx.x;
|
||||
const __hip_bfloat16* g = G + (size_t)row * gstride;
|
||||
const __hip_bfloat16* u = U + (size_t)row * ustride;
|
||||
const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
|
||||
|
||||
float m = 0.f;
|
||||
for (int blk = wave; blk < K / HAD; blk += NW) {
|
||||
const int base = blk * HAD + lane * VPL;
|
||||
float v[VPL];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPL; j++) {
|
||||
const float xg = __bfloat162float(g[base + j]);
|
||||
const float sg = 1.f / (1.f + __expf(-xg));
|
||||
v[j] = (MODE == 0 ? xg * sg : sg) * __bfloat162float(u[base + j]);
|
||||
}
|
||||
halo_fwht_wave<HAD>(v, lane);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPL; j++) {
|
||||
lds[base + j] = v[j];
|
||||
m = fmaxf(m, fabsf(v[j]));
|
||||
}
|
||||
}
|
||||
m = halo_wave_max(m);
|
||||
if (lane == 0) red[wave] = m;
|
||||
__syncthreads();
|
||||
m = red[0];
|
||||
#pragma unroll
|
||||
for (int i = 1; i < NW; i++) m = fmaxf(m, red[i]);
|
||||
m = fmaxf(m, 1e-8f);
|
||||
const float inv = 127.f / m;
|
||||
if (threadIdx.x == 0) S[row] = m * rnorm / 127.f;
|
||||
|
||||
signed char* q = Q + (size_t)row * K;
|
||||
for (int i = threadIdx.x; i < K; i += THR) {
|
||||
const int s = i >> 4, j = i & 15;
|
||||
const int sr = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3);
|
||||
const int t = __float2int_rn(lds[sr] * inv);
|
||||
q[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
|
||||
}
|
||||
}
|
||||
|
||||
// The launch, as the plugin ABI's RadLaunchFn. See the note at the head of halo_quant_act_i8.hip.
|
||||
//
|
||||
// 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 halo_rad_gated_had_quant_i8(const RadArgs* args, RadStream stream) {
|
||||
const RadTensor* ta = halo_opt(args, GH_A);
|
||||
const RadTensor* tb = halo_opt(args, GH_B);
|
||||
const RadTensor* q = halo_opt(args, GH_Q);
|
||||
const RadTensor* sc = halo_opt(args, GH_S);
|
||||
if (!ta || !q || !sc) return HALO_NO(RAD_E_INVAL);
|
||||
if (!halo_contig(q) || !halo_contig(sc)) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
const long long K = halo_geti_or(args, "n", 0); // the GATED width, half of a packed row
|
||||
if (K < 1) return HALO_NO(RAD_E_INVAL);
|
||||
|
||||
long long M = 0, width = 0;
|
||||
int rc = halo_rows_of(ta, &M, &width);
|
||||
if (rc != RAD_OK) return HALO_NO(rc);
|
||||
|
||||
const __hip_bfloat16* pa = (const __hip_bfloat16*)halo_p(ta);
|
||||
const __hip_bfloat16* pb = nullptr;
|
||||
long long a_stride = 0, b_stride = 0;
|
||||
|
||||
if (tb) {
|
||||
if (width != K) return HALO_NO(RAD_E_SHAPE);
|
||||
a_stride = halo_row_pitch(ta);
|
||||
b_stride = halo_row_pitch(tb);
|
||||
if (a_stride < 0 || b_stride < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
pb = (const __hip_bfloat16*)halo_p(tb);
|
||||
} else {
|
||||
if (width != 2 * K) return HALO_NO(RAD_E_SHAPE);
|
||||
a_stride = halo_row_pitch(ta);
|
||||
if (a_stride < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
b_stride = a_stride;
|
||||
pb = pa + K;
|
||||
}
|
||||
|
||||
const long long had = halo_geti_or(args, "group", 0);
|
||||
if (had != 128 && had != 256 && had != 512) return HALO_NO(RAD_E_SHAPE);
|
||||
// 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 HALO_NO(RAD_E_SHAPE);
|
||||
if (K % 16) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
// `act` names the activation ("silu" or "sigmoid"); `mode` is this kernel's integer for it.
|
||||
const int mode = halo_act_code(args, "act", "mode", 0);
|
||||
if (mode != 0 && mode != 1) return HALO_NO(RAD_E_INVAL);
|
||||
if (halo_numel(q) != M * K) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
const int thr = halo_act_threads((int)M, (int)K);
|
||||
const size_t shmem = (size_t)K * sizeof(float) + (thr / 32) * sizeof(float);
|
||||
if (shmem > 65536) return HALO_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);
|
||||
#define HALO_GHQ_LAUNCH(H, MD, T) hipLaunchKernelGGL((halo_gated_had_quant_i8_kernel<H, MD, T>), \
|
||||
dim3((int)M), dim3(T), shmem, (hipStream_t)stream, pa, pb, (signed char*)halo_wp(q), \
|
||||
(float*)halo_wp(sc), (int)K, gs, us, rn)
|
||||
#define HALO_GHQ_T(H, MD) switch (thr) { \
|
||||
case 256: HALO_GHQ_LAUNCH(H, MD, 256); break; \
|
||||
case 512: HALO_GHQ_LAUNCH(H, MD, 512); break; \
|
||||
case 1024: HALO_GHQ_LAUNCH(H, MD, 1024); break; \
|
||||
default: return HALO_NO(RAD_E_INVAL); }
|
||||
#define HALO_GHQ_MODE(MD) switch (had) { \
|
||||
case 128: HALO_GHQ_T(128, MD); break; \
|
||||
case 256: HALO_GHQ_T(256, MD); break; \
|
||||
default: HALO_GHQ_T(512, MD); break; }
|
||||
if (mode == 0) { HALO_GHQ_MODE(0); } else { HALO_GHQ_MODE(1); }
|
||||
#undef HALO_GHQ_MODE
|
||||
#undef HALO_GHQ_T
|
||||
#undef HALO_GHQ_LAUNCH
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : HALO_NO(RAD_E_DEVICE);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/* Derived from libr4d/r4d_gdn_args.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
/* halo_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 HALO_GDN_ARGS_H
|
||||
#define HALO_GDN_ARGS_H
|
||||
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
|
||||
|
||||
/* Every `const void*` libhalo takes has one element type, cast inside the kernel (e.g.
|
||||
* halo_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 halo_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 HALO_DT(t, want) \
|
||||
do { const int _d = halo_dt((t), (want)); if (_d != RAD_OK) return HALO_NO(_d); } while (0)
|
||||
|
||||
/* A raw halo.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 halo_raw_status(int rc, const char* file, int line) {
|
||||
if (rc == 0) return RAD_OK;
|
||||
return halo_refused(rc < 0 ? RAD_E_SHAPE : RAD_E_DEVICE, file, line);
|
||||
}
|
||||
#define HALO_RAW(rc) halo_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 HALO_NO(RAD_E_SHAPE);
|
||||
if (!halo_contig(cu)) return HALO_NO(RAD_E_STRIDE);
|
||||
*out = (int)(cu->shape[0] - 1);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* libhalo's compiled-in geometry, so a rebuild at a different head size cannot silently change what
|
||||
* the rows mean. */
|
||||
static inline int gdn_dims_ok(void) {
|
||||
int hk = 0, hv = 0, ch = 0;
|
||||
halo_gdn_dims(&hk, &hv, &ch);
|
||||
return (hk == 128 && hv == 128 && ch == 64) ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
|
||||
/* 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) {
|
||||
if (t->stride[t->rank - 1] != 1) return -1;
|
||||
return t->rank >= 2 ? t->stride[t->rank - 2] : width;
|
||||
}
|
||||
return halo_contig(t) ? width : -1;
|
||||
}
|
||||
|
||||
#endif /* HALO_GDN_ARGS_H */
|
||||
@@ -0,0 +1,721 @@
|
||||
/* Derived from libr4d/r4d_gdn_chunk_scan_k128_v128_c64_bf16.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gdn: the gated-delta-net chunked scan, gfx1201 WMMA. Entry point
|
||||
// halo_gdn_chunk_scan_k128_v128_c64_bf16 -- head_k 128, head_v 128, chunk 64, bf16 in.
|
||||
// Used by prefill and chunked prefill; decode uses the recurrent update kernel. Replaces FLA's
|
||||
// recompute_w_u_fwd + chunk_gated_delta_rule_fwd_h + chunk_fwd_o: the recurrent state stays in
|
||||
// WMMA accumulators across the chunk loop, so h / w / u / v_new never touch HBM.
|
||||
//
|
||||
// Invariant: every decay factor formed is <= 1. The intra-chunk gate span reaches 558 nats on
|
||||
// real Qwen3.8 prefill activations, so splitting the exponent about a per-chunk reference c
|
||||
// (e^{g_i-c} * e^{c-g_j}) overflows fp32 on one side and underflows on the other for any c.
|
||||
// e^{g_i-g_j} (j <= i) and e^{g_last-g_j} stay in (0, 1].
|
||||
//
|
||||
// ge[j]=e^{g_j} gg[j]=g_j gs[j]=e^{g_last-g_j}
|
||||
// U = K@S W = beta*(V - ge*U) V' = A@W (undecayed)
|
||||
// P = Q@K^T sA = scale*e^{g_i-g_j}*tril(P)
|
||||
// O = scale*ge*(Q@S) + sA@V'
|
||||
// S = e^{g_last}*S + V'^T@(gs*K)
|
||||
// A is FLA's solve_tril output (decay folded in), so no decay enters W or V'. The (i,j) weight
|
||||
// is applied per element in the score step (eight __expf per tile), and the state's
|
||||
// e^{g_last-g_j} is applied to K, which is otherwise dead by then. V' stays undecayed because its
|
||||
// consumers need different references (e^{g_i-g_j} for the output, e^{g_last-g_j} for the state),
|
||||
// and serving both from one scaling would need the unsafe split.
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "halo.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_args.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
// Barriers are lds_barrier(): __syncthreads() fences all address spaces, so the barrier after the
|
||||
// global O store would wait on s_wait_storecnt_dscnt 0x0.
|
||||
//
|
||||
// ---- gfx1151 port notes ---------------------------------------------------------------------
|
||||
// halo_gdn_wmma.h carries the fragment layer, so the *gathers* port by themselves: rowP/rowG lose
|
||||
// libr4d's `4*(lane>>4)` k term and fragP reads the lane's whole 16-wide k run. What does NOT port
|
||||
// is every accumulator write-out: on gfx11 element e is D[2e + (lane>>4)][lane & 15], not
|
||||
// D[8*(lane>>4) + e][lane & 15], so
|
||||
//
|
||||
// * a transposed stage (s.S, s.A's score tile, s.W, s.D's V') keeps libr4d's destination and
|
||||
// takes its eight values from accPackX(), after scaling them per element -- the two halves of
|
||||
// the wave own different rows, so nothing can be scaled after the exchange;
|
||||
// * O needs nothing: its hardware row is the v dim, so accPackX()'s eight consecutive rows are
|
||||
// eight consecutive v of one token -- the contiguous HBM direction -- and both O loops, the
|
||||
// per-lane scale and the store stay exactly as libr4d wrote them.
|
||||
// The per-lane state (St[]) is the one place the wider fragment scatters: a lane's eight k values
|
||||
// are two apart, so h0/ht go through an f32 LDS tile (see SF) rather than straight to HBM.
|
||||
|
||||
// libr4d's rounding helpers (r4d_gdn_wmma.h) -- f2bf / f2bf2 / bf2f -- are halo_gdn_wmma.h's
|
||||
// (included above): f2bf is round-half-AWAY, one add, so the bf16 stages keep libr4d's bits.
|
||||
// gfx1151 has no v_cvt_pk_bf16_f32 either.
|
||||
|
||||
// One accumulator stage: the eight elements accPackX() assembles, as two 8-byte stores (every
|
||||
// buffer here is only 8-byte aligned, so a 16-byte store would be misaligned on odd rows).
|
||||
// accPackX() packs with halo::pk_bf16's round-to-nearest-even, as accPack() does, where libr4d's
|
||||
// f2bf4 rounds half away; the two differ only on an exact bf16 tie. It is accPack()'s values
|
||||
// without its ds_bpermute exchange and per-pack branches (see halo_gdn_wmma.h). Both operand
|
||||
// shapes are offered so a call site reads the same whether it holds a v8f or a float[8].
|
||||
__device__ __forceinline__ uint4 accPk(v8f v, int lane) {
|
||||
union { v8f f; float s[8]; } u;
|
||||
u.f = v;
|
||||
return accPackX(u.s, lane);
|
||||
}
|
||||
__device__ __forceinline__ void accSt(unsigned short* dst, v8f v, int lane) {
|
||||
const uint4 w = accPk(v, lane);
|
||||
*(uint2*)dst = make_uint2(w.x, w.y);
|
||||
*(uint2*)(dst + 4) = make_uint2(w.z, w.w);
|
||||
}
|
||||
__device__ __forceinline__ void accSt(unsigned short* dst, const float v[8], int lane) {
|
||||
const uint4 w = accPackX(v, lane);
|
||||
*(uint2*)dst = make_uint2(w.x, w.y);
|
||||
*(uint2*)(dst + 4) = make_uint2(w.z, w.w);
|
||||
}
|
||||
|
||||
#define BT 64
|
||||
#define KD 128
|
||||
#define VD 128
|
||||
#define BV 64 // V per workgroup; also halves the Q@K^T redundancy
|
||||
// Row pitches are multiples of 8 shorts (16 B) because halo_gdn_wmma.h's fragP reads a lane's whole
|
||||
// 16-wide k run as two 16-byte LDS loads. They used KP = 132 / AP = 68 on gfx12, where a fragment is
|
||||
// two 8-byte reads 16 bytes apart and 8-byte alignment suffices; on gfx1151 a buffer whose pitch is
|
||||
// 136 B or 264 B puts every odd row 8 bytes off a 16-byte boundary, and a misaligned ds_load_b128
|
||||
// returns garbage -- silently, and only for some register allocations (measured: infs in a
|
||||
// trailing partial chunk with the gfx12 pitches, none with these).
|
||||
#define KP 136 // row pitch of the [.][KD] buffers, in shorts (272 B)
|
||||
#define AP 72 // row pitch of the [.][BT] buffers, in shorts (144 B)
|
||||
#define WP AP
|
||||
// Waves per workgroup. The [4 token][4 v] tile grid is fixed by BT and BV, so 8 waves carry two
|
||||
// tiles each.
|
||||
#define NW 8
|
||||
#define NTHR (NW * 32)
|
||||
#define NTV 2 // n tiles per wave in the main / V' / O loops
|
||||
// A wave's slice of the 8 k-tile x 4 v-tile state grid is 2 x 2.
|
||||
#define SKT 2
|
||||
#define SVT 2
|
||||
#define NST (SKT * SVT) // state tiles per wave
|
||||
|
||||
// gfx1151 register plan. libr4d's plan (state, k/v prefetch, six main-loop accumulators) fits
|
||||
// gfx12's 4-VGPR fragment; ported as is, with gfx11's 8-VGPR fragment, every instantiation sat at
|
||||
// 256 VGPRs with 357-379 spilled (1.3 KB of scratch a lane: loop-invariant LDS addresses -- fragT's
|
||||
// sixteen per-row addresses for the transposed K above all -- hoisted out of the chunk loop and
|
||||
// reloaded inside it), and ~100 us a chunk. Measured on gfx1151 (kbench, M=512, the two fixture
|
||||
// head counts: 820 / 493 us before, 155 / 118 after), what replaced it:
|
||||
// * the state update reads gs*K from a transposed copy, s.KT, written by the pass that used to
|
||||
// scale K in place, so every fragment in the kernel is a fragP. s.KT shares storage with the
|
||||
// bf16 state s.S, whose last reader (the main loop) retires at barrier (2); the state is
|
||||
// restaged at the top of the next chunk, after barrier (4) has retired the s.KT reads, so the
|
||||
// alias costs no barrier.
|
||||
// * every per-lane LDS address is one base plus immediates (a wave-uniform term goes in the
|
||||
// base, never in a per-element index), so nothing is left for LICM to hoist.
|
||||
// * no divergent branch on the chunk path: the accumulator write-outs use accPackX() (accPack()
|
||||
// lowers to ds_bpermute + an LDS wait + a branch per pack), the score mask is a select after
|
||||
// the exp, and the prefetch's zero fill is a select at consumption (-12% together).
|
||||
// * the triangular work stops at the diagonal (P^T tiles, V' and O += sA@V' k steps): 544
|
||||
// WMMAs a chunk instead of 640, and the kernel is WMMA-throughput bound now (dropping P^T
|
||||
// entirely saved its full share).
|
||||
// * the first q fragments and the V' A fragments are issued ahead of the barrier that precedes
|
||||
// their loop, so the first WMMAs do not wait out an HBM round trip (-13% / -4%).
|
||||
// * h0 / ht pass through LDS (see SF): with element-wise HBM access the state traffic was ~45%
|
||||
// of a one-chunk call.
|
||||
// The result is 239-248 VGPRs, no spills, with ROCm 7.2.3 and 7.2.4. The margin is not wide: the
|
||||
// main loop with its P^T count fixed (one all-tiles body instead of the three below) spills ~150.
|
||||
// 16 waves of one tile each (<= 192 VGPRs, so two workgroups per WGP still fit) is ~12% slower.
|
||||
struct Smem {
|
||||
unsigned short k[BT][KP]; // A: K / B: K^T for P=Q@K^T
|
||||
unsigned short A[BT][AP]; // B-source for sA (written as [i][j])
|
||||
union {
|
||||
unsigned short S[BV][KP]; // B: state, V-major (matches FLA's [V,K] layout); main loop only
|
||||
unsigned short KT[KD][AP]; // A: gs*K, transposed ([k][token]); state update only
|
||||
};
|
||||
unsigned short W[BV][WP]; // B: W (transposed)
|
||||
unsigned short D[BV][AP]; // staged V as [token][v]; then V' as [v][token].
|
||||
// V dies in the W update; V' is written after barrier (2).
|
||||
float ge[BT], gv[BT], gg[BT], bt[BT]; // gv = gs, gg = raw g
|
||||
};
|
||||
|
||||
// Choices measured against their alternatives on gfx1201, kept so they are not undone:
|
||||
// - LDS rows in the main loop are opaque 32-bit byte offsets (fragO), global q / A fragments a
|
||||
// 32-bit offset off a uniform base (fragGo).
|
||||
// - k and v are staged eight shorts per lane (global_load_b128), issued as a block before the
|
||||
// main loop: interleaving them into it is ~5% slower.
|
||||
// - Every bf16 pack rounds (f2bf2 / accPackX). Truncating W, sA and V' is ~2% faster but
|
||||
// roughly triples the fp64-oracle error, since they feed the recurrence.
|
||||
// And on gfx1151: prefetching the gates (g, beta, g_last) with k / v, and sched_barrier fences
|
||||
// in the main loop, measured neutral; more q fragments ahead of barrier (1) than QP spill.
|
||||
// Byte offset, from the base of the shared block, of the fragment row this lane reads out of
|
||||
// buf[base + (lane&15)][...]. halo_gdn_wmma.h's rowO is libr4d's ROWO without the `4*hi` k term:
|
||||
// on gfx1151 the half-wave no longer selects which quarter of the k run a lane holds.
|
||||
#define ROWO(buf, pitch, base) \
|
||||
rowO((unsigned)((const char*)&(buf)[0][0] - (const char*)&s), (pitch), (base), lane)
|
||||
|
||||
// SDT is the state cache's element type (0 = fp32, 1 = fp16) and nothing else; all arithmetic is
|
||||
// fp32. The cache is shared with the recurrent update (whose time is the state traffic, so it
|
||||
// favours fp16) and allocated from vLLM's --mamba-ssm-cache-dtype, so both kernels must agree.
|
||||
template <int SDT> struct cs_state { using T = float; };
|
||||
template <> struct cs_state<1> { using T = _Float16; };
|
||||
|
||||
// H0 / HT: whether the optional initial and final state operands are present (template parameters,
|
||||
// so the common both-present form has no runtime test). As in libref, no initial state starts from
|
||||
// zero and no final state stores nothing.
|
||||
template <int SDT, bool H0 = true, bool HT = true>
|
||||
__global__ __launch_bounds__(NTHR) void halo_gdn_chunk_scan_kernel(
|
||||
const unsigned short* __restrict__ q, const unsigned short* __restrict__ k,
|
||||
const unsigned short* __restrict__ v, const unsigned short* __restrict__ Amat,
|
||||
const float* __restrict__ gcs, const float* __restrict__ beta,
|
||||
const typename cs_state<SDT>::T* __restrict__ h0, unsigned short* __restrict__ o,
|
||||
typename cs_state<SDT>::T* __restrict__ ht, const int* __restrict__ cu,
|
||||
const int* __restrict__ sidx, long sidx_stride, long st_slot, long st_head,
|
||||
int H, int Hg, float scale)
|
||||
{
|
||||
__shared__ Smem s;
|
||||
const int bv = blockIdx.x, hv = blockIdx.y, nq = blockIdx.z;
|
||||
const int tid = threadIdx.x, w = tid >> 5, lane = tid & 31;
|
||||
const int hq = hv / (H / Hg), v0 = bv * BV;
|
||||
const int tb = cu[nq], te = cu[nq + 1];
|
||||
// The state slot comes from the cache manager (sidx), not the batch position; without sidx the
|
||||
// kernel uses state[nq], valid only while slots match batch order. A row may name several slots
|
||||
// (speculative decode adds scratch slots); column 0 is the state and the only one used here.
|
||||
const long si = sidx ? (long)sidx[(size_t)nq * sidx_stride] : (long)nq;
|
||||
if (si < 0) return; // a padded row owns no state
|
||||
const size_t st_base = (size_t)si * st_slot + (size_t)hv * st_head;
|
||||
const int nchunk = (te - tb + BT - 1) / BT;
|
||||
const int lo = lane & 15, hi = lane >> 4;
|
||||
|
||||
// [BT][BV]: 2 tiles/wave. The token tile mt sets the wave's share of the triangular work (P^T,
|
||||
// V', O += sA@V' all stop at the diagonal), so waves w and w+4 -- likely one SIMD -- pair
|
||||
// mt with 3 - mt, and the n-tile pair is chosen to even out the P^T tiles (3, 2, 3, 2).
|
||||
const int mt = (w >> 1) ^ (w >> 2), ntb = ((w ^ (w >> 2)) & 1) * 2;
|
||||
// The state accumulator is held transposed, C[m=k-dim][n=v]. A and B fragments share a lane
|
||||
// layout, so swapping the state update's operands is free, and k-dim becomes the per-lane
|
||||
// contiguous axis: the per-chunk writeback to s.S is four 8-short stores instead of 32 scalar.
|
||||
const int kt0 = (w >> 1) * 2, vt0 = (w & 1) * 2; // 2 x 2
|
||||
|
||||
#define PFW 8 // shorts staged per lane per step
|
||||
#define NKB (BT * KD / (NTHR * PFW))
|
||||
#define NVB (BT * BV / (NTHR * PFW))
|
||||
uint4 kb[NKB], vb[NVB];
|
||||
// Staging index, split into a wave-uniform row and a loop-invariant lane column. As
|
||||
// `i = tid*4 + u*NTHR*4; r = i>>7` the row looks divergent to LLVM and each load costs ~13
|
||||
// instructions of 64-bit address math; readfirstlane makes the row provably uniform (SALU).
|
||||
// Identities (exact, since u*NTHR*8 is a multiple of both 128 and 64):
|
||||
// k: r = 2*(tid>>5) + kh + KRU*u c = (tid*8) & 127 kh = (tid>>4) & 1
|
||||
// v: r = 4*(tid>>5) + vh + VRU*u c = (tid*8) & 63 vh = (tid>>3) & 3
|
||||
const int wu = __builtin_amdgcn_readfirstlane(tid >> 5);
|
||||
const int kc = (tid * PFW) & (KD - 1), vc = (tid * PFW) & (BV - 1);
|
||||
const int kr0 = 2 * wu + ((tid >> 4) & 1), vr0 = 4 * wu + ((tid >> 3) & 3);
|
||||
#define KRU (2 * NW)
|
||||
#define VRU (4 * NW)
|
||||
// Do not change: staged rows past the chunk end are zeroed, not clamped to the last live row
|
||||
// (~4% faster). A clamp looks harmless (beta and gv are 0 there, the tril mask drops padding j,
|
||||
// the O store is guarded), yet with it any prompt whose trailing chunk is not a multiple of 16
|
||||
// tokens returns one repeated token. Zeroing k alone fixes it, so the leak is through some
|
||||
// consumer of s.k whose path is not yet understood.
|
||||
// The load itself is clamped (pnv >= 1 wherever this runs) and the zero selected when the
|
||||
// staging store consumes it (PFSEL, against that chunk's nval): straight-line code, and a select
|
||||
// at issue would make the prefetch wait for its own loads.
|
||||
#define PFSTORE(dst, val) \
|
||||
do { \
|
||||
unsigned short* dp_ = (dst); \
|
||||
*(uint2*)dp_ = make_uint2((val).x, (val).y); \
|
||||
*(uint2*)(dp_ + 4) = make_uint2((val).z, (val).w); \
|
||||
} while (0)
|
||||
#define PFSEL(r, val) \
|
||||
make_uint4((r) < nval ? (val).x : 0u, (r) < nval ? (val).y : 0u, \
|
||||
(r) < nval ? (val).z : 0u, (r) < nval ? (val).w : 0u)
|
||||
#define PREFETCH(CH) \
|
||||
{ \
|
||||
const int pc0 = tb + (CH) * BT, pnv = min(BT, te - pc0); \
|
||||
const unsigned short* kb_ = k + ((size_t)pc0 * Hg + hq) * KD; \
|
||||
const unsigned short* vb_ = v + ((size_t)pc0 * H + hv) * VD + v0; \
|
||||
_Pragma("unroll") for (int u = 0; u < NKB; ++u) { \
|
||||
const int r = kr0 + KRU * u, rc = min(r, pnv - 1); \
|
||||
kb[u] = *(const uint4*)(kb_ + (unsigned)(rc * (Hg * KD)) + kc); \
|
||||
} \
|
||||
_Pragma("unroll") for (int u = 0; u < NVB; ++u) { \
|
||||
const int r = vr0 + VRU * u, rc = min(r, pnv - 1); \
|
||||
vb[u] = *(const uint4*)(vb_ + (unsigned)(rc * (H * VD)) + vc); \
|
||||
} \
|
||||
}
|
||||
|
||||
v8f St[NST]; // state: SKT k-tiles x SVT v-tiles
|
||||
#define KT(t) (kt0 + (t) / SVT)
|
||||
#define VT(t) (vt0 + (t) % SVT)
|
||||
// State element e is v = VT*16 + lo, k = KT*16 + 2e + hi on gfx1151 (NOT 8*hi + e): a lane's eight
|
||||
// values are two apart in the [v][k] state. Read straight from HBM that is 32 scalar loads a lane,
|
||||
// each wave load touching sixteen rows for 8 bytes apiece; at one or two chunks the state traffic
|
||||
// is half the kernel. So h0 and ht pass through LDS (free before the chunk loop and after barrier
|
||||
// (4)) as an f32 [v][k] tile: coalesced 16-byte global accesses on one side, the accumulator
|
||||
// layout on the other (pitch FP: lanes lo / hi land on banks 4*lo + hi, no conflict).
|
||||
#define FP (KD + 4)
|
||||
static_assert(sizeof(Smem) >= sizeof(float) * BV * FP, "the f32 state tile overlays Smem");
|
||||
float (*const F)[FP] = reinterpret_cast<float (*)[FP]>(&s);
|
||||
#define SF(t, e) F[VT(t) * 16 + lo][KT(t) * 16 + 2 * (e) + hi]
|
||||
if constexpr (!H0) {
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NST; ++t)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) St[t][e] = 0.0f;
|
||||
} else {
|
||||
const typename cs_state<SDT>::T* p = h0 + st_base + (size_t)v0 * KD;
|
||||
if constexpr (SDT == 0) { // a row is 32 float4: wave wu takes rows wu + NW*u
|
||||
float4 r[BV / NW];
|
||||
#pragma unroll
|
||||
for (int u = 0; u < BV / NW; ++u) r[u] = *(const float4*)(p + (wu + NW * u) * KD + lane * 4);
|
||||
#pragma unroll
|
||||
for (int u = 0; u < BV / NW; ++u) *(float4*)&F[wu + NW * u][lane * 4] = r[u];
|
||||
} else { // a row is 16 x 8 halves: rows tid/16 + (NTHR/16)*u
|
||||
const int r0 = tid >> 4, c = (tid & 15) * 8;
|
||||
uint4 r[BV * 16 / NTHR];
|
||||
#pragma unroll
|
||||
for (int u = 0; u < BV * 16 / NTHR; ++u)
|
||||
r[u] = *(const uint4*)(p + (r0 + (NTHR / 16) * u) * KD + c);
|
||||
#pragma unroll
|
||||
for (int u = 0; u < BV * 16 / NTHR; ++u) {
|
||||
union { uint4 w; _Float16 h[8]; } x;
|
||||
x.w = r[u];
|
||||
float* d = &F[r0 + (NTHR / 16) * u][c];
|
||||
*(float4*)d = make_float4(x.h[0], x.h[1], x.h[2], x.h[3]);
|
||||
*(float4*)(d + 4) = make_float4(x.h[4], x.h[5], x.h[6], x.h[7]);
|
||||
}
|
||||
}
|
||||
lds_barrier();
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NST; ++t)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) St[t][e] = SF(t, e);
|
||||
lds_barrier(); // the chunk loop's staging overwrites the tile
|
||||
}
|
||||
if (nchunk > 0) PREFETCH(0);
|
||||
|
||||
const char* const sbase = (const char*)&s;
|
||||
// scale goes inside the score exponent, exp(g_i + log(scale) - g_j), saving eight multiplies
|
||||
// per tile.
|
||||
const float lgs = __logf(scale);
|
||||
for (int ci = 0; ci < nchunk; ++ci) {
|
||||
const int c0 = tb + ci * BT, nval = min(BT, te - c0);
|
||||
const int lim = nval - 1;
|
||||
const unsigned short* qg = q + ((size_t)c0 * Hg + hq) * KD;
|
||||
const unsigned short* ag = Amat + ((size_t)c0 * H + hv) * BT;
|
||||
const size_t qrs = (size_t)Hg * KD, ars = (size_t)H * BT;
|
||||
const float gl = gcs[(size_t)(c0 + lim) * H + hv];
|
||||
|
||||
// Issued before the staging stores so the LDS writes cover their latency. Only waves 0-1
|
||||
// (tid < BT) run this; the others wait at (1).
|
||||
float ggr = 0.f, btr = 0.f;
|
||||
if (tid < BT) {
|
||||
bool ok = tid < nval;
|
||||
ggr = ok ? gcs[(size_t)(c0 + tid) * H + hv] : 0.f;
|
||||
btr = ok ? beta[(size_t)(c0 + tid) * H + hv] : 0.f;
|
||||
}
|
||||
// The main loop's first QP q fragments, issued ahead of the staging and barrier (1) so the
|
||||
// first WMMAs do not wait out a full HBM round trip.
|
||||
#define QP 4
|
||||
const unsigned qo = rowGo((unsigned)qrs, mt * 16, lim, lane);
|
||||
v16bf aq0[QP];
|
||||
#pragma unroll
|
||||
for (int sk = 0; sk < QP; ++sk) aq0[sk] = fragGo(qg, qo + sk * 16);
|
||||
// The bf16 state for this chunk's U and O. s.S aliases s.KT, whose last reads (the previous
|
||||
// chunk's state update) retired at barrier (4).
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NST; ++t)
|
||||
accSt(&s.S[VT(t) * 16 + lo][KT(t) * 16 + 8 * hi], St[t], lane);
|
||||
{ // consume the previous iteration's prefetch, issued a whole chunk of compute ago
|
||||
#pragma unroll
|
||||
for (int u = 0; u < NKB; ++u) PFSTORE(&s.k[kr0 + KRU * u][kc], PFSEL(kr0 + KRU * u, kb[u]));
|
||||
#pragma unroll
|
||||
for (int u = 0; u < NVB; ++u) PFSTORE(&s.D[vr0 + VRU * u][vc], PFSEL(vr0 + VRU * u, vb[u]));
|
||||
}
|
||||
if (tid < BT) {
|
||||
bool ok = tid < nval;
|
||||
s.bt[tid] = btr;
|
||||
s.ge[tid] = __expf(ggr);
|
||||
// g is a within-chunk cumsum of log-sigmoid gates, so it is non-increasing and gl is its
|
||||
// minimum: gl - ggr <= 0, and gs underflowing to 0 is correct.
|
||||
// A padding row gets gl, not 0: it is scored against live j with very negative g_j, and
|
||||
// g_i = 0 would give exp(+400) = inf in s.A. With gl (the chunk minimum) the exponent
|
||||
// stays in (0, scale]. The row is discarded anyway (O store is guarded).
|
||||
s.gg[tid] = ok ? ggr : gl;
|
||||
s.gv[tid] = ok ? __expf(gl - ggr) : 0.f; // gs
|
||||
}
|
||||
lds_barrier(); // (1)
|
||||
if (ci + 1 < nchunk) PREFETCH(ci + 1); // issue only; consumed next iteration
|
||||
|
||||
// ---- U = K@S, O^T = S@Q^T and P^T = K@Q^T share the q and k fragments.
|
||||
// P^T tiles above the diagonal are skipped (sA masks them). On gfx12 that was 2.4% slower --
|
||||
// some wave still carries two tiles, so the barrier arrival does not move -- but here the
|
||||
// kernel is throughput bound with two workgroups per WGP, so the WMMAs saved are time saved.
|
||||
v8f O[NTV], u[NTV], p[NTV];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NTV; ++i) { O[i] = (v8f){}; u[i] = (v8f){}; p[i] = (v8f){}; }
|
||||
{
|
||||
const char* sb = sbase;
|
||||
// The two n tiles are 16 rows apart, so one base per buffer serves both (an immediate).
|
||||
unsigned okm = ROWO(s.k, KP, mt * 16), oSn = ROWO(s.S, KP, ntb * 16),
|
||||
okn = ROWO(s.k, KP, ntb * 16);
|
||||
LDSOPAQUE(okm); LDSOPAQUE(oSn); LDSOPAQUE(okn);
|
||||
#define pSnf(i, ko) fragO(sb, oSn + ((i) * 16 * KP + (ko)) * 2u)
|
||||
#define pkmf(ko) fragO(sb, okm + (ko) * 2u)
|
||||
#define pknf(i, ko) fragO(sb, okn + ((i) * 16 * KP + (ko)) * 2u)
|
||||
#define pqf(ko) ((ko) / 16 < QP ? aq0[min((ko) / 16, QP - 1)] : fragGo(qg, qo + (ko)))
|
||||
// P^T tile ntb+i is wholly above the diagonal (masked in sA) when ntb + i > mt: only the
|
||||
// first np tiles are computed. np is wave-uniform, so each count gets its own loop.
|
||||
auto mainloop = [&](auto npc) {
|
||||
constexpr int NP = decltype(npc)::value;
|
||||
#pragma unroll
|
||||
for (int sk = 0; sk < KD / 16; ++sk) {
|
||||
const int ko = sk * 16;
|
||||
v16bf ak = pkmf(ko), aq = pqf(ko);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NTV; ++i) {
|
||||
v16bf b = pSnf(i, ko);
|
||||
u[i] = mma(ak, b, u[i]); // U: m = token, n = v-tile
|
||||
O[i] = mma(b, aq, O[i]); // O^T: m = v-tile, n = token-tile
|
||||
if (i < NP) p[i] = mma(pknf(i, ko), aq, p[i]); // P^T: m = j
|
||||
}
|
||||
}
|
||||
};
|
||||
const int np = __builtin_amdgcn_readfirstlane(min(max(mt - ntb + 1, 0), NTV));
|
||||
if (np == NTV) mainloop(std::integral_constant<int, NTV>{});
|
||||
else if (np) mainloop(std::integral_constant<int, 1>{});
|
||||
else mainloop(std::integral_constant<int, 0>{});
|
||||
}
|
||||
{
|
||||
// O's hardware row is the v dim and its column the token, which is the one place gfx1151 and
|
||||
// gfx12 agree: accPackX()'s eight consecutive rows are eight consecutive v of one token, so
|
||||
// this is libr4d's scale and store unchanged (a lane's token is mt*16 + lo).
|
||||
float g = scale * s.ge[mt * 16 + lo]; // token index is constant per lane
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NTV; ++i)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) O[i][e] *= g;
|
||||
}
|
||||
// The V' loop's A fragments come from HBM/L2: issued here, their latency is covered by the
|
||||
// W / sA epilogue and barrier (2) instead of stalling the first V' WMMA.
|
||||
v16bf af[BT / 16];
|
||||
{
|
||||
const unsigned ao = rowGo((unsigned)ars, mt * 16, lim, lane);
|
||||
#pragma unroll
|
||||
for (int sk = 0; sk < BT / 16; ++sk) af[sk] = fragGo(ag, ao + sk * 16);
|
||||
}
|
||||
// W = beta * (V - ge*U) (beta folded here: (A*beta_col)@W == A@(beta_row*W))
|
||||
{
|
||||
// Element e is token mt*16 + 2e + hi: one row pointer per lane, e and i are immediates.
|
||||
const unsigned short* dv = &s.D[mt * 16 + hi][ntb * 16 + lo];
|
||||
const float* bp = &s.bt[mt * 16 + hi];
|
||||
const float* gp = &s.ge[mt * 16 + hi];
|
||||
float wa[NTV][8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) { // beta / ge read once for both tiles
|
||||
const float f = bp[2 * e], g = gp[2 * e];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NTV; ++i)
|
||||
wa[i][e] = f * (bf2f(dv[2 * e * AP + i * 16]) - g * u[i][e]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NTV; ++i)
|
||||
accSt(&s.W[(ntb + i) * 16 + lo][mt * 16 + 8 * hi], wa[i], lane);
|
||||
}
|
||||
// sA = scale * e^{g_i-g_j} * tril(P). Row ii is constant per lane and the eight g_j are
|
||||
// uniform per 16 lanes: eight broadcast LDS reads, v_sub and v_exp per tile (log(scale) is
|
||||
// in the exponent). Where kept, g_i - g_j <= 0, so the exp cannot overflow.
|
||||
// gfx1151: element e is the key (ntb+i)*16 + 2e + hi, so j and its mask are per element; the
|
||||
// 16 consecutive keys of the row are reassembled by accPackX().
|
||||
{
|
||||
const int ii = mt * 16 + lo;
|
||||
const float gis = s.gg[ii] + lgs;
|
||||
const float* gj = &s.gg[ntb * 16 + hi];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NTV; ++i) {
|
||||
// The exp is taken for every element and the mask applied as a select after it: written
|
||||
// as one conditional expression it lowers to a divergent branch around each LDS read
|
||||
// and exp. Above the diagonal the exponent may overflow; the select discards it.
|
||||
float a[8], x[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
x[e] = p[i][e] * __expf(gis - gj[i * 16 + 2 * e]);
|
||||
asm volatile("" : "+v"(x[e])); // keeps MachineSink from re-forming the branch
|
||||
}
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int j = (ntb + i) * 16 + 2 * e + hi;
|
||||
a[e] = (j <= ii) ? x[e] : 0.f;
|
||||
}
|
||||
accSt(&s.A[ii][(ntb + i) * 16 + 8 * hi], a, lane);
|
||||
}
|
||||
}
|
||||
lds_barrier(); // (2)
|
||||
|
||||
// ---- V' = gv * (A @ W) -> D (transposed store is one contiguous pair of dwords)
|
||||
{
|
||||
v8f d[NTV];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NTV; ++i) d[i] = (v8f){};
|
||||
const unsigned short* pwn = rowP(&s.W[0][0], WP, ntb * 16, lane);
|
||||
#define pwnf(i, ko) fragP(pwn + (i) * 16 * WP + (ko))
|
||||
#pragma unroll
|
||||
for (int sk = 0; sk < BT / 16; ++sk) {
|
||||
if (sk <= mt) { // A is lower triangular: A[mt][sk > mt] = 0
|
||||
const int ko = sk * 16;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NTV; ++i) d[i] = mma(af[sk], pwnf(i, ko), d[i]);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NTV; ++i)
|
||||
accSt(&s.D[(ntb + i) * 16 + lo][mt * 16 + 8 * hi], d[i], lane);
|
||||
}
|
||||
// KT = (gs * K)^T, for the state's V'^T @ K: (diag(gs) V')^T K == V'^T (diag(gs) K). All raw-K
|
||||
// reads (U, P) and s.S reads retired before barrier (2); barrier (3) publishes KT. A lane
|
||||
// takes a token pair and eight k: two 16-byte row reads, eight dword stores of a [k] row
|
||||
// (32 lanes, 32 consecutive dwords: no bank conflict). Same rounding as the old in-place
|
||||
// scale: one f2bf of bf16(k) * gs per element.
|
||||
{
|
||||
const int t0 = 2 * lane;
|
||||
const float f0 = s.gv[t0], f1 = s.gv[t0 + 1];
|
||||
#pragma unroll
|
||||
for (int it = 0; it < KD / (8 * NW); ++it) {
|
||||
const int c = (it * NW + wu) * 8;
|
||||
const uint4 a = *(const uint4*)&s.k[t0][c], b = *(const uint4*)&s.k[t0 + 1][c];
|
||||
const unsigned av[4] = { a.x, a.y, a.z, a.w }, bw[4] = { b.x, b.y, b.z, b.w };
|
||||
unsigned* kt = (unsigned*)&s.KT[c][t0];
|
||||
#pragma unroll
|
||||
for (int h = 0; h < 4; ++h) {
|
||||
const float a0 = __builtin_bit_cast(float, av[h] << 16);
|
||||
const float a1 = __builtin_bit_cast(float, av[h] & 0xffff0000u);
|
||||
const float b0 = __builtin_bit_cast(float, bw[h] << 16);
|
||||
const float b1 = __builtin_bit_cast(float, bw[h] & 0xffff0000u);
|
||||
kt[(2 * h) * (AP / 2)] = f2bf2(a0 * f0, b0 * f1);
|
||||
kt[(2 * h + 1) * (AP / 2)] = f2bf2(a1 * f0, b1 * f1);
|
||||
}
|
||||
}
|
||||
}
|
||||
lds_barrier(); // (3)
|
||||
|
||||
// ---- O += sA @ V' ; store. V' also feeds the state update, unchanged.
|
||||
{
|
||||
const unsigned short* pA = rowP(&s.A[0][0], AP, mt * 16, lane);
|
||||
const unsigned short* pdn = rowP(&s.D[0][0], AP, ntb * 16, lane);
|
||||
#define pAf(ko) fragP(pA + (ko))
|
||||
#define pdnf(i, ko) fragP(pdn + (i) * 16 * AP + (ko))
|
||||
#pragma unroll
|
||||
for (int sk = 0; sk < BT / 16; ++sk) {
|
||||
if (sk <= mt) { // sA is masked to j <= i
|
||||
const int ko = sk * 16;
|
||||
v16bf b = pAf(ko);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NTV; ++i) O[i] = mma(pdnf(i, ko), b, O[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
// The half-wave exchange accPackX() does is a wave-wide lane operation (v_permlanex16), so it is
|
||||
// taken for the whole wave and only the stores are guarded. A trailing partial chunk leaves
|
||||
// lanes without a token, and a lane op under a divergent exec mask reads an inactive partner:
|
||||
// measured as infinities in exactly those lanes' rows (see the pitch note above).
|
||||
const int tok = mt * 16 + lo;
|
||||
uint4 w[NTV];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NTV; ++i) w[i] = accPk(O[i], lane);
|
||||
if (tok < nval) {
|
||||
// O's eight packed values are eight consecutive v of row tok (see the scale above).
|
||||
unsigned short* op = o + ((size_t)(c0 + tok) * H + hv) * VD + v0;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NTV; ++i)
|
||||
*(uint4*)(op + (ntb + i) * 16 + 8 * hi) = w[i];
|
||||
}
|
||||
}
|
||||
|
||||
// ---- S = e^{gl} * S + V'^T @ (gs*K) (A = KT rows, B = V' rows: both k-contiguous)
|
||||
{
|
||||
const float ec = __expf(gl); // gl <= 0: no lam, the decay is already on K
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NST; ++t)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) St[t][e] *= ec;
|
||||
const unsigned short* pvn = rowP(&s.D[0][0], AP, vt0 * 16, lane);
|
||||
const unsigned short* pkt = rowP(&s.KT[0][0], AP, kt0 * 16, lane);
|
||||
#pragma unroll
|
||||
for (int sk = 0; sk < BT / 16; ++sk) {
|
||||
v16bf bv[SVT];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < SVT; ++j) bv[j] = fragP(pvn + j * 16 * AP + sk * 16);
|
||||
#pragma unroll
|
||||
for (int ki = 0; ki < SKT; ++ki) {
|
||||
v16bf ak = fragP(pkt + ki * 16 * AP + sk * 16); // K^T: m = k-dim
|
||||
#pragma unroll
|
||||
for (int j = 0; j < SVT; ++j)
|
||||
St[ki * SVT + j] = mma(ak, bv[j], St[ki * SVT + j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
lds_barrier(); // (4)
|
||||
}
|
||||
|
||||
if constexpr (!HT) return;
|
||||
// Barrier (4) (or, with no chunk, the h0 load's last barrier) has retired every LDS read.
|
||||
#pragma unroll
|
||||
for (int t = 0; t < NST; ++t)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) SF(t, e) = St[t][e];
|
||||
lds_barrier();
|
||||
typename cs_state<SDT>::T* p = ht + st_base + (size_t)v0 * KD;
|
||||
if constexpr (SDT == 0) {
|
||||
#pragma unroll
|
||||
for (int u = 0; u < BV / NW; ++u)
|
||||
*(float4*)(p + (wu + NW * u) * KD + lane * 4) = *(const float4*)&F[wu + NW * u][lane * 4];
|
||||
} else {
|
||||
const int r0 = tid >> 4, c = (tid & 15) * 8;
|
||||
#pragma unroll
|
||||
for (int u = 0; u < BV * 16 / NTHR; ++u) {
|
||||
const float* d = &F[r0 + (NTHR / 16) * u][c];
|
||||
const float4 a = *(const float4*)d, b = *(const float4*)(d + 4);
|
||||
union { uint4 w; _Float16 h[8]; } x;
|
||||
x.h[0] = (_Float16)a.x; x.h[1] = (_Float16)a.y; x.h[2] = (_Float16)a.z; x.h[3] = (_Float16)a.w;
|
||||
x.h[4] = (_Float16)b.x; x.h[5] = (_Float16)b.y; x.h[6] = (_Float16)b.z; x.h[7] = (_Float16)b.w;
|
||||
*(uint4*)(p + (r0 + (NTHR / 16) * u) * KD + c) = x.w;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Slot-indexed form (the one radiance calls). `sidx` names each batch row's state slot; without
|
||||
// it the cache is indexed by row. `st_slot` and `st_head` are the cache strides in elements, which
|
||||
// may exceed H*V*K when a caller pads its slots (vLLM pads to the attention page size). Pass
|
||||
// sidx = null and strides 0 for the packed [N, H, V, K] layout.
|
||||
extern "C" int halo_gdn_chunk_scan_k128_v128_c64_bf16_sidx(
|
||||
const void* q, const void* k, const void* v, const void* A, const void* g,
|
||||
const void* beta, const void* h0, void* o, void* ht, const void* cu,
|
||||
const void* ssm_state_indices, long indices_stride, long state_slot_stride,
|
||||
long state_head_stride,
|
||||
int N, int H, int Hg, int K, int V, int bt, float scale, int state_fp16, void* stream)
|
||||
{
|
||||
if (K != KD || V != VD || bt != BT) return -1;
|
||||
// hq = hv / (H / Hg) truncates: H not a multiple of Hg would silently map v heads to the wrong
|
||||
// k heads. Refused with -2, as in the kkt_solve and recurrent_update siblings.
|
||||
if (Hg <= 0 || H % Hg) return -2;
|
||||
const long st_head = state_head_stride > 0 ? state_head_stride : (long)VD * KD;
|
||||
const long st_slot = state_slot_stride > 0 ? state_slot_stride : (long)H * VD * KD;
|
||||
dim3 grid(V / BV, H, N), blk(NTHR);
|
||||
#define CS_LAUNCH(SDTC, H0C, HTC) \
|
||||
hipLaunchKernelGGL((halo_gdn_chunk_scan_kernel<SDTC, H0C, HTC>), grid, blk, 0, \
|
||||
(hipStream_t)stream, \
|
||||
(const unsigned short*)q, (const unsigned short*)k, (const unsigned short*)v, \
|
||||
(const unsigned short*)A, (const float*)g, (const float*)beta, \
|
||||
(const cs_state<SDTC>::T*)h0, (unsigned short*)o, (cs_state<SDTC>::T*)ht, \
|
||||
(const int*)cu, (const int*)ssm_state_indices, (indices_stride > 0 ? indices_stride : 1), \
|
||||
st_slot, st_head, H, Hg, scale)
|
||||
#define CS_PICK(SDTC) \
|
||||
do { if (h0 && ht) CS_LAUNCH(SDTC, true, true); \
|
||||
else if (h0) CS_LAUNCH(SDTC, true, false); \
|
||||
else if (ht) CS_LAUNCH(SDTC, false, true); \
|
||||
else CS_LAUNCH(SDTC, false, false); } while (0)
|
||||
if (state_fp16) CS_PICK(1); else CS_PICK(0);
|
||||
#undef CS_PICK
|
||||
#undef CS_LAUNCH
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
|
||||
// Packed-layout entry point for the out-of-tree vLLM caller: one state per batch row,
|
||||
// [N, H, V, K].
|
||||
extern "C" int halo_gdn_chunk_scan_k128_v128_c64_bf16(
|
||||
const void* q, const void* k, const void* v, const void* A, const void* g,
|
||||
const void* beta, const void* h0, void* o, void* ht, const void* cu,
|
||||
int N, int H, int Hg, int K, int V, int bt, float scale, int state_fp16, void* stream)
|
||||
{
|
||||
return halo_gdn_chunk_scan_k128_v128_c64_bf16_sidx(q, k, v, A, g, beta, h0, o, ht, cu,
|
||||
nullptr, 0, 0, 0, N, H, Hg, K, V, bt, scale,
|
||||
state_fp16, stream);
|
||||
}
|
||||
|
||||
// The compiled geometry, so callers can check a model's GDN shape against it.
|
||||
extern "C" void halo_gdn_dims(int* head_k, int* head_v, int* chunk) {
|
||||
if (head_k) *head_k = KD;
|
||||
if (head_v) *head_v = VD;
|
||||
if (chunk) *chunk = BT;
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
// Shared operand helpers: halo_gdn_args.h.
|
||||
/* ------------------------------------------------------------------ chunk scan */
|
||||
|
||||
enum { CS_Q = 0, CS_K, CS_V, CS_A, CS_G, CS_BETA, CS_H0, CS_CU, CS_O, CS_HT, CS_SIDX };
|
||||
|
||||
extern "C" int halo_rad_gdn_chunk_scan(const RadArgs* a, RadStream s) {
|
||||
if (gdn_dims_ok() != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
const RadTensor* q = halo_opt(a, CS_Q);
|
||||
const RadTensor* k = halo_opt(a, CS_K);
|
||||
const RadTensor* v = halo_opt(a, CS_V);
|
||||
const RadTensor* A = halo_opt(a, CS_A);
|
||||
const RadTensor* g = halo_opt(a, CS_G);
|
||||
const RadTensor* bt = halo_opt(a, CS_BETA);
|
||||
const RadTensor* h0 = halo_opt(a, CS_H0);
|
||||
const RadTensor* cu = halo_opt(a, CS_CU);
|
||||
const RadTensor* o = halo_opt(a, CS_O);
|
||||
const RadTensor* ht = halo_opt(a, CS_HT);
|
||||
const RadTensor* sidx = halo_opt(a, CS_SIDX);
|
||||
if (!q || !k || !v || !A || !g || !bt || !cu || !o) return HALO_NO(RAD_E_INVAL);
|
||||
if (q->rank != 3 || k->rank != 3 || v->rank != 3 || o->rank != 3) return HALO_NO(RAD_E_SHAPE);
|
||||
if (A->rank != 3 || g->rank != 2 || bt->rank != 2) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
int N = 0;
|
||||
int rc = seqs_of(cu, &N);
|
||||
if (rc != RAD_OK) return rc;
|
||||
|
||||
/* The entry point takes no pitches: everything must be dense. */
|
||||
if (!halo_contig(q) || !halo_contig(k) || !halo_contig(v) || !halo_contig(A) ||
|
||||
!halo_contig(g) || !halo_contig(bt) || !halo_contig(o)) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
/* bf16 q/k/v/A/out, fp32 gate/beta. */
|
||||
HALO_DT(q, RAD_BF16); HALO_DT(k, RAD_BF16); HALO_DT(v, RAD_BF16); HALO_DT(A, RAD_BF16);
|
||||
HALO_DT(o, RAD_BF16); HALO_DT(g, RAD_F32); HALO_DT(bt, RAD_F32);
|
||||
/* The state cache is f32 or f16, taken from the operand's dtype (a property of the
|
||||
* allocation), so this kernel and the recurrent update, which share the cache, agree on it. */
|
||||
const uint32_t st_dt = h0 ? h0->dtype : (ht ? ht->dtype : (uint32_t)RAD_F32);
|
||||
if (st_dt != RAD_F32 && st_dt != RAD_F16) return HALO_NO(RAD_E_DTYPE);
|
||||
if (h0) HALO_DT(h0, st_dt);
|
||||
if (ht) HALO_DT(ht, st_dt);
|
||||
/* Slot strides come from the tensor, not from H, V and K, so a cache with padded slots is
|
||||
* served too; the engine's own state cache is dense ([n_states, H, V, K] per layer). h0 and
|
||||
* ht must share strides, since the kernel uses one base offset for both. */
|
||||
long long st_slot = 0, st_head = 0;
|
||||
if (h0) {
|
||||
if (h0->rank < 2) return HALO_NO(RAD_E_SHAPE);
|
||||
st_slot = h0->stride[0];
|
||||
st_head = h0->stride[1];
|
||||
}
|
||||
if (ht) {
|
||||
if (ht->rank < 2) return HALO_NO(RAD_E_SHAPE);
|
||||
if (h0 && (ht->stride[0] != st_slot || ht->stride[1] != st_head))
|
||||
return HALO_NO(RAD_E_STRIDE);
|
||||
st_slot = ht->stride[0];
|
||||
st_head = ht->stride[1];
|
||||
}
|
||||
if (sidx) {
|
||||
HALO_DT(sidx, RAD_I32);
|
||||
if (sidx->rank < 1 || sidx->shape[0] != N) return HALO_NO(RAD_E_SHAPE);
|
||||
if (sidx->stride[sidx->rank - 1] != 1) return HALO_NO(RAD_E_STRIDE);
|
||||
}
|
||||
|
||||
const long long T = q->shape[0];
|
||||
const long long Hg = q->shape[1];
|
||||
const long long K = q->shape[2];
|
||||
const long long H = v->shape[1];
|
||||
const long long V = v->shape[2];
|
||||
const long long bt_chunk = A->shape[2];
|
||||
if (k->shape[0] != T || k->shape[1] != Hg || k->shape[2] != K) return HALO_NO(RAD_E_SHAPE);
|
||||
if (v->shape[0] != T || o->shape[0] != T || o->shape[1] != H || o->shape[2] != V)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
if (A->shape[0] != T || A->shape[1] != H) return HALO_NO(RAD_E_SHAPE);
|
||||
if (g->shape[0] != T || g->shape[1] != H) return HALO_NO(RAD_E_SHAPE);
|
||||
if (bt->shape[0] != T || bt->shape[1] != H) return HALO_NO(RAD_E_SHAPE);
|
||||
if (H == 0 || Hg == 0 || H % Hg) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
const float scale = (float)halo_getf(a, "scale", 1.0);
|
||||
const int state_fp16 = st_dt == RAD_F16;
|
||||
|
||||
return HALO_RAW(halo_gdn_chunk_scan_k128_v128_c64_bf16_sidx(
|
||||
q->data, k->data, v->data, A->data, g->data, bt->data,
|
||||
h0 ? h0->data : nullptr, o->data, ht ? ht->data : nullptr, cu->data,
|
||||
sidx ? sidx->data : nullptr, sidx && sidx->rank >= 2 ? (long)sidx->stride[0] : 1,
|
||||
(long)st_slot, (long)st_head,
|
||||
N, (int)H, (int)Hg, (int)K, (int)V, (int)bt_chunk, scale, state_fp16, s));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/* Derived from libr4d/r4d_gdn_conv_tap.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
// halo_gdn_conv_tap.h -- the arithmetic of one gated-delta-net convolution output, shared by the
|
||||
// standalone conv kernels (halo_gdn_conv_w4_h128_bf16.hip) and the recurrent update that folds the
|
||||
// decode convolution into its prologue (halo_gdn_recurrent_update_k128_v128_bf16_fp32state.hip).
|
||||
// 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 HALO_GDN_CONV_W 4 // conv width; the state holds HALO_GDN_CONV_W - 1 taps of history
|
||||
|
||||
// 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) {
|
||||
return z * __builtin_amdgcn_rcpf(1.0f + __expf(-z));
|
||||
}
|
||||
@@ -0,0 +1,623 @@
|
||||
/* Derived from libr4d/r4d_gdn_conv_w4_h128_bf16.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gdn_conv_w4_h128_bf16.hip -- the gated-delta-net depthwise causal convolution and the work fused around
|
||||
// it, one entry point per serving phase.
|
||||
//
|
||||
// PREFILL (halo_gdn_conv_prep): everything the layer does between the qkv projection and the
|
||||
// chunked scan, in one kernel:
|
||||
//
|
||||
// conv(x) depthwise causal convolution, width 4, silu, varlen, with the conv-state
|
||||
// cache read at a sequence's first chunk and rewritten from its last tokens
|
||||
// split the packed [q | k | v] channel range into three contiguous tensors
|
||||
// l2norm over each 128-dim q and k head
|
||||
// gate g = -exp(A_log) . softplus(a + dt_bias), beta = sigmoid(b)
|
||||
// cumsum g summed along the chunk, which is what the scan actually consumes
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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 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, as in the unfused pair, so
|
||||
// this kernel is a bit-exact drop-in for it.
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "halo.h"
|
||||
#include "halo_gdn_args.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_conv_tap.h"
|
||||
|
||||
// libr4d's rounding helpers (r4d_gdn_wmma.h) -- f2bf / f2bf2 / bf2f -- come from halo_gdn_wmma.h
|
||||
// (included above): round-half-AWAY (one add, no bfe), the rounding libr4d uses. This kernel's
|
||||
// bf16 rounding is observable, since the conv output is rounded before the l2 norm as the unfused
|
||||
// pair does, so that same rounding is kept. gfx1151 has no v_cvt_pk_bf16_f32 either.
|
||||
|
||||
#define CP_HD 128 // dims per head, q k and v alike
|
||||
#define CP_BT 64 // token block = the scan's chunk, so the cumsum stays wave-local
|
||||
#define CP_W HALO_GDN_CONV_W // conv width
|
||||
#define CP_ST (CP_W - 1) // conv state depth
|
||||
// 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
|
||||
#define CP_DPL 4 // dims per lane (CP_HD / 32)
|
||||
|
||||
// cp_silu is in halo_gdn_conv_tap.h, shared with the recurrent update's folded convolution.
|
||||
|
||||
// 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 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; 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 halo_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;
|
||||
}
|
||||
|
||||
template <int HPB, int ABF16>
|
||||
__global__ __launch_bounds__(HPB * 32)
|
||||
void halo_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch,
|
||||
const unsigned short* __restrict__ wgt,
|
||||
const unsigned short* __restrict__ bias,
|
||||
unsigned short* __restrict__ cstate,
|
||||
long cs_seq, long cs_dim, long cs_tok,
|
||||
const int* __restrict__ cache_idx, long ci_stride,
|
||||
const void* __restrict__ has_init, int hi_i32,
|
||||
const void* __restrict__ av, const void* __restrict__ bv,
|
||||
long ab_stride,
|
||||
const float* __restrict__ A_log, const float* __restrict__ dt_bias,
|
||||
unsigned short* __restrict__ q, unsigned short* __restrict__ k,
|
||||
unsigned short* __restrict__ v,
|
||||
float* __restrict__ go, float* __restrict__ beta,
|
||||
const int* __restrict__ cu, int N, int H, int Hg, float sp_thr)
|
||||
{
|
||||
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
|
||||
// flat chunk id -> (sequence, chunk); the grid is an upper bound (see
|
||||
// halo_gdn_kkt_solve_k128_c64_bf16.hip)
|
||||
int n = -1, t0 = 0, bos = 0, rows = 0, slen = 0;
|
||||
{
|
||||
int acc = 0, want = blockIdx.x;
|
||||
for (int i = 0; i < N; ++i) {
|
||||
const int b = cu[i], e = cu[i + 1];
|
||||
const int nc = (e - b + CP_BT - 1) / CP_BT;
|
||||
if (want < acc + nc) { n = i; bos = b; slen = e - b; t0 = (want - acc) * CP_BT;
|
||||
rows = min(CP_BT, slen - t0); break; }
|
||||
acc += nc;
|
||||
}
|
||||
if (n < 0) return;
|
||||
}
|
||||
const bool first = (t0 == 0);
|
||||
|
||||
// ---- the gating half, on one workgroup per chunk ----------------------------------------
|
||||
// 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];
|
||||
const int i0 = 2 * lane, i1 = i0 + 1;
|
||||
float g0 = 0.0f, g1 = 0.0f;
|
||||
if (i0 < rows)
|
||||
g0 = -alog * cp_softplus(cp_ab<ABF16>(av, (size_t)(bos + t0 + i0) * ab_stride + hv)
|
||||
+ dtb, sp_thr);
|
||||
if (i1 < rows)
|
||||
g1 = -alog * cp_softplus(cp_ab<ABF16>(av, (size_t)(bos + t0 + i1) * ab_stride + hv)
|
||||
+ dtb, sp_thr);
|
||||
// inclusive wave scan of the per-lane pair sums, made exclusive by subtracting the pair
|
||||
float p = g0 + g1;
|
||||
#pragma unroll
|
||||
for (int d = 1; d < 32; d <<= 1) {
|
||||
const float o = __shfl_up(p, d, 32);
|
||||
if (lane >= d) p += o;
|
||||
}
|
||||
const float pre = p - (g0 + g1); // sum of all lanes before this one
|
||||
if (i0 < rows) {
|
||||
go[(size_t)(bos + t0 + i0) * H + hv] = pre + g0;
|
||||
beta[(size_t)(bos + t0 + i0) * H + hv] = 1.0f / (1.0f + __expf(
|
||||
-cp_ab<ABF16>(bv, (size_t)(bos + t0 + i0) * ab_stride + hv)));
|
||||
}
|
||||
if (i1 < rows) {
|
||||
go[(size_t)(bos + t0 + i1) * H + hv] = pre + g0 + g1;
|
||||
beta[(size_t)(bos + t0 + i1) * H + hv] = 1.0f / (1.0f + __expf(
|
||||
-cp_ab<ABF16>(bv, (size_t)(bos + t0 + i1) * ab_stride + hv)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the convolution half ----------------------------------------------------------------
|
||||
const int unit = blockIdx.y * HPB + warp; // global 128-dim head unit
|
||||
const int d0 = unit * CP_HD + lane * CP_DPL; // this lane's first channel
|
||||
const unsigned short* xp = x + (size_t)(bos + t0) * xpitch + d0;
|
||||
|
||||
float wt[CP_W][CP_DPL], bs[CP_DPL];
|
||||
#pragma unroll
|
||||
for (int c = 0; c < CP_DPL; ++c) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < CP_W; ++i) wt[i][c] = bf2f(wgt[(size_t)(d0 + c) * CP_W + i]);
|
||||
bs[c] = bias ? bf2f(bias[d0 + c]) : 0.0f;
|
||||
}
|
||||
|
||||
// win[i] holds x[t - (W-1) + i]; seeded from the previous tokens, or from the conv state cache
|
||||
// at the sequence's first chunk
|
||||
float win[CP_W][CP_DPL];
|
||||
{
|
||||
const bool init = first && halo_has_init(has_init, hi_i32, n);
|
||||
const unsigned short* sp = init ? (cstate + (size_t)cache_idx[(size_t)n * ci_stride] * cs_seq
|
||||
+ (size_t)d0 * cs_dim) : nullptr;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < CP_ST; ++i) { // i = 0,1,2 -> x[t0-3+i]
|
||||
const int src = t0 - CP_ST + i;
|
||||
#pragma unroll
|
||||
for (int c = 0; c < CP_DPL; ++c) {
|
||||
float val = 0.0f;
|
||||
if (src >= 0) val = bf2f(x[(size_t)(bos + src) * xpitch + d0 + c]);
|
||||
else if (init) val = bf2f(sp[(size_t)c * cs_dim + (size_t)(CP_ST + src) * cs_tok]);
|
||||
win[i][c] = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- write the new conv state, from x, at the sequence's first chunk ---------------------
|
||||
// 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 = halo_has_init(has_init, hi_i32, n);
|
||||
// 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
|
||||
for (int i = 0; i < CP_ST; ++i) {
|
||||
const int src = slen - CP_ST + i;
|
||||
unsigned short val = 0;
|
||||
if (src >= 0) val = x[(size_t)(bos + src) * xpitch + d0 + c];
|
||||
else if (init) val = sp[(size_t)c * cs_dim + (size_t)(CP_ST + src) * cs_tok];
|
||||
sp[(size_t)c * cs_dim + (size_t)i * cs_tok] = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const int hq = unit, hk = unit - Hg, hv = unit - 2 * Hg;
|
||||
const int region = (unit < Hg) ? 0 : ((unit < 2 * Hg) ? 1 : 2);
|
||||
|
||||
for (int t = 0; t < rows; ++t) {
|
||||
float o[CP_DPL];
|
||||
{
|
||||
const unsigned short* xr = xp + (size_t)t * xpitch;
|
||||
const ushort4 raw = *(const ushort4*)xr;
|
||||
win[CP_W - 1][0] = bf2f(raw.x); win[CP_W - 1][1] = bf2f(raw.y);
|
||||
win[CP_W - 1][2] = bf2f(raw.z); win[CP_W - 1][3] = bf2f(raw.w);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int c = 0; c < CP_DPL; ++c) {
|
||||
float acc = bs[c];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < CP_W; ++i) acc += wt[i][c] * win[i][c];
|
||||
// round as the unfused pair does on the way to HBM
|
||||
o[c] = bf2f(f2bf(cp_silu(acc)));
|
||||
}
|
||||
|
||||
if (region < 2) {
|
||||
float ss = 0.0f;
|
||||
#pragma unroll
|
||||
for (int c = 0; c < CP_DPL; ++c) ss += o[c] * o[c];
|
||||
ss += halo_xor_lane<16>(ss); ss += halo_xor_lane<8>(ss); ss += halo_xor_lane<4>(ss);
|
||||
ss += halo_xor_lane<2>(ss); ss += halo_xor_lane<1>(ss);
|
||||
const float inv = 1.0f / sqrtf(ss + 1e-6f); // L2NORM_EPS, as in the kernel it replaces
|
||||
unsigned short* dst = (region ? k : q)
|
||||
+ ((size_t)(bos + t0 + t) * Hg + (region ? hk : hq)) * CP_HD
|
||||
+ lane * CP_DPL;
|
||||
*(ushort4*)dst = make_ushort4(f2bf(o[0] * inv), f2bf(o[1] * inv),
|
||||
f2bf(o[2] * inv), f2bf(o[3] * inv));
|
||||
} else {
|
||||
unsigned short* dst = v + ((size_t)(bos + t0 + t) * H + hv) * CP_HD + lane * CP_DPL;
|
||||
*(ushort4*)dst = make_ushort4(f2bf(o[0]), f2bf(o[1]), f2bf(o[2]), f2bf(o[3]));
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < CP_W - 1; ++i)
|
||||
#pragma unroll
|
||||
for (int c = 0; c < CP_DPL; ++c) win[i][c] = win[i + 1][c];
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" int halo_gdn_conv_prep_w4_h128_bf16(
|
||||
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
|
||||
long cs_seq, long cs_dim, long cs_tok, const void* cache_idx, long ci_stride,
|
||||
const void* has_init, int hi_i32,
|
||||
const void* a, const void* b, long ab_stride, int ab_is_bf16, const void* A_log,
|
||||
const void* dt_bias, void* q, void* k, void* v, void* g, void* beta, const void* cu,
|
||||
int N, int T, int H, int Hg, int K, int V, int width, float softplus_thr, void* stream)
|
||||
{
|
||||
if (K != CP_HD || V != CP_HD || width != CP_W) return -1;
|
||||
const int units = 2 * Hg + H;
|
||||
int hpb = 8;
|
||||
while (hpb > 1 && (Hg % hpb || H % hpb)) hpb >>= 1;
|
||||
const int nchunk_ub = (T + CP_BT - 1) / CP_BT + N;
|
||||
dim3 grid(nchunk_ub, units / hpb), blk(hpb * 32);
|
||||
#define CP_LAUNCH(P, AB) \
|
||||
hipLaunchKernelGGL((halo_gdn_conv_prep_kernel<P, AB>), grid, blk, 0, (hipStream_t)stream, \
|
||||
(const unsigned short*)x, xpitch, (const unsigned short*)wgt, \
|
||||
(const unsigned short*)bias, (unsigned short*)cstate, \
|
||||
cs_seq, cs_dim, cs_tok, (const int*)cache_idx, ci_stride, \
|
||||
has_init, hi_i32, a, b, ab_stride, \
|
||||
(const float*)A_log, (const float*)dt_bias, (unsigned short*)q, \
|
||||
(unsigned short*)k, (unsigned short*)v, (float*)g, (float*)beta, \
|
||||
(const int*)cu, N, H, Hg, softplus_thr)
|
||||
#define CP_SWITCH(AB) \
|
||||
switch (hpb) { \
|
||||
case 8: CP_LAUNCH(8, AB); break; \
|
||||
case 4: CP_LAUNCH(4, AB); break; \
|
||||
case 2: CP_LAUNCH(2, AB); break; \
|
||||
default: CP_LAUNCH(1, AB); break; \
|
||||
}
|
||||
if (ab_is_bf16) { CP_SWITCH(1); } else { CP_SWITCH(0); }
|
||||
#undef CP_SWITCH
|
||||
#undef CP_LAUNCH
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// 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)
|
||||
void halo_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitch,
|
||||
const unsigned short* __restrict__ wgt,
|
||||
const unsigned short* __restrict__ bias,
|
||||
unsigned short* __restrict__ cstate,
|
||||
long cs_seq, long cs_dim, long cs_tok, int state_len_max,
|
||||
const int* __restrict__ cache_idx, long ci_stride,
|
||||
const int* __restrict__ naccept,
|
||||
unsigned short* __restrict__ q, unsigned short* __restrict__ k,
|
||||
unsigned short* __restrict__ v,
|
||||
const int* __restrict__ cu, int H, int Hg, int maxq)
|
||||
{
|
||||
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
const int n = blockIdx.x;
|
||||
const int bos = cu[n], slen = cu[n + 1] - bos;
|
||||
if (slen <= 0) return;
|
||||
const int slot = cache_idx[(size_t)n * ci_stride];
|
||||
// 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;
|
||||
// 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;
|
||||
|
||||
// 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) {
|
||||
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]);
|
||||
bs[c] = bias ? bf2f(bias[d0 + c]) : 0.0f;
|
||||
}
|
||||
|
||||
// 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;
|
||||
// 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);
|
||||
float win[CP_W][CP_DPL];
|
||||
unsigned short hist[CP_ST][CP_DPL]; // the raw history, for the shifted rewrite
|
||||
{
|
||||
const unsigned short* hp = sp + off * cst;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < CP_ST; ++i)
|
||||
#pragma unroll
|
||||
for (int c = 0; c < CP_DPL; ++c) {
|
||||
const unsigned short raw = hp[c * csd + i * cst];
|
||||
hist[i][c] = raw;
|
||||
win[i][c] = bf2f(raw);
|
||||
}
|
||||
}
|
||||
|
||||
const int hq = unit, hk = unit - Hg, hv = unit - 2 * Hg;
|
||||
const int region = (unit < Hg) ? 0 : ((unit < 2 * Hg) ? 1 : 2);
|
||||
|
||||
// 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);
|
||||
const int ostep = (region == 2) ? H * CP_HD : Hg * CP_HD;
|
||||
|
||||
#define CU_TOKEN_BODY(RAW) \
|
||||
{ \
|
||||
const ushort4 raw_ = (RAW); \
|
||||
win[CP_W - 1][0] = bf2f(raw_.x); win[CP_W - 1][1] = bf2f(raw_.y); \
|
||||
win[CP_W - 1][2] = bf2f(raw_.z); win[CP_W - 1][3] = bf2f(raw_.w); \
|
||||
unsigned short out[CP_DPL]; \
|
||||
_Pragma("unroll") \
|
||||
for (int c = 0; c < CP_DPL; ++c) { \
|
||||
float acc = bs[c]; \
|
||||
_Pragma("unroll") \
|
||||
for (int i = 0; i < CP_W; ++i) acc += wt[i][c] * win[i][c]; \
|
||||
out[c] = f2bf(cp_silu(acc)); \
|
||||
} \
|
||||
*(ushort4*)op = make_ushort4(out[0], out[1], out[2], out[3]); \
|
||||
op += ostep; \
|
||||
_Pragma("unroll") \
|
||||
for (int i = 0; i < CP_W - 1; ++i) \
|
||||
_Pragma("unroll") \
|
||||
for (int c = 0; c < CP_DPL; ++c) win[i][c] = win[i + 1][c]; \
|
||||
}
|
||||
if (xpre) {
|
||||
// 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
|
||||
}
|
||||
} else {
|
||||
for (int t = 0; t < slen; ++t) CU_TOKEN_BODY(*(const ushort4*)(xrow + t * xpi))
|
||||
}
|
||||
|
||||
// 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;
|
||||
// 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];
|
||||
// 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 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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];
|
||||
}
|
||||
}
|
||||
#undef CU_TOKEN_BODY
|
||||
}
|
||||
|
||||
extern "C" int halo_gdn_conv_update_w4_h128_bf16(
|
||||
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
|
||||
long cs_seq, long cs_dim, long cs_tok, int state_len_max, const void* cache_idx,
|
||||
long ci_stride, const void* num_accepted, void* q, void* k, void* v, const void* cu,
|
||||
int N, int H, int Hg, int K, int V, int width, int max_query_len, void* stream)
|
||||
{
|
||||
if (K != CP_HD || V != CP_HD || width != CP_W) return -1;
|
||||
const int units = 2 * Hg + H;
|
||||
int hpb = 8;
|
||||
while (hpb > 1 && (Hg % hpb || H % hpb)) hpb >>= 1;
|
||||
// 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) \
|
||||
hipLaunchKernelGGL((halo_gdn_conv_update_kernel<P>), grid, blk, 0, (hipStream_t)stream, \
|
||||
(const unsigned short*)x, xpitch, (const unsigned short*)wgt, \
|
||||
(const unsigned short*)bias, (unsigned short*)cstate, cs_seq, cs_dim, \
|
||||
cs_tok, state_len_max, (const int*)cache_idx, ci_stride, \
|
||||
(const int*)num_accepted, (unsigned short*)q, (unsigned short*)k, \
|
||||
(unsigned short*)v, (const int*)cu, H, Hg, max_query_len)
|
||||
switch (hpb) {
|
||||
case 8: CU_LAUNCH(8); break;
|
||||
case 4: CU_LAUNCH(4); break;
|
||||
case 2: CU_LAUNCH(2); break;
|
||||
default: CU_LAUNCH(1); break;
|
||||
}
|
||||
#undef CU_LAUNCH
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
// Shared operand helpers: halo_gdn_args.h. Operand enums use an OPD_ prefix because CP_W and CP_ST
|
||||
// are already kernel constants in this unit.
|
||||
/* ------------------------------------------------------------------ conv prep */
|
||||
|
||||
|
||||
/* Inputs first, outputs last -- docs/OPS.md's resolved table. */
|
||||
enum { OPD_CP_X = 0, OPD_CP_W, OPD_CP_B, OPD_CP_ALOG, OPD_CP_DTB, OPD_CP_CSTATE, OPD_CP_CU,
|
||||
OPD_CP_A, OPD_CP_BGATE, OPD_CP_CACHE_IDX, OPD_CP_HAS_INIT,
|
||||
OPD_CP_Q, OPD_CP_K, OPD_CP_V, OPD_CP_G, OPD_CP_BETA };
|
||||
|
||||
extern "C" int halo_rad_gdn_conv_prep(const RadArgs* a, RadStream s) {
|
||||
if (gdn_dims_ok() != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
const RadTensor* x = halo_opt(a, OPD_CP_X);
|
||||
const RadTensor* w = halo_opt(a, OPD_CP_W);
|
||||
const RadTensor* b = halo_opt(a, OPD_CP_B);
|
||||
const RadTensor* alog = halo_opt(a, OPD_CP_ALOG);
|
||||
const RadTensor* dtb = halo_opt(a, OPD_CP_DTB);
|
||||
const RadTensor* cst = halo_opt(a, OPD_CP_CSTATE);
|
||||
const RadTensor* cu = halo_opt(a, OPD_CP_CU);
|
||||
const RadTensor* q = halo_opt(a, OPD_CP_Q);
|
||||
const RadTensor* k = halo_opt(a, OPD_CP_K);
|
||||
const RadTensor* v = halo_opt(a, OPD_CP_V);
|
||||
const RadTensor* g = halo_opt(a, OPD_CP_G);
|
||||
const RadTensor* beta = halo_opt(a, OPD_CP_BETA);
|
||||
const RadTensor* ta = halo_opt(a, OPD_CP_A);
|
||||
const RadTensor* tb = halo_opt(a, OPD_CP_BGATE);
|
||||
const RadTensor* cidx = halo_opt(a, OPD_CP_CACHE_IDX);
|
||||
const RadTensor* hin = halo_opt(a, OPD_CP_HAS_INIT);
|
||||
|
||||
if (!x || !w || !alog || !dtb || !cst || !cu || !q || !k || !v || !g || !beta)
|
||||
return HALO_NO(RAD_E_INVAL);
|
||||
/* 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 HALO_NO(RAD_E_INVAL);
|
||||
|
||||
if (x->rank < 2 || q->rank != 3 || k->rank != 3 || v->rank != 3) return HALO_NO(RAD_E_SHAPE);
|
||||
if (g->rank != 2 || beta->rank != 2 || cst->rank != 3 || ta->rank != 2) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
int N = 0;
|
||||
int rc = seqs_of(cu, &N);
|
||||
if (rc != RAD_OK) return rc;
|
||||
|
||||
/* 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 = halo_row_pitch(x);
|
||||
if (xpitch < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
const long long ab_stride = halo_row_pitch(ta);
|
||||
if (ab_stride < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
if (halo_row_pitch(tb) != ab_stride) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
if (!halo_contig(q) || !halo_contig(k) || !halo_contig(v) || !halo_contig(g) ||
|
||||
!halo_contig(beta) || !halo_contig(w) || !halo_contig(alog) || !halo_contig(dtb))
|
||||
return HALO_NO(RAD_E_STRIDE);
|
||||
if (cidx->rank < 1) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
const long long T = q->shape[0];
|
||||
const long long Hg = q->shape[1];
|
||||
const long long K = q->shape[2];
|
||||
const long long H = v->shape[1];
|
||||
const long long V = v->shape[2];
|
||||
if (k->shape[0] != T || k->shape[1] != Hg || k->shape[2] != K) return HALO_NO(RAD_E_SHAPE);
|
||||
if (v->shape[0] != T) return HALO_NO(RAD_E_SHAPE);
|
||||
if (g->shape[0] != T || g->shape[1] != H) return HALO_NO(RAD_E_SHAPE);
|
||||
if (beta->shape[0] != T || beta->shape[1] != H) return HALO_NO(RAD_E_SHAPE);
|
||||
if (H == 0 || Hg == 0 || H % Hg) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
const int width = (int)halo_geti_or(a, "conv_width", 4);
|
||||
const float thr = (float)halo_getf(a, "softplus_thr", 20.0);
|
||||
/* The l2 norm epsilon is compiled in (1e-6f); refuse any other value. */
|
||||
if ((float)halo_getf(a, "l2_eps", 1e-6) != 1e-6f) return HALO_NO(RAD_E_UNSUPPORTED);
|
||||
/* 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 HALO_NO(RAD_E_DTYPE);
|
||||
if (!ab_is_bf16 && ta->dtype != RAD_F32) return HALO_NO(RAD_E_DTYPE);
|
||||
|
||||
/* bf16 x, weights, conv state and q/k/v; fp32 A_log, dt_bias, g and beta. */
|
||||
HALO_DT(x, RAD_BF16); HALO_DT(w, RAD_BF16); HALO_DT(cst, RAD_BF16);
|
||||
HALO_DT(q, RAD_BF16); HALO_DT(k, RAD_BF16); HALO_DT(v, RAD_BF16);
|
||||
HALO_DT(alog, RAD_F32); HALO_DT(dtb, RAD_F32); HALO_DT(g, RAD_F32); HALO_DT(beta, RAD_F32);
|
||||
|
||||
return HALO_RAW(halo_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,
|
||||
/* has_init element width (see halo_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));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ conv update */
|
||||
|
||||
enum { CUP_X = 0, CUP_W, CUP_B, CUP_CSTATE, CUP_SIDX, CUP_NACC, CUP_CU, CUP_Q, CUP_K, CUP_V };
|
||||
|
||||
extern "C" int halo_rad_gdn_conv_update(const RadArgs* a, RadStream s) {
|
||||
if (gdn_dims_ok() != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
const RadTensor* x = halo_opt(a, CUP_X);
|
||||
const RadTensor* w = halo_opt(a, CUP_W);
|
||||
const RadTensor* b = halo_opt(a, CUP_B);
|
||||
const RadTensor* cst = halo_opt(a, CUP_CSTATE);
|
||||
const RadTensor* sidx = halo_opt(a, CUP_SIDX);
|
||||
const RadTensor* nacc = halo_opt(a, CUP_NACC);
|
||||
const RadTensor* cu = halo_opt(a, CUP_CU);
|
||||
const RadTensor* q = halo_opt(a, CUP_Q);
|
||||
const RadTensor* k = halo_opt(a, CUP_K);
|
||||
const RadTensor* v = halo_opt(a, CUP_V);
|
||||
if (!x || !w || !cst || !sidx || !cu || !q || !k || !v) return HALO_NO(RAD_E_INVAL);
|
||||
if (cst->rank != 3 || q->rank != 3 || k->rank != 3 || v->rank != 3) return HALO_NO(RAD_E_SHAPE);
|
||||
if (sidx->rank < 1) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
int N = 0;
|
||||
int rc = seqs_of(cu, &N);
|
||||
if (rc != RAD_OK) return rc;
|
||||
|
||||
const long long xpitch = halo_row_pitch(x);
|
||||
if (xpitch < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
if (!halo_contig(q) || !halo_contig(k) || !halo_contig(v) || !halo_contig(w))
|
||||
return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
const long long T = q->shape[0];
|
||||
const long long Hg = q->shape[1];
|
||||
const long long K = q->shape[2];
|
||||
const long long H = v->shape[1];
|
||||
const long long V = v->shape[2];
|
||||
if (H == 0 || Hg == 0 || H % Hg) return HALO_NO(RAD_E_SHAPE);
|
||||
if (v->shape[0] != T || k->shape[0] != T) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
/* bf16 x, weights, conv state and q/k/v, as in the prefill conv. */
|
||||
HALO_DT(x, RAD_BF16); HALO_DT(w, RAD_BF16); HALO_DT(cst, RAD_BF16);
|
||||
HALO_DT(q, RAD_BF16); HALO_DT(k, RAD_BF16); HALO_DT(v, RAD_BF16);
|
||||
|
||||
const int width = (int)halo_geti_or(a, "conv_width", 4);
|
||||
/* 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 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 HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
return HALO_RAW(halo_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));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
/* Derived from libr4d/r4d_gdn_gated_norm_had_quant_i8.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gdn_gated_norm_had_quant_i8.hip -- the GDN block's gated RMS norm, block Hadamard and
|
||||
// per-row int8 quantiser in one pass: out_proj's input on the 48 linear-attention layers (the
|
||||
// fourth rotated site in a W4A8 layer).
|
||||
//
|
||||
// out = x * rsqrt(mean_head(x^2) + eps) * w * silu(z)
|
||||
//
|
||||
// Two extents, which is why halo_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 mixes only within a head; wider widths mix across heads. Activation
|
||||
// error is 0.00679 at width 128 vs 0.00521 at 512.
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_fwht.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <cmath>
|
||||
|
||||
#define HALO_GNHQ_HEAD 128
|
||||
|
||||
template <int HAD, int THR>
|
||||
__global__ __launch_bounds__(THR) void halo_gdn_gated_norm_had_quant_i8_kernel(
|
||||
const __hip_bfloat16* __restrict__ X, const __hip_bfloat16* __restrict__ Z,
|
||||
const float* __restrict__ Wg, signed char* __restrict__ Q, float* __restrict__ S,
|
||||
int K, long xrow, long zrow, int zgrp, int zblk, float eps, float rnorm) {
|
||||
constexpr int VPL = HAD / 32, NW = THR / 32;
|
||||
constexpr int LPH = HALO_GNHQ_HEAD / VPL; // lanes spanned by one head
|
||||
extern __shared__ float lds[];
|
||||
float* red = lds + K;
|
||||
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 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;
|
||||
for (int blk = wave; blk < K / HAD; blk += NW) {
|
||||
const int base = blk * HAD + lane * VPL;
|
||||
const int zbase = zgrp ? (base / zblk) * zgrp + (base % zblk) : base;
|
||||
float v[VPL];
|
||||
float ss = 0.f;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPL; j++) {
|
||||
v[j] = __bfloat162float(x[base + j]);
|
||||
ss += v[j] * v[j];
|
||||
}
|
||||
// segmented: masks below LPH never cross a head
|
||||
ss = halo_xor_sum<LPH>(ss);
|
||||
const float rms = __frsqrt_rn(ss * (1.f / (float)HALO_GNHQ_HEAD) + eps);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPL; j++) {
|
||||
const float g = __bfloat162float(z[zbase + j]);
|
||||
v[j] = v[j] * rms * Wg[(base + j) & (HALO_GNHQ_HEAD - 1)] * (g / (1.f + __expf(-g)));
|
||||
}
|
||||
halo_fwht_wave<HAD>(v, lane);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPL; j++) {
|
||||
lds[base + j] = v[j];
|
||||
m = fmaxf(m, fabsf(v[j]));
|
||||
}
|
||||
}
|
||||
|
||||
m = halo_wave_max(m);
|
||||
if (lane == 0) red[wave] = m;
|
||||
__syncthreads();
|
||||
m = red[0];
|
||||
#pragma unroll
|
||||
for (int i = 1; i < NW; i++) m = fmaxf(m, red[i]);
|
||||
m = fmaxf(m, 1e-8f);
|
||||
const float inv = 127.f / m;
|
||||
if (threadIdx.x == 0) S[row] = m * rnorm / 127.f;
|
||||
|
||||
signed char* q = Q + (size_t)row * K;
|
||||
for (int i = threadIdx.x; i < K; i += THR) {
|
||||
const int st = i >> 4, j = i & 15;
|
||||
const int sr = (st << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3);
|
||||
const int t = __float2int_rn(lds[sr] * inv);
|
||||
q[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
|
||||
}
|
||||
}
|
||||
|
||||
// The plugin ABI launch (RadLaunchFn); see the note at the head of halo_quant_act_i8.hip.
|
||||
enum { GG_X = 0, GG_Z, GG_W, GG_Q, GG_S };
|
||||
|
||||
extern "C" int halo_rad_gdn_gated_norm_hq_i8(const RadArgs* args, RadStream stream) {
|
||||
const RadTensor* x = halo_opt(args, GG_X);
|
||||
const RadTensor* z = halo_opt(args, GG_Z);
|
||||
const RadTensor* w = halo_opt(args, GG_W);
|
||||
const RadTensor* q = halo_opt(args, GG_Q);
|
||||
const RadTensor* sc = halo_opt(args, GG_S);
|
||||
if (!x || !z || !w || !q || !sc) return HALO_NO(RAD_E_INVAL);
|
||||
if (!halo_contig(q) || !halo_contig(sc) || !halo_contig(w)) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
long long M = 0, K = 0;
|
||||
int rc = halo_rows_of(x, &M, &K);
|
||||
if (rc != RAD_OK) return HALO_NO(rc);
|
||||
const long long head = halo_geti_or(args, "head_dim", HALO_GNHQ_HEAD);
|
||||
if (head != HALO_GNHQ_HEAD) return HALO_NO(RAD_E_SHAPE);
|
||||
if (K % HALO_GNHQ_HEAD) return HALO_NO(RAD_E_SHAPE);
|
||||
if (halo_numel(w) != head) return HALO_NO(RAD_E_SHAPE); // wgain is 128 floats, not K
|
||||
|
||||
const long long had = halo_geti_or(args, "group", 0);
|
||||
if (had != 128 && had != 256 && had != 512) return HALO_NO(RAD_E_SHAPE);
|
||||
// A rotation block cannot straddle a tensor-parallel shard boundary.
|
||||
if (K % had) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
const long long xrow = halo_row_pitch(x);
|
||||
const long long zrow = halo_row_pitch(z);
|
||||
if (xrow < 0 || zrow < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
// Interleaved-gate layout (see the kernel); zgrp 0 means contiguous.
|
||||
const long long zgrp = halo_geti_or(args, "zgrp", 0);
|
||||
const long long zblk = halo_geti_or(args, "zblk", 0);
|
||||
if (zgrp && (zblk % had || zblk < had || zgrp < zblk)) return HALO_NO(RAD_E_INVAL);
|
||||
|
||||
const float eps = (float)halo_getf(args, "eps", 1e-6);
|
||||
const int thr = halo_act_threads((int)M, (int)K);
|
||||
const size_t shmem = (size_t)K * sizeof(float) + (thr / 32) * sizeof(float);
|
||||
if (shmem > 65536) return HALO_NO(RAD_E_SCRATCH);
|
||||
const float rn = 1.f / sqrtf((float)had);
|
||||
const long xr = (long)(xrow ? xrow : K), zr = (long)(zrow ? zrow : K);
|
||||
#define HALO_GNHQ_LAUNCH(H, T) hipLaunchKernelGGL((halo_gdn_gated_norm_had_quant_i8_kernel<H, T>), \
|
||||
dim3((int)M), dim3(T), shmem, (hipStream_t)stream, (const __hip_bfloat16*)halo_p(x), \
|
||||
(const __hip_bfloat16*)halo_p(z), (const float*)halo_p(w), (signed char*)halo_wp(q), \
|
||||
(float*)halo_wp(sc), (int)K, xr, zr, (int)zgrp, (int)zblk, eps, rn)
|
||||
#define HALO_GNHQ_T(H) switch (thr) { \
|
||||
case 256: HALO_GNHQ_LAUNCH(H, 256); break; \
|
||||
case 512: HALO_GNHQ_LAUNCH(H, 512); break; \
|
||||
case 1024: HALO_GNHQ_LAUNCH(H, 1024); break; \
|
||||
default: return HALO_NO(RAD_E_INVAL); }
|
||||
switch (had) {
|
||||
case 128: HALO_GNHQ_T(128); break;
|
||||
case 256: HALO_GNHQ_T(256); break;
|
||||
default: HALO_GNHQ_T(512); break;
|
||||
}
|
||||
#undef HALO_GNHQ_T
|
||||
#undef HALO_GNHQ_LAUNCH
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : HALO_NO(RAD_E_DEVICE);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/* Derived from libr4d/r4d_gdn_gated_rmsnorm_h128_bf16.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gdn_gated_rmsnorm_h128_bf16.hip -- the gated RMS norm a gated-delta-net layer applies to its own
|
||||
// output before the output projection:
|
||||
//
|
||||
// out[r][d] = x[r][d] . rsqrt(mean_d(x[r][:]^2) + eps) . w[d] . act(z[r][d])
|
||||
//
|
||||
// one row per (token, head), 128 wide. Replaces FLA's `rmsnorm_fn` (mamba/ops/layernorm_gated).
|
||||
//
|
||||
// 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 (halo_gdn_recurrent_update_k128_v128_bf16_fp32state.hip).
|
||||
//
|
||||
// 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 "halo.h"
|
||||
#include "halo_gdn_args.h"
|
||||
#include "halo_common.h" // halo_wave_sum, bf16_to_f32 / f32_to_bf16
|
||||
|
||||
#define GN_D 128 // channels per row
|
||||
#define GN_DPL 4 // channels per lane
|
||||
#define GN_NW 8 // rows in flight per workgroup
|
||||
|
||||
__device__ __forceinline__ float gn_act(float z, int kind) {
|
||||
const float s = 1.0f / (1.0f + __expf(-z));
|
||||
return kind ? s : z * s; // 1 = sigmoid, 0 = silu / swish
|
||||
}
|
||||
|
||||
template <int ACT>
|
||||
__global__ __launch_bounds__(GN_NW * 32)
|
||||
void halo_gdn_gated_rmsnorm_kernel(const unsigned short* __restrict__ x,
|
||||
const unsigned short* __restrict__ z,
|
||||
const float* __restrict__ w,
|
||||
unsigned short* __restrict__ o,
|
||||
long rows, long xrow, long zrow, long orow,
|
||||
long zheads, long ztok, float eps)
|
||||
{
|
||||
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
|
||||
const long r = (long)blockIdx.x * GN_NW + warp;
|
||||
if (r >= rows) return;
|
||||
const int d0 = lane * GN_DPL;
|
||||
// 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);
|
||||
float v[GN_DPL] = {bf16_to_f32(xv.x), bf16_to_f32(xv.y), bf16_to_f32(xv.z),
|
||||
bf16_to_f32(xv.w)};
|
||||
|
||||
float ss = 0.0f;
|
||||
#pragma unroll
|
||||
for (int c = 0; c < GN_DPL; ++c) ss += v[c] * v[c];
|
||||
ss = halo_wave_sum(ss);
|
||||
const float scale = __frsqrt_rn(ss * (1.0f / GN_D) + eps);
|
||||
|
||||
const ushort4 zv = *(const ushort4*)(z + zoff + d0);
|
||||
const float zz[GN_DPL] = {bf16_to_f32(zv.x), bf16_to_f32(zv.y), bf16_to_f32(zv.z),
|
||||
bf16_to_f32(zv.w)};
|
||||
const float4 ww = *(const float4*)(w + d0);
|
||||
const float wv[GN_DPL] = {ww.x, ww.y, ww.z, ww.w};
|
||||
|
||||
unsigned short out[GN_DPL];
|
||||
#pragma unroll
|
||||
for (int c = 0; c < GN_DPL; ++c)
|
||||
out[c] = f32_to_bf16(v[c] * scale * wv[c] * gn_act(zz[c], ACT));
|
||||
*(ushort4*)(o + r * orow + d0) = make_ushort4(out[0], out[1], out[2], out[3]);
|
||||
}
|
||||
|
||||
extern "C" int halo_gdn_gated_rmsnorm_h128_bf16(const void* x, const void* z, const void* w,
|
||||
void* o, long rows, long xrow, long zrow,
|
||||
long orow, long zheads, long ztok, int width,
|
||||
float eps, int act, void* stream)
|
||||
{
|
||||
if (width != GN_D) return -1;
|
||||
dim3 grid((unsigned)((rows + GN_NW - 1) / GN_NW)), blk(GN_NW * 32);
|
||||
if (act)
|
||||
hipLaunchKernelGGL((halo_gdn_gated_rmsnorm_kernel<1>), grid, blk, 0, (hipStream_t)stream,
|
||||
(const unsigned short*)x, (const unsigned short*)z, (const float*)w,
|
||||
(unsigned short*)o, rows, xrow, zrow, orow, zheads, ztok, eps);
|
||||
else
|
||||
hipLaunchKernelGGL((halo_gdn_gated_rmsnorm_kernel<0>), grid, blk, 0, (hipStream_t)stream,
|
||||
(const unsigned short*)x, (const unsigned short*)z, (const float*)w,
|
||||
(unsigned short*)o, rows, xrow, zrow, orow, zheads, ztok, eps);
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
// Shared operand helpers: halo_gdn_args.h.
|
||||
/* ------------------------------------------------------------------ gated rms norm */
|
||||
|
||||
enum { GN_X = 0, GN_Z, GN_W, GN_O };
|
||||
|
||||
extern "C" int halo_rad_gdn_gated_rmsnorm(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* x = halo_opt(a, GN_X);
|
||||
const RadTensor* z = halo_opt(a, GN_Z);
|
||||
const RadTensor* w = halo_opt(a, GN_W);
|
||||
const RadTensor* o = halo_opt(a, GN_O);
|
||||
/* bf16 x, z, out; fp32 weight. */
|
||||
HALO_DT(x, RAD_BF16); HALO_DT(z, RAD_BF16); HALO_DT(o, RAD_BF16); HALO_DT(w, RAD_F32);
|
||||
if (!x || !z || !w || !o) return HALO_NO(RAD_E_INVAL);
|
||||
if (x->rank < 2 || z->rank < 2 || o->rank < 2) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
if (!halo_contig(w)) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
/* One row is one (token, head). x and out are [tokens, heads, channels] (rank 3, as the chunk
|
||||
* scan requires) while the gate may be the flat [tokens, heads*channels] projection. So the
|
||||
* width comes from `channels` (or x's last axis), the row count from x, and each operand's
|
||||
* pitch between consecutive (token, head) rows is read per its shape. */
|
||||
const long long width = halo_geti_or(a, "channels", x->shape[x->rank - 1]);
|
||||
if (width <= 0 || halo_numel(x) % width) return HALO_NO(RAD_E_SHAPE);
|
||||
const long long rows = halo_numel(x) / width;
|
||||
if (halo_numel(z) < rows * width || halo_numel(o) < rows * width) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
const long long xrow = gn_row_pitch(x, width);
|
||||
const long long orow = gn_row_pitch(o, width);
|
||||
if (xrow < 0 || orow < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
/* The gate may also be a column slice of a wider [q|k|v|z] row (fp8 delta net): heads are
|
||||
* `width` apart within a token and tokens are the slice's stride apart, so the kernel also
|
||||
* takes the head count. zheads stays 0 for the flat layouts. */
|
||||
long long zrow = gn_row_pitch(z, width), zheads = 0, ztok = 0;
|
||||
if (zrow < 0 && z->rank == 2 && z->stride[1] == 1 && z->shape[1] % width == 0) {
|
||||
zheads = z->shape[1] / width;
|
||||
ztok = z->stride[0];
|
||||
zrow = width;
|
||||
/* 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 HALO_NO(RAD_E_SHAPE);
|
||||
if (x->rank >= 3 && x->shape[x->rank - 2] != zheads) return HALO_NO(RAD_E_SHAPE);
|
||||
}
|
||||
if (zrow < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
const float eps = (float)halo_getf(a, "eps", 1e-6);
|
||||
/* "silu" (0) or "sigmoid" (1). */
|
||||
const int act = halo_act_code(a, "act", nullptr, -1);
|
||||
if (act != 0 && act != 1) return HALO_NO(RAD_E_INVAL);
|
||||
|
||||
return HALO_RAW(halo_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));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
/* Derived from libr4d/r4d_gdn_kkt_solve_k128_c64_bf16.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gdn_kkt_solve_k128_c64_bf16.hip -- the gated-delta-net chunk preamble in one kernel:
|
||||
//
|
||||
// A = (I + strict_lower(diag(beta) . K K^T . e^{g_i - g_j}))^{-1} per chunk of 64
|
||||
//
|
||||
// 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:
|
||||
//
|
||||
// * 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 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 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]]
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// ---- gfx1151 port notes (everything below the gram loop is unchanged in arithmetic) -----------
|
||||
// A gfx11 accumulator element e is D[2e + (lane>>4)][lane & 15], not gfx12's D[8*(lane>>4) + e]
|
||||
// [lane & 15], so NO write-out here can keep libr4d's store arithmetic (halo_gdn_wmma.h). Two
|
||||
// cases, and the kernel is split between them by where the value has to land:
|
||||
//
|
||||
// * a TRANSPOSED stage (TMP, and the gram's slice of A) -- eight consecutive rows of one column.
|
||||
// accPack() reassembles exactly that from the half-pair, so the store is libr4d's (dst[lo]
|
||||
// [8*hi]) with the eight values coming from accPack instead of f2bf4. The per-element scale
|
||||
// and mask must be applied BEFORE the exchange: the two halves scale different rows.
|
||||
// * a ROW-MAJOR stage into A (the two merge results), eight consecutive columns of one row.
|
||||
// accPack() of the gfx11 accumulator gives rows, so the merge is taken with its two operands
|
||||
// swapped -- mma is X.Y^T, so swapping them transposes the result and accPack then hands out
|
||||
// C[lo][8*hi + 0..7]. Same two fragments, read on the other side.
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "halo.h"
|
||||
#include "halo_common.h" // lds_barrier
|
||||
#include "halo_gdn_args.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
|
||||
// libr4d's rounding helpers (r4d_gdn_wmma.h) -- f2bf / bf2f -- are halo_gdn_wmma.h's (included
|
||||
// above): f2bf is round-half-AWAY, one add, which is what makes this kernel bit-comparable with the
|
||||
// libr4d path. gfx1151 has no v_cvt_pk_bf16_f32 either.
|
||||
|
||||
// One accumulator stage: the eight elements accPack() assembles, as two 8-byte stores. The buffers
|
||||
// here are only 8-byte aligned (AP = 68 shorts), so a 16-byte store would be misaligned on odd rows.
|
||||
// accPack() packs with halo::pk_bf16, i.e. round-to-nearest-even, where libr4d's f2bf4 rounds half
|
||||
// away; the two differ only on an exact bf16 tie, and these are inverse intermediates. Both operand
|
||||
// shapes are offered so a call site reads the same whether it holds a v8f or a float[8].
|
||||
__device__ __forceinline__ void accSt(unsigned short* dst, v8f v, int lane) {
|
||||
union { v8f f; float s[8]; } u;
|
||||
u.f = v;
|
||||
const uint4 w = accPack(u.s, lane);
|
||||
*(uint2*)dst = make_uint2(w.x, w.y);
|
||||
*(uint2*)(dst + 4) = make_uint2(w.z, w.w);
|
||||
}
|
||||
__device__ __forceinline__ void accSt(unsigned short* dst, const float v[8], int lane) {
|
||||
const uint4 w = accPack(v, lane);
|
||||
*(uint2*)dst = make_uint2(w.x, w.y);
|
||||
*(uint2*)(dst + 4) = make_uint2(w.z, w.w);
|
||||
}
|
||||
|
||||
#define BT 64 // chunk
|
||||
#define KD 128 // head_k
|
||||
#define NBK 4 // 16x16 blocks per chunk edge
|
||||
// Row pitches are multiples of 8 shorts (16 B): halo_gdn_wmma.h's fragP reads a lane's whole 16-wide
|
||||
// k run as two 16-byte LDS loads, so a buffer whose pitch is 136 B or 264 B (libr4d's AP = 68 / TMP
|
||||
// = 36) puts every odd row 8 bytes off a 16-byte boundary, and a misaligned ds_load_b128 returns
|
||||
// garbage. See halo_gdn_chunk_scan.hip's note: measured there as infs in a partial chunk.
|
||||
#define AP 72 // row pitch of the [BT][BT] buffers, in shorts (144 B), 16-byte
|
||||
// aligned for the paired stores; 16 rows still cover every bank
|
||||
#define TMPP 40 // row pitch of the 32x32 transposed scratch, in shorts (80 B)
|
||||
#define NW 4
|
||||
#define NTHR (NW * 32)
|
||||
#define NTILE 10 // upper-triangular tiles of a 4x4 tiling
|
||||
#define MAXT ((NTILE + NW - 1) / NW)
|
||||
|
||||
// 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 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][TMPP]; // one 32x32 intermediate, transposed
|
||||
float gb[BT], bt[BT]; // the chunk's gate cumsum and beta, per token
|
||||
};
|
||||
|
||||
// (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;
|
||||
}
|
||||
|
||||
// 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__
|
||||
__launch_bounds__(NTHR)
|
||||
void halo_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
|
||||
const float* __restrict__ beta,
|
||||
const float* __restrict__ g,
|
||||
unsigned short* __restrict__ Ao,
|
||||
const int* __restrict__ cu,
|
||||
int N, int H, int Hg)
|
||||
{
|
||||
__shared__ KkSmem s;
|
||||
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
const int lo = lane & 15, hi = lane >> 4;
|
||||
const int hg = blockIdx.y;
|
||||
|
||||
// Resolve the flat chunk id to (sequence, chunk). The grid is an upper bound on the chunk
|
||||
// count, so surplus workgroups exit here; this saves the host a device-to-host sync to size
|
||||
// the grid exactly.
|
||||
int n = -1, t0 = 0, bos = 0, rows = 0;
|
||||
{
|
||||
int acc = 0, want = blockIdx.x;
|
||||
for (int i = 0; i < N; ++i) {
|
||||
const int b = cu[i], e = cu[i + 1];
|
||||
const int nc = (e - b + BT - 1) / BT;
|
||||
if (want < acc + nc) { n = i; bos = b; t0 = (want - acc) * BT;
|
||||
rows = min(BT, e - b - t0); break; }
|
||||
acc += nc;
|
||||
}
|
||||
if (n < 0) return;
|
||||
}
|
||||
|
||||
// ---- zero A once: the parts no store reaches (the upper tiles) are the same for every head.
|
||||
// 16-byte stores (the buffer is 8704 bytes, 16-byte aligned).
|
||||
for (int i = tid; i < 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 -----------------------------
|
||||
const unsigned short* kp = k + ((size_t)(bos + t0) * Hg + hg) * KD;
|
||||
const unsigned krow = (unsigned)(Hg * KD);
|
||||
v8f P[MAXT];
|
||||
#pragma unroll
|
||||
for (int t = 0; t < MAXT; ++t) P[t] = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
#pragma unroll
|
||||
for (int t = 0; t < MAXT; ++t) {
|
||||
const int ti = warp + t * NW;
|
||||
if (ti < NTILE) {
|
||||
int mt, nt; kkt_tile(ti, &mt, &nt);
|
||||
// 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
|
||||
for (int sk = 0; sk < KD / 16; ++sk)
|
||||
P[t] = mma(fragGo(kp, om + sk * 16), fragGo(kp, on + sk * 16), P[t]);
|
||||
}
|
||||
}
|
||||
|
||||
for (int hh = 0; hh < HG_RATIO; ++hh) {
|
||||
const int hv = hg * HG_RATIO + hh;
|
||||
|
||||
// ---- per-head gate and beta for this chunk
|
||||
if (tid < BT) {
|
||||
const int t = min(tid, rows - 1);
|
||||
s.gb[tid] = g[(size_t)(bos + t0 + t) * H + hv];
|
||||
s.bt[tid] = beta[(size_t)(bos + t0 + t) * H + hv];
|
||||
}
|
||||
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], 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 8-short store.
|
||||
//
|
||||
// gfx1151: element e is m = mt*16 + 2e + hi, not mt*16 + 8hi + e, so the eight columns this
|
||||
// lane owns are two-apart and interleaved with its half-partner's. Each element is scaled by
|
||||
// its OWN exponent first, and accPack() then reassembles the 16 consecutive columns of row i
|
||||
// out of the half-pair: this lane keeps columns mt*16 + 8*hi .. +7, as on gfx12.
|
||||
#pragma unroll
|
||||
for (int t = 0; t < MAXT; ++t) {
|
||||
const int ti = warp + t * NW;
|
||||
if (ti < NTILE) {
|
||||
int mt, nt; kkt_tile(ti, &mt, &nt);
|
||||
const int i = nt * 16 + lo; // row of A
|
||||
const int j0 = mt * 16 + 8 * hi; // first column of A, after the exchange
|
||||
const bool live = (i < rows);
|
||||
const float bi = live ? s.bt[i] : 0.0f;
|
||||
const float gi = live ? s.gb[i] : 0.0f;
|
||||
float vv[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int j = mt * 16 + 2 * e + hi;
|
||||
// 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];
|
||||
}
|
||||
accSt(&s.A[i][j0], vv, lane);
|
||||
}
|
||||
}
|
||||
lds_barrier();
|
||||
|
||||
// ---- 1. the four diagonal blocks, by fp32 forward substitution --------------------------
|
||||
// D = (I + N)^-1 solves D = I - N D row by row. Lane l owns column l of D, so the dot product
|
||||
// over j < i is in 16 registers and N[i][j] is a broadcast LDS read.
|
||||
for (int p = warp; p < NBK; p += NW) {
|
||||
const int b0 = p * 16;
|
||||
float d[16];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
float acc = 0.0f;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 16; ++j)
|
||||
if (j < i) acc += bf2f(s.A[b0 + i][b0 + j]) * d[j];
|
||||
d[i] = ((lo == i) ? 1.0f : 0.0f) - acc;
|
||||
}
|
||||
if (lane < 16) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 16; ++i) s.A[b0 + i][b0 + lo] = f2bf(d[i]);
|
||||
}
|
||||
}
|
||||
lds_barrier();
|
||||
|
||||
// ---- 2. the two 32-merges: M10 = -D1 A10 D0 --------------------------------------------
|
||||
for (int blk = warp; blk < 2; blk += NW) {
|
||||
const int r0 = blk * 32; // 32-block origin
|
||||
// X = A10 . D0 (left A10 row-major, right D0 transposed = MT)
|
||||
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; each of the two merges owns 16 rows of TMP.
|
||||
accSt(&s.TMP[blk * 16 + lo][8 * hi], X, lane);
|
||||
// Same wave writes and reads TMP here, and LDS accesses from one wave complete in order.
|
||||
__builtin_amdgcn_wave_barrier();
|
||||
// M10 = -D1 . X (left D1 row-major, in place in A; right X transposed, in TMP)
|
||||
// Operands swapped on gfx1151: this accumulates Y^T, so accPack() below hands out eight
|
||||
// consecutive rows of Y -- which is a row-major store into A. TMP already holds X^T (what
|
||||
// libr4d stages), which is this product's LEFT operand here, and D1 the right one.
|
||||
v8f Y = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
Y = mma(frag(&s.TMP[0][0], TMPP, blk * 16, 0, lane),
|
||||
frag(&s.A[0][0], AP, r0 + 16, r0 + 16, lane), Y);
|
||||
float yv[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) yv[e] = -Y[e];
|
||||
accSt(&s.A[r0 + 16 + lo][r0 + 8 * hi], yv, lane); // rows of M10, 8 columns each
|
||||
}
|
||||
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
|
||||
for (int t = warp; t < 4; t += NW) {
|
||||
const int mt = t >> 1, nt = t & 1;
|
||||
v8f Y = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
#pragma unroll
|
||||
for (int sk = 0; sk < 2; ++sk)
|
||||
Y = mma(frag(&s.A[0][0], AP, 32 + mt * 16, sk * 16, lane),
|
||||
fragT(&s.A[0][0], AP, nt * 16, sk * 16, lane), Y);
|
||||
accSt(&s.TMP[nt * 16 + lo][mt * 16 + 8 * hi], Y, lane);
|
||||
}
|
||||
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
|
||||
// Swapped, as M10 above: this accumulates Z^T so accPack() gives a row-major store. Y^T sits
|
||||
// in TMP ([col][row]) and is the left operand here; Q^-1's rows are the right one.
|
||||
for (int t = warp; t < 4; t += NW) {
|
||||
const int mt = t >> 1, nt = t & 1;
|
||||
v8f Z = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
|
||||
#pragma unroll
|
||||
for (int sk = 0; sk < 2; ++sk)
|
||||
Z = mma(frag(&s.TMP[0][0], TMPP, nt * 16, sk * 16, lane),
|
||||
frag(&s.A[0][0], AP, 32 + mt * 16, 32 + sk * 16, lane), Z);
|
||||
float zv[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) zv[e] = -Z[e];
|
||||
accSt(&s.A[32 + mt * 16 + lo][nt * 16 + 8 * hi], zv, lane);
|
||||
}
|
||||
lds_barrier();
|
||||
|
||||
// ---- store: one row of the inverse is 64 bf16, contiguous in HBM -----------------------
|
||||
{
|
||||
unsigned short* op = Ao + ((size_t)(bos + t0) * H + hv) * BT;
|
||||
const size_t orow = (size_t)H * BT;
|
||||
for (int r = tid / 8; r < rows; r += NTHR / 8) {
|
||||
const int c8 = (tid & 7) * 8;
|
||||
*(uint4*)(op + (size_t)r * orow + c8) = *(const uint4*)(&s.A[r][c8]);
|
||||
}
|
||||
}
|
||||
if (hh + 1 < HG_RATIO) lds_barrier();
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" int halo_gdn_kkt_solve_k128_c64_bf16(const void* k, const void* beta, const void* g,
|
||||
void* A, const void* cu, int N, int T, int H,
|
||||
int Hg, int K, int bt, void* stream)
|
||||
{
|
||||
if (K != KD || bt != BT) return -1;
|
||||
if (H % Hg) return -2;
|
||||
const int nchunk_ub = (T + BT - 1) / BT + N; // sum of per-sequence chunk counts, bounded
|
||||
dim3 grid(nchunk_ub, Hg), blk(NTHR);
|
||||
#define KK_LAUNCH(R) \
|
||||
hipLaunchKernelGGL((halo_gdn_kkt_solve_kernel<R>), grid, blk, 0, (hipStream_t)stream, \
|
||||
(const unsigned short*)k, (const float*)beta, (const float*)g, \
|
||||
(unsigned short*)A, (const int*)cu, N, H, Hg)
|
||||
switch (H / Hg) {
|
||||
case 1: KK_LAUNCH(1); break;
|
||||
case 2: KK_LAUNCH(2); break;
|
||||
case 3: KK_LAUNCH(3); break;
|
||||
case 4: KK_LAUNCH(4); break;
|
||||
case 6: KK_LAUNCH(6); break;
|
||||
case 8: KK_LAUNCH(8); break;
|
||||
default: return -3;
|
||||
}
|
||||
#undef KK_LAUNCH
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
// Shared operand helpers: halo_gdn_args.h.
|
||||
/* ------------------------------------------------------------------ kkt solve */
|
||||
|
||||
enum { KS_K = 0, KS_BETA, KS_G, KS_CU, KS_A };
|
||||
|
||||
extern "C" int halo_rad_gdn_kkt_solve(const RadArgs* a, RadStream s) {
|
||||
if (gdn_dims_ok() != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
const RadTensor* k = halo_opt(a, KS_K);
|
||||
const RadTensor* bt = halo_opt(a, KS_BETA);
|
||||
const RadTensor* g = halo_opt(a, KS_G);
|
||||
const RadTensor* cu = halo_opt(a, KS_CU);
|
||||
const RadTensor* A = halo_opt(a, KS_A);
|
||||
if (!k || !bt || !g || !cu || !A) return HALO_NO(RAD_E_INVAL);
|
||||
if (k->rank != 3 || bt->rank != 2 || g->rank != 2 || A->rank != 3) return HALO_NO(RAD_E_SHAPE);
|
||||
if (!halo_contig(k) || !halo_contig(bt) || !halo_contig(g) || !halo_contig(A))
|
||||
return HALO_NO(RAD_E_STRIDE);
|
||||
/* bf16 k and A (the output, written as bf16); fp32 beta and gate. */
|
||||
HALO_DT(k, RAD_BF16); HALO_DT(A, RAD_BF16); HALO_DT(bt, RAD_F32); HALO_DT(g, RAD_F32);
|
||||
|
||||
int N = 0;
|
||||
int rc = seqs_of(cu, &N);
|
||||
if (rc != RAD_OK) return rc;
|
||||
|
||||
const long long T = k->shape[0];
|
||||
const long long Hg = k->shape[1];
|
||||
const long long K = k->shape[2];
|
||||
const long long H = bt->shape[1];
|
||||
const long long chunk = A->shape[2];
|
||||
if (g->shape[0] != T || g->shape[1] != H || bt->shape[0] != T) return HALO_NO(RAD_E_SHAPE);
|
||||
if (A->shape[0] != T || A->shape[1] != H) return HALO_NO(RAD_E_SHAPE);
|
||||
if (H == 0 || Hg == 0 || H % Hg) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
return HALO_RAW(halo_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
@@ -0,0 +1,218 @@
|
||||
/* Carried over from the strix-halo-vllm project's libhalo, where this layer was
|
||||
* established and measured on the part; see libhalo/README.md. */
|
||||
// Fragment layer for the GDN kernels on gfx1151 / RDNA 3.5.
|
||||
//
|
||||
// This is the gfx11 counterpart of libr4d's r4d_gdn_wmma.h, and the difference is
|
||||
// the whole reason the GDN kernels cannot simply be copied across:
|
||||
//
|
||||
// A/B per lane the k that lane's element e holds
|
||||
// gfx1201 (RDNA4) 8 bf16 k = 8*(e>>2) + 4*(lane>>4) + (e&3)
|
||||
// gfx1151 (RDNA3.5) 16 bf16 k = e
|
||||
//
|
||||
// RDNA 3.5 replicates each operand row across both halves of the wave, so a lane
|
||||
// holds the WHOLE 16-wide k run. Established on the part itself by
|
||||
// bench/wmma_layout_probe.hip; see halo_wmma.h.
|
||||
//
|
||||
// For this layer that is a simplification, not extra work:
|
||||
//
|
||||
// * a fragment is ONE 32-byte contiguous read of the row, so two dwordx4 rather
|
||||
// than libr4d's two 8-byte groups sixteen bytes apart. All of its careful
|
||||
// ds_read2_b32 / ds_load_2addr_b64 pairing notes are about making THAT split
|
||||
// addressable in one register; there is no split here to pair.
|
||||
// * the row pointer loses its k term entirely -- `4 * (lane >> 4)` disappears
|
||||
// from rowP, rowG and rowGo, because the half-wave no longer selects k.
|
||||
//
|
||||
// What does NOT simplify is fragT, the transposed source: a lane needs 16 strided
|
||||
// scalar reads instead of 8.
|
||||
#pragma once
|
||||
#include "halo_common.h"
|
||||
#include "halo_wmma.h"
|
||||
|
||||
// ---- the gated residual's own bf16 arithmetic ----------------------------------
|
||||
// libr4d's r4d_gdn_wmma.h carries these three and the kernels written against it use them
|
||||
// (halo_ar_hc.h, halo_hc_bf16.hip); the port's header lost them, so they are restored here, in
|
||||
// the same place and with the same rounding libr4d uses (round-half-away: one add + a shift,
|
||||
// against RTNE's three instructions, and they differ only when the discarded bits are exactly
|
||||
// 0x8000). halo::f32_to_bf16 is the RTNE form the WMMA helpers pack with; keep them apart.
|
||||
__device__ __forceinline__ unsigned short f2bf(float f) {
|
||||
return (unsigned short)((__builtin_bit_cast(unsigned, f) + 0x8000u) >> 16);
|
||||
}
|
||||
__device__ __forceinline__ unsigned f2bf2(float a, float b) {
|
||||
const unsigned ua = __builtin_bit_cast(unsigned, a) + 0x8000u;
|
||||
const unsigned ub = __builtin_bit_cast(unsigned, b) + 0x8000u;
|
||||
return __builtin_amdgcn_perm(ub, ua, 0x07060302u); // {b_hi16, a_hi16}
|
||||
}
|
||||
__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.
|
||||
__device__ __forceinline__ v16bf fragP(const unsigned short* p) {
|
||||
union { uint4 w[2]; v16bf f; } u;
|
||||
u.w[0] = ((const uint4*)p)[0];
|
||||
u.w[1] = ((const uint4*)p)[1];
|
||||
return u.f;
|
||||
}
|
||||
|
||||
// Row pointer for the fragment above: LDS source, `pitch` in elements. No k term --
|
||||
// on gfx11 the lane's half does not select k.
|
||||
__device__ __forceinline__ const unsigned short* rowP(const unsigned short* src,
|
||||
int pitch, int base, int lane) {
|
||||
return src + (size_t)(base + (lane & 15)) * pitch;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 32-bit element offset for a global fragment source, split from a uniform base:
|
||||
// keeps the whole k loop as global_load_dwordx4 vdst, voff, s[base] with an
|
||||
// immediate, instead of rematerialising 64-bit address arithmetic per load.
|
||||
__device__ __forceinline__ unsigned rowGo(unsigned rowstride, int row0, int lim,
|
||||
int lane) {
|
||||
int r = row0 + (lane & 15);
|
||||
r = r < lim ? r : lim;
|
||||
return (unsigned)r * rowstride;
|
||||
}
|
||||
__device__ __forceinline__ v16bf fragGo(const unsigned short* base, unsigned off) {
|
||||
return fragP(base + off);
|
||||
}
|
||||
|
||||
// Fragment from a 32-bit LDS byte offset off the shared-block base. Holding the
|
||||
// offset in one opaque register keeps the two dwordx4 as immediates rather than
|
||||
// letting LLVM rematerialise a base add in front of every fragment.
|
||||
__device__ __forceinline__ v16bf fragO(const char* sb, unsigned off) {
|
||||
return fragP((const unsigned short*)(sb + off));
|
||||
}
|
||||
#define LDSOPAQUE(x) asm("" : "+v"(x))
|
||||
|
||||
// K-contiguous fragment: src[idx][k], row pitch `pitch` (in elements)
|
||||
__device__ __forceinline__ v16bf frag(const unsigned short* src, int pitch,
|
||||
int base, int kbase, int lane) {
|
||||
return fragP(rowP(src, pitch, base, lane) + kbase);
|
||||
}
|
||||
|
||||
// Same fragment, source stored transposed: src[k][idx]. 16 scalar reads on gfx11
|
||||
// against 8 on gfx12 -- the one place the wider fragment costs rather than saves.
|
||||
__device__ __forceinline__ v16bf fragT(const unsigned short* src, int pitch,
|
||||
int base, int kbase, int lane) {
|
||||
const int idx = base + (lane & 15);
|
||||
union { unsigned short h[16]; v16bf f; } u;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 16; ++e) u.h[e] = src[(size_t)(kbase + e) * pitch + idx];
|
||||
return u.f;
|
||||
}
|
||||
|
||||
// Fragment straight from global memory (no LDS staging). `lim` clamps the row so a
|
||||
// partial last chunk cannot read past the tensor.
|
||||
__device__ __forceinline__ v16bf 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;
|
||||
return fragP(base + (size_t)r * rowstride + kbase);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v8f mma(v16bf a, v16bf b, v8f c) {
|
||||
return halo::mma(a, b, c);
|
||||
}
|
||||
|
||||
// C[mt*16..][nt*16..] += A[M][KA] @ B[N][KA]^T over KSTEP 16-wide steps
|
||||
template <int KSTEP>
|
||||
__device__ __forceinline__ v8f gemm(const unsigned short* A, int Ap, int mt,
|
||||
const unsigned short* B, int Bp, int nt,
|
||||
int lane, v8f acc) {
|
||||
#pragma unroll
|
||||
for (int s = 0; s < KSTEP; ++s)
|
||||
acc = mma(frag(A, Ap, mt * 16, s * 16, lane),
|
||||
frag(B, Bp, nt * 16, s * 16, lane), acc);
|
||||
return acc;
|
||||
}
|
||||
|
||||
// Where a result element lives. gfx11 wave32 puts D[2*e + (lane>>4)][lane & 15] in
|
||||
// element e, which is NOT gfx12's mapping -- any kernel that writes an accumulator
|
||||
// out by hand has to use these rather than the row/col arithmetic it came with.
|
||||
__device__ __forceinline__ int accRow(int lane, int e) { return 2 * e + (lane >> 4); }
|
||||
__device__ __forceinline__ int accCol(int lane) { return lane & 15; }
|
||||
|
||||
// ---- writing an accumulator out ------------------------------------------------
|
||||
// gfx11 hands lane l element e the value D[2e + (l>>4)][l & 15]: eight rows of ONE
|
||||
// column, stride two. libr4d's gfx12 mapping is D[8*(l>>4) + e][l & 15] -- eight
|
||||
// CONSECUTIVE rows -- which is why every one of its accumulator write-outs is a
|
||||
// single 16-byte store of a transposed tile. Ported naively that inverts into eight
|
||||
// strided 2-byte stores.
|
||||
//
|
||||
// It need not. The partner lane l^16 holds exactly the eight rows interleaved
|
||||
// between this lane's, so ONE cross-half exchange per dword reassembles sixteen
|
||||
// consecutive rows, and each half-wave then owns eight of them -- the same single
|
||||
// 16-byte store, for four v_permlanex16.
|
||||
//
|
||||
// Exchange the half the PARTNER needs rather than the half this lane owns: that is
|
||||
// what keeps it at four shuffles instead of eight (a shuffle reads one VGPR for the
|
||||
// whole wave, so the two halves cannot ask for different elements).
|
||||
//
|
||||
// v[] must ALREADY be scaled per element, because the two halves are scaling
|
||||
// different rows -- see the gram store in halo_gdn_kkt_solve.hip.
|
||||
__device__ __forceinline__ uint4 accPack(const float v[8], int lane) {
|
||||
const int hi = lane >> 4;
|
||||
uint32_t w[4];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const float mine = hi ? v[i + 4] : v[i]; // the row this lane already holds
|
||||
const float send = hi ? v[i] : v[i + 4]; // the row the partner is missing
|
||||
const float got = halo::swap16(send);
|
||||
w[i] = hi ? halo::pk_bf16(got, mine) : halo::pk_bf16(mine, got);
|
||||
}
|
||||
return make_uint4(w[0], w[1], w[2], w[3]);
|
||||
}
|
||||
// First row of the eight accPack() returns for this lane.
|
||||
__device__ __forceinline__ int accPackRow(int lane) { return 8 * (lane >> 4); }
|
||||
|
||||
// accPack() with the same values and rounding, for a kernel where the write-out sits on the
|
||||
// critical path. accPack() exchanges four floats per lane through halo::swap16 -- a __shfl_xor,
|
||||
// so ds_bpermute_b32 and an LDS wait per dword -- and LLVM lowers its
|
||||
// `hi ? pk(got, mine) : pk(mine, got)` to a divergent branch around each pack. This one rounds
|
||||
// first (pk_bf16's round-to-nearest-even, the same bits), so the partner's four rows travel as two
|
||||
// packed dwords over v_permlanex16, and the half-dependent order of the final pairs is a per-lane
|
||||
// v_perm selector rather than a select per value:
|
||||
//
|
||||
// p[i] = {v[2i], v[2i+1]} rows {4i + hi, 4i + 2 + hi}
|
||||
// lanes 0-15 keep p[0..1] and need the partner's p[0..1] (rows 1, 3, 5, 7)
|
||||
// lanes 16-31 keep p[2..3] and need the partner's p[2..3] (rows 8, 10, 12, 14)
|
||||
//
|
||||
// Same precondition as accPack(): the whole wave is active.
|
||||
__device__ __forceinline__ uint4 accPackX(const float v[8], int lane) {
|
||||
const bool hi = (lane >> 4) != 0;
|
||||
uint32_t r[8], p[4];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) { // f32_to_bf16's rounding, the result in the high half
|
||||
const uint32_t u = __builtin_bit_cast(uint32_t, v[e]);
|
||||
r[e] = u + 0x7fffu + ((u >> 16) & 1u);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) p[i] = __builtin_amdgcn_perm(r[2 * i + 1], r[2 * i], 0x07060302u);
|
||||
const uint32_t k0 = hi ? p[2] : p[0], k1 = hi ? p[3] : p[1]; // kept
|
||||
const uint32_t g0 = halo_xor_lane_u32<16>(hi ? p[0] : p[2]); // got: the partner's kept
|
||||
const uint32_t g1 = halo_xor_lane_u32<16>(hi ? p[1] : p[3]);
|
||||
// {own, partner} below, {partner, own} above: low halves, then high halves.
|
||||
const uint32_t sl = hi ? 0x01000504u : 0x05040100u, sh = hi ? 0x03020706u : 0x07060302u;
|
||||
return make_uint4(__builtin_amdgcn_perm(g0, k0, sl), __builtin_amdgcn_perm(g0, k0, sh),
|
||||
__builtin_amdgcn_perm(g1, k1, sl), __builtin_amdgcn_perm(g1, k1, sh));
|
||||
}
|
||||
|
||||
// Byte offset, from the base of a shared block, of the fragment row this lane reads out
|
||||
// of `buf[base + (lane&15)][...]` with the given row pitch in elements.
|
||||
//
|
||||
// This is the gfx11 form of libr4d's ROWO macro, and the difference is the whole port in
|
||||
// one line: gfx12 adds `4 * (lane >> 4)` because the half-wave selects which quarter of
|
||||
// the k run the lane holds, and gfx11 has no such term because the lane holds all of it.
|
||||
// Every LDS fragment site in a ported kernel goes through here, so getting it wrong is a
|
||||
// single-point failure rather than a scattered one.
|
||||
__device__ __forceinline__ unsigned rowO(unsigned buf_off, int pitch, int base, int lane) {
|
||||
return buf_off + (unsigned)(((base + (lane & 15)) * pitch) * 2);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/* Derived from libr4d/r4d_gelu_mul_quant_i8.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gelu_mul_quant_i8.hip - halo_gelu_mul_quant_i8: gelu(gate) * up and the per-row int8 quantiser
|
||||
// halo_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, 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 "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_emit.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_chain.h"
|
||||
#include <cstdint>
|
||||
|
||||
namespace {
|
||||
|
||||
// CHAIN brackets the body with the chained launch's wait and add (halo_chain.h); every block runs
|
||||
// to the end. The plain kernel and the chained one (halo_r4dchain*) follow.
|
||||
template <uint32_t THR, bool CHAIN>
|
||||
__device__ __forceinline__ void gelu_mul_quant_i8_body(
|
||||
const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S,
|
||||
uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
|
||||
if (CHAIN) halo_chain_wait();
|
||||
extern __shared__ uint16_t ybuf[];
|
||||
__shared__ float lm[THR / 32];
|
||||
const uint32_t row = blockIdx.x;
|
||||
const uint16_t* __restrict__ gr = gu + (size_t)row * gu_ld;
|
||||
signed char* __restrict__ qr = q + (size_t)row * n;
|
||||
|
||||
float m = 0.0f;
|
||||
for (uint32_t i = threadIdx.x; i < n; i += THR) {
|
||||
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 * bf16_to_f32(gr[n + i]));
|
||||
ybuf[i] = y;
|
||||
if (yo) yo[(size_t)row * y_ld + i] = y;
|
||||
m = fmaxf(m, fabsf(bf16_to_f32(y)));
|
||||
}
|
||||
m = halo_wave_max(m);
|
||||
if ((threadIdx.x & 31) == 0) lm[threadIdx.x >> 5] = m;
|
||||
__syncthreads(); // also publishes ybuf to every thread
|
||||
m = lm[0];
|
||||
#pragma unroll
|
||||
for (uint32_t i = 1; i < THR / 32; i++) m = fmaxf(m, lm[i]);
|
||||
const float scale = fmaxf(m, 1e-8f) / 127.f;
|
||||
const float inv = 1.f / scale;
|
||||
if (threadIdx.x == 0) S[row] = scale;
|
||||
// quant_act_i8's fragment order, see halo_quant_act_i8.hip
|
||||
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(bf16_to_f32(ybuf[src]) * inv);
|
||||
qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
|
||||
}
|
||||
if (CHAIN) halo_chain_done();
|
||||
}
|
||||
|
||||
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,
|
||||
uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
|
||||
gelu_mul_quant_i8_body<THR, false>(gu, q, S, yo, n, gu_ld, y_ld);
|
||||
}
|
||||
template <uint32_t THR>
|
||||
__global__ __launch_bounds__(THR) void halo_r4dchain_gelu_mul_quant_i8(
|
||||
const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S,
|
||||
uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
|
||||
gelu_mul_quant_i8_body<THR, true>(gu, q, S, yo, n, gu_ld, y_ld);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Operands (halo_rows.cpp, oGeluMulQuantI8): gate_up [M][2n] bf16 (gate first), q [M][n] int8 in the
|
||||
// fragment order, scale [M][1] f32, out_bf16 [M][n] bf16 optional.
|
||||
enum { GM_GU = 0, GM_Q, GM_S, GM_Y };
|
||||
|
||||
extern "C" int halo_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream stream) {
|
||||
int emit_rc = RAD_OK;
|
||||
const RadTensor* gu = halo_opt(a, GM_GU);
|
||||
const RadTensor* q = halo_opt(a, GM_Q);
|
||||
const RadTensor* s = halo_opt(a, GM_S);
|
||||
const RadTensor* y = halo_opt(a, GM_Y);
|
||||
if (!gu || !q || !s) return HALO_NO(RAD_E_INVAL);
|
||||
if (gu->dtype != RAD_BF16 || q->dtype != RAD_I8 || s->dtype != RAD_F32) return HALO_NO(RAD_E_DTYPE);
|
||||
long long M = 0, n = 0;
|
||||
if (halo_rows_of(q, &M, &n) != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
if (n % 16 || !halo_contig(q)) return HALO_NO(RAD_E_SHAPE);
|
||||
long long Mg = 0;
|
||||
const long long gp = halo_rows_pitch(gu, 2 * n, &Mg);
|
||||
if (gp < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
if (Mg < M) return HALO_NO(RAD_E_SHAPE);
|
||||
if (halo_numel(s) != M || !halo_contig(s)) return HALO_NO(RAD_E_SHAPE);
|
||||
if (y && halo_numel(y) != M * n) return HALO_NO(RAD_E_SHAPE);
|
||||
const long long yp = y ? halo_row_pitch(y) : n;
|
||||
if (yp < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
const size_t lds = (size_t)n * sizeof(uint16_t);
|
||||
if (lds > 60 * 1024) return HALO_NO(RAD_E_SHAPE);
|
||||
const int thr = halo_act_threads((int)M, (int)n);
|
||||
const bool chain = halo_geti_or(a, "chain", 0) != 0 && M <= 64; /* RadKernelChainFn, decode */
|
||||
#define HALO_GMQ_C(T, C) HALO_EMIT(stream, (C ? halo_r4dchain_gelu_mul_quant_i8<T> : gelu_mul_quant_i8_kernel<T>), \
|
||||
dim3((uint32_t)M), dim3(T), lds, \
|
||||
(const uint16_t*)halo_p(gu), (signed char*)halo_wp(q), (float*)halo_wp(s), (uint16_t*)halo_wp(y), \
|
||||
(uint32_t)n, (uint32_t)gp, (uint32_t)yp)
|
||||
#define HALO_GMQ_T(T) emit_rc = chain ? HALO_GMQ_C(T, true) : HALO_GMQ_C(T, false)
|
||||
if (thr == 1024) HALO_GMQ_T(1024);
|
||||
else if (thr == 512) HALO_GMQ_T(512);
|
||||
else if (thr == 256) HALO_GMQ_T(256);
|
||||
else return HALO_NO(RAD_E_INVAL);
|
||||
#undef HALO_GMQ_T
|
||||
#undef HALO_GMQ_C
|
||||
return emit_rc;
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
/* Derived from libr4d/r4d_gemm_args.h by the libhalo rename transform (2026-10-26);
|
||||
* see libhalo/README.md. Op schemas, row names and stored weight layouts are
|
||||
* shared with libr4d by design. Everything else in this file is libhalo's own
|
||||
* and diverges as it is measured on gfx1151. */
|
||||
/* halo_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
|
||||
* so an out-of-tree kernel library carries its own rule. The tunable axes (halo_rows.cpp) are what
|
||||
* a tuner walks; this resolves a shape left on the axis defaults.
|
||||
*
|
||||
* 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 HALO_GEMM_ARGS_H
|
||||
#define HALO_GEMM_ARGS_H
|
||||
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
|
||||
|
||||
/* 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 halo_args.h's layout constant. */
|
||||
#define HALO_GEMM_W4_GROUP 128
|
||||
#define HALO_GEMM_W8_GROUP 128
|
||||
#define HALO_GEMM_W4A8_GROUP 128
|
||||
#define HALO_GEMM_W8A8_GROUP 128
|
||||
#define HALO_GEMM_W2A8_GROUP 128
|
||||
static_assert(HALO_W4_GROUP == HALO_GEMM_W4_GROUP, "w4 group differs from the layout constant");
|
||||
static_assert(HALO_W8_GROUP == HALO_GEMM_W8_GROUP, "w8 group differs from the layout constant");
|
||||
static_assert(HALO_W4_GROUP == HALO_GEMM_W4A8_GROUP, "w4a8 group differs from the layout constant");
|
||||
static_assert(HALO_W8_GROUP == HALO_GEMM_W8A8_GROUP, "w8a8 group differs from the layout constant");
|
||||
static_assert(HALO_W2_GROUP == HALO_GEMM_W2A8_GROUP, "w2a8 group differs from the layout constant");
|
||||
|
||||
|
||||
static inline int gemm_caught(const char* who, const char* what) {
|
||||
static bool said = false;
|
||||
if (!said) {
|
||||
said = true;
|
||||
std::fprintf(stderr, "[r4d] %s threw: %s\n", who, what ? what : "(null)");
|
||||
}
|
||||
return HALO_NO(RAD_E_DEVICE);
|
||||
}
|
||||
|
||||
#define HALO_TRY(who, ...) \
|
||||
do { \
|
||||
try { __VA_ARGS__; } \
|
||||
catch (const std::exception& e_) { return gemm_caught(who, e_.what()); } \
|
||||
catch (...) { return gemm_caught(who, "unknown exception"); } \
|
||||
} while (0)
|
||||
|
||||
/* ------------------------------------------------------------------ the split count
|
||||
*
|
||||
* 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 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.
|
||||
*
|
||||
* 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 };
|
||||
|
||||
static inline int block_bound(BoundRule r, int mb, int npw) {
|
||||
switch (r) {
|
||||
case BR_W2A8: return (mb >= 4) ? 256 : (((mb >= 2) || (npw >= 4)) ? 512 : 1024);
|
||||
case BR_NPW: return (npw >= 8) ? 256 : ((npw >= 4) ? 512 : 1024);
|
||||
case BR_MBNPW: return (mb * npw >= 8) ? 256 : ((mb * npw >= 4) ? 512 : 1024);
|
||||
default: return 1024;
|
||||
}
|
||||
}
|
||||
|
||||
/* 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(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 || unit <= 0 || (K % ((long long)s * unit))) continue;
|
||||
best = s;
|
||||
if (n_tiles > 0 && n_tiles * s >= (long long)kFlatTileTarget) return s;
|
||||
}
|
||||
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 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, int npw_default = 1, int sk_cap = 0) {
|
||||
HaloGemmCfg cv;
|
||||
halo_cfg_gemm(a, &cv);
|
||||
const HaloGemmCfg* c = &cv;
|
||||
out->wv = c->wv > 0 ? c->wv : 1;
|
||||
/* 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;
|
||||
/* 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.
|
||||
*
|
||||
* 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
|
||||
* (halo_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;
|
||||
/* halo_cfg_gemm always materialises the shared table's default, so an untuned axis
|
||||
* is invisible in `c`; the caller's own default applies only where the launch
|
||||
* carries no explicit "npw" tunable. */
|
||||
out->npw = c->npw > 0 ? c->npw : npw_default;
|
||||
if (npw_default != 1 && halo_geti_or(a, "npw", 0) <= 0) out->npw = npw_default;
|
||||
out->nt = c->nt;
|
||||
/* 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.
|
||||
*
|
||||
* 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;
|
||||
out->npw = 4;
|
||||
sk_pin = 8;
|
||||
}
|
||||
const int bound = block_bound(br, out->mb, out->npw);
|
||||
if (sk_pin && (out->wv * sk_pin * 32 > bound ||
|
||||
(unit > 0 && (K % ((long long)sk_pin * unit)))))
|
||||
sk_pin = 0;
|
||||
out->sk = c->sk > 0 ? c->sk : (sk_pin ? sk_pin : pick_sk(n_tiles, K, unit, out->wv, bound));
|
||||
/* A caller-capped split (mxfp4: the ladder's largest legal split, 20, over-splits on
|
||||
* gfx1151 -- the wave's K walk shortens past the point where the LDS reduction and
|
||||
* the extra activation re-reads pay; 8..16 measured flat, 20 ~25% slower). Only the
|
||||
* untuned path is capped, and only to a split this K still divides. */
|
||||
if (sk_cap > 0 && c->sk <= 0 && out->sk > sk_cap) {
|
||||
for (int s = sk_cap; s >= 1; --s) {
|
||||
if (out->wv * s * 32 <= bound && (unit <= 0 || (K % ((long long)s * unit)) == 0)) {
|
||||
out->sk = s;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* 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 HALO_NO(RAD_E_UNSUPPORTED);
|
||||
/* 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 HALO_NO(RAD_E_SHAPE);
|
||||
/* HALO_GEMMCFG=1 prints each distinct (tuned point, K, M, n_tiles) resolution once. */
|
||||
static const bool dbg = [] { const char* e = std::getenv("HALO_GEMMCFG");
|
||||
return e && e[0] && e[0] != '0'; }();
|
||||
if (dbg) {
|
||||
/* 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)
|
||||
^ ((uint64_t)(unsigned)br << 52)
|
||||
^ ((uint64_t)(unsigned)n_tiles << 26) ^ (uint64_t)(unsigned)M
|
||||
^ ((uint64_t)(unsigned)K << 13);
|
||||
int i = 0;
|
||||
while (i < nseen && seen[i] != key) ++i;
|
||||
if (i == nseen && nseen < 64) {
|
||||
seen[nseen++] = key;
|
||||
std::fprintf(stderr,
|
||||
"[gemmcfg] K=%lld M=%lld tiles=%lld br=%d -> wv=%d sk=%d mb=%d npw=%d nt=%d\n",
|
||||
(long long)K, (long long)M, (long long)n_tiles, (int)br,
|
||||
out->wv, out->sk, out->mb, out->npw, out->nt);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ operand plumbing */
|
||||
|
||||
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 {
|
||||
/* 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. 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 HALO_NO(RAD_E_INVAL);
|
||||
long long cols = 1, rstride = 1;
|
||||
if (s->rank >= 2) {
|
||||
cols = s->shape[s->rank - 1];
|
||||
rstride = s->stride[s->rank - 2];
|
||||
if (s->shape[s->rank - 2] < g.M) return HALO_NO(RAD_E_SHAPE);
|
||||
} else if (s->rank == 1) {
|
||||
if (s->shape[0] < g.M) return HALO_NO(RAD_E_SHAPE);
|
||||
cols = s->shape[0] / g.M;
|
||||
rstride = cols;
|
||||
}
|
||||
const long long kb = (g.K + 127) / 128;
|
||||
/* 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 HALO_NO(RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* 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 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. 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 };
|
||||
long long lda = 0; /* 0: the plane's own K */
|
||||
};
|
||||
|
||||
/* The bounds `pb1`/`pb2` name over N rows, as every reader takes them: { 0, e1, e2, N }, part i
|
||||
* being [bound[i], bound[i+1]). Returns how many copies of the activation they imply, 1..3. */
|
||||
static inline int mx_part_bounds(long long N, long long pb1, long long pb2, long long bound[4]) {
|
||||
const long long e1 = pb1 > 0 && pb1 < N ? pb1 : N;
|
||||
long long e2 = pb2 > 0 && pb2 < N ? pb2 : N;
|
||||
if (e2 < e1) e2 = e1;
|
||||
bound[0] = 0;
|
||||
bound[1] = e1;
|
||||
bound[2] = e2;
|
||||
bound[3] = N;
|
||||
return e2 < N ? 3 : (e1 < N ? 2 : 1);
|
||||
}
|
||||
|
||||
static inline int mx_parts(const RadArgs* a, GemmOps* g, MxParts* p) {
|
||||
p->n = 1;
|
||||
p->n0[0] = 0;
|
||||
p->n1[0] = g->N;
|
||||
p->lda = 0;
|
||||
long long bound[4];
|
||||
const int segs = mx_part_bounds(g->N, halo_geti_or(a, "pb1", 0), halo_geti_or(a, "pb2", 0), bound);
|
||||
if (segs == 1) return RAD_OK;
|
||||
const long long K = halo_geti_or(a, "K", 0);
|
||||
if (K <= 0) return HALO_NO(RAD_E_INVAL);
|
||||
if (g->K != (long long)segs * K || (bound[1] % 16) || (bound[2] % 16)) return HALO_NO(RAD_E_SHAPE);
|
||||
p->n = 0;
|
||||
for (int i = 0; i < 3; ++i)
|
||||
if (bound[i + 1] > bound[i]) {
|
||||
p->n0[p->n] = bound[i];
|
||||
p->n1[p->n] = bound[i + 1];
|
||||
++p->n;
|
||||
}
|
||||
if (p->n != segs) return HALO_NO(RAD_E_SHAPE); /* an empty middle part has no copy to meet */
|
||||
p->lda = g->K;
|
||||
g->K = K;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* gemm_nt_q's MXFP4 GEMM through the LDS-staged tile (halo_gemm_mxfp4a8_tiled.hip) at `sk` splits:
|
||||
* nt_m64's bytes at that split, for the gemv and decode rows past one row tile. RAD_E_UNSUPPORTED
|
||||
* (quietly) where the tile does not take the shape; the caller then runs its own kernel. */
|
||||
__attribute__((visibility("hidden")))
|
||||
int halo_mxfp4a8_tiled_split(const RadArgs* a, RadStream s, const GemmOps& g, const MxParts& mp,
|
||||
int as_group, int as_rs, int sk);
|
||||
|
||||
/* 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 HALO_NO(RAD_E_SHAPE);
|
||||
if ((*t)->rank == 2) return RAD_OK;
|
||||
if (!halo_contig(*t)) return HALO_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 && (halo_geti_or(a, "pb1", 0) > 0 || halo_geti_or(a, "pb2", 0) > 0))
|
||||
return HALO_NO(RAD_E_UNSUPPORTED);
|
||||
if (quantised) {
|
||||
g->a = halo_opt(a, Q_A);
|
||||
g->ascale = halo_opt(a, Q_ASCALE);
|
||||
g->b = halo_opt(a, Q_B);
|
||||
g->bscale = halo_opt(a, Q_BSCALE);
|
||||
g->y = halo_opt(a, Q_Y);
|
||||
g->asum = halo_opt(a, Q_ASUM);
|
||||
g->bref = halo_opt(a, Q_BREF);
|
||||
if (!g->a || !g->b || !g->bscale || !g->y) return HALO_NO(RAD_E_INVAL);
|
||||
} else {
|
||||
g->a = halo_opt(a, G_A);
|
||||
g->b = halo_opt(a, G_B);
|
||||
g->y = halo_opt(a, G_Y);
|
||||
if (!g->a || !g->b || !g->y) return HALO_NO(RAD_E_INVAL);
|
||||
}
|
||||
/* 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 (!halo_contig(g->a) || !halo_contig(g->y)) return HALO_NO(RAD_E_STRIDE);
|
||||
if (!halo_aligned(g->a->data, 16) || !halo_aligned(g->b->data, 16)) return HALO_NO(RAD_E_ALIGN);
|
||||
|
||||
g->M = g->a->shape[0];
|
||||
g->K = g->a->shape[1];
|
||||
g->N = g->y->shape[1];
|
||||
if (g->y->shape[0] != g->M) return HALO_NO(RAD_E_SHAPE);
|
||||
if (g->M < 1 || g->N < 1 || g->K < 1) return HALO_NO(RAD_E_SHAPE);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/* 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 = halo_gets(a, "dtype");
|
||||
return dt && std::strstr(dt, "_asym") != nullptr;
|
||||
}
|
||||
|
||||
/* The tiled and prefill kernels take an opaque tile variant into libhalo'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 HaloTileCfg* t, long long N) {
|
||||
if (!t) return HALO_NO(RAD_E_INVAL);
|
||||
if (t->bn > 0 && (N % t->bn)) return HALO_NO(RAD_E_SHAPE);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
#endif /* HALO_GEMM_ARGS_H */
|
||||
@@ -0,0 +1,173 @@
|
||||
/* The kernel is carried over from the strix-halo-vllm project's libhalo
|
||||
* (halo_gemm_bf16_nt.hip), itself a port of libr4d's earlier dot2 m16 kernel,
|
||||
* measured on this part in production; see libhalo/README.md. The shim and
|
||||
* split law are written for radiance. */
|
||||
// halo_gemm_bf16_nt_m16.hip - halo_gemm_bf16_nt_m16: skinny bf16 GEMM at M <= 16, gfx1151.
|
||||
//
|
||||
// C[M,N] = A[M,K] @ W[N,K]^T, bf16 in and out, fp32 accumulate. A wave owns one output column
|
||||
// and one contiguous K slice (SK splits, reduced through LDS in split order, so the result does
|
||||
// not depend on scheduling); each lane holds eight consecutive K of the slice and dots them with
|
||||
// v_dot2_f32_bf16. No WMMA: at these heights the weight read is the whole cost and this streams
|
||||
// it faster than the fragment form (halo_gemm_bf16_nt_m64.hip) -- the opposite of the R9700,
|
||||
// where libr4d retired this kernel in favour of forwarding to its WMMA. The reduction tree
|
||||
// differs from the WMMA row's, so the two rows' outputs differ in low bits; each is
|
||||
// deterministic. Weight loads for the whole slice are issued up front (eight 256-element tiles
|
||||
// in registers) so the latency overlaps the dots.
|
||||
//
|
||||
// A masked tail tile means K/SK need only be a multiple of 8 (VEC), not of 256: masking is at
|
||||
// lane granularity and no lane ever holds a partial 128-bit load.
|
||||
#include "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
|
||||
#define WAVE 32
|
||||
#define VEC 8 // bf16 per 128-bit (dwordx4) load
|
||||
#define HALO_GEMM16_MAX_M 16
|
||||
|
||||
typedef int int4v __attribute__((ext_vector_type(4)));
|
||||
typedef __bf16 bf162 __attribute__((ext_vector_type(2))); // v_dot2_f32_bf16 operand
|
||||
|
||||
template <int MT, int TEMPORAL>
|
||||
__global__ __launch_bounds__(1024) void halo_gemm_bf16_nt_m16_kernel(
|
||||
const __hip_bfloat16* __restrict__ A, const __hip_bfloat16* __restrict__ W,
|
||||
__hip_bfloat16* __restrict__ C, int K, int N, int WV, int SK) {
|
||||
extern __shared__ float red[]; // WV*SK*MT split-K scratch
|
||||
const int tid = threadIdx.x, wave = tid / WAVE, lane = tid % WAVE;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
const int j = blockIdx.x * WV + col_local;
|
||||
const int Ks = K / SK, kbase = ksplit * Ks;
|
||||
|
||||
float acc[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; ++i) acc[i] = 0.f;
|
||||
|
||||
if (j < N) {
|
||||
const __hip_bfloat16* Wj = W + (size_t)j * K + kbase + lane * VEC;
|
||||
const int niter = Ks / (WAVE * VEC);
|
||||
const int rem = Ks - niter * (WAVE * VEC);
|
||||
const int tail_lanes = rem / VEC;
|
||||
const bool has_tail = rem > 0 && lane < tail_lanes;
|
||||
int4v wbuf[8];
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 8; ++t) // all weight loads up-front
|
||||
if (t < niter) wbuf[t] = TEMPORAL ? *(const int4v*)(Wj + t * WAVE * VEC)
|
||||
: __builtin_nontemporal_load((const int4v*)(Wj + t * WAVE * VEC));
|
||||
int4v wtail;
|
||||
if (has_tail) {
|
||||
const __hip_bfloat16* Wt = Wj + niter * WAVE * VEC;
|
||||
wtail = TEMPORAL ? *(const int4v*)Wt
|
||||
: __builtin_nontemporal_load((const int4v*)Wt);
|
||||
}
|
||||
for (int t = 0; t < niter; ++t) {
|
||||
const bf162* wp = (const bf162*)&wbuf[t];
|
||||
const int kk = kbase + lane * VEC + t * WAVE * VEC;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; ++i) {
|
||||
int4 av = *(const int4*)(A + (size_t)i * K + kk);
|
||||
const bf162* ap = (const bf162*)&av;
|
||||
#pragma unroll
|
||||
for (int p = 0; p < VEC / 2; ++p)
|
||||
acc[i] = __builtin_amdgcn_fdot2_f32_bf16(ap[p], wp[p], acc[i], false);
|
||||
}
|
||||
}
|
||||
if (has_tail) {
|
||||
const bf162* wp = (const bf162*)&wtail;
|
||||
const int kk = kbase + lane * VEC + niter * WAVE * VEC;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; ++i) {
|
||||
int4 av = *(const int4*)(A + (size_t)i * K + kk);
|
||||
const bf162* ap = (const bf162*)&av;
|
||||
#pragma unroll
|
||||
for (int p = 0; p < VEC / 2; ++p)
|
||||
acc[i] = __builtin_amdgcn_fdot2_f32_bf16(ap[p], wp[p], acc[i], false);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; ++i) {
|
||||
float v = acc[i];
|
||||
for (int off = WAVE / 2; off > 0; off >>= 1) v += __shfl_xor(v, off);
|
||||
if (lane == 0) red[(col_local * SK + ksplit) * MT + i] = v;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (ksplit == 0 && j < N && lane < MT) { // split-K reduce, one column of C
|
||||
float v = 0.f;
|
||||
for (int s = 0; s < SK; ++s) v += red[(col_local * SK + s) * MT + lane];
|
||||
C[(size_t)lane * N + j] = (__hip_bfloat16)v;
|
||||
}
|
||||
}
|
||||
|
||||
static int gemm_bf16_m16_launch(long a, long w, long c, int M, int K, int N, int WV, int SK,
|
||||
int nt, long stream) {
|
||||
if (M < 1 || M > HALO_GEMM16_MAX_M) return -1;
|
||||
if (K % SK != 0 || (K / SK) % VEC != 0) return -2;
|
||||
if (WV * SK * WAVE > 1024) return -3;
|
||||
if ((K / SK) / (WAVE * VEC) > 8) return -4; // wbuf holds 8 tiles
|
||||
dim3 grid((N + WV - 1) / WV), block(WV * SK * WAVE);
|
||||
size_t smem = (size_t)WV * SK * M * sizeof(float);
|
||||
auto A = (const __hip_bfloat16*)a; auto Wp = (const __hip_bfloat16*)w;
|
||||
auto Cp = (__hip_bfloat16*)c; auto st = (hipStream_t)stream;
|
||||
#define LAUNCH(MT) \
|
||||
do { if (nt) hipLaunchKernelGGL((halo_gemm_bf16_nt_m16_kernel<MT, 0>), grid, block, smem, st, A, Wp, Cp, K, N, WV, SK); \
|
||||
else hipLaunchKernelGGL((halo_gemm_bf16_nt_m16_kernel<MT, 1>), grid, block, smem, st, A, Wp, Cp, K, N, WV, SK); } while (0)
|
||||
switch (M) {
|
||||
case 1: LAUNCH(1); break; case 2: LAUNCH(2); break; case 3: LAUNCH(3); break;
|
||||
case 4: LAUNCH(4); break; case 5: LAUNCH(5); break; case 6: LAUNCH(6); break;
|
||||
case 7: LAUNCH(7); break; case 8: LAUNCH(8); break; case 9: LAUNCH(9); break;
|
||||
case 10: LAUNCH(10); break; case 11: LAUNCH(11); break; case 12: LAUNCH(12); break;
|
||||
case 13: LAUNCH(13); break; case 14: LAUNCH(14); break; case 15: LAUNCH(15); break;
|
||||
case 16: LAUNCH(16); break; default: return -1;
|
||||
}
|
||||
#undef LAUNCH
|
||||
return hipGetLastError() == hipSuccess ? 0 : -5;
|
||||
}
|
||||
|
||||
int halo_gemm_bf16_nt_m16(long a, long w, long c, int M, int K, int N, int WV, int SK, int nt,
|
||||
long stream) {
|
||||
return gemm_bf16_m16_launch(a, w, c, M, K, N, WV, SK, nt, stream);
|
||||
}
|
||||
|
||||
int halo_gemm_bf16_nt_m16_max_m(void) { return HALO_GEMM16_MAX_M; }
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
//
|
||||
// The operand reader is halo_gemm_args.h. The split law is this kernel's own: cfg_for's unit
|
||||
// law would insist on K % (SK*256) == 0 and can pick SK=1 at large N, which this kernel's
|
||||
// eight-tile register file refuses at large K. A tuned (wv, sk, nt) is honoured when legal;
|
||||
// a shape no legal split serves goes to the WMMA row's shim, which owns the rest of the band.
|
||||
extern "C" int halo_rad_gemm_bf16_m64(const RadArgs*, RadStream);
|
||||
|
||||
static bool m16_legal(int K, int WV, int SK) {
|
||||
return SK >= 1 && WV >= 1 && WV * SK * WAVE <= 1024 && K % SK == 0 &&
|
||||
((K / SK) % VEC) == 0 && (K / SK) / (WAVE * VEC) <= 8;
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_gemm_bf16_m16(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 0);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.M < 1 || g.M > HALO_GEMM16_MAX_M) return HALO_NO(RAD_E_SHAPE);
|
||||
HaloGemmCfg cv;
|
||||
halo_cfg_gemm(a, &cv);
|
||||
const int wv = cv.wv > 0 ? cv.wv : 1;
|
||||
int sk = cv.sk;
|
||||
if (sk <= 0 || !m16_legal((int)g.K, wv, sk)) {
|
||||
/* The smallest legal split that puts one full card of waves (1280) in flight; the
|
||||
* largest legal split when even that is not reachable. */
|
||||
static const int ladder[] = { 1, 2, 4, 5, 8, 10, 16, 20, 32 };
|
||||
sk = 0;
|
||||
for (int cand : ladder) {
|
||||
if (!m16_legal((int)g.K, wv, cand)) continue;
|
||||
sk = cand;
|
||||
if (g.N * cand >= 1280) break;
|
||||
}
|
||||
if (!sk) return halo_rad_gemm_bf16_m64(a, s);
|
||||
}
|
||||
rc = gemm_bf16_m16_launch(halo_addr(g.a), halo_addr(g.b), halo_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, wv, sk, cv.nt,
|
||||
(long)(uintptr_t)s);
|
||||
if (rc != 0) return halo_rad_gemm_bf16_m64(a, s);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
/* Derived from libr4d/r4d_gemm_bf16_nt_m64.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_bf16_nt_m64.hip - halo_gemm_bf16_nt_m64: skinny bf16 GEMM at any M, gfx1151.
|
||||
//
|
||||
// C[M,N] = A[M,K] @ W[N,K]^T, bf16 in and out, fp32 accumulate.
|
||||
//
|
||||
// General in M up to HALO_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.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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: rows past M or N re-read the last valid row and their
|
||||
// results are never stored.
|
||||
#include "halo.h"
|
||||
#include "halo_launch.h" // HALO_DYN_LDS: tests/halo_emu runs this unit on the host
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include "halo_chain.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define HALO_GEMM64_MAX_M 65536
|
||||
#define WAVE32 32
|
||||
|
||||
// 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 global: a plain pointer held in an array across iterations becomes
|
||||
// generic, so loads become flat_load_b64, which on RDNA also increments dscnt and makes later LDS
|
||||
// waits wait on global memory. The element is a scalar because HIP's vector structs cannot be
|
||||
// assigned from an address-space-qualified source.
|
||||
//
|
||||
// gfx11 form: the fragment is the row's whole 16-wide k run, 32 contiguous bytes (halo_wmma.h),
|
||||
// where libr4d's gfx12 form is two 8-byte halves sixteen bytes apart. The pointer arithmetic is
|
||||
// unchanged -- a k step is 32 bytes either way -- only what one step loads differs.
|
||||
typedef unsigned halo_u4v __attribute__((ext_vector_type(4)));
|
||||
typedef __attribute__((address_space(1))) const halo_u4v* halo_gu4;
|
||||
|
||||
__device__ __forceinline__ v16bf fragU(halo_gu4 p, int u) {
|
||||
union { halo_u4v w[2]; v16bf f; } x;
|
||||
x.w[0] = p[2 * u];
|
||||
x.w[1] = p[2 * u + 1];
|
||||
return x.f;
|
||||
}
|
||||
|
||||
// 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.
|
||||
// CHAIN brackets the body with the chained launch's wait and add (halo_chain.h); no block returns
|
||||
// early. halo_gemm_bf16_nt_m64_kernel and halo_r4dchain_gemm_bf16_nt_m64 below wrap it.
|
||||
template <int MT, bool CHAIN>
|
||||
__device__ __forceinline__ void halo_gemm_bf16_nt_m64_body(
|
||||
const unsigned short* __restrict__ A, const unsigned short* __restrict__ W,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) {
|
||||
if (CHAIN) halo_chain_wait();
|
||||
HALO_DYN_LDS(float, red); // WV*SK*256 floats: one 16x16 tile per (column, split)
|
||||
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
const int nt = blockIdx.x * WV + col_local;
|
||||
const int n0 = nt * 16;
|
||||
const int mt0 = blockIdx.y * MT;
|
||||
const int Ks = K / SK, ksteps = Ks / 16, kbase = ksplit * Ks;
|
||||
|
||||
v8f acc[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[i] = (v8f)(0.f);
|
||||
|
||||
// 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;
|
||||
|
||||
// The k walk is a ring of D steps' fragments in registers: step s + D's loads issue as soon as
|
||||
// step s's WMMAs have consumed its slot, so D steps of loads are in flight under the WMMAs. With
|
||||
// only the next step in flight (the plain KU-unrolled loop) every step waited out a memory round
|
||||
// trip -- 270 us at N 2048, K 4096, M 17 against a 75 us weight stream. Each accumulator still
|
||||
// takes its WMMAs in ascending k, so the bits are the plain loop's. A k step is a load immediate
|
||||
// (the 13-bit field of global_load_b64) and the base pointers advance once per D steps; rolled,
|
||||
// LLVM rebuilds a 64-bit address every step.
|
||||
// D at the VGPR bound: a fragment is 8 VGPRs, (MT + 1) of them a step. MT 1 spills from D 6 on
|
||||
// (the compiler double-buffers that ring), so it stays at 4.
|
||||
constexpr int D = MT == 1 ? 4 : (MT == 2 ? 6 : (MT == 3 ? 4 : 3));
|
||||
if (n0 < N) {
|
||||
halo_gu4 pw = (halo_gu4)(const halo_u4v*)(W + woff);
|
||||
halo_gu4 pa[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] = (halo_gu4)(const halo_u4v*)(A + aoff[i]);
|
||||
if (ksteps < D) {
|
||||
for (int s = 0; s < ksteps; s++) {
|
||||
const v16bf b = fragU(pw, 0);
|
||||
pw += 2;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
acc[i] = mma(fragU(pa[i], 0), b, acc[i]);
|
||||
pa[i] += 2;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
v16bf rb[D], ra[D][MT];
|
||||
#pragma unroll
|
||||
for (int d = 0; d < D; d++) {
|
||||
rb[d] = fragU(pw, d);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) ra[d][i] = fragU(pa[i], d);
|
||||
}
|
||||
int s = 0;
|
||||
for (; s + 2 * D <= ksteps; s += D) {
|
||||
#pragma unroll
|
||||
for (int d = 0; d < D; d++) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[i] = mma(ra[d][i], rb[d], acc[i]);
|
||||
rb[d] = fragU(pw, D + d);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) ra[d][i] = fragU(pa[i], D + d);
|
||||
}
|
||||
pw += D * 2;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] += D * 2;
|
||||
}
|
||||
// The ring holds steps s .. s+D-1; r = ksteps - s - D more (0 <= r < D) refill its first r
|
||||
// slots and run last, so the order stays ascending.
|
||||
const int r = ksteps - s - D;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < D; d++) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[i] = mma(ra[d][i], rb[d], acc[i]);
|
||||
if (d < r) {
|
||||
rb[d] = fragU(pw, D + d);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) ra[d][i] = fragU(pa[i], D + d);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int d = 0; d < D - 1; d++) {
|
||||
if (d >= r) break;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[i] = mma(ra[d][i], rb[d], acc[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
for (int i = 0; i < MT; i++) {
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) red[slot + e * WAVE32 + lane] = acc[i][e]; // conflict-free
|
||||
__syncthreads();
|
||||
for (int idx = tid; idx < WV * 256; idx += nthreads) {
|
||||
const int col = idx >> 8, off = idx & 255;
|
||||
float v = 0.f;
|
||||
for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off];
|
||||
const int l = off & 31;
|
||||
const int n = (blockIdx.x * WV + col) * 16 + (l & 15);
|
||||
const int m = (mt0 + i) * 16 + accRow(l, off >> 5); // gfx11 D mapping (halo_gdn_wmma.h)
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
if (CHAIN) halo_chain_done();
|
||||
}
|
||||
|
||||
template <int MT>
|
||||
__global__ __launch_bounds__(1024) void halo_gemm_bf16_nt_m64_kernel(
|
||||
const unsigned short* __restrict__ A, const unsigned short* __restrict__ W,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) {
|
||||
halo_gemm_bf16_nt_m64_body<MT, false>(A, W, C, M, K, N, WV, SK);
|
||||
}
|
||||
template <int MT>
|
||||
__global__ __launch_bounds__(1024) void halo_r4dchain_gemm_bf16_nt_m64(
|
||||
const unsigned short* __restrict__ A, const unsigned short* __restrict__ W,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) {
|
||||
halo_gemm_bf16_nt_m64_body<MT, true>(A, W, C, M, K, N, WV, SK);
|
||||
}
|
||||
|
||||
// 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.
|
||||
static void gemm_bf16_m64_launch(long a, long w, long c, int M, int K, int N, int WV, int SK,
|
||||
int MB, long stream, bool chain);
|
||||
void halo_gemm_bf16_nt_m64(long a, long w, long c, int M, int K, int N, int WV, int SK, int MB,
|
||||
long stream) {
|
||||
gemm_bf16_m64_launch(a, w, c, M, K, N, WV, SK, MB, stream, false);
|
||||
}
|
||||
/* `chain`: the chained form (halo_rad_gemm_bf16_m64 passes the row's parameter; M <= 64 always). */
|
||||
static void gemm_bf16_m64_launch(long a, long w, long c, int M, int K, int N, int WV, int SK,
|
||||
int MB, long stream, bool chain) {
|
||||
if (M < 1 || M > HALO_GEMM64_MAX_M) throw std::runtime_error("r4d gemm_bf16_nt_m64: M out of range");
|
||||
if (K % (SK * 16)) throw std::runtime_error("r4d gemm_bf16_nt_m64: K must be divisible by SK*16");
|
||||
if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_bf16_nt_m64: threads/block > 1024");
|
||||
const int ntiles = (N + 15) / 16, mtiles = (M + 15) / 16;
|
||||
if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_bf16_nt_m64: MB must be 1..4");
|
||||
dim3 grid((ntiles + WV - 1) / WV, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32);
|
||||
size_t smem = (size_t)WV * SK * 256 * sizeof(float);
|
||||
auto Ap = (const unsigned short*)a; auto Wp = (const unsigned short*)w;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH(MT) hipLaunchKernelGGL((chain ? halo_r4dchain_gemm_bf16_nt_m64<MT> \
|
||||
: halo_gemm_bf16_nt_m64_kernel<MT>), \
|
||||
grid, block, smem, st, Ap, Wp, Cp, M, K, N, WV, SK)
|
||||
switch (MB) {
|
||||
case 1: LAUNCH(1); break;
|
||||
case 2: LAUNCH(2); break;
|
||||
case 3: LAUNCH(3); break;
|
||||
case 4: LAUNCH(4); break;
|
||||
default: throw std::runtime_error("r4d gemm_bf16_nt_m64: MB unsupported");
|
||||
}
|
||||
#undef LAUNCH
|
||||
}
|
||||
|
||||
int halo_gemm_bf16_nt_m64_max_m(void) { return HALO_GEMM64_MAX_M; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in halo_gemm_args.h; see libhalo/halo_args.h.
|
||||
extern "C" int halo_rad_gemm_bf16_m64(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 0);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.M > halo_gemm_bf16_nt_m64_max_m()) return HALO_NO(RAD_E_SHAPE);
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, g.M, 16, BR_FLAT, &c, (g.N + 15) / 16); /* "K divisible by SK*16" */
|
||||
if (rc != RAD_OK) return rc;
|
||||
/* cfg_for's decode band gives MB = 1 (one row tile a block). With the k ring that stays
|
||||
* right for a narrow weight, but from 64 column tiles on every row-tile block re-streams the
|
||||
* weight, and one block over all of them reads it once: on gfx1151 at N 2048, K 4096, M 64,
|
||||
* 350 -> 194 us; 4608 x 4608 455 -> 285; at N <= 256 MB = 1 stays 20-90% faster. BR_FLAT
|
||||
* keeps the split, so the bits do not move; a tuned mb is kept. */
|
||||
if (halo_geti_or(a, "mb", 0) <= 0 && g.M <= 64 && (g.N + 15) / 16 >= 64)
|
||||
c.mb = (int)((g.M + 15) / 16);
|
||||
HALO_TRY("gemm_bf16_nt_m64",
|
||||
gemm_bf16_m64_launch(halo_addr(g.a), halo_addr(g.b), halo_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb,
|
||||
(long)(uintptr_t)s, halo_geti_or(a, "chain", 0) != 0));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
/* Derived from libr4d/r4d_gemm_bf16_nt_tiled.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_bf16_nt_tiled.hip - halo_gemm_bf16_nt_tiled: the bf16 GEMM at prefill row counts, gfx1151.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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, so each staged fragment feeds TM or TN WMMA.
|
||||
// The next K tile is loaded into registers while the current one is computed.
|
||||
//
|
||||
// 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: rows past M or N re-read the last valid row
|
||||
// and their results are never stored.
|
||||
#include "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
|
||||
#define BT_BK 64 // K per staged tile: four WMMA k steps
|
||||
// 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
|
||||
|
||||
// TM x TN WMMA tiles a wave; BM = 2*TM*16, BN = 4*TN*16. SPLIT carries the slice sum.
|
||||
template <int TM, int TN, bool SPLIT>
|
||||
__global__ __launch_bounds__(256) void halo_gemm_bf16_nt_tiled_kernel(
|
||||
const unsigned short* __restrict__ A, const unsigned short* __restrict__ W,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int spk) {
|
||||
constexpr int BM = BT_WM * TM * 16, BN = BT_WN * TN * 16;
|
||||
constexpr int CPR = BT_BK / 8; // 16-byte chunks a staged row
|
||||
constexpr int AL = BM * CPR / 256, WL = BN * CPR / 256;
|
||||
static_assert(AL >= 1 && WL >= 1 && BM * CPR % 256 == 0 && BN * CPR % 256 == 0,
|
||||
"a tile is whole 16-byte chunks for every thread");
|
||||
__shared__ __attribute__((aligned(16))) unsigned short sA[BM * BT_PITCH];
|
||||
__shared__ __attribute__((aligned(16))) unsigned short sW[BN * BT_PITCH];
|
||||
|
||||
const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31;
|
||||
const int wm = wave / BT_WN, wn = wave % BT_WN;
|
||||
// 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. 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];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) {
|
||||
const int c = tid + 256 * i, r = c / CPR, e = (c % CPR) * 8;
|
||||
const int gr = m0 + r < M ? m0 + r : M - 1;
|
||||
aoff[i] = (unsigned)gr * (unsigned)K + (unsigned)e;
|
||||
adst[i] = sA + r * BT_PITCH + e;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) {
|
||||
const int c = tid + 256 * i, r = c / CPR, e = (c % CPR) * 8;
|
||||
const int gr = n0 + r < N ? n0 + r : N - 1;
|
||||
woff[i] = (unsigned)gr * (unsigned)K + (unsigned)e;
|
||||
wdst[i] = sW + r * BT_PITCH + e;
|
||||
}
|
||||
|
||||
// Fragment sources: this lane's row of each tile at its half-K offset, as in rowP.
|
||||
const unsigned short* fa = sA + (wm * TM * 16 + (lane & 15)) * BT_PITCH; // no half-k term on gfx11 (halo_gdn_wmma.h)
|
||||
const unsigned short* fw = sW + (wn * TN * 16 + (lane & 15)) * BT_PITCH;
|
||||
|
||||
v8f acc[TM][TN], tot[SPLIT ? TM : 1][SPLIT ? TN : 1];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) acc[i][j] = (v8f)(0.f);
|
||||
if constexpr (SPLIT) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) tot[i][j] = (v8f)(0.f);
|
||||
}
|
||||
|
||||
halo_u32x4 ra[AL], rw[WL]; // registers; uint4 would sit in scratch
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) ra[i] = *(const halo_u32x4*)(A + aoff[i]);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) rw[i] = *(const halo_u32x4*)(W + woff[i]);
|
||||
|
||||
const int nk = K / BT_BK;
|
||||
int left = spk; // k steps to the end of this split slice
|
||||
for (int kt = 0; kt < nk; ++kt) {
|
||||
__syncthreads(); // the previous tile's fragments are all read
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) *(halo_u32x4*)adst[i] = ra[i];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) *(halo_u32x4*)wdst[i] = rw[i];
|
||||
__syncthreads();
|
||||
if (kt + 1 < nk) {
|
||||
const unsigned k1 = (unsigned)(kt + 1) * BT_BK;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) ra[i] = *(const halo_u32x4*)(A + aoff[i] + k1);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) rw[i] = *(const halo_u32x4*)(W + woff[i] + k1);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int s = 0; s < BT_BK / 16; ++s) {
|
||||
v16bf af[TM], bf[TN];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) af[i] = fragP(fa + i * 16 * BT_PITCH + s * 16);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) bf[j] = fragP(fw + j * 16 * BT_PITCH + s * 16);
|
||||
#pragma unroll
|
||||
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]);
|
||||
/* 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) {
|
||||
if (--left == 0) {
|
||||
left = spk;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
tot[i][j] += acc[i][j];
|
||||
acc[i][j] = (v8f)(0.f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The skinny kernel's store: lane l holds column (l & 15) of a tile and rows accRow(l, e).
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
const int n = n0 + (wn * TN + j) * 16 + (lane & 15);
|
||||
const int mb = m0 + (wm * TM + i) * 16;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
float v = 0.f;
|
||||
if constexpr (SPLIT) v = tot[i][j][e];
|
||||
else v += acc[i][j][e];
|
||||
const int m = mb + accRow(lane, e);
|
||||
if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 halo_gemm_bf16_nt_tiled_arm(int M, int N) {
|
||||
const long long g = (long long)((N + 127) / 128) * ((M + 127) / 128);
|
||||
return g >= kBtLargeGrid ? 1 : 2;
|
||||
}
|
||||
|
||||
// `tile`: 1 = 128 x 128, 2 = 64 x 64 (M x N).
|
||||
int halo_gemm_bf16_nt_tiled(long a, long w, long c, int M, int K, int N, int SK, int tile,
|
||||
long stream) {
|
||||
if (M < 1 || N < 1 || K < BT_BK || K % BT_BK) return -1;
|
||||
if (SK < 1 || K % (SK * 16)) return -1;
|
||||
if (tile != 1 && tile != 2) return -1;
|
||||
// 32-bit element offsets: the last row of either operand has to be addressable.
|
||||
if ((long long)M * K >= (1ll << 32) || (long long)N * K >= (1ll << 32)) return -1;
|
||||
const int spk = K / SK / 16;
|
||||
const int bt = tile == 1 ? 128 : 64;
|
||||
dim3 grid((N + bt - 1) / bt, (M + bt - 1) / bt), block(256);
|
||||
auto Ap = (const unsigned short*)a; auto Wp = (const unsigned short*)w;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH(TM, TN, S) hipLaunchKernelGGL((halo_gemm_bf16_nt_tiled_kernel<TM, TN, S>), grid, \
|
||||
block, 0, st, Ap, Wp, Cp, M, K, N, spk)
|
||||
const bool split = SK > 1;
|
||||
if (tile == 1) { if (split) LAUNCH(4, 2, true); else LAUNCH(4, 2, false); }
|
||||
else { if (split) LAUNCH(2, 1, true); else LAUNCH(2, 1, false); }
|
||||
#undef LAUNCH
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
extern "C" int halo_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 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;
|
||||
int tile = (int)halo_geti_or(a, "tile", 0);
|
||||
if (tile == 0) tile = halo_gemm_bf16_nt_tiled_arm((int)g.M, (int)g.N);
|
||||
const int e = halo_gemm_bf16_nt_tiled(halo_addr(g.a), halo_addr(g.b), halo_addr(g.y), (int)g.M,
|
||||
(int)g.K, (int)g.N, c.sk, tile, (long)(uintptr_t)s);
|
||||
return e == 0 ? RAD_OK : HALO_NO(e < 0 ? RAD_E_SHAPE : RAD_E_DEVICE);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
/* Derived from libr4d/r4d_gemm_f32_nt_bias.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_f32_nt_bias.hip -- gemm_nt_bias at f32: C = res + act(A @ W^T + bias) with an f32
|
||||
// activation and weight, f32 accumulation, and the result f32 or rounded to bf16 at the store.
|
||||
// The epilogue is libref's: the biased product, the activation of it and the residual sum each
|
||||
// rounded to C's dtype, as the unfused chain's tensors would be; at an f32 C only the arithmetic
|
||||
// rounds. A diffusion transformer's patch projections and output heads, its timestep MLP, and a
|
||||
// video decoder's 1x1 projections run here: K from 24 to a few thousand, N from 24 to 5376, M up
|
||||
// to a hundred thousand rows.
|
||||
//
|
||||
// The tile is halo_f32_tile.h's at 128 rows: 128 columns where N is wider than 96, 96 where it is
|
||||
// wider than 64, 64 where it is wider than 32, 32 otherwise, so a narrow head (N 32 or 96) fills
|
||||
// its tile. No split-K: the narrow-N shapes have hundreds of row tiles.
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_emit.h"
|
||||
#include "halo_f32_tile.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kTM = 8, kBM = 16 * kTM;
|
||||
|
||||
__device__ __forceinline__ float gelu_erf(float x) {
|
||||
return 0.5f * x * (1.0f + erff(x * 0.70710678118654752f));
|
||||
}
|
||||
__device__ __forceinline__ float gelu_tanh(float x) {
|
||||
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
|
||||
return 0.5f * x * (1.0f + tanhf(k0 * (x + k1 * x * x * x)));
|
||||
}
|
||||
|
||||
// C's element: f32 as it is, or bf16 rounded to nearest even.
|
||||
__device__ __forceinline__ float rd(const float*, float v) { return v; }
|
||||
__device__ __forceinline__ float rd(const uint16_t*, float v) { return bf16_to_f32(f32_to_bf16(v)); }
|
||||
__device__ __forceinline__ float ld1(const float* p) { return *p; }
|
||||
__device__ __forceinline__ float ld1(const uint16_t* p) { return bf16_to_f32(*p); }
|
||||
__device__ __forceinline__ void st1(float* p, float v) { *p = v; }
|
||||
__device__ __forceinline__ void st1(uint16_t* p, float v) { *p = f32_to_bf16(v); }
|
||||
// Four (or two) adjacent elements in one store: 16 (8) bytes at f32, 8 (4) at bf16.
|
||||
__device__ __forceinline__ void stv(float* p, int cnt, const float* v) {
|
||||
if (cnt == 4) *(float4*)p = make_float4(v[0], v[1], v[2], v[3]);
|
||||
else *(float2*)p = make_float2(v[0], v[1]);
|
||||
}
|
||||
__device__ __forceinline__ void stv(uint16_t* p, int cnt, const float* v) {
|
||||
if (cnt == 4) *(uint2*)p = make_uint2(bf16x2_rne(v[0], v[1]), bf16x2_rne(v[2], v[3]));
|
||||
else *(uint32_t*)p = bf16x2_rne(v[0], v[1]);
|
||||
}
|
||||
|
||||
// `act` 0 none, 1 exact GELU, 2 tanh GELU. `R` may be `C` itself (a residual updated in place):
|
||||
// each element is read by the thread that stores it, before the store. `vec` says C's rows take
|
||||
// whole-run stores (a pitch of whole runs at an aligned base).
|
||||
template <int TN, typename TY>
|
||||
__global__ __launch_bounds__(halo_f32::kThr) void gemm_f32_bias_kernel(
|
||||
const float* __restrict__ A, int lda, const float* __restrict__ W, int K,
|
||||
const void* __restrict__ bias, int bias_f32, const TY* R, int ldr, TY* C, int ldc, int M,
|
||||
int N, int act, int vec) {
|
||||
constexpr int BN = 16 * TN, CW = halo_f32::run_of(TN);
|
||||
const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4;
|
||||
const int m0 = blockIdx.y * kBM, n0 = blockIdx.x * BN;
|
||||
halo_f32::RowsLoader<kTM> la{ A, lda, M, K };
|
||||
halo_f32::RowsLoader<TN> lw{ W, K, N, K };
|
||||
la.init(m0 + ty, tx);
|
||||
lw.init(n0 + ty, tx);
|
||||
/* The bias of this thread's TN columns (runs of CW, 16 CW apart), read once. */
|
||||
float bc[TN];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
const int n = n0 + (j / CW) * 16 * CW + tx * CW + j % CW;
|
||||
const int nc = n < N ? n : N - 1;
|
||||
bc[j] = bias_f32 ? ((const float*)bias)[nc] : bf16_to_f32(((const uint16_t*)bias)[nc]);
|
||||
}
|
||||
auto ep = [&](int r, int c, int cnt, float4 q, int g) {
|
||||
const int m = m0 + r, n = n0 + c;
|
||||
if (m >= M || n >= N) return;
|
||||
float v[4] = { q.x, q.y, q.z, q.w };
|
||||
#pragma unroll
|
||||
for (int e = 0; e < CW; ++e) {
|
||||
float t = rd(C, v[e] + bc[g * CW + e]);
|
||||
if (act == 1) t = rd(C, gelu_erf(t));
|
||||
else if (act == 2) t = rd(C, gelu_tanh(t));
|
||||
if (R && n + e < N) t = ld1(R + (size_t)m * ldr + n + e) + t;
|
||||
v[e] = t;
|
||||
}
|
||||
TY* dst = C + (size_t)m * ldc + n;
|
||||
if (vec && n + cnt <= N) {
|
||||
stv(dst, cnt, v);
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 4; ++e)
|
||||
if (e < cnt && n + e < N) st1(dst + e, v[e]);
|
||||
}
|
||||
};
|
||||
halo_f32::tile<kTM, TN>(la, lw, K, ep);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
enum { GF_A = 0, GF_W, GF_BIAS, GF_RES, GF_Y };
|
||||
|
||||
extern "C" int halo_rad_gemm_f32_nt_bias(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* A = halo_opt(a, GF_A);
|
||||
const RadTensor* W = halo_opt(a, GF_W);
|
||||
const RadTensor* B = halo_opt(a, GF_BIAS);
|
||||
const RadTensor* R = halo_opt(a, GF_RES);
|
||||
const RadTensor* Y = halo_opt(a, GF_Y);
|
||||
if (!A || !W || !B || !Y) return HALO_NO(RAD_E_INVAL);
|
||||
/* f32 A and W; C f32 or bf16, the residual C's dtype; the bias f32 or bf16. */
|
||||
if (A->dtype != RAD_F32 || W->dtype != RAD_F32) return HALO_NO(RAD_E_DTYPE);
|
||||
if (Y->dtype != RAD_F32 && Y->dtype != RAD_BF16) return HALO_NO(RAD_E_DTYPE);
|
||||
if (B->dtype != RAD_F32 && B->dtype != RAD_BF16) return HALO_NO(RAD_E_DTYPE);
|
||||
if (R && R->dtype != Y->dtype) return HALO_NO(RAD_E_DTYPE);
|
||||
if (!halo_contig(W) || !halo_contig(B)) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
const long long K = halo_geti_or(a, "K", halo_dim(W, (int)W->rank - 1));
|
||||
const long long N = halo_geti_or(a, "N", halo_numel(W) / (K > 0 ? K : 1));
|
||||
if (K <= 0 || N <= 0 || halo_numel(W) < N * K || halo_numel(B) < N) return HALO_NO(RAD_E_SHAPE);
|
||||
long long M = 0, Ma = 0, Mr = 0;
|
||||
const long long ldc = halo_rows_pitch(Y, N, &M);
|
||||
const long long lda = halo_rows_pitch(A, K, &Ma);
|
||||
const long long ldr = R ? halo_rows_pitch(R, N, &Mr) : 0;
|
||||
if (ldc < 0 || lda < 0 || ldr < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || Ma < M || (R && Mr < M)) return HALO_NO(RAD_E_SHAPE);
|
||||
/* The tile's loaders index A and W with 32-bit element offsets. */
|
||||
if (M > 0x7fffffffll || N > 0x7fffffffll || K > 0x7fffffffll || lda > 0x7fffffffll ||
|
||||
ldc > 0x7fffffffll || ldr > 0x7fffffffll || (M + kBM - 1) / kBM > 65535 ||
|
||||
M * lda >= (1ll << 32) || N * K >= (1ll << 32))
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
const char* act_s = halo_gets(a, "act");
|
||||
int act = 0;
|
||||
if (act_s && *act_s) {
|
||||
if (!std::strcmp(act_s, "gelu")) act = 1;
|
||||
else if (!std::strcmp(act_s, "gelu_tanh")) act = 2;
|
||||
else if (std::strcmp(act_s, "none")) return HALO_NO(RAD_E_SCHEMA);
|
||||
}
|
||||
const int bias_f32 = B->dtype == RAD_F32;
|
||||
const bool f32 = Y->dtype == RAD_F32;
|
||||
/* Whole-run stores where every row starts aligned to a run of four. */
|
||||
const unsigned run_bytes = f32 ? 16u : 8u;
|
||||
const int vec = (ldc % 4) == 0 && halo_aligned(halo_p(Y), run_bytes);
|
||||
|
||||
const int tn = N > 96 ? 8 : N > 64 ? 6 : N > 32 ? 4 : 2;
|
||||
const dim3 grid((unsigned)((N + 16 * tn - 1) / (16 * tn)), (unsigned)((M + kBM - 1) / kBM));
|
||||
const dim3 block(halo_f32::kThr);
|
||||
#define GF_L(TN, TY) \
|
||||
return HALO_EMIT(stream, (gemm_f32_bias_kernel<TN, TY>), grid, block, 0, \
|
||||
(const float*)halo_p(A), (int)lda, (const float*)halo_p(W), (int)K, halo_p(B), \
|
||||
bias_f32, (const TY*)halo_p(R), (int)ldr, (TY*)halo_wp(Y), (int)ldc, (int)M, \
|
||||
(int)N, act, vec)
|
||||
if (f32) {
|
||||
if (tn == 8) GF_L(8, float);
|
||||
if (tn == 6) GF_L(6, float);
|
||||
if (tn == 4) GF_L(4, float);
|
||||
GF_L(2, float);
|
||||
}
|
||||
if (tn == 8) GF_L(8, uint16_t);
|
||||
if (tn == 6) GF_L(6, uint16_t);
|
||||
if (tn == 4) GF_L(4, uint16_t);
|
||||
GF_L(2, uint16_t);
|
||||
#undef GF_L
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
/* Derived from libr4d/r4d_fp8_f32scale.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// Canonical E4M3 weights with exact F32 block scales: C[M,N] = A[M,K] @ (W[N,K] * ws)^T, one f32
|
||||
// scale per (row, 128 of K) on the activation and one per (128 of N, 128 of K) on the weight.
|
||||
//
|
||||
// gfx1201 runs this as an fp8 WMMA with the block scale folded on the accumulator. gfx1151 has no
|
||||
// fp8 matrix instruction, so both operands dequantise to EXACT bf16 (e4m3 has 3 mantissa bits,
|
||||
// bf16 7, so the widening loses nothing) and the product runs on halo_wmma.h's bf16 WMMA -- the
|
||||
// recipe the block-scaled MXFP4 GEMMs already use (halo_gemm_mxfp4a8_tiled.hip). A bf16 WMMA with
|
||||
// an f32 accumulator does what the fp8 one did: each 128-K block is a fresh chain of eight 16-wide
|
||||
// WMMAs from zero, and the block's sum folds into the running accumulator once, as
|
||||
// `acc += raw * (a_scale * w_scale)` -- fp8_f32scale's own fold. So the products are the fp8
|
||||
// kernel's exact products and the unit's own loss is only the WMMA's f32 accumulation order (1 ulp
|
||||
// on a 16-term dot), where the output is bf16.
|
||||
//
|
||||
// One dense form serves every shape. libr4d splits that op into a decode form, two row-tile forms
|
||||
// and a legacy 16x64 tile, byte-identical and chosen for speed; here the dequantise is the same
|
||||
// work in each, so the unit ships the row-tile form alone at any M, and the legacy activation pitch
|
||||
// (K + 8, off a 16-byte multiple) runs through the same kernel -- hence the dword operand reads,
|
||||
// which keep 4-byte alignment enough. The grouped op is expert-major: a block takes one expert's
|
||||
// run of the sorted rows, 16 rows at a time, so an expert's weights are read once per run however
|
||||
// its rows fall in the sort.
|
||||
//
|
||||
// Meta and the operand reading are libr4d's, including the two-parity weight tables (even experts
|
||||
// in `w`/`ws`, odd in the second pair) and their pointer-table form (stride[0] == 0: the operand is
|
||||
// an array of expert pointers).
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_fp8_wmma.h"
|
||||
#include "halo_wmma.h"
|
||||
|
||||
#include <climits>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
#define F8S_CHK() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0)
|
||||
|
||||
namespace {
|
||||
|
||||
struct Meta {
|
||||
long ar, asr, yr, wr, sr, wstep[2], sstep[2];
|
||||
int T, N, K, experts, topk, sorted_a;
|
||||
};
|
||||
|
||||
// Expert `e`'s bytes: a stepped plane, or an entry of a pointer table (step 0).
|
||||
__device__ __forceinline__ const uint8_t* f8_entry(const void* p, long step, int e) {
|
||||
return step ? (const uint8_t*)p + step * e : ((const uint8_t* const*)p)[e];
|
||||
}
|
||||
|
||||
/* Sixteen e4m3 bytes to the exact bf16 fragment (halo_gemm_mxfp4a8_nt_m64's mx_deq16_exact): the
|
||||
* hardware's fp8 -> f32 conversion, then bf16, which holds every e4m3 value. NOT halo_wmma.h's
|
||||
* deq16_e4m3, whose shift-only form comes out low by 2^-120. */
|
||||
__device__ __forceinline__ v16bf f8s_deq16(const uint32_t* __restrict__ w4) {
|
||||
union { uint32_t u[8]; v16bf f; } q;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
const v2f p0 = halo_fp8::e4m3_pk<false>(w4[d]);
|
||||
const v2f p1 = halo_fp8::e4m3_pk<true>(w4[d]);
|
||||
q.u[d * 2] = halo::pk_bf16(p0.x, p0.y);
|
||||
q.u[d * 2 + 1] = halo::pk_bf16(p1.x, p1.y);
|
||||
}
|
||||
return q.f;
|
||||
}
|
||||
|
||||
// The same from sixteen bytes at any 4-byte alignment (the activation's pitch may be K + 8).
|
||||
__device__ __forceinline__ v16bf f8s_deq16p(const uint8_t* __restrict__ p) {
|
||||
uint32_t w4[4];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) w4[i] = ((const uint32_t*)p)[i];
|
||||
return f8s_deq16(w4);
|
||||
}
|
||||
|
||||
// ================================================================ the dense form
|
||||
//
|
||||
// A block is 4 waves along M, each owning TM = 2 sixteen-row fragments, over TN = 2 sixteen-column
|
||||
// fragments -- 128 rows by 32 columns. N is a multiple of 128, so a block's columns all lie in one
|
||||
// weight-scale group and the block's weight scale is a scalar a K block. The weight slab of 128 K
|
||||
// is dequantised once into LDS and read by all four waves; the activation fragments are read
|
||||
// straight from global, one 16-byte run a lane a step, and dequantised in registers.
|
||||
#define F8S_NW 4
|
||||
#define F8S_TM 2
|
||||
#define F8S_TN 2
|
||||
#define F8S_KB 128 // K per scale block
|
||||
#define F8S_STR (F8S_KB + 8) // LDS weight pitch, bf16: 16-byte rows
|
||||
#define F8S_NTHR (F8S_NW * 32)
|
||||
#define F8S_BMF (F8S_NW * F8S_TM * 16) // rows a block covers
|
||||
#define F8S_BNF (F8S_TN * 16) // columns a block covers
|
||||
#define F8S_NS (F8S_KB / 16) // 16-wide k steps in a scale block
|
||||
#define F8S_WPT (F8S_BNF * (F8S_KB / 16) / F8S_NTHR) // 16-byte weight runs a thread stages
|
||||
|
||||
__global__ __launch_bounds__(F8S_NTHR) void halo_fp8_f32scale_dense(
|
||||
const uint8_t* __restrict__ a, const float* __restrict__ as, const uint8_t* __restrict__ w,
|
||||
const float* __restrict__ ws, uint16_t* __restrict__ y, Meta m) {
|
||||
constexpr int BMF = F8S_BMF, BNF = F8S_BNF, NS = F8S_NS, STR = F8S_STR, WPT = F8S_WPT;
|
||||
__shared__ __align__(16) uint16_t sW[BNF * STR];
|
||||
__shared__ float sR[BMF];
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int m0 = blockIdx.y * BMF, n0 = blockIdx.x * BNF;
|
||||
const int col = halo::b_col(lane);
|
||||
// How many of this wave's fragments hold a row below M. Few rows are the decode shapes, and a
|
||||
// fragment past M costs its WMMAs for nothing; the test is wave-uniform (halo_gemm_mxfp4a8_tiled
|
||||
// skips padding fragments the same way), so the loads and WMMAs of the rest are never issued.
|
||||
const int live = min(F8S_TM, max(0, ((m.T + 15) >> 4) - ((m0 >> 4) + wave * F8S_TM)));
|
||||
|
||||
v8f acc[F8S_TM][F8S_TN];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < F8S_TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < F8S_TN; ++j) acc[i][j] = (v8f)(0.f);
|
||||
|
||||
for (int k0 = 0; k0 < m.K; k0 += F8S_KB) {
|
||||
// The weight slab, dequantised to exact bf16 on the way into LDS.
|
||||
#pragma unroll
|
||||
for (int t = 0; t < WPT; ++t) {
|
||||
const int u = tid + t * F8S_NTHR;
|
||||
const int r = u / (F8S_KB / 16), c = (u % (F8S_KB / 16)) * 16;
|
||||
union { uint32_t u[8]; v16bf f; } s;
|
||||
s.f = f8s_deq16p(w + (size_t)(n0 + r) * m.wr + k0 + c);
|
||||
uint16_t* dst = &sW[r * STR + c];
|
||||
*(uint2*)(dst) = make_uint2(s.u[0], s.u[1]);
|
||||
*(uint2*)(dst + 4) = make_uint2(s.u[2], s.u[3]);
|
||||
*(uint2*)(dst + 8) = make_uint2(s.u[4], s.u[5]);
|
||||
*(uint2*)(dst + 12) = make_uint2(s.u[6], s.u[7]);
|
||||
}
|
||||
// Every row's activation scale for this block, then the block's one weight scale.
|
||||
const int trow = m0 + tid;
|
||||
sR[tid] = trow < m.T ? as[(size_t)trow * m.asr + k0 / F8S_KB] : 0.f;
|
||||
const float wsc = ws[(size_t)(n0 / F8S_KB) * m.sr + k0 / F8S_KB];
|
||||
lds_barrier();
|
||||
|
||||
// The wave's activation fragments: lane holds row (lane & 15) of the fragment, k = e.
|
||||
const uint8_t* arow[F8S_TM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < F8S_TM; ++i) {
|
||||
int r = m0 + wave * F8S_TM * 16 + i * 16 + halo::a_row(lane);
|
||||
r = r < m.T ? r : m.T - 1;
|
||||
arow[i] = a + (size_t)r * m.ar + k0;
|
||||
}
|
||||
if (live <= 0) { lds_barrier(); continue; }
|
||||
v8f raw[F8S_TM][F8S_TN];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < F8S_TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < F8S_TN; ++j) raw[i][j] = (v8f)(0.f);
|
||||
#pragma unroll
|
||||
for (int step = 0; step < NS; ++step) {
|
||||
v16bf af[F8S_TM], wf[F8S_TN];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < F8S_TM; ++i) {
|
||||
if (i >= live) break;
|
||||
af[i] = f8s_deq16p(arow[i] + step * 16);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < F8S_TN; ++j) {
|
||||
const uint16_t* p = &sW[(j * 16 + col) * STR + step * 16];
|
||||
union { uint4 w[2]; v16bf f; } u;
|
||||
u.w[0] = *(const uint4*)p;
|
||||
u.w[1] = *(const uint4*)(p + 8);
|
||||
wf[j] = u.f;
|
||||
}
|
||||
__builtin_amdgcn_sched_barrier(0);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < F8S_TM; ++i) {
|
||||
if (i >= live) break; // wave-uniform: padding fragments past M
|
||||
#pragma unroll
|
||||
for (int j = 0; j < F8S_TN; ++j) raw[i][j] = halo::mma(af[i], wf[j], raw[i][j]);
|
||||
}
|
||||
}
|
||||
// fp8_f32scale's fold: one rounding of the block sum times the scale pair, one add.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < F8S_TM; ++i) {
|
||||
if (i >= live) break;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < F8S_TN; ++j)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e)
|
||||
acc[i][j][e] +=
|
||||
raw[i][j][e] * (sR[wave * F8S_TM * 16 + i * 16 + halo::d_row(lane, e)] * wsc);
|
||||
}
|
||||
lds_barrier();
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < F8S_TN; ++j) {
|
||||
const int nb = n0 + j * 16 + col;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < F8S_TM; ++i)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int r = m0 + wave * F8S_TM * 16 + i * 16 + halo::d_row(lane, e);
|
||||
if (r < m.T) y[(size_t)r * m.yr + nb] = halo::f32_to_bf16(acc[i][j][e]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================ the grouped form
|
||||
//
|
||||
// Expert-major, 4 waves of 16 columns (64 a block), 16 rows of the sorted order a tile: a block
|
||||
// walks its expert's run [offsets[e], offsets[e+1]) and every tile is one expert's weights, so the
|
||||
// rows of a tile never disagree about the weight. A row whose `sorted` entry is negative (dropped by
|
||||
// capacity) is written as zeros, as libr4d writes it, and so are the rows past offsets[experts]
|
||||
// (the block of row `experts`).
|
||||
#define F8G_NW 4
|
||||
#define F8G_BNF (F8G_NW * 16)
|
||||
#define F8G_NTHR (F8G_NW * 32)
|
||||
|
||||
__global__ __launch_bounds__(F8G_NTHR) void halo_fp8_f32scale_experts(
|
||||
const uint8_t* __restrict__ a, const float* __restrict__ as, const void* w0, const void* s0,
|
||||
const void* w1, const void* s1, const int* __restrict__ sorted, const int* __restrict__ off,
|
||||
uint16_t* __restrict__ y, Meta m) {
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int e = blockIdx.y, n0 = blockIdx.x * F8G_BNF;
|
||||
if (e == m.experts) {
|
||||
// The rows past the last expert's run: zero, never stale arena bytes.
|
||||
const int r0 = off[m.experts];
|
||||
for (long i = tid; i < (long)(m.T - r0) * F8G_BNF; i += F8G_NTHR) {
|
||||
const int c = (int)(i % F8G_BNF);
|
||||
if (n0 + c < m.N) y[(size_t)(r0 + i / F8G_BNF) * m.yr + n0 + c] = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
const int lo = off[e], hi = off[e + 1];
|
||||
if (lo >= hi) return;
|
||||
const int parity = e & 1;
|
||||
const uint8_t* w = f8_entry(parity ? w1 : w0, m.wstep[parity], e / 2);
|
||||
const float* ws = (const float*)f8_entry(parity ? s1 : s0, m.sstep[parity], e / 2);
|
||||
const int col = n0 + wave * 16 + halo::b_col(lane);
|
||||
// A class's columns past its width hold zeros (equal parity widths today, kept for the shape).
|
||||
const bool live_col = col < m.N;
|
||||
const int cc = live_col ? col : m.N - 1;
|
||||
const uint8_t* wrow = w + (size_t)cc * m.wr;
|
||||
const float* wsr = ws + (size_t)(cc / F8S_KB) * m.sr;
|
||||
const int rowbase = halo::a_row(lane);
|
||||
|
||||
for (int r0 = lo; r0 < hi; r0 += 16) {
|
||||
// Each slot e of the accumulator is output row 2e + (lane >> 4) of the tile, and its
|
||||
// activation row -- and so its activation scale -- is that row's, not the fragment row's
|
||||
// this lane happens to hold.
|
||||
int src[8];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const int r = r0 + halo::d_row(lane, j);
|
||||
int s = -1;
|
||||
if (r < hi) {
|
||||
const int flat = sorted[r];
|
||||
s = flat >= 0 ? (m.sorted_a ? r : flat / m.topk) : -1;
|
||||
if (s >= m.T) s = -1;
|
||||
}
|
||||
src[j] = s;
|
||||
}
|
||||
const int rowA = r0 + rowbase;
|
||||
const int flatA = rowA < hi ? sorted[rowA] : -1;
|
||||
int srcA = flatA >= 0 ? (m.sorted_a ? rowA : flatA / m.topk) : -1;
|
||||
if (srcA >= m.T) srcA = -1;
|
||||
const uint8_t* arow = a + (size_t)(srcA >= 0 ? srcA : 0) * m.ar;
|
||||
float acc[8];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) acc[j] = 0.f;
|
||||
for (int k0 = 0; k0 < m.K; k0 += F8S_KB) {
|
||||
v8f raw = (v8f)(0.f);
|
||||
#pragma unroll
|
||||
for (int step = 0; step < F8S_NS; ++step) {
|
||||
const v16bf af = f8s_deq16p(arow + k0 + step * 16);
|
||||
const v16bf wf = f8s_deq16p(wrow + k0 + step * 16);
|
||||
if (step == 0) __builtin_amdgcn_sched_barrier(0);
|
||||
raw = halo::mma(af, wf, raw);
|
||||
}
|
||||
const int kb = k0 / F8S_KB;
|
||||
const float sw = live_col ? wsr[kb] : 0.f;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const float sa = src[j] >= 0 ? as[(size_t)src[j] * m.asr + kb] : 0.f;
|
||||
acc[j] += raw[j] * (sa * sw);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const int r = r0 + halo::d_row(lane, j);
|
||||
if (r >= hi) continue;
|
||||
const bool keep = src[j] >= 0 && live_col;
|
||||
y[(size_t)r * m.yr + col] = halo::f32_to_bf16(keep ? acc[j] : 0.f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================ the entry points
|
||||
static int body(const RadArgs* a, RadStream stream, bool grouped) {
|
||||
if (!a || !a->t || a->n_t < (grouped ? 9 : 5)) return RAD_E_INVAL;
|
||||
const auto &x = a->t[0], &xs = a->t[1], &w = a->t[2], &ws = a->t[3], &y = a->t[grouped ? 8 : 4];
|
||||
const int64_t N = halo_geti_or(a, "N", 0), K = halo_geti_or(a, "K", 0);
|
||||
if (N < 128 || N % 128 || K < 128 || K % 128 || N > INT_MAX || K > INT_MAX ||
|
||||
halo_geti_or(a, "group", 0) != 128 || halo_geti_or(a, "pb1", 0) > 0)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
if (x.dtype != RAD_F8E4M3 || xs.dtype != RAD_F32 || w.dtype != RAD_F8E4M3 ||
|
||||
ws.dtype != RAD_F32 || y.dtype != RAD_BF16)
|
||||
return HALO_NO(RAD_E_DTYPE);
|
||||
if (!x.data || !xs.data || !w.data || !ws.data || !y.data || x.rank != 2 || xs.rank != 2 ||
|
||||
y.rank != 2 || x.shape[1] != K || xs.shape[0] != x.shape[0] || xs.shape[1] != K / 128 ||
|
||||
y.shape[1] != N || x.stride[1] != 1 || xs.stride[1] != 1 || y.stride[1] != 1 ||
|
||||
y.shape[0] < 1 || y.shape[0] > INT_MAX)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
const uint32_t rank = grouped ? 3 : 2;
|
||||
if (w.rank != rank || ws.rank != rank || w.shape[rank - 2] != N || w.shape[rank - 1] != K ||
|
||||
ws.shape[rank - 2] != N / 128 || ws.shape[rank - 1] != K / 128 || w.stride[rank - 1] != 1 ||
|
||||
ws.stride[rank - 1] != 1)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
Meta m{};
|
||||
m.ar = x.stride[0];
|
||||
m.asr = xs.stride[0];
|
||||
m.yr = y.stride[0];
|
||||
m.wr = w.stride[rank - 2];
|
||||
m.sr = ws.stride[rank - 2];
|
||||
m.T = (int)y.shape[0];
|
||||
m.N = (int)N;
|
||||
m.K = (int)K;
|
||||
if (!grouped) {
|
||||
if (x.shape[0] != m.T) return HALO_NO(RAD_E_SHAPE);
|
||||
const dim3 grid((unsigned)(N / F8S_BNF), (unsigned)((m.T + F8S_BMF - 1) / F8S_BMF));
|
||||
hipLaunchKernelGGL(halo_fp8_f32scale_dense, grid, dim3(F8S_NTHR), 0, (hipStream_t)stream,
|
||||
(const uint8_t*)x.data, (const float*)xs.data, (const uint8_t*)w.data,
|
||||
(const float*)ws.data, (uint16_t*)y.data, m);
|
||||
F8S_CHK();
|
||||
return RAD_OK;
|
||||
}
|
||||
m.experts = (int)halo_geti_or(a, "n_expert", 0);
|
||||
m.topk = (int)halo_geti_or(a, "top_k", 0);
|
||||
const char* order = halo_gets(a, "a_order");
|
||||
m.sorted_a = order && !std::strcmp(order, "sorted");
|
||||
const auto &wo = a->t[6], &so = a->t[7], &st = a->t[4], &off = a->t[5];
|
||||
if (m.experts < 2 || m.topk < 1 || halo_geti_or(a, "N_odd", N) != N ||
|
||||
halo_geti_or(a, "K_odd", K) != K || wo.dtype != RAD_F8E4M3 || so.dtype != RAD_F32 ||
|
||||
wo.rank != 3 || so.rank != 3 || wo.shape[1] != N || wo.shape[2] != K ||
|
||||
so.shape[1] != N / 128 || so.shape[2] != K / 128 || wo.stride[1] != m.wr ||
|
||||
so.stride[1] != m.sr || wo.stride[2] != 1 || so.stride[2] != 1 || st.dtype != RAD_I32 ||
|
||||
off.dtype != RAD_I32 || st.rank != 1 || off.rank != 1 || st.stride[0] != 1 ||
|
||||
off.stride[0] != 1 || st.shape[0] < m.T || off.shape[0] < m.experts + 1 || !wo.data ||
|
||||
!so.data || !st.data || !off.data)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
m.wstep[0] = w.stride[0];
|
||||
m.wstep[1] = wo.stride[0];
|
||||
m.sstep[0] = ws.stride[0] * 4;
|
||||
m.sstep[1] = so.stride[0] * 4;
|
||||
if (w.shape[0] < (m.experts + 1) / 2 || wo.shape[0] < m.experts / 2) return HALO_NO(RAD_E_SHAPE);
|
||||
const dim3 grid((unsigned)((N + F8G_BNF - 1) / F8G_BNF), (unsigned)m.experts + 1);
|
||||
hipLaunchKernelGGL(halo_fp8_f32scale_experts, grid, dim3(F8G_NTHR), 0, (hipStream_t)stream,
|
||||
(const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, wo.data,
|
||||
so.data, (const int*)st.data, (const int*)off.data, (uint16_t*)y.data, m);
|
||||
F8S_CHK();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" int halo_rad_fp8_f32scale(const RadArgs* a, RadStream stream) {
|
||||
return body(a, stream, false);
|
||||
}
|
||||
extern "C" int halo_rad_moe_fp8_f32scale(const RadArgs* a, RadStream stream) {
|
||||
return body(a, stream, true);
|
||||
}
|
||||
|
||||
/* Both canonical planes (E4M3 codes, F32 scales per 128x128) are read where they lie, so there is
|
||||
* no stored layout to arrange: like libr4d's hook, this validates the encoding and answers
|
||||
* RAD_E_UNSUPPORTED, which the caller takes as "the canonical planes, bytes unchanged". */
|
||||
extern "C" int halo_layout_fp8_f32scale(const RadParam*, int, int operand, const RadEncoding* e,
|
||||
const int* sel, const RadTensor*, int n, RadLayout*) {
|
||||
if (operand != 2 && operand != 3 && operand != 6 && operand != 7) return RAD_E_UNSUPPORTED;
|
||||
if (!e || !sel || n != 1 || !rad_enc_is(e, "affine") || e->n_planes != 2 ||
|
||||
e->plane[0].dtype != RAD_F8E4M3 || e->plane[1].dtype != RAD_F32 ||
|
||||
e->plane[1].block[0] != 128 || e->plane[1].block[1] != 128 ||
|
||||
sel[0] != (operand == 3 || operand == 7 ? 1 : 0))
|
||||
return RAD_E_DTYPE;
|
||||
return RAD_E_UNSUPPORTED; // Both canonical planes are read without a relayout.
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// halo_gemm_fp8a16_m1.hip - gemm_fp8a16_nt_m1: block-scaled FP8 matvec against the
|
||||
// checkpoint's own weight bytes. C[M, N] bf16 = X[M, K] bf16 @ dequant(W)[N, K]^T with W
|
||||
// E4M3 row-major and a bf16 scale per 128x128 tile at [ceil(N/128)][ceil(K/128)].
|
||||
//
|
||||
// One wave owns `rb` weight rows (the row's one tunable; 0 is libhalo's rule, 4). Within a
|
||||
// row the lanes walk 16-byte chunks of K, decode E4M3 in pairs, and fold the block scale of
|
||||
// the chunk's 128-group into the partial before the xor butterfly closes the row. The weight
|
||||
// stream is the whole cost: at M rows the activation row is re-read from L2 per row, which
|
||||
// is why one weight read serves all M <= 8 rows inside the lane loop.
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_fp8_wmma.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace {
|
||||
|
||||
__global__ void __launch_bounds__(128) fp8a16_mv_kernel(const uint16_t* __restrict__ x,
|
||||
const uint8_t* __restrict__ w,
|
||||
const uint16_t* __restrict__ ws,
|
||||
uint16_t* __restrict__ y,
|
||||
int M, int N, long K, int sk, int rb,
|
||||
long a_ld, long w_ld, long sw_ld,
|
||||
long c_ld) {
|
||||
const int lane = (int)threadIdx.x & 31;
|
||||
const int wave = (int)threadIdx.x >> 5;
|
||||
const int n0 = ((int)blockIdx.x * 4 + wave) * rb;
|
||||
const long nchunks = K >> 4; /* 16 codes a chunk */
|
||||
for (int r = 0; r < rb; ++r) {
|
||||
const int n = n0 + r;
|
||||
if (n >= N) return;
|
||||
const uint8_t* wr = w + (long)n * w_ld;
|
||||
const uint16_t* sr = ws + (long)(n >> 7) * sw_ld;
|
||||
float acc[8];
|
||||
#pragma unroll
|
||||
for (int m = 0; m < 8; ++m) acc[m] = 0.0f;
|
||||
for (long c = lane; c < nchunks; c += 32) {
|
||||
const long k0 = c << 4;
|
||||
const float wsc = bf16_to_f32(sr[k0 >> 7]);
|
||||
const uint4 wb = *(const uint4*)(wr + k0);
|
||||
const uint32_t qw[4] = { wb.x, wb.y, wb.z, wb.w };
|
||||
for (int m = 0; m < M; ++m) {
|
||||
const uint16_t* xr = x + (long)m * a_ld + k0;
|
||||
const uint4 xb0 = *(const uint4*)xr; /* elements 0..7 */
|
||||
const uint4 xb1 = *(const uint4*)(xr + 8); /* elements 8..15 */
|
||||
const uint32_t xp[8] = { xb0.x, xb0.y, xb0.z, xb0.w, xb1.x, xb1.y, xb1.z, xb1.w };
|
||||
float part = 0.0f;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
/* qw[d]'s bytes are elements 4d..4d+3; xp[2d], xp[2d+1] pack their bf16
|
||||
* halves in the same order. */
|
||||
const v2f wlo = halo_fp8::e4m3_pk<false>(qw[d]);
|
||||
const v2f whi = halo_fp8::e4m3_pk<true>(qw[d]);
|
||||
part = fmaf(wlo.x, bf16_to_f32((uint16_t)(xp[2 * d] & 0xffffu)), part);
|
||||
part = fmaf(wlo.y, bf16_to_f32((uint16_t)(xp[2 * d] >> 16)), part);
|
||||
part = fmaf(whi.x, bf16_to_f32((uint16_t)(xp[2 * d + 1] & 0xffffu)), part);
|
||||
part = fmaf(whi.y, bf16_to_f32((uint16_t)(xp[2 * d + 1] >> 16)), part);
|
||||
}
|
||||
acc[m] = fmaf(wsc, part, acc[m]);
|
||||
}
|
||||
}
|
||||
for (int m = 0; m < M; ++m) {
|
||||
float v = acc[m];
|
||||
#pragma unroll
|
||||
for (int mask = 16; mask; mask >>= 1) v += __shfl_xor(v, mask);
|
||||
if (lane == 0) y[(long)m * c_ld + n] = f32_to_bf16(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
extern "C" int halo_rad_gemm_fp8a16_m1(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* X = halo_opt(a, 0);
|
||||
const RadTensor* W = halo_opt(a, 2);
|
||||
const RadTensor* S = halo_opt(a, 3);
|
||||
const RadTensor* Y = halo_opt(a, 4);
|
||||
if (!X || !W || !S || !Y) return HALO_NO(RAD_E_INVAL);
|
||||
if (X->dtype != RAD_BF16 || W->dtype != RAD_F8E4M3 || S->dtype != RAD_BF16 ||
|
||||
Y->dtype != RAD_BF16)
|
||||
return HALO_NO(RAD_E_DTYPE);
|
||||
const char* dt = halo_gets(a, "dtype");
|
||||
if (!dt || std::strcmp(dt, "fp8a16")) return HALO_NO(RAD_E_DTYPE);
|
||||
if (halo_geti_or(a, "group", 128) != 128) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
const long long K = halo_geti_or(a, "K", halo_dim(W, (int)W->rank - 1));
|
||||
const long long N = halo_geti_or(a, "N", K > 0 ? halo_numel(W) / K : 0);
|
||||
/* The rows are X's; `M` is the band (at most 8 here), which a step may undershoot. */
|
||||
if (K <= 0 || (K % 128) || N <= 0) return HALO_NO(RAD_E_SHAPE);
|
||||
const long long M = halo_numel(X) / K;
|
||||
if (M < 1 || M > 8 || M > halo_geti_or(a, "M", M)) return HALO_NO(RAD_E_SHAPE);
|
||||
if (halo_numel(X) < M * K || halo_numel(W) < N * K || halo_numel(Y) < M * N)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
const long long sk = (K + 127) / 128;
|
||||
if (halo_numel(S) < ((N + 127) / 128) * sk) return HALO_NO(RAD_E_SHAPE);
|
||||
if (!halo_contig(X) || !halo_contig(W) || !halo_contig(S) || !halo_contig(Y))
|
||||
return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
HaloMvCfg mv;
|
||||
halo_cfg_mv(a, &mv);
|
||||
const int rb = mv.rb > 0 ? mv.rb : 4;
|
||||
const int waves = (int)((N + rb - 1) / rb);
|
||||
fp8a16_mv_kernel<<<dim3((waves + 3) / 4), 128, 0, (hipStream_t)stream>>>(
|
||||
(const uint16_t*)halo_p(X), (const uint8_t*)halo_p(W), (const uint16_t*)halo_p(S),
|
||||
(uint16_t*)halo_p(Y), (int)M, (int)N, K, (int)sk, rb, K, K, sk, N);
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* The raw-pointer entries libr4d exports beside the row (halo.h): same kernel, the row's
|
||||
* strides spelled out. Negative codes, as libr4d's: -1 a null pointer, -2 a non-positive
|
||||
* extent, -3 M past the band, -4 K not a whole 128-block, -5 an rb the kernel has no arm
|
||||
* for, -6 the launch failed. */
|
||||
extern "C" int halo_gemm_fp8a16_nt_m1_block(void) { return 128; }
|
||||
extern "C" int halo_gemm_fp8a16_nt_m1_max_m(void) { return 8; }
|
||||
|
||||
static int fp8a16_mv_launch(long a, long wq, long ws, long c, int M, int K, int N,
|
||||
int a_ld, int c_ld, int w_ld, int sw_ld, int rb, long stream) {
|
||||
if (!a || !wq || !ws || !c) return -1;
|
||||
if (M <= 0 || K <= 0 || N <= 0) return -2;
|
||||
if (M > 8) return -3;
|
||||
if (K % 128) return -4;
|
||||
if (rb != 0 && rb != 1 && rb != 2 && rb != 4 && rb != 8) return -5;
|
||||
if (!a_ld) a_ld = K;
|
||||
if (!c_ld) c_ld = N;
|
||||
if (!w_ld) w_ld = K;
|
||||
if (!sw_ld) sw_ld = K / 128;
|
||||
if (!rb) rb = 4;
|
||||
const int waves = (N + rb - 1) / rb;
|
||||
fp8a16_mv_kernel<<<dim3((waves + 3) / 4), 128, 0, (hipStream_t)stream>>>(
|
||||
(const uint16_t*)(uintptr_t)a, (const uint8_t*)(uintptr_t)wq,
|
||||
(const uint16_t*)(uintptr_t)ws, (uint16_t*)(uintptr_t)c, M, N, K, K / 128, rb,
|
||||
a_ld, w_ld, sw_ld, c_ld);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -6;
|
||||
}
|
||||
|
||||
extern "C" int halo_gemm_fp8a16_nt_m1(long a, long wq, long ws, long c, int M, int K, int N,
|
||||
int w_ld, int sw_ld, int rb, long stream) {
|
||||
if (!a || !wq || !ws || !c) return -1;
|
||||
if (M <= 0 || K <= 0 || N <= 0) return -2;
|
||||
if (M > 1) return -3;
|
||||
return fp8a16_mv_launch(a, wq, ws, c, M, K, N, K, N, w_ld, sw_ld, rb, stream);
|
||||
}
|
||||
|
||||
extern "C" int halo_gemm_fp8a16_nt_mt(long a, long wq, long ws, long c, int M, int K, int N,
|
||||
int a_ld, int c_ld, int w_ld, int sw_ld, long stream) {
|
||||
return fp8a16_mv_launch(a, wq, ws, c, M, K, N, a_ld, c_ld, w_ld, sw_ld, 0, stream);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,379 @@
|
||||
/* Derived from libr4d/r4d_gemm_mxfp4a8_decode.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_mxfp4a8_decode.hip - gemm_mxfp4a8_decode and gemm_mxfp4a8_decode_shortk (the
|
||||
// same entry point): the MXFP4 GEMM at M up to 128 with K split across workgroups.
|
||||
//
|
||||
// Split partials land in the op's scratch, one f32 [M][N] plane a split, and a second kernel
|
||||
// sums the planes in split order (times the per-row activation scale on the per-row grid).
|
||||
// The summation order is the split index order at every M, so a row's bits do not depend on
|
||||
// how many rows ride with it; with ks == 1 the GEMM kernel writes the output itself and no
|
||||
// scratch is touched. libr4d fuses the reduction into the last workgroup to arrive (arrival
|
||||
// counters keyed on the output); the separate reduction kernel is the same arithmetic with
|
||||
// no shared state at all, which is what the row's concurrent-stream contract wants: two
|
||||
// launches on unordered streams with disjoint scratch slices cannot interfere, and there
|
||||
// are no counters to leave behind.
|
||||
//
|
||||
// The per-element accumulation is the skinny kernel's: bf16 WMMA over 16-wide steps, the
|
||||
// weight element e2m1 * 2^(exp - ref) exact in bf16, folds at each 32-block close (and at
|
||||
// the split's end) with 2^(ref - 127) and the (row, 128) activation scale.
|
||||
#include "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_plugin.h" // halo_rad_gemm_mxfp4a8_tiled: the band past 64 rows
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include "halo_fp8_wmma.h"
|
||||
#include "halo_wmma.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
|
||||
#define WAVE32 32
|
||||
|
||||
typedef int int4v __attribute__((ext_vector_type(4)));
|
||||
|
||||
__device__ __forceinline__ v16bf mxd_deq16_exact(const uint32_t* __restrict__ w4) {
|
||||
union { uint32_t u[8]; v16bf f; } q;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
const v2f p0 = halo_fp8::e4m3_pk<false>(w4[d]);
|
||||
const v2f p1 = halo_fp8::e4m3_pk<true>(w4[d]);
|
||||
q.u[d * 2] = halo::pk_bf16(p0.x, p0.y);
|
||||
q.u[d * 2 + 1] = halo::pk_bf16(p1.x, p1.y);
|
||||
}
|
||||
return q.f;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ unsigned mxd_e2m1_bf16(unsigned code, int ediff) {
|
||||
const unsigned mag = code & 7u;
|
||||
if (!mag) return (code & 8u) << 12;
|
||||
unsigned E = mag >> 1, m = mag & 1u;
|
||||
if (mag == 1) m = 0; /* the subnormal 0.5 */
|
||||
const unsigned ef = E + (unsigned)(ediff + 126);
|
||||
return ((code & 8u) << 12) | (ef << 7) | (m << 6);
|
||||
}
|
||||
|
||||
/* Eight e2m1 codes at one (exp - ref) to four bf16-pair dwords, four codes a pass:
|
||||
* halo_gemm_mxfp4a8_tiled.hip's mxt_frag8 (that file says how), bit-identical to the scalar
|
||||
* form for every code and every ediff with 0 <= E + ediff + 126 <= 255. */
|
||||
typedef unsigned short mxd_us2 __attribute__((ext_vector_type(2)));
|
||||
__device__ __forceinline__ void mxd_frag8(unsigned dw, int ediff, uint32_t* out) {
|
||||
const uint32_t ed = (uint32_t)(ediff << 7) & 0xFFFFu;
|
||||
const mxd_us2 ED2 = __builtin_bit_cast(mxd_us2, ed | (ed << 16));
|
||||
const uint32_t z = (0u - ed) & 0xFFFFu;
|
||||
const uint32_t T_LO = 0xC0800000u | (z & 0xFFu), T_HI = 0x3F3F3F00u | (z >> 8);
|
||||
#pragma unroll
|
||||
for (int h = 0; h < 2; ++h) {
|
||||
const uint32_t x = __builtin_amdgcn_perm(dw, dw, h ? 0x03030202u : 0x01010000u);
|
||||
const uint32_t mag = (x & 0x00070007u) | ((x >> 4) & 0x07000700u);
|
||||
const uint32_t sg = ((x << 4) & 0x00800080u) | (x & 0x80008000u);
|
||||
const uint32_t lo = __builtin_amdgcn_perm(0xC0804000u, T_LO, mag);
|
||||
const uint32_t hi = __builtin_amdgcn_perm(0x40404040u, T_HI, mag);
|
||||
const mxd_us2 p0 = __builtin_bit_cast(mxd_us2, __builtin_amdgcn_perm(hi, lo, 0x05010400u)) + ED2;
|
||||
const mxd_us2 p1 = __builtin_bit_cast(mxd_us2, __builtin_amdgcn_perm(hi, lo, 0x07030602u)) + ED2;
|
||||
out[2 * h] = __builtin_bit_cast(uint32_t, p0) | __builtin_amdgcn_perm(0u, sg, 0x010C000Cu);
|
||||
out[2 * h + 1] = __builtin_bit_cast(uint32_t, p1) | __builtin_amdgcn_perm(0u, sg, 0x030C020Cu);
|
||||
}
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v16bf mxd_frag16(unsigned dw0, unsigned dw1, int exp, int ref) {
|
||||
union { uint32_t u[8]; v16bf f; } q;
|
||||
mxd_frag8(dw0, exp - ref, q.u);
|
||||
mxd_frag8(dw1, exp - ref, q.u + 4);
|
||||
return q.f;
|
||||
}
|
||||
|
||||
/* One split's partial: rows [0, M), its K range [kbase, kbase + Ks). Writes f32 partials
|
||||
* (PARTIAL) or the bf16 output directly (ks == 1). WPW waves share a block; a wave's tile
|
||||
* and its K order are unchanged by the block's width, so the output bits do not depend
|
||||
* on WPW -- it only buys latency hiding on a part whose grid is otherwise a wave a CU. */
|
||||
template <int MT, int NPW, bool ABLK, bool PARTIAL, int WPW = 8>
|
||||
__global__ __launch_bounds__(WPW * WAVE32) void mxd_partial_kernel(
|
||||
const unsigned char* __restrict__ A, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, void* __restrict__ Out,
|
||||
int M, int K, int N, int lda, int ldws, int ldc, int kbase, int Ks, int as_rs,
|
||||
const uint16_t* __restrict__ Adq = nullptr) {
|
||||
const int lane = threadIdx.x & (WAVE32 - 1), wave = threadIdx.x / WAVE32;
|
||||
const int nt0 = ((int)blockIdx.x * WPW + wave) * NPW;
|
||||
const int mt0 = (int)blockIdx.y * MT;
|
||||
const int nlane = lane & 15;
|
||||
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
|
||||
const int ksteps = K / 16;
|
||||
const int kend = kbase + Ks;
|
||||
|
||||
const int ntmax = N / 16 - 1;
|
||||
int wtile[NPW], wrow[NPW];
|
||||
float rf[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int t = nt0 + j;
|
||||
wtile[j] = t < ntmax ? t : ntmax;
|
||||
wrow[j] = wtile[j] * 16 + nlane;
|
||||
rf[j] = __int_as_float((int)Wref[wrow[j]] << 23);
|
||||
}
|
||||
|
||||
v8f acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
v8f tmp[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) tmp[j][i] = (v8f)(0.f);
|
||||
|
||||
for (int kg = kbase; kg < kend; kg += 16) {
|
||||
const int kstep = kg / 16;
|
||||
v16bf af[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
int r = (mt0 + i) * 16 + nlane;
|
||||
r = r < M - 1 ? r : M - 1;
|
||||
if (Adq) {
|
||||
/* The launch's activation plane (mxd_deq16_exact's outputs, [M, K] bf16). */
|
||||
const uint16_t* src = Adq + (size_t)r * K + kg;
|
||||
uint32_t* dst = (uint32_t*)&af[i];
|
||||
*(uint4*)dst = *(const uint4*)src;
|
||||
*(uint4*)(dst + 4) = *(const uint4*)(src + 8);
|
||||
} else {
|
||||
const int4v av = *(const int4v*)(A + (size_t)r * lda + kg);
|
||||
af[i] = mxd_deq16_exact((const uint32_t*)&av);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int n = wrow[j];
|
||||
const unsigned dw0 = Wp[((size_t)wtile[j] * ksteps + kstep) * WAVE32 + nlane];
|
||||
const unsigned dw1 = Wp[((size_t)wtile[j] * ksteps + kstep) * WAVE32 + 16 + nlane];
|
||||
const v16bf bf = mxd_frag16(dw0, dw1,
|
||||
(int)Ws[(size_t)(kg / 32) * ldws + n], (int)Wref[n]);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) tmp[j][i] = halo::mma(af[i], bf, tmp[j][i]);
|
||||
}
|
||||
if (((kg + 16) % 32 == 0) || (kg + 16 == kend)) {
|
||||
/* The 32-block (or the split tail) closed: fold it. kg/128 is its scale group. */
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
float f = rf[j];
|
||||
if constexpr (ABLK) {
|
||||
int r = (mt0 + i) * 16 + 2 * e + (lane >> 4);
|
||||
r = r < M - 1 ? r : M - 1;
|
||||
f *= As[(size_t)r * as_rs + (kg >> 7)];
|
||||
}
|
||||
acc[j][i][e] = fmaf(tmp[j][i][e], f, acc[j][i][e]);
|
||||
tmp[j][i][e] = 0.f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int n = nt0 * 16 + j * 16 + nlane;
|
||||
if (n >= N) continue;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
const int mb = (mt0 + i) * 16;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int m = mb + accRow(lane, e);
|
||||
if (m >= M) continue;
|
||||
if constexpr (PARTIAL) {
|
||||
((float*)Out)[(size_t)m * N + n] = acc[j][i][e];
|
||||
} else {
|
||||
((__hip_bfloat16*)Out)[(size_t)m * ldc + n] =
|
||||
(__hip_bfloat16)(ABLK ? acc[j][i][e] : acc[j][i][e] * As[m]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* The split reduction. `N` is the part's width (the partial planes' stride) and `ldc` the output's
|
||||
* row pitch: a part is a window of the real [M, N_full] output at column `n0`, so with a partitioned
|
||||
* weight N != ldc and writing at idx would land the part's columns in the wrong place (and leave
|
||||
* the rest of the row at its initial NaN). */
|
||||
template <bool ABLK>
|
||||
__global__ void mxd_reduce_kernel(const float* __restrict__ P, const float* __restrict__ As,
|
||||
__hip_bfloat16* __restrict__ C, int M, int N, int ldc, int ks) {
|
||||
const long idx = (long)blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (idx >= (long)M * N) return;
|
||||
const int m = (int)(idx / N), n = (int)(idx % N);
|
||||
float v = 0.f;
|
||||
for (int s = 0; s < ks; ++s) v += P[(size_t)s * M * N + idx];
|
||||
if constexpr (!ABLK) v *= As[m];
|
||||
C[(size_t)m * ldc + n] = (__hip_bfloat16)v;
|
||||
}
|
||||
|
||||
/* The activation plane: mxd_deq16_exact over the whole [M, K) activation, once per
|
||||
* launch; the partial kernel's waves read fragments instead of each
|
||||
* re-dequantising the same codes for its column. Bit-identical products. */
|
||||
__global__ __launch_bounds__(256) void mxd_adq_kernel(const unsigned char* __restrict__ A,
|
||||
uint16_t* __restrict__ Adq,
|
||||
int M, int K, int lda) {
|
||||
const int idx = blockIdx.x * (int)blockDim.x + threadIdx.x;
|
||||
if (idx >= M * (K / 16)) return;
|
||||
const int r = idx / (K / 16), c = (idx % (K / 16)) * 16;
|
||||
const int4v av = *(const int4v*)(A + (size_t)r * lda + c);
|
||||
const v16bf f = mxd_deq16_exact((const uint32_t*)&av);
|
||||
uint4* dst = (uint4*)(Adq + (size_t)r * K + c);
|
||||
const uint4* src = (const uint4*)&f;
|
||||
dst[0] = src[0];
|
||||
dst[1] = src[1];
|
||||
}
|
||||
|
||||
/* The fill rule for the split count: enough workgroups to occupy the card, from (N, K)
|
||||
* alone so a row's bits never depend on M. Legal splits divide K/32. The smallest split
|
||||
* that fills the card wins: a wider split is more launches and more partial traffic
|
||||
* for the same waves. (An earlier form took the largest, which at this geometry split
|
||||
* a full-width part sixteen ways for no occupancy gain.) */
|
||||
static int mxd_ks_law(long long N, long long K) {
|
||||
const long long tiles = N / 16;
|
||||
const long long colblocks = (tiles + 7) / 8; /* WPW 8 waves x NPW 1 tiles a block */
|
||||
for (int s : { 1, 2, 4, 8, 16 }) {
|
||||
if (((K / 32) % s) == 0 && colblocks * s >= 40) return s;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
template <bool ABLK>
|
||||
static int mxd_run(const RadArgs* a, RadStream s, const GemmOps& g, const MxParts& mp,
|
||||
int as_rs) {
|
||||
const long long M = g.M, K = g.K;
|
||||
const int ks_t = (int)halo_geti_or(a, "ks", 0);
|
||||
(void)halo_geti_or(a, "bk", 0); /* the slab: folded per 32 either way */
|
||||
(void)halo_geti_or(a, "nt", 0); /* the load hint */
|
||||
int ks = ks_t > 0 ? ks_t : mxd_ks_law(g.N, g.K);
|
||||
if (ks > 1 && ((K / 32) % ks)) ks = 1;
|
||||
const long long plane = M * g.N * 4;
|
||||
/* A split needs one f32 plane per split in the op's scratch, and a shorter one is refused
|
||||
* rather than clamped: the row's bits depend on the split count, so silently reducing it would
|
||||
* answer a shape with a different kernel than the one the hook sized the scratch for (and a
|
||||
* caller that under-sized it hears about it here, as libr4d's row does). */
|
||||
if (ks > 1) {
|
||||
while (ks > 1 && ((K / 32) % ks)) --ks;
|
||||
if (!a->scratch || a->scratch_bytes < (long long)ks * plane)
|
||||
return HALO_NO(RAD_E_SCRATCH);
|
||||
}
|
||||
const long long kb = (K + 127) / 128;
|
||||
for (int p = 0; p < mp.n; ++p) {
|
||||
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
|
||||
const int lda = (int)(mp.lda ? mp.lda : K);
|
||||
const float* as_base = (const float*)(halo_addr(g.ascale) + p * kb * 4);
|
||||
/* The activation plane sits behind this part's split partials in the
|
||||
* scratch (at offset 0 when the direct path writes none). Callers that
|
||||
* sized no room for it keep the in-kernel decode. */
|
||||
const long long partial_bytes = ks > 1 ? (long long)ks * M * np * 4 : 0;
|
||||
const uint16_t* adq = nullptr;
|
||||
if (a->scratch && a->scratch_bytes >= partial_bytes + (long long)M * K * 2) {
|
||||
adq = (const uint16_t*)((const char*)a->scratch + partial_bytes);
|
||||
const int total = (int)(M * (K / 16));
|
||||
hipLaunchKernelGGL((mxd_adq_kernel), dim3((total + 255) / 256), 256, 0, (hipStream_t)s,
|
||||
(const unsigned char*)halo_addr(g.a) + p * K, (uint16_t*)adq, (int)M, (int)K, lda);
|
||||
}
|
||||
/* One tile a wave (NPW 1) and, at M <= 16, one M tile: this part has no
|
||||
* in-block split, so the wave count is its parallelism -- NPW 2 halves it and
|
||||
* measured ~2x slower here, unlike the m64 kernel where SK supplies waves.
|
||||
* Per-output accumulation order is unchanged either way. */
|
||||
auto launch_partial = [&](int split, int kbase, int Ks, void* out, bool partial) {
|
||||
const int mt = M <= 16 ? 1 : 2;
|
||||
const dim3 grid((unsigned)((np / 16 + 7) / 8), (unsigned)((M + mt * 16 - 1) / (mt * 16)), 1);
|
||||
auto emit = [&](auto kern) {
|
||||
hipLaunchKernelGGL((kern), grid, 256, 0, (hipStream_t)s,
|
||||
(const unsigned char*)halo_addr(g.a) + p * K, as_base,
|
||||
(const unsigned char*)halo_addr(g.b) + n0 * K / 2,
|
||||
(const unsigned char*)halo_addr(g.bscale) + n0,
|
||||
(const unsigned char*)halo_addr(g.bref) + n0, out,
|
||||
(int)M, (int)K, (int)np, lda, (int)g.N, (int)g.N, kbase, Ks, as_rs, adq);
|
||||
};
|
||||
if (partial) {
|
||||
if (ABLK) { if (mt == 1) emit(mxd_partial_kernel<1, 1, true, true>); else emit(mxd_partial_kernel<2, 1, true, true>); }
|
||||
else { if (mt == 1) emit(mxd_partial_kernel<1, 1, false, true>); else emit(mxd_partial_kernel<2, 1, false, true>); }
|
||||
} else {
|
||||
if (ABLK) { if (mt == 1) emit(mxd_partial_kernel<1, 1, true, false>); else emit(mxd_partial_kernel<2, 1, true, false>); }
|
||||
else { if (mt == 1) emit(mxd_partial_kernel<1, 1, false, false>); else emit(mxd_partial_kernel<2, 1, false, false>); }
|
||||
}
|
||||
};
|
||||
if (ks == 1) {
|
||||
launch_partial(0, 0, (int)K,
|
||||
(void*)((const char*)halo_p(g.y) + (size_t)n0 * 2), false);
|
||||
} else {
|
||||
const int Ks = (int)(K / ks);
|
||||
for (int sp = 0; sp < ks; ++sp)
|
||||
launch_partial(sp, sp * Ks, Ks,
|
||||
(char*)a->scratch + (size_t)sp * M * np * 4, true);
|
||||
const long elems = M * np;
|
||||
const int threads = 256;
|
||||
const long blocks = (elems + threads - 1) / threads;
|
||||
if (ABLK)
|
||||
hipLaunchKernelGGL((mxd_reduce_kernel<true>), (unsigned)blocks, threads, 0, (hipStream_t)s,
|
||||
(const float*)a->scratch, as_base,
|
||||
(__hip_bfloat16*)((const char*)halo_p(g.y) + (size_t)n0 * 2),
|
||||
(int)M, (int)np, (int)g.N, ks);
|
||||
else
|
||||
hipLaunchKernelGGL((mxd_reduce_kernel<false>), (unsigned)blocks, threads, 0, (hipStream_t)s,
|
||||
(const float*)a->scratch, as_base,
|
||||
(__hip_bfloat16*)((const char*)halo_p(g.y) + (size_t)n0 * 2),
|
||||
(int)M, (int)np, (int)g.N, ks);
|
||||
}
|
||||
if (hipGetLastError() != hipSuccess) return HALO_NO(RAD_E_DEVICE);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int64_t halo_rad_gemm_mxfp4a8_decode_scratch(const RadArgs* a) {
|
||||
const long long M = halo_geti_or(a, "M", 0);
|
||||
const long long N = halo_geti_or(a, "N", 0);
|
||||
const long long K = halo_geti_or(a, "K", 0);
|
||||
if (M <= 0 || N <= 0 || K <= 0) return 0;
|
||||
int ks = (int)halo_geti_or(a, "ks", 0);
|
||||
if (ks <= 0) ks = mxd_ks_law(N, K);
|
||||
if (ks > 1 && ((K / 32) % ks)) ks = 1;
|
||||
return (int64_t)ks * M * N * 4 + M * K * 2; /* partials + the activation plane */
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_gemm_mxfp4a8_decode(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N % 16) return HALO_NO(RAD_E_SHAPE);
|
||||
if (g.M < 1 || g.M > 128) return HALO_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale) return HALO_NO(RAD_E_INVAL);
|
||||
if (!g.bref) return HALO_NO(RAD_E_INVAL);
|
||||
/* Past 64 rows the tiled row's kernel (byte-identical to nt_m64 at one split): this
|
||||
* kernel's M unroll costs more than the tile there (3.2 ms against 1.3 ms at M 128, N 5120,
|
||||
* K 25600; 2.1 against 1.3 at M 65). The row's bits stay M-invariant through 64 rows, the
|
||||
* band the verify steps and the gemv rows share; at 64 -> 65 the selection changes rows
|
||||
* anyway. The scratch the hook sized holds the tiled kernel's activation plane. */
|
||||
if (g.M > 64) return halo_rad_gemm_mxfp4a8_tiled(a, s);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
if (rc != RAD_OK) return rc;
|
||||
int as_group = 0, as_rs = 1;
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
|
||||
if (rc != RAD_OK) return rc;
|
||||
/* Past one row tile at one split (the law's answer from 640 column tiles up, so every
|
||||
* decode_shortk shape), the LDS-staged tile at one split: the same bytes (one chain of folds
|
||||
* in K order, stored as is), the weight read once for all the rows rather than once a 32-row
|
||||
* block (19456 x 2560 at 64 rows: 520 -> ~320 us on gfx1151). The plane sits where mxd_run
|
||||
* puts it, at the scratch's start when there are no partials. */
|
||||
{
|
||||
const int ks_t = (int)halo_geti_or(a, "ks", 0);
|
||||
int ks = ks_t > 0 ? ks_t : mxd_ks_law(g.N, g.K);
|
||||
if (ks > 1 && ((g.K / 32) % ks)) ks = 1;
|
||||
if (ks == 1 && g.M > 16) {
|
||||
rc = halo_mxfp4a8_tiled_split(a, s, g, mp, as_group, as_rs, 1);
|
||||
if (rc != RAD_E_UNSUPPORTED) return rc;
|
||||
}
|
||||
}
|
||||
return as_group == 128 ? mxd_run<true>(a, s, g, mp, as_rs)
|
||||
: mxd_run<false>(a, s, g, mp, as_rs);
|
||||
}
|
||||
|
||||
/* The raw-pointer query libr4d exports beside the row (halo.h): the decode band's
|
||||
* widest M, 16 rows a tile times the 8-deep M unroll. */
|
||||
extern "C" int halo_gemm_mxfp4a8_decode_max_m(void) { return 128; }
|
||||
@@ -0,0 +1,431 @@
|
||||
/* Derived from libr4d/r4d_gemm_mxfp4a8_gemv.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_mxfp4a8_gated.hip - gemm_mxfp4a8_gated_gemv: the m64 kernel's WMMA form over a gate_up
|
||||
// weight with gated_quant_fp8's pass in its epilogue, gfx1151. The row's constraint set is M <= 8,
|
||||
// K a multiple of 128, N a multiple of 256. A block is one 16-column tile of the gated output:
|
||||
// sixteen waves, eight K waves over the gate tile (weight rows 16 j ..) and eight over the up tile
|
||||
// (rows n + 16 j ..), each tile's partials met in LDS in the m64 kernel's order.
|
||||
//
|
||||
// The block forms silu(gate) * up in bf16 for its sixteen columns and each row's amax over them.
|
||||
// The quantiser's scale is per 128 columns (one activation scale group of the down projection's
|
||||
// input), so the eight blocks of a group leave their products and amaxes in the op's scratch (a
|
||||
// bf16 product plane [M, n] and amax tiles [n/16][M]) and the last of a group's eight blocks to
|
||||
// arrive (an agent-scope counter per group, keyed on the output as the decode row's) takes the
|
||||
// group's amax and writes its codes and scales.
|
||||
//
|
||||
// Byte-identical to the m64 kernel (halo_gemm_mxfp4a8_nt_m64.hip, the row `gemm_mxfp4a8_gemv`
|
||||
// resolves to at every M) followed by gated_quant_fp8 on gfx1151, because the m64 kernel's
|
||||
// accumulation order is shape-deterministic and M-independent:
|
||||
// - A and W both dequantise to exact bf16 and take halo::mma (the bf16 WMMA, exact products),
|
||||
// the e2m1 fold per 32-block against the per-row reference, exactly m64's fragment arithmetic;
|
||||
// - a chunk is a whole 32-block pair (the m64 k-loop step), one (row, 128) activation scale per
|
||||
// chunk on the block-scaled grid, fmaf'd into the running total exactly as m64's fold; the
|
||||
// per-32 fold d = ref - e8 reads N and K only (never M), so wave v of a tile runs chunk
|
||||
// v, v+16, ... of the same block's chunk order, and the LDS partials are summed v = 0, 1, ...
|
||||
// from zero, as the m64 kernel's epilogue adds its waves' rows of red[] in split order;
|
||||
// - on the per-row grid the m64 kernel scales the total once at the store; here the scale
|
||||
// multiplies into the bf16 round before silu, which is what the pair (m64 then
|
||||
// gated_quant_fp8) does too;
|
||||
// - from there the arithmetic is halo_fused_quant_fp8.hip's gated_quant_fp8_kernel: silu(gate)
|
||||
// * up rounded to bf16, the group's amax (a max, so the blocks' order does not matter), scale
|
||||
// amax / 448, codes through q8_pack4. ACT 1 is the GeGLU form: gelu_mul's tanh GELU with its
|
||||
// constants (halo_model_bf16.hip), the product rounded to bf16 as gelu_mul stores it, then
|
||||
// quant_act_fp8's quantiser, the same arithmetic as gated_quant_fp8's.
|
||||
//
|
||||
// gfx1151 differences from the reference form: both fragments are the gfx11 layout (a lane holds
|
||||
// its one row's whole 16-wide k run of exact bf16), and the LDS partial is written at the gfx11
|
||||
// accumulator mapping sP[half][kv][2e + (lane>>4)][lane & 15] -- for each (m, c) exactly one
|
||||
// (lane, slot) writes, so the m64-order reduction over kv is unchanged. The A fragment is the
|
||||
// row's full sixteen bytes (gfx12's khalf split of the load is gone with the half-split fragment).
|
||||
#include "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include "halo_fp8_wmma.h"
|
||||
#include "halo_wmma.h"
|
||||
#include "halo_mxfp4.h"
|
||||
#include "halo_q8.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
|
||||
#define HALO_MXG_MAX_M 8 // the row's band (gemv's: M <= 8)
|
||||
#define HALO_MXGG_MAX_GROUPS 1024 // the gated fold's counter block: a gated width up to 131072
|
||||
|
||||
typedef unsigned mxg_u2 __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned mxg_u4 __attribute__((ext_vector_type(4)));
|
||||
typedef float mxg_v8f __attribute__((ext_vector_type(8)));
|
||||
|
||||
__device__ __forceinline__ float mxg_bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); }
|
||||
__device__ __forceinline__ uint16_t mxg_f2bf(float f) { // as halo_fused_quant_fp8.hip's f2bf
|
||||
const uint32_t u = __float_as_uint(f);
|
||||
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
|
||||
/* One e2m1 code and its block's (exp - ref) as a bf16 bit pattern (m64's arithmetic). */
|
||||
__device__ __forceinline__ unsigned mxg_e2m1_bf16(unsigned code, int ediff) {
|
||||
const unsigned mag = code & 7u;
|
||||
if (!mag) return (code & 8u) << 12;
|
||||
unsigned E = mag >> 1, m = mag & 1u;
|
||||
if (mag == 1) m = 0; /* the subnormal 0.5: (1 + 0) * 2^-1, not (1 + 1/2) * 2^-1 */
|
||||
const unsigned ef = E + (unsigned)(ediff + 126);
|
||||
return ((code & 8u) << 12) | (ef << 7) | (m << 6);
|
||||
}
|
||||
|
||||
/* Eight e2m1 codes at one (exp - ref) to four bf16-pair dwords, four codes a pass:
|
||||
* halo_gemm_mxfp4a8_tiled.hip's mxt_frag8 (that file says how), bit-identical to the scalar
|
||||
* form for every code and every ediff with 0 <= E + ediff + 126 <= 255. */
|
||||
typedef unsigned short mxg_us2 __attribute__((ext_vector_type(2)));
|
||||
__device__ __forceinline__ void mxg_frag8(unsigned dw, int ediff, uint32_t* out) {
|
||||
const uint32_t ed = (uint32_t)(ediff << 7) & 0xFFFFu;
|
||||
const mxg_us2 ED2 = __builtin_bit_cast(mxg_us2, ed | (ed << 16));
|
||||
const uint32_t z = (0u - ed) & 0xFFFFu;
|
||||
const uint32_t T_LO = 0xC0800000u | (z & 0xFFu), T_HI = 0x3F3F3F00u | (z >> 8);
|
||||
#pragma unroll
|
||||
for (int h = 0; h < 2; ++h) {
|
||||
const uint32_t x = __builtin_amdgcn_perm(dw, dw, h ? 0x03030202u : 0x01010000u);
|
||||
const uint32_t mag = (x & 0x00070007u) | ((x >> 4) & 0x07000700u);
|
||||
const uint32_t sg = ((x << 4) & 0x00800080u) | (x & 0x80008000u);
|
||||
const uint32_t lo = __builtin_amdgcn_perm(0xC0804000u, T_LO, mag);
|
||||
const uint32_t hi = __builtin_amdgcn_perm(0x40404040u, T_HI, mag);
|
||||
const mxg_us2 p0 = __builtin_bit_cast(mxg_us2, __builtin_amdgcn_perm(hi, lo, 0x05010400u)) + ED2;
|
||||
const mxg_us2 p1 = __builtin_bit_cast(mxg_us2, __builtin_amdgcn_perm(hi, lo, 0x07030602u)) + ED2;
|
||||
out[2 * h] = __builtin_bit_cast(uint32_t, p0) | __builtin_amdgcn_perm(0u, sg, 0x010C000Cu);
|
||||
out[2 * h + 1] = __builtin_bit_cast(uint32_t, p1) | __builtin_amdgcn_perm(0u, sg, 0x030C020Cu);
|
||||
}
|
||||
}
|
||||
|
||||
/* The B fragment from this lane's own slot dword (row l & 15, codes k + 8 * (l >> 4) .. + 8) to
|
||||
* sixteen exact bf16 in consecutive-K order (m64's mx_frag16x): each half unpacks its dword and
|
||||
* the halves trade results by v_permlanex16, so a slot is one load and each code one unpack. */
|
||||
__device__ __forceinline__ v16bf mxg_frag16x(unsigned dw, int exp, int ref, int lane) {
|
||||
uint32_t own[4], oth[4];
|
||||
mxg_frag8(dw, exp - ref, own);
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q)
|
||||
oth[q] = __builtin_amdgcn_permlanex16(own[q], own[q], 0x76543210u, 0xfedcba98u, false, false);
|
||||
const bool up = lane >= 16;
|
||||
union { uint32_t u[8]; v16bf f; } r;
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
r.u[q] = up ? oth[q] : own[q];
|
||||
r.u[4 + q] = up ? own[q] : oth[q];
|
||||
}
|
||||
return r.f;
|
||||
}
|
||||
|
||||
/* The A fragment: sixteen e4m3 bytes to the exact bf16 fragment (m64's mx_deq16_exact). */
|
||||
__device__ __forceinline__ v16bf mxg_af16(const uint32_t* __restrict__ w4) {
|
||||
union { uint32_t u[8]; v16bf f; } q;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
const v2f p0 = halo_fp8::e4m3_pk<false>(w4[d]);
|
||||
const v2f p1 = halo_fp8::e4m3_pk<true>(w4[d]);
|
||||
q.u[d * 2] = halo::pk_bf16(p0.x, p0.y);
|
||||
q.u[d * 2 + 1] = halo::pk_bf16(p1.x, p1.y);
|
||||
}
|
||||
return q.f;
|
||||
}
|
||||
|
||||
/* The activation plane: mxg_af16 over the whole [M, K) activation, once per launch, so the
|
||||
* blocks read their fragments instead of each re-decoding the same codes (n / 16 blocks of SK
|
||||
* waves). Values are mxg_af16's own; products through the plane are bit-identical. */
|
||||
__global__ __launch_bounds__(256) void mxg_adq_kernel(const unsigned char* __restrict__ A,
|
||||
uint16_t* __restrict__ Adq, int M, int K,
|
||||
int lda) {
|
||||
const int idx = blockIdx.x * (int)blockDim.x + threadIdx.x;
|
||||
if (idx >= M * (K / 16)) return;
|
||||
const int r = idx / (K / 16), c = (idx % (K / 16)) * 16;
|
||||
const v16bf f = mxg_af16((const uint32_t*)(A + (size_t)r * lda + c));
|
||||
uint4* dst = (uint4*)(Adq + (size_t)r * K + c);
|
||||
const uint4* src = (const uint4*)&f;
|
||||
dst[0] = src[0];
|
||||
dst[1] = src[1];
|
||||
}
|
||||
|
||||
template <bool ABLK, int ACT, bool APLANE>
|
||||
__global__ void halo_gemm_mxfp4a8_gated_kernel(
|
||||
const unsigned char* __restrict__ A, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, uint8_t* __restrict__ Q, float* __restrict__ S,
|
||||
uint16_t* __restrict__ Y, uint16_t* __restrict__ H, unsigned* __restrict__ cnt, int M, int K,
|
||||
int n, int SK, int as_rs, int lda, int ldws, int q_ld, int s_ld, int y_ld,
|
||||
const uint16_t* __restrict__ Adq) {
|
||||
// One block per 16-column tile of the gated output: SK waves, each a contiguous K split, as the
|
||||
// m64 kernel's geometry (halo_gemm_mxfp4a8_nt_m64.hip), whose accumulation order this row must
|
||||
// reproduce bit for bit. red[] holds each split's 8 accumulators per half: [2][SK][256].
|
||||
extern __shared__ float red[];
|
||||
__shared__ unsigned s_last;
|
||||
const int tid = threadIdx.x;
|
||||
const int lane = tid & 31;
|
||||
const int nwaves = __builtin_amdgcn_readfirstlane(blockDim.x >> 5);
|
||||
const int ksplit = __builtin_amdgcn_readfirstlane(tid >> 5);
|
||||
const int j = blockIdx.x; // the gated output's 16-column tile
|
||||
const int nlane = lane & 15;
|
||||
const int ntg = j, ntu = (n >> 4) + j; // the gate and up weight tiles
|
||||
const int wrowg = ntg * 16 + nlane, wrowu = ntu * 16 + nlane;
|
||||
const float rfg = __int_as_float((int)Wref[wrowg] << 23);
|
||||
const float rfu = __int_as_float((int)Wref[wrowu] << 23);
|
||||
const int Ks = K / SK, kbase = ksplit * Ks;
|
||||
const int ksteps = K >> 4;
|
||||
const unsigned* __restrict__ Wp = (const unsigned*)W;
|
||||
const int r = nlane < M - 1 ? nlane : M - 1; // m64's A-row clamp, discarded rows included
|
||||
mxg_v8f accg = (mxg_v8f)(0.f), accu = (mxg_v8f)(0.f);
|
||||
for (int k = kbase; k < kbase + Ks; k += 32) {
|
||||
mxg_v8f tg = (mxg_v8f)(0.f), tu = (mxg_v8f)(0.f);
|
||||
#pragma unroll
|
||||
for (int u = 0; u < 2; ++u) {
|
||||
const int kg = k + u * 16, kstep = kg >> 4;
|
||||
v16bf af;
|
||||
if constexpr (APLANE) {
|
||||
union { uint4 q[2]; v16bf f; } x;
|
||||
x.q[0] = *(const uint4*)(Adq + (size_t)r * K + kg);
|
||||
x.q[1] = *(const uint4*)(Adq + (size_t)r * K + kg + 8);
|
||||
af = x.f;
|
||||
} else {
|
||||
af = mxg_af16((const uint32_t*)(A + (size_t)r * lda + kg));
|
||||
}
|
||||
const unsigned gw = __builtin_nontemporal_load(&Wp[((size_t)ntg * ksteps + kstep) * 32 + lane]);
|
||||
tg = halo::mma(af, mxg_frag16x(gw, (int)Ws[(size_t)(k >> 5) * ldws + wrowg],
|
||||
(int)Wref[wrowg], lane),
|
||||
tg);
|
||||
const unsigned uw = __builtin_nontemporal_load(&Wp[((size_t)ntu * ksteps + kstep) * 32 + lane]);
|
||||
tu = halo::mma(af, mxg_frag16x(uw, (int)Ws[(size_t)(k >> 5) * ldws + wrowu],
|
||||
(int)Wref[wrowu], lane),
|
||||
tu);
|
||||
}
|
||||
// The 32-block's fold, exactly as m64's: f = rf, and on the block-scaled grid times the
|
||||
// element row's (row, 128) activation scale. The element row is 2e + (lane >> 4).
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int re = 2 * e + (lane >> 4);
|
||||
const int rc = re < M - 1 ? re : M - 1;
|
||||
float fg = rfg, fu = rfu;
|
||||
if constexpr (ABLK) {
|
||||
const float am = As[(size_t)rc * as_rs + (k >> 7)];
|
||||
fg *= am;
|
||||
fu *= am;
|
||||
}
|
||||
accg[e] = fmaf(tg[e], fg, accg[e]);
|
||||
accu[e] = fmaf(tu[e], fu, accu[e]);
|
||||
}
|
||||
}
|
||||
// Each split's partials in LDS, reduced in ascending split order as m64's epilogue sums its red[].
|
||||
float* __restrict__ sg_ = red + (size_t)ksplit * 256;
|
||||
float* __restrict__ su_ = red + (size_t)(SK + ksplit) * 256;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
sg_[e * 32 + lane] = accg[e];
|
||||
su_[e * 32 + lane] = accu[e];
|
||||
}
|
||||
__syncthreads();
|
||||
const int g = j >> 3; // the 128-column group
|
||||
if (tid < 256) {
|
||||
const int e = tid >> 5, l = tid & 31;
|
||||
const int m = 2 * e + (l >> 4), c = l & 15;
|
||||
float vg = 0.f, vu = 0.f;
|
||||
for (int s = 0; s < SK; ++s) {
|
||||
vg += red[(size_t)s * 256 + tid];
|
||||
vu += red[(size_t)(SK + s) * 256 + tid];
|
||||
}
|
||||
// m64's store: the per-row grid multiplies by As[m] once, the block-scaled grid does not.
|
||||
if constexpr (!ABLK) {
|
||||
const float am = As[(size_t)m * as_rs];
|
||||
vg *= am;
|
||||
vu *= am;
|
||||
}
|
||||
const uint16_t hg = mxg_f2bf(vg), hu = mxg_f2bf(vu);
|
||||
const float gv = mxg_bf2f(hg);
|
||||
// silu (SwiGLU) or the tanh GELU gelu_mul uses (GeGLU), both in float then rounded once.
|
||||
float a_;
|
||||
if constexpr (ACT == 0)
|
||||
a_ = gv / (1.0f + expf(-gv));
|
||||
else {
|
||||
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
|
||||
a_ = 0.5f * gv * (1.0f + tanhf(k0 * (gv + k1 * gv * gv * gv)));
|
||||
}
|
||||
const uint16_t h = mxg_f2bf(a_ * mxg_bf2f(hu));
|
||||
const int cg = j * 16 + c;
|
||||
if (m < M) {
|
||||
if (Y) Y[(size_t)m * y_ld + cg] = h;
|
||||
H[(size_t)m * n + cg] = h;
|
||||
}
|
||||
}
|
||||
// Every thread's stores are ordered before the counter; then the group's last arriver quantises.
|
||||
__threadfence();
|
||||
__syncthreads();
|
||||
if (tid == 0)
|
||||
s_last = __hip_atomic_fetch_add(&cnt[g], 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT);
|
||||
__syncthreads();
|
||||
if (s_last != 7u) return; // the group's eight blocks all landed
|
||||
if (tid == 0) cnt[g] = 0u; // reset for the next launch
|
||||
__threadfence(); // acquire, before reading the other blocks'
|
||||
// gated_quant_fp8's quantiser: one wave a row's group, a lane four consecutive columns.
|
||||
for (int m = __builtin_amdgcn_readfirstlane(tid >> 5); m < M; m += nwaves) {
|
||||
const int c0 = g * 128 + lane * 4;
|
||||
float v[4];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) v[i] = mxg_bf2f(H[(size_t)m * n + c0 + i]);
|
||||
float mx = fmaxf(fmaxf(fabsf(v[0]), fabsf(v[1])), fmaxf(fabsf(v[2]), fabsf(v[3])));
|
||||
#pragma unroll
|
||||
for (int o = 16; o > 0; o >>= 1) mx = fmaxf(mx, __shfl_xor(mx, o));
|
||||
const float sc = mx > 0.0f ? mx * (1.0f / q8_top<false>()) : 1.0f;
|
||||
if (lane == 0) S[(size_t)m * s_ld + g] = sc;
|
||||
const float inv = 1.0f / sc;
|
||||
*(uint32_t*)(Q + (size_t)m * q_ld + c0) = q8_pack4<false>(v[0], v[1], v[2], v[3], inv);
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
// The arrival counters, one block per output buffer, as the decode row's (mxd_out_ctr): not in the
|
||||
// scratch, which other ops overwrite, since they must be zero at entry. One allocation per (device,
|
||||
// output), kept zero by the reducer and never freed (a recorded pass replays the pointer).
|
||||
unsigned* mxgg_out_ctr(const void* out) {
|
||||
static std::mutex mu;
|
||||
static std::map<std::pair<int, const void*>, unsigned*> blocks;
|
||||
int dev = 0;
|
||||
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
const auto key = std::make_pair(dev, out);
|
||||
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
|
||||
unsigned* p = nullptr;
|
||||
if (hipMalloc((void**)&p, HALO_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess) return nullptr;
|
||||
// Zero before any launch reads it: the memset is on the null stream, which the engine's streams
|
||||
// need not wait for, so wait here (as mxd_out_ctr and the MoE router counters do).
|
||||
if (hipMemset(p, 0, HALO_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess ||
|
||||
hipDeviceSynchronize() != hipSuccess) {
|
||||
(void)hipFree(p);
|
||||
return nullptr;
|
||||
}
|
||||
blocks.emplace(key, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
// The scratch: the gated product [M, n] in bf16. The quantiser reads it back after the group's
|
||||
// last block arrives (it needs all 128 columns' values for the amax), so it cannot live in LDS.
|
||||
// Behind it, the decoded activation plane [M, K] bf16 when the hook sized it (else the blocks
|
||||
// decode in-kernel).
|
||||
long long mxgg_h_bytes(long long M, long long n) { return (M * n * 2 + 255) / 256 * 256; }
|
||||
long long mxgg_scratch_bytes(long long M, long long n) { return mxgg_h_bytes(M, n); }
|
||||
long long mxgg_plane_bytes(long long M, long long K) { return M * K * 2; }
|
||||
|
||||
void mxgg_launch(bool ablk, int act, const void* a, const void* as, const void* w, const void* ws,
|
||||
const void* wr, void* q, void* s, void* y, void* scratch, long long scratch_bytes,
|
||||
unsigned* cnt, int M, int K, int n, int SK, int as_rs, int lda, int ldws, int q_ld,
|
||||
int s_ld, int y_ld, RadStream stream) {
|
||||
const dim3 grid((uint32_t)(n / 16)), block((uint32_t)(SK * 32));
|
||||
const size_t smem = (size_t)2 * SK * 256 * sizeof(float);
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
uint16_t* h = (uint16_t*)scratch;
|
||||
const long long hb = mxgg_h_bytes(M, n);
|
||||
uint16_t* adq = scratch_bytes >= hb + mxgg_plane_bytes(M, K) ? (uint16_t*)((char*)scratch + hb)
|
||||
: nullptr;
|
||||
if (adq) {
|
||||
const int total = M * (K / 16);
|
||||
hipLaunchKernelGGL(mxg_adq_kernel, dim3((total + 255) / 256), dim3(256), 0, st,
|
||||
(const unsigned char*)a, adq, M, K, lda);
|
||||
}
|
||||
#define MXGG_G(AB_, ACT_, PL_) \
|
||||
hipLaunchKernelGGL((halo_gemm_mxfp4a8_gated_kernel<AB_, ACT_, PL_>), grid, block, smem, st, \
|
||||
(const unsigned char*)a, (const float*)as, (const unsigned char*)w, \
|
||||
(const unsigned char*)ws, (const unsigned char*)wr, (uint8_t*)q, (float*)s, \
|
||||
(uint16_t*)y, h, cnt, M, K, n, SK, as_rs, lda, ldws, q_ld, s_ld, y_ld, adq)
|
||||
#define MXGG_L(AB_, ACT_) do { if (adq) MXGG_G(AB_, ACT_, true); else MXGG_G(AB_, ACT_, false); } while (0)
|
||||
if (act == 0) { if (ablk) MXGG_L(true, 0); else MXGG_L(false, 0); }
|
||||
else { if (ablk) MXGG_L(true, 1); else MXGG_L(false, 1); }
|
||||
#undef MXGG_L
|
||||
#undef MXGG_G
|
||||
}
|
||||
} // namespace
|
||||
|
||||
|
||||
/* The gated GEMM's shim. Operand indices are `gemm_nt_q_gated_mx`'s (oGemmNtQGatedMx in
|
||||
* halo_rows.cpp): gemm_nt_q_gated's with the per-row reference `b_ref` after `b_scale`. The weight
|
||||
* is one [N, K] plane, gate rows then up rows, N = 2 * the gated width; no parts. */
|
||||
enum { MXGG_A = 0, MXGG_AS = 1, MXGG_B = 2, MXGG_BS = 3, MXGG_BR = 4, MXGG_Q = 5, MXGG_S = 6,
|
||||
MXGG_Y = 7 };
|
||||
|
||||
extern "C" int halo_rad_gemm_mxfp4a8_gated(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* x = halo_opt(a, MXGG_A);
|
||||
const RadTensor* xs = halo_opt(a, MXGG_AS);
|
||||
const RadTensor* w = halo_opt(a, MXGG_B);
|
||||
const RadTensor* ws = halo_opt(a, MXGG_BS);
|
||||
const RadTensor* wr = halo_opt(a, MXGG_BR);
|
||||
const RadTensor* q = halo_opt(a, MXGG_Q);
|
||||
const RadTensor* sc = halo_opt(a, MXGG_S);
|
||||
const RadTensor* y = halo_opt(a, MXGG_Y);
|
||||
if (!x || !xs || !w || !ws || !wr || !q || !sc) return HALO_NO(RAD_E_INVAL);
|
||||
if (x->dtype != RAD_F8E4M3 || xs->dtype != RAD_F32 || q->dtype != RAD_F8E4M3 ||
|
||||
sc->dtype != RAD_F32 || (y && y->dtype != RAD_BF16))
|
||||
return HALO_NO(RAD_E_DTYPE);
|
||||
if (q->rank != 2 || sc->rank != 2 || x->rank != 2) return HALO_NO(RAD_E_SHAPE);
|
||||
if (y && y->rank != 2) return HALO_NO(RAD_E_SHAPE);
|
||||
if (halo_geti_or(a, "group", 32) != 32) return HALO_NO(RAD_E_SHAPE);
|
||||
/* silu (the SwiGLU MLP) or gelu_tanh (GeGLU, gelu_mul's). The GeGLU chain's bf16 plane is
|
||||
* gelu_mul's output, which the fold's replaces-hook cannot hand to the optional `out_bf16`, so
|
||||
* that form writes none. */
|
||||
const char* act = halo_gets(a, "act");
|
||||
const int actm = !act ? -1 : !std::strcmp(act, "silu") ? 0 : !std::strcmp(act, "gelu_tanh") ? 1 : -1;
|
||||
if (actm < 0) return HALO_NO(RAD_E_UNSUPPORTED);
|
||||
if (actm == 1 && y) return HALO_NO(RAD_E_UNSUPPORTED);
|
||||
|
||||
/* The gated width from `q`, the buffer written; N and K from the op's parameters, since the
|
||||
* weight operands are packed bytes. */
|
||||
const long long M = q->shape[0], nout = q->shape[1];
|
||||
const long long N = halo_geti_or(a, "N", 0), K = halo_geti_or(a, "K", 0);
|
||||
if (M < 1 || M > HALO_MXG_MAX_M || nout < 128 || nout % 128 || nout / 128 > HALO_MXGG_MAX_GROUPS)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
if (N != 2 * nout || K < 128 || K % 128) return HALO_NO(RAD_E_SHAPE);
|
||||
if (x->shape[0] != M || halo_numel(x) != M * K) return HALO_NO(RAD_E_SHAPE);
|
||||
if (sc->shape[0] != M || sc->shape[1] != nout / 128) return HALO_NO(RAD_E_SHAPE);
|
||||
if (y && (y->shape[0] != M || y->shape[1] != nout)) return HALO_NO(RAD_E_SHAPE);
|
||||
/* The activation scale grid as the gemm_nt_q rows read it (mx_ascale_grid), so the fold and the
|
||||
* GEMM it replaces take every scale plane the same way. */
|
||||
GemmOps go{};
|
||||
go.ascale = xs; go.M = M; go.K = K;
|
||||
int as_group = 0, as_rs_i = 1;
|
||||
if (mx_ascale_grid(go, &as_group, &as_rs_i) != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
const bool ablk = as_group == 128;
|
||||
const long long as_rs = as_rs_i;
|
||||
/* Row pitches; halo_row_pitch is -1 for a tensor not contiguous past its leading axis. A is read
|
||||
* a dword at a time. */
|
||||
const long long lda = halo_row_pitch(x), qp = halo_row_pitch(q), sp = halo_row_pitch(sc);
|
||||
const long long yp = y ? halo_row_pitch(y) : 0;
|
||||
if (lda < K || lda % 4 || qp < nout || sp < nout / 128 || (y && yp < nout))
|
||||
return HALO_NO(RAD_E_STRIDE);
|
||||
if (!halo_aligned(x->data, 16) || !halo_aligned(w->data, 16) || !halo_aligned(q->data, 4) ||
|
||||
!halo_aligned(ws->data, 4) || !halo_aligned(wr->data, 4) || qp % 4)
|
||||
return HALO_NO(RAD_E_ALIGN);
|
||||
/* The split law. This row must reproduce gemv's accumulation order bit for bit, and gemv
|
||||
* resolves to gemm_mxfp4a8_nt_m64 with cfg_for(K, M, 32, BR_FLAT) (halo_gemm_mxfp4a8_gemv.hip).
|
||||
* Asking the same law the same question gets the same SK, hence the same contiguous splits in
|
||||
* the same order. A tuned cfg that widens WV or NPW would change m64's geometry, so it is
|
||||
* refused here rather than silently differing. */
|
||||
Cfg cfg{};
|
||||
if (cfg_for(a, K, M, HALO_MXFP4_GROUP, BR_FLAT, &cfg, 0, 1, 16) != RAD_OK) return HALO_NO(RAD_E_SHAPE);
|
||||
if (cfg.wv != 1 || cfg.npw != 1) return HALO_NO(RAD_E_UNSUPPORTED);
|
||||
const int SK = cfg.sk;
|
||||
if ((size_t)2 * SK * 256 * sizeof(float) > 60 * 1024) return HALO_NO(RAD_E_UNSUPPORTED);
|
||||
/* The cross-block product plane is the op's scratch (sized by the hook below); a shorter one is
|
||||
* refused. */
|
||||
if (!a->scratch || a->scratch_bytes < mxgg_scratch_bytes(M, nout)) return HALO_NO(RAD_E_SCRATCH);
|
||||
unsigned* cnt = mxgg_out_ctr(q->data);
|
||||
if (!cnt) return HALO_NO(RAD_E_NOMEM);
|
||||
|
||||
HALO_TRY("gemm_mxfp4a8_gated",
|
||||
mxgg_launch(ablk, actm, x->data, xs->data, w->data, ws->data, wr->data, q->data, sc->data,
|
||||
y ? y->data : nullptr, a->scratch, a->scratch_bytes, cnt, (int)M, (int)K, (int)nout, SK,
|
||||
(int)as_rs, (int)lda, (int)N, (int)qp, (int)sp, (int)yp, s));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The op's scratch: the product and amaxes at the band's widest M, from N (twice the gated
|
||||
* width), and the decoded activation plane behind them. */
|
||||
extern "C" int64_t halo_rad_gemm_mxfp4a8_gated_scratch(const RadArgs* a) {
|
||||
const long long M = halo_geti_or(a, "M", 0), N = halo_geti_or(a, "N", 0);
|
||||
const long long K = halo_geti_or(a, "K", 0);
|
||||
if (M < 1 || M > HALO_MXG_MAX_M || N < 256 || N % 256) return 0;
|
||||
return (int64_t)(mxgg_scratch_bytes(M, N / 2) + (K > 0 && K % 16 == 0 ? mxgg_plane_bytes(M, K) : 0));
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/* Derived from libr4d/r4d_gemm_mxfp4a8_gemv.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_mxfp4a8_gemv.hip - gemm_mxfp4a8_gemv (M <= 8) and gemm_mxfp4a8_gemv_wide
|
||||
// (9..64 rows): the MXFP4 GEMM at decode heights.
|
||||
//
|
||||
// A row's output bits must not depend on how many rows ride with it (the selftest compares
|
||||
// row 0 bit for bit from M = 1 through the wide row's 64). Both rows therefore run the
|
||||
// skinny kernel's own accumulation -- per-32-block folds in ascending K, split partials
|
||||
// summed in split order -- whose order is a function of (N, K) alone: the split law reads
|
||||
// neither M nor the tile counts. libr4d reaches the same invariance with a register-streamed
|
||||
// matvec at M <= 8 and a second WMMA form past it. Here the skinny kernel serves one row tile
|
||||
// and narrow weights, and past 16 rows of a weight 3072 or more wide the LDS-staged tile
|
||||
// (halo_gemm_mxfp4a8_tiled.hip) runs the same order at the same split: the skinny kernel
|
||||
// re-reads and re-unpacks the weight once a row tile, the tile once (34816 x 5120 at 64 rows:
|
||||
// 2.68 ms -> ~1.1 ms on gfx1151). The rows are told apart only by the M each accepts.
|
||||
#include "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include <cstdint>
|
||||
|
||||
static int rad_mxfp4_gemv(const RadArgs* a, RadStream s, long long m_lo, long long m_hi) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N % 16) return HALO_NO(RAD_E_SHAPE);
|
||||
if (g.M < m_lo || g.M > m_hi) return HALO_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale) return HALO_NO(RAD_E_INVAL);
|
||||
if (!g.bref) return HALO_NO(RAD_E_INVAL);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
if (rc != RAD_OK) return rc;
|
||||
int as_group = 0, as_rs = 1;
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
|
||||
if (rc != RAD_OK) return rc;
|
||||
Cfg c;
|
||||
/* NPW 2 untuned: two tiles a wave hide the unpack behind the second tile's loads
|
||||
* (measured 1367 -> ~970 us at N=5120 K=25600 M=1 on gfx1151; NPW 4 starves). */
|
||||
rc = cfg_for(a, g.K, g.M, HALO_MXFP4_GROUP, BR_FLAT, &c, 0, 2, 16);
|
||||
if (rc != RAD_OK) return rc;
|
||||
/* Past one row tile, on a weight wide enough to fill the card with 128-column blocks, the
|
||||
* LDS-staged tile at this split: the same bytes, since a row's order is the split law's
|
||||
* (K, SK) alone, but the weight is read and unpacked once for all the rows instead of once a
|
||||
* row tile, and the activation is shared through LDS. One row tile (M <= 16) and narrow N
|
||||
* stay here, where the skinny kernel's split-K waves are the parallelism. */
|
||||
if (g.M > 16 && g.N >= 3072) {
|
||||
rc = halo_mxfp4a8_tiled_split(a, s, g, mp, as_group, as_rs, c.sk);
|
||||
if (rc != RAD_E_UNSUPPORTED) return rc;
|
||||
}
|
||||
const long long kb = (g.K + 127) / 128;
|
||||
for (int p = 0; p < mp.n; ++p) {
|
||||
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
|
||||
HALO_TRY("gemm_mxfp4a8_gemv",
|
||||
halo_gemm_mxfp4a8_nt_m64_plane(halo_addr(g.a) + p * g.K,
|
||||
halo_addr(g.ascale) + (long)(p * kb * 4),
|
||||
halo_addr(g.b) + n0 * g.K / 2, halo_addr(g.bscale) + n0,
|
||||
halo_addr(g.bref) + n0, halo_addr(g.y) + n0 * 2,
|
||||
(int)g.M, (int)g.K, (int)np, c.wv, c.sk, c.mb, c.npw,
|
||||
as_group, as_rs, (long)(uintptr_t)s,
|
||||
(int)(mp.lda ? mp.lda : g.K), (int)g.N, (int)g.N,
|
||||
(long)(uintptr_t)a->scratch, a->scratch_bytes));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One entry point serves both rows (the wide row's table entry names this same function, as
|
||||
* in libr4d): the band is M itself, and the accumulation order does not change across it. */
|
||||
extern "C" int halo_rad_gemm_mxfp4a8_gemv(const RadArgs* a, RadStream s) {
|
||||
return rad_mxfp4_gemv(a, s, 1, 64);
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
/* Derived from libr4d/r4d_gemm_mxfp4a8_nt_m64.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_mxfp4a8_nt_m64.hip - halo_gemm_mxfp4a8_nt_m64: OCP-MXFP4 weight, fp8 activation
|
||||
// skinny GEMM for M up to 64, gfx1151. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, A quantised per
|
||||
// row (or per (row, 128)) to e4m3, W an e2m1 element per nibble with one E8M0 exponent per
|
||||
// 32 elements along K.
|
||||
//
|
||||
// The stored weight is libr4d's byte for byte (halo_layout.cpp's mx_slot): one 32-lane slot
|
||||
// per (n-tile, k-step), lane (lh*16 + r)'s dword holding row r's eight codes from
|
||||
// k + 8*lh. The gfx11 fragment wants sixteen consecutive K of one column in both halves of
|
||||
// the wave, so each lane unpacks its own slot dword and the halves trade the results
|
||||
// (mx_frag16x): one 128-byte load a slot and each code unpacked once. The unpack is the M <= 8
|
||||
// rows' bound (VALU, not DRAM): the four-codes-a-pass form and the half split took 34816 x 5120
|
||||
// at M = 1 from ~690 to ~520 us on gfx1151. The per-32 exponent is folded into the element
|
||||
// against the row's reference exponent: e2m1 value * 2^(exp - ref) is an exact bf16 (the
|
||||
// exponent field lands in [114, 129] for the checkpoint's spread), and one factor per row,
|
||||
// 2^(ref - 127), is applied as the scales fold. On gfx1201 the same fold targets e4m3 and
|
||||
// its fp8 WMMA; here both operands dequantise to bf16 and take the bf16 WMMA, whose products
|
||||
// are exact either way.
|
||||
//
|
||||
// The fold is per 32-block (two WMMA steps): acc += tmp * (2^(ref-127) * a_scale), with
|
||||
// a_scale the (row, 128) activation scale on the block-scaled grid and 1 on the per-row
|
||||
// grid, whose scale multiplies once at the store. Split-K is within the workgroup, reduced
|
||||
// in LDS in split order, so a run repeats exactly and the kernel needs no scratch.
|
||||
#include "halo.h"
|
||||
#include "halo_launch.h" // HALO_DYN_LDS: tests/halo_emu runs this unit on the host
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include "halo_fp8_wmma.h"
|
||||
#include "halo_wmma.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define HALO_GEMM_MXFP4_MAX_M 64
|
||||
#define HALO_GEMM_MXFP4_GROUP 32
|
||||
#define WAVE32 32
|
||||
|
||||
typedef int v8i __attribute__((ext_vector_type(8)));
|
||||
typedef float v8f __attribute__((ext_vector_type(8)));
|
||||
typedef int v4i __attribute__((ext_vector_type(4)));
|
||||
typedef int int4v __attribute__((ext_vector_type(4)));
|
||||
|
||||
/* Sixteen e4m3 bytes to the exact bf16 fragment (as in halo_gemm_fp8a8). */
|
||||
__device__ __forceinline__ v16bf mx_deq16_exact(const uint32_t* __restrict__ w4) {
|
||||
union { uint32_t u[8]; v16bf f; } q;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
const v2f p0 = halo_fp8::e4m3_pk<false>(w4[d]);
|
||||
const v2f p1 = halo_fp8::e4m3_pk<true>(w4[d]);
|
||||
q.u[d * 2] = halo::pk_bf16(p0.x, p0.y);
|
||||
q.u[d * 2 + 1] = halo::pk_bf16(p1.x, p1.y);
|
||||
}
|
||||
return q.f;
|
||||
}
|
||||
|
||||
/* One e2m1 code and its block's (exp - ref) as a bf16 bit pattern: value (2+m) * 2^(E-2)
|
||||
* with E = mag>>1, m = mag&1, scaled by 2^(exp-ref); zero stays zero (signed). */
|
||||
__device__ __forceinline__ unsigned mx_e2m1_bf16(unsigned code, int ediff) {
|
||||
const unsigned mag = code & 7u;
|
||||
if (!mag) return (code & 8u) << 12;
|
||||
unsigned E = mag >> 1, m = mag & 1u;
|
||||
if (mag == 1) m = 0; /* the subnormal 0.5: (1 + 0) * 2^-1, not (1 + 1/2) * 2^-1 */
|
||||
const unsigned ef = E + (unsigned)(ediff + 126);
|
||||
return ((code & 8u) << 12) | (ef << 7) | (m << 6);
|
||||
}
|
||||
|
||||
/* Eight e2m1 codes (one dword) at one (exp - ref) to four bf16-pair dwords, four codes a pass:
|
||||
* halo_gemm_mxfp4a8_tiled.hip's mxt_frag8 (that file says how), bit-identical to the scalar
|
||||
* mx_e2m1_bf16 for every code and every ediff with 0 <= E + ediff + 126 <= 255 (the range the
|
||||
* relayout's reference exponent keeps; host-verified for every byte at every position). */
|
||||
typedef unsigned short mx_us2 __attribute__((ext_vector_type(2)));
|
||||
__device__ __forceinline__ void mx_frag8(unsigned dw, int ediff, uint32_t* out) {
|
||||
const uint32_t ed = (uint32_t)(ediff << 7) & 0xFFFFu;
|
||||
const mx_us2 ED2 = __builtin_bit_cast(mx_us2, ed | (ed << 16));
|
||||
const uint32_t z = (0u - ed) & 0xFFFFu;
|
||||
const uint32_t T_LO = 0xC0800000u | (z & 0xFFu), T_HI = 0x3F3F3F00u | (z >> 8);
|
||||
#pragma unroll
|
||||
for (int h = 0; h < 2; ++h) {
|
||||
const uint32_t x = __builtin_amdgcn_perm(dw, dw, h ? 0x03030202u : 0x01010000u);
|
||||
const uint32_t mag = (x & 0x00070007u) | ((x >> 4) & 0x07000700u);
|
||||
const uint32_t sg = ((x << 4) & 0x00800080u) | (x & 0x80008000u);
|
||||
const uint32_t lo = __builtin_amdgcn_perm(0xC0804000u, T_LO, mag);
|
||||
const uint32_t hi = __builtin_amdgcn_perm(0x40404040u, T_HI, mag);
|
||||
const mx_us2 p0 = __builtin_bit_cast(mx_us2, __builtin_amdgcn_perm(hi, lo, 0x05010400u)) + ED2;
|
||||
const mx_us2 p1 = __builtin_bit_cast(mx_us2, __builtin_amdgcn_perm(hi, lo, 0x07030602u)) + ED2;
|
||||
out[2 * h] = __builtin_bit_cast(uint32_t, p0) | __builtin_amdgcn_perm(0u, sg, 0x010C000Cu);
|
||||
out[2 * h + 1] = __builtin_bit_cast(uint32_t, p1) | __builtin_amdgcn_perm(0u, sg, 0x030C020Cu);
|
||||
}
|
||||
}
|
||||
|
||||
/* The B fragment from the slot's dword `dw` of THIS lane (lane l: row l & 15, codes
|
||||
* k + 8 * (l >> 4) .. + 8), to sixteen bf16 in consecutive-K order. The fragment wants both of
|
||||
* its column's dwords in both halves of the wave; each half unpacks its own and the halves trade
|
||||
* the results by v_permlanex16 (lane i reads lane i of the other half), so a slot is one 128-byte
|
||||
* load and each code is unpacked once rather than once a half. */
|
||||
__device__ __forceinline__ v16bf mx_frag16x(unsigned dw, int exp, int ref, int lane) {
|
||||
uint32_t own[4], oth[4];
|
||||
mx_frag8(dw, exp - ref, own);
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q)
|
||||
oth[q] = __builtin_amdgcn_permlanex16(own[q], own[q], 0x76543210u, 0xfedcba98u, false, false);
|
||||
const bool up = lane >= 16;
|
||||
union { uint32_t u[8]; v16bf f; } r;
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
r.u[q] = up ? oth[q] : own[q];
|
||||
r.u[4 + q] = up ? own[q] : oth[q];
|
||||
}
|
||||
return r.f;
|
||||
}
|
||||
|
||||
#define HALO_MX_BOUNDS(MT, NPW) ((MT) * (NPW) >= 8 ? 256 : ((MT) * (NPW) >= 4 ? 512 : 1024))
|
||||
|
||||
template <int MT, int NPW, bool ABLK>
|
||||
__global__ __launch_bounds__(HALO_MX_BOUNDS(MT, NPW)) void halo_gemm_mxfp4a8_nt_m64_kernel(
|
||||
const unsigned char* __restrict__ A, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int WV, int SK, int as_rs, int lda, int ldws, int ldc,
|
||||
const uint16_t* __restrict__ Adq = nullptr) {
|
||||
HALO_DYN_LDS(float, red);
|
||||
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
const int nt0 = (blockIdx.x * WV + col_local) * NPW;
|
||||
const int mt0 = blockIdx.y * MT;
|
||||
const int Ks = K / SK, kbase = ksplit * Ks;
|
||||
const int nlane = lane & 15;
|
||||
|
||||
v8f acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
const int ntmax = N / 16 - 1;
|
||||
int wtile[NPW], wrow[NPW];
|
||||
float rf[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int t = nt0 + j;
|
||||
wtile[j] = t < ntmax ? t : ntmax;
|
||||
wrow[j] = wtile[j] * 16 + nlane;
|
||||
rf[j] = __int_as_float((int)Wref[wrow[j]] << 23); /* 2^(ref - 127) */
|
||||
}
|
||||
|
||||
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
|
||||
const int ksteps = K / 16;
|
||||
|
||||
for (int k = kbase; k < kbase + Ks; k += 32) {
|
||||
const int blk = k / HALO_GEMM_MXFP4_GROUP; /* this 32-block's exponent index */
|
||||
v8f tmp[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) tmp[j][i] = (v8f)(0.f);
|
||||
#pragma unroll
|
||||
for (int u = 0; u < 2; ++u) {
|
||||
const int kg = k + u * 16, kstep = kg / 16;
|
||||
v16bf af[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
int r = (mt0 + i) * 16 + nlane;
|
||||
r = r < M - 1 ? r : M - 1;
|
||||
if (Adq) {
|
||||
/* The launch's activation plane: mx_deq16_exact's outputs in row-major
|
||||
* [M, K] bf16, read back as the fragment's eight dwords. */
|
||||
const uint16_t* src = Adq + (size_t)r * K + kg;
|
||||
uint32_t* dst = (uint32_t*)&af[i];
|
||||
*(uint4*)dst = *(const uint4*)src;
|
||||
*(uint4*)(dst + 4) = *(const uint4*)(src + 8);
|
||||
} else {
|
||||
const int4v av = *(const int4v*)(A + (size_t)r * lda + kg);
|
||||
af[i] = mx_deq16_exact((const uint32_t*)&av);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int n = wrow[j];
|
||||
const unsigned dw = Wp[((size_t)wtile[j] * ksteps + kstep) * WAVE32 + lane];
|
||||
const v16bf bf = mx_frag16x(dw, (int)Ws[(size_t)blk * ldws + n], (int)Wref[n], lane);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) tmp[j][i] = halo::mma(af[i], bf, tmp[j][i]);
|
||||
}
|
||||
}
|
||||
/* Fold this 32-block: per accumulator row, the (row, 128) scale on the block grid. */
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
float f = rf[j];
|
||||
if constexpr (ABLK) {
|
||||
int r = (mt0 + i) * 16 + 2 * e + (lane >> 4);
|
||||
r = r < M - 1 ? r : M - 1;
|
||||
f *= As[(size_t)r * as_rs + (k >> 7)];
|
||||
}
|
||||
acc[j][i][e] = fmaf(tmp[j][i][e], f, acc[j][i][e]);
|
||||
}
|
||||
}
|
||||
|
||||
const int ncols = WV * NPW;
|
||||
const int nthreads = WV * SK * WAVE32;
|
||||
if (SK == 1) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int n = nt0 * 16 + j * 16 + nlane;
|
||||
if (n >= N) continue;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
const int mb = (mt0 + i) * 16;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int m = mb + accRow(lane, e);
|
||||
if (m < M)
|
||||
C[(size_t)m * ldc + (nt0 + j) * 16 + nlane] =
|
||||
(__hip_bfloat16)(ABLK ? acc[j][i][e] : acc[j][i][e] * As[m]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int slot = ((col_local * NPW + j) * SK + ksplit) * 256;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) red[slot + e * WAVE32 + lane] = acc[j][i][e];
|
||||
}
|
||||
__syncthreads();
|
||||
for (int idx = tid; idx < ncols * 256; idx += nthreads) {
|
||||
const int col = idx >> 8, off = idx & 255;
|
||||
float v = 0.f;
|
||||
for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off];
|
||||
const int l = off & 31;
|
||||
const int n = (blockIdx.x * ncols + col) * 16 + (l & 15);
|
||||
const int m = (mt0 + i) * 16 + accRow(l, off >> 5);
|
||||
if (n < N && m < M)
|
||||
C[(size_t)m * ldc + n] = (__hip_bfloat16)(ABLK ? v : v * As[m]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* The activation plane: mx_deq16_exact over the whole [M, K) activation, once per
|
||||
* launch, so the GEMM's waves read fragments instead of each re-dequantising the
|
||||
* same codes for its column. Values are mx_deq16_exact's own; products through
|
||||
* the plane are bit-identical. */
|
||||
__global__ __launch_bounds__(256) void mxfp4_adq_kernel(const unsigned char* __restrict__ A,
|
||||
uint16_t* __restrict__ Adq,
|
||||
int M, int K, int lda) {
|
||||
const int idx = blockIdx.x * (int)blockDim.x + threadIdx.x;
|
||||
if (idx >= M * (K / 16)) return;
|
||||
const int r = idx / (K / 16), c = (idx % (K / 16)) * 16;
|
||||
const int4v av = *(const int4v*)(A + (size_t)r * lda + c);
|
||||
const v16bf f = mx_deq16_exact((const uint32_t*)&av);
|
||||
uint4* dst = (uint4*)(Adq + (size_t)r * K + c);
|
||||
const uint4* src = (const uint4*)&f;
|
||||
dst[0] = src[0];
|
||||
dst[1] = src[1];
|
||||
}
|
||||
|
||||
static void gemm_mxfp4a8_m64_impl(long a, long ascale, long wq, long ws, long wref, long c,
|
||||
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, long adq = 0) {
|
||||
if (M < 1 || M > HALO_GEMM_MXFP4_MAX_M)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: M must be 1..64");
|
||||
if (N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: N must be a multiple of 16");
|
||||
if (K % (SK * HALO_GEMM_MXFP4_GROUP))
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: K must be divisible by SK*32");
|
||||
if (WV * SK * WAVE32 > HALO_MX_BOUNDS(MB, NPW))
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: WV*SK*32 exceeds this tile's launch bound");
|
||||
if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: MB must be 1..4");
|
||||
if (NPW != 1 && NPW != 2 && NPW != 4 && NPW != 8)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: NPW must be 1, 2, 4 or 8");
|
||||
if (as_group != 0 && as_group != 128)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: the activation scale is per row or per 128 of K");
|
||||
if (!lda) lda = K;
|
||||
if (!ldws) ldws = N;
|
||||
if (!ldc) ldc = N;
|
||||
const bool ablk = as_group == 128;
|
||||
const int ntiles = N / 16, mtiles = (M + 15) / 16;
|
||||
const int ncols = WV * NPW;
|
||||
dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32);
|
||||
size_t smem = (size_t)ncols * SK * 256 * sizeof(float);
|
||||
if (smem > 64 * 1024) throw std::runtime_error("r4d gemm_mxfp4a8_nt_m: WV*NPW*SK too large");
|
||||
auto Ap = (const unsigned char*)a;
|
||||
auto Sp = (const float*)ascale;
|
||||
auto Wp = (const unsigned char*)wq;
|
||||
auto Zp = (const unsigned char*)ws;
|
||||
auto Rp = (const unsigned char*)wref;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
const uint16_t* Adq = nullptr;
|
||||
if (adq) {
|
||||
Adq = (const uint16_t*)(uintptr_t)adq;
|
||||
const int total = M * (K / 16);
|
||||
hipLaunchKernelGGL((mxfp4_adq_kernel), dim3((total + 255) / 256), 256, 0, st, Ap, (uint16_t*)Adq, M, K, lda);
|
||||
if (hipGetLastError() != hipSuccess) throw std::runtime_error("mxfp4 adq launch");
|
||||
}
|
||||
#define MX_LAUNCH(MTv, NPv) \
|
||||
do { \
|
||||
if (ablk) hipLaunchKernelGGL((halo_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv, true>), grid, block, \
|
||||
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs, lda, \
|
||||
ldws, ldc, Adq); \
|
||||
else hipLaunchKernelGGL((halo_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv, false>), grid, block, \
|
||||
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs, lda, \
|
||||
ldws, ldc, Adq); \
|
||||
} while (0)
|
||||
#define MX_LAUNCH_MB(NPv) switch (MB) { \
|
||||
case 1: MX_LAUNCH(1, NPv); break; \
|
||||
case 2: MX_LAUNCH(2, NPv); break; \
|
||||
case 3: MX_LAUNCH(3, NPv); break; \
|
||||
case 4: MX_LAUNCH(4, NPv); break; \
|
||||
default: throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: MB unsupported"); }
|
||||
switch (NPW) {
|
||||
case 1: MX_LAUNCH_MB(1); break;
|
||||
case 2: MX_LAUNCH_MB(2); break;
|
||||
case 4: MX_LAUNCH_MB(4); break;
|
||||
case 8: MX_LAUNCH_MB(8); break;
|
||||
default: throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: NPW must be 1, 2, 4 or 8");
|
||||
}
|
||||
#undef MX_LAUNCH_MB
|
||||
#undef MX_LAUNCH
|
||||
}
|
||||
|
||||
void halo_gemm_mxfp4a8_nt_m64_plane(long a, long ascale, long wq, long ws, long wref, long c,
|
||||
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, long scratch, long scratch_bytes) {
|
||||
const long adq = (scratch && scratch_bytes >= (long)M * K * 2) ? scratch : 0;
|
||||
gemm_mxfp4a8_m64_impl(a, ascale, wq, ws, wref, c, M, K, N, WV, SK, MB, NPW, as_group, as_rs,
|
||||
stream, lda, ldws, ldc, adq);
|
||||
}
|
||||
void halo_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, long c,
|
||||
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) {
|
||||
gemm_mxfp4a8_m64_impl(a, ascale, wq, ws, wref, c, M, K, N, WV, SK, MB, NPW, as_group, as_rs,
|
||||
stream, lda, ldws, ldc, 0);
|
||||
}
|
||||
int halo_gemm_mxfp4a8_nt_m64_max_m(void) { return HALO_GEMM_MXFP4_MAX_M; }
|
||||
int halo_gemm_mxfp4a8_nt_m64_group(void) { return HALO_GEMM_MXFP4_GROUP; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
extern "C" int halo_rad_gemm_mxfp4a8_m64(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) return HALO_NO(RAD_E_SHAPE);
|
||||
if (g.M > halo_gemm_mxfp4a8_nt_m64_max_m()) return HALO_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale) return HALO_NO(RAD_E_INVAL);
|
||||
/* The per-row reference exponent arrives as gemm_nt_q's trailing optional operand. */
|
||||
if (!g.bref) return HALO_NO(RAD_E_INVAL);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
if (rc != RAD_OK) return rc;
|
||||
const int group = halo_gemm_mxfp4a8_nt_m64_group();
|
||||
int as_group = 0, as_rs = 1;
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
|
||||
if (rc != RAD_OK) return rc;
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, g.M, group, BR_FLAT, &c, 0, 2, 16); /* NPW 2 untuned, as the gemv row */
|
||||
if (rc != RAD_OK) return rc;
|
||||
const long long kb = (g.K + 127) / 128;
|
||||
for (int p = 0; p < mp.n; ++p) {
|
||||
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
|
||||
HALO_TRY("gemm_mxfp4a8_nt_m64",
|
||||
halo_gemm_mxfp4a8_nt_m64_plane(halo_addr(g.a) + p * g.K,
|
||||
halo_addr(g.ascale) + (long)(p * kb * 4),
|
||||
halo_addr(g.b) + n0 * g.K / 2, halo_addr(g.bscale) + n0,
|
||||
halo_addr(g.bref) + n0, halo_addr(g.y) + n0 * 2,
|
||||
(int)g.M, (int)g.K, (int)np, c.wv, c.sk, c.mb, c.npw,
|
||||
as_group, as_rs, (long)(uintptr_t)s,
|
||||
(int)(mp.lda ? mp.lda : g.K), (int)g.N, (int)g.N,
|
||||
(long)(uintptr_t)a->scratch, a->scratch_bytes));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int64_t halo_rad_gemm_mxfp4a8_m64_scratch(const RadArgs* a) {
|
||||
const long long M = halo_geti_or(a, "M", 0), K = halo_geti_or(a, "K", 0);
|
||||
if (M < 1 || K < 1) return 0;
|
||||
return M * K * 2; /* the activation plane */
|
||||
}
|
||||
@@ -0,0 +1,931 @@
|
||||
/* Derived from libr4d/r4d_gemm_mxfp4a8_tiled.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_mxfp4a8_tiled.hip - halo_gemm_mxfp4a8_tiled: the OCP-MXFP4 x fp8 GEMM for prefill row
|
||||
// counts, gfx1151. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the operands, weight layout and fold
|
||||
// of halo_gemm_mxfp4a8_nt_m64 and halo_gemm_mxfp4a8_decode, for the band above theirs.
|
||||
//
|
||||
// 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 goes from global straight into registers. A WMMA A fragment (gfx1151: lane l holds row l%16 and
|
||||
// the whole 16-wide k run -- halo_wmma.h) 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) * 256 + (k/16) * 256 + (m%16) * 16 + k%16] = A[m][k]
|
||||
//
|
||||
// (libr4d writes row m%16 to slot (m%16) + 16*((k/8)%2), the gfx12 fragment's half-split layout;
|
||||
// on gfx1151 the lane's k run is consecutive, so a fragment is sixteen consecutive fp8 bytes of one
|
||||
// row and a fragment is 256 contiguous bytes.) A lane's fragment bytes are one aligned 16-byte
|
||||
// load, so a slab's A fragments issue back to back 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 same plane serves the w4a8i8/w5a8i8 rows (their int8 fragments want the same 16 consecutive
|
||||
// bytes; fp8 and int8 are both one byte per element), which is why this op owns the scratch hook
|
||||
// their rows declare.
|
||||
//
|
||||
// Weight and fold as in the skinny kernel: the fragment-order weight from halo_layout.cpp, its
|
||||
// e2m1 codes unfolded to EXACT bf16 (m64's mx_e2m1_bf16 arithmetic, the (exp - ref) difference
|
||||
// folded per 32-block), staged as bf16 pairs in LDS. On gfx1201 the staged form is the folded e4m3
|
||||
// byte and the fp8 WMMA consumes it; gfx1151 has no fp8 WMMA, and since the gather must
|
||||
// dequantise anyway, the staging dequantises once instead -- which also makes this row's
|
||||
// accumulation the skinny kernel's exact-product arithmetic (no e4m3 re-rounding of 2^-d for
|
||||
// d >= 9; the table's ties are gone). The per-row factor 2^(Wref[n]-127) is applied at the
|
||||
// epilogue, exactly m64's.
|
||||
//
|
||||
// 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 wins from M = 1024 on
|
||||
// (on the reference part at a 27B's per-rank weights, mixed below), so tn=0 picks TN=4 from
|
||||
// M >= 1024. The K slab is 128 at TN=2 (64 if K % 128 != 0) and 64 at TN=4, which holds twice the
|
||||
// accumulators. TN does not change an output's bits: each fragment runs the same WMMAs in the same
|
||||
// K order, and the staged bf16 weight does not depend on TN.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// The weight words and exponents a thread stages are loaded a slab ahead, into registers, right
|
||||
// after the staging barrier, so their DRAM round trip runs under the slab's WMMAs instead of in
|
||||
// front of the next unpack (+1 VGPR at TN=4). Loading the A fragments a slab ahead too is slower
|
||||
// (and here impossible at bf16 width); the A load of step s+1 issues under step s's WMMAs (one
|
||||
// step of lookahead, two 16-byte fragments a row in flight).
|
||||
//
|
||||
// A thin last row of blocks (1..160 rows, under 1024 rows in all) runs a second kernel whose
|
||||
// blocks of that row skip the WMMAs of their padding fragments past M. Every other M runs the
|
||||
// plain kernel, whose body declares its own LDS: a guard inside the one kernel, or the body
|
||||
// taking the LDS by pointer, slows the full blocks.
|
||||
//
|
||||
// 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 the direct C: the WMMA takes the activation as A and the weight as B, so a
|
||||
// lane's accumulator slot e holds row 2e + (lane>>4) (accRow) and column lane&15 -- the skinny
|
||||
// kernel's own store mapping, one single-bf16 store per slot, the per-column 2^(Wref-127) hoisted
|
||||
// per lane (gfx1151 gives each lane one column, where gfx12's transposed store gave it eight
|
||||
// consecutive ones and read the reference per slot).
|
||||
//
|
||||
// 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 slot row (accRow, not a lane constant as on gfx12).
|
||||
//
|
||||
// Benchmarking note: as for the skinny kernel, a looped weight stays Infinity-Cache resident.
|
||||
#include "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include "halo_fp8_wmma.h"
|
||||
#include "halo_wmma.h"
|
||||
#include "halo_mxfp4.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define HALO_MXT_TM 4 // 16-row fragments per wave
|
||||
#define HALO_MXT_WM 4 // waves along M
|
||||
#define HALO_MXT_WN 2 // waves along N
|
||||
#define HALO_MXT_PAD 8 // LDS row pad, in bf16 elements, and 8 because the staged weight is
|
||||
// read and written as 16-byte vectors: every row must start on a
|
||||
// 16-byte boundary. (LBK+8)*2 B per row also turns by 16 B an
|
||||
// element row, so the gather's 16 lanes stay bank-staggered.
|
||||
#define HALO_MXT_NTHR (HALO_MXT_WM * HALO_MXT_WN * 32)
|
||||
#define HALO_MXT_BMF (HALO_MXT_WM * HALO_MXT_TM * 16)
|
||||
#define HALO_MXT_KUNIT 64 // the narrowest K slab, so K must be a multiple of it
|
||||
#define HALO_MXT_TN4_MIN_M 1024 // tn=0's crossover, see above
|
||||
#define HALO_MXT_GROUP 32 // K per E8M0 exponent (the OCP MX group)
|
||||
|
||||
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)));
|
||||
typedef int mxt_v4i __attribute__((ext_vector_type(4)));
|
||||
|
||||
/* Sixteen e4m3 bytes to the exact bf16 fragment (as halo_gemm_mxfp4a8_nt_m64's mx_deq16_exact). */
|
||||
__device__ __forceinline__ v16bf mxt_deq16_exact(const uint32_t* __restrict__ w4) {
|
||||
union { uint32_t u[8]; v16bf f; } q;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
const v2f p0 = halo_fp8::e4m3_pk<false>(w4[d]);
|
||||
const v2f p1 = halo_fp8::e4m3_pk<true>(w4[d]);
|
||||
q.u[d * 2] = halo::pk_bf16(p0.x, p0.y);
|
||||
q.u[d * 2 + 1] = halo::pk_bf16(p1.x, p1.y);
|
||||
}
|
||||
return q.f;
|
||||
}
|
||||
|
||||
/* One e2m1 code and its block's (exp - ref) as a bf16 bit pattern (m64's mx_e2m1_bf16). NOTE the
|
||||
* argument is exp MINUS ref, as m64's mx_frag16x passes it -- NOT the e4m3 table's d = ref - exp
|
||||
* (halo_mxfp4_fold_d), whose sign is the other way because there the fold divides the magnitude
|
||||
* by 2^d. Passing the table's d here flips every staged exponent. */
|
||||
/* Eight e2m1 codes (one dword) to four bf16-pair dwords, branchless, four codes a pass: one perm
|
||||
* spreads two bytes to [b, b, b', b'], so masks give each code's magnitude (the table selector)
|
||||
* and sign a byte; two table perms give the four codes' low and high bf16 bytes at ediff 0
|
||||
* (magnitudes 0, .5, 1, 1.5, 2, 3, 4, 6; v_perm_b32 selects bytes 0-3 from its SECOND operand),
|
||||
* two perms interleave them into bf16 pairs, one packed 16-bit add shifts the exponents by ediff
|
||||
* (magnitude 0's entry is -(ediff << 7), which the add returns to zero), and the signs land at
|
||||
* bits 15 and 31 by one more perm each. Bit-identical to the scalar mxt_e2m1_bf16 (and to the
|
||||
* byte-a-pass perm form it replaces) for every code and every ediff with
|
||||
* 0 <= E + ediff + 126 <= 255: host-verified for every byte value at every position over that
|
||||
* range. About 40% fewer VALU than the byte-a-pass form; the skinny, decode and gated kernels
|
||||
* carry the same function. */
|
||||
typedef unsigned short mxt_us2 __attribute__((ext_vector_type(2)));
|
||||
__device__ __forceinline__ void mxt_frag8(unsigned dw, int ediff, uint32_t* out) {
|
||||
const uint32_t ed = (uint32_t)(ediff << 7) & 0xFFFFu;
|
||||
const mxt_us2 ED2 = __builtin_bit_cast(mxt_us2, ed | (ed << 16));
|
||||
const uint32_t z = (0u - ed) & 0xFFFFu;
|
||||
const uint32_t T_LO = 0xC0800000u | (z & 0xFFu), T_HI = 0x3F3F3F00u | (z >> 8);
|
||||
#pragma unroll
|
||||
for (int h = 0; h < 2; ++h) {
|
||||
const uint32_t x = __builtin_amdgcn_perm(dw, dw, h ? 0x03030202u : 0x01010000u);
|
||||
const uint32_t mag = (x & 0x00070007u) | ((x >> 4) & 0x07000700u);
|
||||
const uint32_t sg = ((x << 4) & 0x00800080u) | (x & 0x80008000u);
|
||||
const uint32_t lo = __builtin_amdgcn_perm(0xC0804000u, T_LO, mag);
|
||||
const uint32_t hi = __builtin_amdgcn_perm(0x40404040u, T_HI, mag);
|
||||
const mxt_us2 p0 = __builtin_bit_cast(mxt_us2, __builtin_amdgcn_perm(hi, lo, 0x05010400u)) + ED2;
|
||||
const mxt_us2 p1 = __builtin_bit_cast(mxt_us2, __builtin_amdgcn_perm(hi, lo, 0x07030602u)) + ED2;
|
||||
out[2 * h] = __builtin_bit_cast(uint32_t, p0) | __builtin_amdgcn_perm(0u, sg, 0x010C000Cu);
|
||||
out[2 * h + 1] = __builtin_bit_cast(uint32_t, p1) | __builtin_amdgcn_perm(0u, sg, 0x030C020Cu);
|
||||
}
|
||||
}
|
||||
|
||||
__device__ __forceinline__ unsigned mxt_e2m1_bf16(unsigned code, int ediff) {
|
||||
const unsigned mag = code & 7u;
|
||||
if (!mag) return (code & 8u) << 12;
|
||||
unsigned E = mag >> 1, m = mag & 1u;
|
||||
if (mag == 1) m = 0; /* the subnormal 0.5: (1 + 0) * 2^-1, not (1 + 1/2) * 2^-1 */
|
||||
const unsigned ef = E + (unsigned)(ediff + 126);
|
||||
return ((code & 8u) << 12) | (ef << 7) | (m << 6);
|
||||
}
|
||||
|
||||
// The re-tile: one thread per 8-byte slot of the fragment-ordered plane; the slot map is r4d's
|
||||
// (slot s of a fragment = row s&15, k-bytes 8*(s>>4)..+8 of the 16-wide step), so the reads keep
|
||||
// r4d's schedule; only the store lands at gfx1151's consecutive-k slot.
|
||||
__global__ __launch_bounds__(256) void halo_mxfp4a8_tile_a_kernel(
|
||||
const unsigned char* __restrict__ A, unsigned char* __restrict__ AT, int M, int K,
|
||||
long long slots, int lda) {
|
||||
const long long o = (long long)blockIdx.x * 256 + threadIdx.x;
|
||||
if (o >= slots) return;
|
||||
const int ks = K / 16;
|
||||
const int lane = (int)(o & 31);
|
||||
const long long f = o >> 5;
|
||||
const int mt = (int)(f / ks), kst = (int)(f % ks);
|
||||
const int r = mt * 16 + (lane & 15), k = kst * 16 + (lane >> 4) * 8;
|
||||
mxt_u2 v = { 0u, 0u };
|
||||
if (r < M) v = *(const mxt_u2*)(A + (size_t)r * lda + k);
|
||||
*(mxt_u2*)(AT + f * 256 + (lane & 15) * 16 + (lane >> 4) * 8) = v;
|
||||
}
|
||||
|
||||
// The kernel's body. OWN: it declares its LDS arrays itself (the plain kernel); otherwise it takes
|
||||
// the caller's (the two-body kernel, one set for both bodies). PART: a block the M edge cuts,
|
||||
// which skips the WMMAs of its padding fragments past M.
|
||||
template <int TN, int LBK, bool ABLK, bool PART, bool OWN>
|
||||
__device__ __forceinline__ void halo_gemm_mxfp4a8_tiled_body(
|
||||
const unsigned char* __restrict__ AT, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int as_rs, int ldws, int ldc, unsigned short* __restrict__ sW_in,
|
||||
float* __restrict__ sR_in) {
|
||||
constexpr int TM = HALO_MXT_TM, WN = HALO_MXT_WN, NTHR = HALO_MXT_NTHR, BMF = HALO_MXT_BMF;
|
||||
constexpr int NS = LBK / 16, STR = LBK + HALO_MXT_PAD, BNF = WN * TN * 16;
|
||||
constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32;
|
||||
// 4 weight slots (one 16 B read) wherever the tile has enough of them, else 2 (8 B), else 1.
|
||||
constexpr int WSLOTS = (TOT_SLOTS >= NTHR * 4) ? 4 : (TOT_SLOTS >= NTHR * 2 ? 2 : 1);
|
||||
constexpr int NW = TOT_SLOTS / (NTHR * WSLOTS);
|
||||
static_assert(NW * NTHR * WSLOTS == TOT_SLOTS, "the W tile must split evenly over the block");
|
||||
__shared__ unsigned short sW_own[OWN ? BNF * STR : 1]; // the staged weight, exact bf16 pairs
|
||||
__shared__ float sR_own[OWN && ABLK ? BMF : 1]; // ABLK: a boundary's ratio a row, then each row's final scale
|
||||
unsigned short* __restrict__ sW = OWN ? sW_own : sW_in;
|
||||
float* __restrict__ sR = OWN ? sR_own : sR_in;
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int wm = wave / WN, wn = wave % WN;
|
||||
const int col = lane & 15;
|
||||
const int m0 = blockIdx.y * BMF, n0 = blockIdx.x * BNF;
|
||||
const int ksteps = K / 16, Mt = (M + 15) >> 4;
|
||||
// PART: this wave's M fragments that hold a row below M, 0..TM and wave-uniform; the rest are
|
||||
// padding whose WMMAs are skipped (their rows are dropped at the store). Their A loads stay,
|
||||
// clamped, one step in flight.
|
||||
const int live = PART ? __builtin_amdgcn_readfirstlane(min(TM, max(0, Mt - ((m0 >> 4) + wm * TM))))
|
||||
: TM;
|
||||
|
||||
// One A base per M fragment, wave-uniform: readfirstlane keeps it in an SGPR so loads take the
|
||||
// SADDR form with a 32-bit lane offset. A tile past M reads the last real one.
|
||||
const unsigned char* abase[TM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) {
|
||||
int mt = (m0 >> 4) + wm * TM + i;
|
||||
mt = mt < Mt - 1 ? mt : Mt - 1;
|
||||
abase[i] = AT + (size_t)__builtin_amdgcn_readfirstlane(mt * ksteps * 256);
|
||||
}
|
||||
const unsigned int aoff = (unsigned int)col * 16;
|
||||
|
||||
// The W slots this thread stages, fixed across slabs: WSLOTS adjacent rows of one (n-tile,
|
||||
// k-step), so the wave reads contiguous bytes; the clamp keeps the vector read aligned.
|
||||
int wrow[NW], wkloc[NW], wrc[NW], wkst[NW], wlanec[NW];
|
||||
unsigned int wref[NW];
|
||||
#pragma unroll
|
||||
for (int it = 0; it < NW; ++it) {
|
||||
const int sl = it * NTHR * WSLOTS + tid * WSLOTS;
|
||||
const int lane_ = sl & 31, rest = sl >> 5;
|
||||
const int kst = rest % NS, ntl = rest / NS;
|
||||
wrow[it] = ntl * 16 + (lane_ & 15);
|
||||
wkloc[it] = kst * 16 + (lane_ >> 4) * 8;
|
||||
const int gn = n0 + wrow[it];
|
||||
wrc[it] = gn < N - WSLOTS ? gn : N - WSLOTS;
|
||||
wlanec[it] = (lane_ & 16) | (wrc[it] & 15);
|
||||
wkst[it] = kst;
|
||||
wref[it] = WSLOTS == 4 ? *(const unsigned int*)(Wref + wrc[it])
|
||||
: WSLOTS == 2 ? *(const unsigned short*)(Wref + wrc[it])
|
||||
: Wref[wrc[it]];
|
||||
}
|
||||
|
||||
v8f acc[TM][TN];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) acc[i][j] = (v8f)(0.f);
|
||||
|
||||
// ABLK: thread t owns row m0 + t (BMF == NTHR) and loads the next 128 boundary's two scales (the
|
||||
// block starting there and the one before it) a boundary early.
|
||||
const int trow = m0 + tid < M ? m0 + tid : M - 1;
|
||||
const float* __restrict__ asrow = As + (size_t)trow * as_rs;
|
||||
float ns = 0.f, np = 0.f;
|
||||
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
|
||||
|
||||
// The per-lane reference factors: the lane's one column per N fragment (gfx1151's D mapping
|
||||
// keeps the column on lane&15). Clamped reads; the epilogue drops the padding columns.
|
||||
float rf[TN];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j)
|
||||
rf[j] = __int_as_float((int)Wref[n0 + wn * TN * 16 + j * 16 + col < N
|
||||
? n0 + wn * TN * 16 + j * 16 + col : N - 1] << 23);
|
||||
|
||||
// The slab's weight words and exponents, loaded a slab ahead (the first one here).
|
||||
unsigned int wqn[NW][WSLOTS], wswn[NW];
|
||||
auto wload = [&](int k0) {
|
||||
const int kstep0 = k0 / 16;
|
||||
#pragma unroll
|
||||
for (int it = 0; it < NW; ++it) {
|
||||
const unsigned int* src =
|
||||
&Wp[((size_t)(wrc[it] >> 4) * ksteps + kstep0 + wkst[it]) * 32 + wlanec[it]];
|
||||
const int blk = (k0 + wkst[it] * 16) / HALO_MXT_GROUP;
|
||||
if constexpr (WSLOTS == 4) {
|
||||
const mxt_u4 v = *(const mxt_u4*)src;
|
||||
wqn[it][0] = v[0]; wqn[it][1] = v[1]; wqn[it][2] = v[2]; wqn[it][3] = v[3];
|
||||
wswn[it] = *(const unsigned int*)(Ws + (size_t)blk * ldws + wrc[it]);
|
||||
} else if constexpr (WSLOTS == 2) {
|
||||
const mxt_u2 v = *(const mxt_u2*)src;
|
||||
wqn[it][0] = v[0]; wqn[it][1] = v[1];
|
||||
wswn[it] = *(const unsigned short*)(Ws + (size_t)blk * ldws + wrc[it]);
|
||||
} else {
|
||||
wqn[it][0] = *src;
|
||||
wswn[it] = Ws[(size_t)blk * ldws + wrc[it]];
|
||||
}
|
||||
}
|
||||
};
|
||||
wload(0);
|
||||
|
||||
// The A fragments one step of lookahead ahead (int4v = 16 fp8 bytes = the lane's fragment row).
|
||||
mxt_v4i af_buf[2][TM];
|
||||
auto aload = [&](int step, int kb) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
af_buf[step & 1][i] =
|
||||
*(const mxt_v4i*)(abase[i] + aoff + (unsigned int)(kb * 16) + (unsigned int)(step * 256));
|
||||
};
|
||||
aload(0, 0);
|
||||
|
||||
for (int k0 = 0; k0 < K; k0 += LBK) {
|
||||
// ABLK: at a 128 boundary each row's ratio goes to LDS, published by the staging barrier below
|
||||
// (sR's previous readers finished before the last slab's closing barrier). A zero block keeps
|
||||
// the carried scale; after a zero block the carried scale is looked up from the grid.
|
||||
const bool bnd = ABLK && k0 && (k0 & 127) == 0;
|
||||
if constexpr (ABLK) {
|
||||
if (bnd)
|
||||
sR[tid] = ns > 0.f ? (np > 0.f ? np : halo_mxfp4_carried(asrow, (k0 >> 7) - 2)) / ns : 1.f;
|
||||
}
|
||||
// W slab -> LDS, unfolded to exact bf16 with the 32-block's (exp - ref) folded in, from the
|
||||
// words loaded a slab ago.
|
||||
#pragma unroll
|
||||
for (int it = 0; it < NW; ++it) {
|
||||
#pragma unroll
|
||||
for (int q = 0; q < WSLOTS; ++q) {
|
||||
const int ed = (int)((wswn[it] >> (8 * q)) & 0xFF) - (int)((wref[it] >> (8 * q)) & 0xFF);
|
||||
union { uint32_t u[4]; mxt_u4 v; } pk;
|
||||
mxt_frag8(wqn[it][q], ed, pk.u);
|
||||
*(mxt_u4*)(&sW[(wrow[it] + q) * STR + wkloc[it]]) = pk.v;
|
||||
}
|
||||
}
|
||||
lds_barrier();
|
||||
if (k0 + LBK < K) wload(k0 + LBK); // the next slab's weight flies across this slab's WMMAs
|
||||
|
||||
if constexpr (ABLK) {
|
||||
// Re-express each row's partial sum in the new block's scale: one ratio a slot row.
|
||||
if (bnd) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e)
|
||||
acc[i][j][e] *= sR[wm * TM * 16 + i * 16 + accRow(lane, e)];
|
||||
}
|
||||
// The next boundary's scales, issued behind this slab's loads and needed a boundary later.
|
||||
if ((k0 & 127) == 0 && k0 + 128 < K) {
|
||||
ns = asrow[(k0 >> 7) + 1];
|
||||
np = asrow[k0 >> 7];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int step = 0; step < NS; ++step) {
|
||||
// The weight fragments: the lane's column, sixteen consecutive k, straight out of LDS.
|
||||
v16bf wf[TN];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
const unsigned short* p = &sW[(wn * TN * 16 + j * 16 + col) * STR + step * 16];
|
||||
union { uint4 w[2]; v16bf f; } u;
|
||||
u.w[0] = *(const uint4*)p;
|
||||
u.w[1] = *(const uint4*)(p + 8);
|
||||
wf[j] = u.f;
|
||||
}
|
||||
// The activation fragments staged for this step (loaded under the previous step's WMMAs).
|
||||
v16bf af[TM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) af[i] = mxt_deq16_exact((const uint32_t*)&af_buf[step & 1][i]);
|
||||
// Keep one step's fragments live at a time; otherwise the compiler hoists every step's
|
||||
// loads above the first WMMA.
|
||||
__builtin_amdgcn_sched_barrier(0);
|
||||
if (step + 1 < NS) aload(step + 1, k0);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) {
|
||||
if (PART && i >= live) break; // wave-uniform: padding fragments past M
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j)
|
||||
acc[i][j] = halo::mma(af[i], wf[j], acc[i][j]);
|
||||
}
|
||||
}
|
||||
// The next slab's first A step flies across this slab's closing barrier; the current slab's
|
||||
// last step is done, so buffer (NS - 1) & 1 is dead, and step 0's buffer 0 is dead too --
|
||||
// NS = LBK/16 is even here (LBK is 64 or 128), so the last step used buffer 1.
|
||||
if (k0 + LBK < K) aload(0, k0 + LBK);
|
||||
lds_barrier();
|
||||
}
|
||||
|
||||
// Epilogue. A lane holds row m0 + 64*wm + 16i + accRow(lane, e) of M fragment i for slot e, and
|
||||
// the one column n0 + wn*TN*16 + j*16 + lane&15 of N fragment j. 2^(Wref[n]-127) is the float
|
||||
// whose exponent field is Wref[n] (hoisted above); N % 16 keeps a lane's column inside one
|
||||
// fragment, so a column is entirely inside or entirely outside N.
|
||||
float sc[TM][8];
|
||||
if constexpr (ABLK) {
|
||||
// the scale each row ends in, once a row; the K loop's closing barrier retired the ratio reads
|
||||
sR[tid] = halo_mxfp4_carried(asrow, (K - 1) >> 7);
|
||||
lds_barrier();
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e)
|
||||
sc[i][e] = sR[wm * TM * 16 + i * 16 + accRow(lane, e)];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
const int nb = n0 + wn * TN * 16 + j * 16 + col;
|
||||
if (nb >= N) continue;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int m = m0 + wm * TM * 16 + i * 16 + accRow(lane, e);
|
||||
if (m >= M) continue;
|
||||
const float s = ABLK ? sc[i][e] : As[(size_t)m * as_rs];
|
||||
C[(size_t)m * ldc + nb] = (__hip_bfloat16)(acc[i][j][e] * rf[j] * s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The plain kernel: every block the unguarded body, over the body's own LDS.
|
||||
template <int TN, int LBK, bool ABLK>
|
||||
__global__ __launch_bounds__(HALO_MXT_NTHR) void halo_gemm_mxfp4a8_tiled_kernel(
|
||||
const unsigned char* __restrict__ AT, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int as_rs, int ldws, int ldc) {
|
||||
halo_gemm_mxfp4a8_tiled_body<TN, LBK, ABLK, false, true>(AT, As, W, Ws, Wref, C, M, K, N, as_rs,
|
||||
ldws, ldc, nullptr, nullptr);
|
||||
}
|
||||
|
||||
// The two-body kernel, for a thin last row of blocks: a block of that row takes the guarded body,
|
||||
// every other block the unguarded one, uniform over the block, over one set of LDS arrays.
|
||||
template <int TN, int LBK, bool ABLK>
|
||||
__global__ __launch_bounds__(HALO_MXT_NTHR) void halo_gemm_mxfp4a8_tiled_part_kernel(
|
||||
const unsigned char* __restrict__ AT, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int as_rs, int ldws, int ldc) {
|
||||
constexpr int BNF = HALO_MXT_WN * TN * 16, STR = LBK + HALO_MXT_PAD;
|
||||
__shared__ unsigned short sW[BNF * STR];
|
||||
__shared__ float sR[ABLK ? HALO_MXT_BMF : 1];
|
||||
if ((int)(blockIdx.y + 1) * HALO_MXT_BMF > M)
|
||||
halo_gemm_mxfp4a8_tiled_body<TN, LBK, ABLK, true, false>(AT, As, W, Ws, Wref, C, M, K, N,
|
||||
as_rs, ldws, ldc, (unsigned short*)sW,
|
||||
sR);
|
||||
else
|
||||
halo_gemm_mxfp4a8_tiled_body<TN, LBK, ABLK, false, false>(AT, As, W, Ws, Wref, C, M, K, N,
|
||||
as_rs, ldws, ldc,
|
||||
(unsigned short*)sW, sR);
|
||||
}
|
||||
|
||||
extern "C" int halo_gemm_mxfp4a8_tiled_group(void) { return HALO_MXT_GROUP; }
|
||||
|
||||
extern "C" long halo_mxfp4a8_tile_a_bytes(int M, int K) {
|
||||
return M < 1 || K < 16 ? 0 : (long)((M + 15) / 16) * 16 * K;
|
||||
}
|
||||
|
||||
extern "C" void halo_mxfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda) {
|
||||
if (!lda) lda = K;
|
||||
if (M < 1) throw std::runtime_error("halo mxfp4a8_tile_a: M must be >= 1");
|
||||
if (K < 16 || K % 16) throw std::runtime_error("halo mxfp4a8_tile_a: K must be a multiple of 16");
|
||||
const long long slots = (long long)((M + 15) / 16) * (K / 16) * 32;
|
||||
hipLaunchKernelGGL(halo_mxfp4a8_tile_a_kernel, dim3((unsigned)((slots + 255) / 256)), dim3(256),
|
||||
0, (hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K,
|
||||
slots, lda);
|
||||
}
|
||||
|
||||
extern "C" void halo_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c,
|
||||
int M, int K, int N, int TN, int as_group, int as_rs,
|
||||
long stream, int ldws, int ldc) {
|
||||
if (!ldws) ldws = N;
|
||||
if (!ldc) ldc = N;
|
||||
if (M < 1) throw std::runtime_error("halo gemm_mxfp4a8_tiled: M must be >= 1");
|
||||
if (N < 16 || N % 16) throw std::runtime_error("halo gemm_mxfp4a8_tiled: N must be a multiple of 16");
|
||||
if (K < HALO_MXT_KUNIT || K % HALO_MXT_KUNIT)
|
||||
throw std::runtime_error("halo 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 fewer than 128 blocks
|
||||
// (narrow N), where TN=2's extra blocks win.
|
||||
if (TN == 0)
|
||||
TN = M >= HALO_MXT_TN4_MIN_M && (long)((N + 127) / 128) * ((M + HALO_MXT_BMF - 1) / HALO_MXT_BMF) >= 128
|
||||
? 4 : 2;
|
||||
if (TN != 2 && TN != 4) throw std::runtime_error("halo gemm_mxfp4a8_tiled: TN must be 2 or 4");
|
||||
if (as_group != 0 && as_group != 128)
|
||||
throw std::runtime_error("halo gemm_mxfp4a8_tiled: the activation scale is per row or per 128 of K");
|
||||
const bool ablk = as_group == 128;
|
||||
if (ablk && as_rs < (K + 127) / 128)
|
||||
throw std::runtime_error("halo gemm_mxfp4a8_tiled: activation scale rows shorter than ceil(K/128)");
|
||||
const bool wide_slab = TN == 2 && K % 128 == 0;
|
||||
const int bnf = HALO_MXT_WN * TN * 16;
|
||||
dim3 grid((N + bnf - 1) / bnf, (M + HALO_MXT_BMF - 1) / HALO_MXT_BMF), block(HALO_MXT_NTHR);
|
||||
auto Ap = (const unsigned char*)at;
|
||||
auto Sp = (const float*)ascale;
|
||||
auto Wp = (const unsigned char*)wq;
|
||||
auto Zp = (const unsigned char*)ws;
|
||||
auto Rp = (const unsigned char*)wref;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
// The two-body kernel only for a thin last row of blocks (1..160 rows) under 1024 rows; see the
|
||||
// header.
|
||||
const int rem = M % HALO_MXT_BMF;
|
||||
const bool part = rem > 0 && rem <= 160 && M < 1024;
|
||||
#define MXT_LAUNCH(TNv, LBKv, ABv) do { \
|
||||
if (part) \
|
||||
hipLaunchKernelGGL((halo_gemm_mxfp4a8_tiled_part_kernel<TNv, LBKv, ABv>), grid, block, 0, st,\
|
||||
Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, as_rs, ldws, ldc); \
|
||||
else \
|
||||
hipLaunchKernelGGL((halo_gemm_mxfp4a8_tiled_kernel<TNv, LBKv, ABv>), grid, block, 0, st, Ap, \
|
||||
Sp, Wp, Zp, Rp, Cp, M, K, N, as_rs, ldws, ldc); \
|
||||
} while (0)
|
||||
if (TN == 4) { if (ablk) MXT_LAUNCH(4, 64, true); else MXT_LAUNCH(4, 64, false); }
|
||||
else if (wide_slab) { if (ablk) MXT_LAUNCH(2, 128, true); else MXT_LAUNCH(2, 128, false); }
|
||||
else { if (ablk) MXT_LAUNCH(2, 64, true); else MXT_LAUNCH(2, 64, false); }
|
||||
#undef MXT_LAUNCH
|
||||
}
|
||||
|
||||
// ============================================================== the LDS-staged row kernel
|
||||
//
|
||||
// What the row launches, and what the gemv rows launch past one row tile on a wide weight. The
|
||||
// kernel above keeps the activation in fp8 and every wave re-runs the exact e4m3 decode (~180 VALU
|
||||
// a fragment) for each of its row fragments at every k step -- about three times the WMMA work it
|
||||
// feeds -- and spills at every instantiation on gfx1151. This one is halo_gemm_fp8a8.hip's prefill
|
||||
// tile: eight waves stage a BM x 64 activation tile and a BN x 64 weight tile through LDS as exact
|
||||
// bf16, the next tiles' loads in flight under the current one's WMMAs. The activation comes from a
|
||||
// bf16 plane the launch decodes once (mxt2_adq_kernel, when the op's scratch holds it) or is
|
||||
// decoded while staging; the weight is unpacked once a block with mxt_frag8.
|
||||
//
|
||||
// Contract: byte-identical to gemm_mxfp4a8_nt_m64 at the same split (one, for the tiled row; the
|
||||
// gemv split law's, for the gemv rows). Each 32-block runs its two 16-K WMMAs from zero, then folds
|
||||
// with fmaf(tmp, 2^(ref-127) [* As(row, k/128)], acc) in K order, each split's chain from zero and
|
||||
// the chains summed from zero in split order, and the store is m64's (ABLK ? v : v * As[m]); the A
|
||||
// values are mx_deq16_exact's, the weight values mx_frag16x's. Only where operands sit changes.
|
||||
//
|
||||
// The weight's fragment order (halo_layout.cpp): per (16-row tile, 16-k step), 32 dwords, dword l
|
||||
// row l & 15 with k 8*(l >> 4) .. +8 in nibble order. Four steps are 512 contiguous bytes, so a
|
||||
// thread's 16-byte chunk is one k run of four adjacent rows, whose exponents and reference
|
||||
// exponents are four adjacent bytes.
|
||||
#define MXT2_BK 64
|
||||
#define MXT2_PITCH (MXT2_BK + 8)
|
||||
|
||||
__global__ __launch_bounds__(256) void mxt2_adq_kernel(const unsigned char* __restrict__ A,
|
||||
uint16_t* __restrict__ Adq, int M, int K,
|
||||
int lda) {
|
||||
const long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (idx >= (long long)M * (K / 16)) return;
|
||||
const int r = (int)(idx / (K / 16)), c = (int)(idx % (K / 16)) * 16;
|
||||
const mxt_v4i av = *(const mxt_v4i*)(A + (size_t)r * lda + c);
|
||||
const v16bf f = mxt_deq16_exact((const uint32_t*)&av);
|
||||
uint4* dst = (uint4*)(Adq + (size_t)r * K + c);
|
||||
const uint4* src = (const uint4*)&f;
|
||||
dst[0] = src[0];
|
||||
dst[1] = src[1];
|
||||
}
|
||||
|
||||
/* The tile is WMW x (8 / WMW) waves, each a TM x TN patch of 16 x 16 fragments: BM = WMW*TM*16
|
||||
* rows by BN = (8/WMW)*TN*16 columns. The prefill tiles are 2 x 4 waves; the decode band's
|
||||
* (gemv_wide, 17..64 rows) one block row tall, so the weight is read and unpacked once whatever
|
||||
* the row count (the skinny kernel reads and unpacks it once a row tile).
|
||||
*
|
||||
* SPLIT: the skinny kernel at SK splits, not one. nt_m64 runs each contiguous K/SK range as its
|
||||
* own chain of folds from zero and sums the chains' totals from zero in split order
|
||||
* (v = 0; v += acc_s); one wave walking all of K reproduces that exactly with the running chain
|
||||
* `acc` and a running total `v`: at each split's last fold, v += acc and acc restarts from zero.
|
||||
* At one split v = 0 + acc is acc's own bits (acc is never -0: it starts at +0, and a
|
||||
* round-to-nearest sum is -0 only of two -0s), so the decode band runs SPLIT at every split and
|
||||
* the prefill band, always one split, without it.
|
||||
*
|
||||
* The weight's raw words and exponents, and the activation's chunks, are loaded PD slabs ahead into
|
||||
* a register ring, so PD slabs of DRAM latency hide under the WMMAs (the barriers fence LDS only,
|
||||
* so the ring stays in flight across them). At PD 1 this is the one slab of lookahead the prefill
|
||||
* tiles keep (their accumulators leave no room for more).
|
||||
*
|
||||
* PART: a launch whose last row of blocks the M edge cuts; each wave skips the WMMAs and folds of
|
||||
* its fragments wholly past M (wave-uniform), so a thin tail band costs its staging, not a band of
|
||||
* WMMAs (M 129: 2487 -> 2116 us at N 5120, K 25600). */
|
||||
template <int WMW, int TM, int TN, int PD, bool APLANE, bool ABLK, bool SPLIT, bool PART>
|
||||
__global__ __launch_bounds__(256) void halo_gemm_mxfp4a8_tiled2_kernel(
|
||||
const unsigned char* __restrict__ A, const uint16_t* __restrict__ Adq,
|
||||
const float* __restrict__ As, const unsigned char* __restrict__ W,
|
||||
const unsigned char* __restrict__ Ws, const unsigned char* __restrict__ Wref,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int lda, int as_rs, int ldws, int ldc,
|
||||
int Ks) {
|
||||
constexpr int WNW = 8 / WMW;
|
||||
constexpr int BM = WMW * TM * 16, BN = WNW * TN * 16;
|
||||
constexpr int ACH = APLANE ? 8 : 16; // activation elements a 16-byte chunk
|
||||
constexpr int CPR = MXT2_BK / ACH; // ... chunks a row
|
||||
constexpr int ACN = BM * CPR; // chunks a tile
|
||||
constexpr int AL = (ACN + 255) / 256; // ... a thread (a small tile: the low threads)
|
||||
constexpr int WCH = BN * MXT2_BK / 2 / 16; // 16-byte weight chunks a tile
|
||||
constexpr int WL = (WCH + 255) / 256; // ... a thread (a 64-wide tile: half)
|
||||
static_assert(WMW * WNW == 8 && (WCH % 256 == 0 || WCH < 256), "a tile is whole chunks");
|
||||
__shared__ __attribute__((aligned(16))) unsigned short sA[BM * MXT2_PITCH];
|
||||
__shared__ __attribute__((aligned(16))) unsigned short sW[BN * MXT2_PITCH];
|
||||
__shared__ __attribute__((aligned(16))) float sS[ABLK ? BM : 1];
|
||||
|
||||
const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31;
|
||||
const int wm = wave / WNW, wn = wave % WNW;
|
||||
constexpr unsigned kGroupM = 8;
|
||||
const unsigned per = kGroupM * gridDim.x, lin = blockIdx.y * gridDim.x + blockIdx.x;
|
||||
const unsigned first = lin / per * kGroupM, rr = lin % per;
|
||||
const unsigned gm = min(gridDim.y - first, kGroupM);
|
||||
const int m0 = (int)(first + rr % gm) * BM, n0 = (int)(rr / gm) * BN;
|
||||
const int ksteps = K / 16, ntmax = N / 16 - 1;
|
||||
|
||||
/* Each thread's loads are a 32-bit byte offset off a slab base that is uniform over the block
|
||||
* (SGPRs), so a ring slot costs its data registers alone, not a 64-bit address a slab. */
|
||||
unsigned aoff[AL];
|
||||
unsigned short* adst[AL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) {
|
||||
/* A thread past the tile's chunks (a 16- or 48-row tile) loads a real one and stores none. */
|
||||
const int c = (tid + 256 * i) % ACN, r = c / CPR, e = (c % CPR) * ACH;
|
||||
const int gr = m0 + r < M ? m0 + r : M - 1;
|
||||
aoff[i] = APLANE ? ((unsigned)gr * (unsigned)K + e) * 2u : (unsigned)gr * (unsigned)lda + e;
|
||||
adst[i] = sA + r * MXT2_PITCH + e;
|
||||
}
|
||||
/* Weight chunk c: n tile c >> 5 of the block (clamped to the last real one, as m64 clamps),
|
||||
* dwords d0 .. d0+3 of its 512-byte four-step run: step d0 >> 5, rows (d0 & 15) .. +3, k run
|
||||
* 8 * ((d0 >> 4) & 1). */
|
||||
unsigned woff[WL], eoff[WL];
|
||||
unsigned short* wdst[WL];
|
||||
unsigned wref4[WL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) {
|
||||
const int c = WCH < 256 ? tid % WCH : tid + 256 * i, t = c >> 5, d0 = (c & 31) * 4;
|
||||
const int s = d0 >> 5, l0 = d0 & 31;
|
||||
int gt = (n0 >> 4) + t;
|
||||
gt = gt < ntmax ? gt : ntmax;
|
||||
const int n4 = gt * 16 + (l0 & 15);
|
||||
woff[i] = (((unsigned)gt * (unsigned)ksteps + s) * 32u + l0) * 4u;
|
||||
eoff[i] = (unsigned)(s >> 1) * (unsigned)ldws + n4; /* the step's 32-block, past the slab's first */
|
||||
wref4[i] = *(const unsigned*)(Wref + n4);
|
||||
wdst[i] = sW + (t * 16 + (l0 & 15)) * MXT2_PITCH + s * 16 + (l0 >> 4) * 8;
|
||||
}
|
||||
const int srow = tid < BM ? (m0 + tid < M ? m0 + tid : M - 1) : 0;
|
||||
const unsigned soff = (unsigned)srow * (unsigned)as_rs * 4u;
|
||||
|
||||
float rf[TN];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
int t = (n0 >> 4) + wn * TN + j;
|
||||
t = t < ntmax ? t : ntmax;
|
||||
rf[j] = __int_as_float((int)Wref[t * 16 + (lane & 15)] << 23); /* 2^(ref - 127) */
|
||||
}
|
||||
|
||||
/* PART: this wave's fragments that hold a row below M, wave-uniform; past them (the padding of
|
||||
* a block the M edge cuts) the WMMAs and folds are skipped and the rows dropped at the store. */
|
||||
const int live = PART ? __builtin_amdgcn_readfirstlane(
|
||||
min(TM, max(0, (M + 15) / 16 - (m0 / 16 + wm * TM))))
|
||||
: TM;
|
||||
const unsigned short* fa = sA + (wm * TM * 16 + (lane & 15)) * MXT2_PITCH;
|
||||
const unsigned short* fw = sW + (wn * TN * 16 + (lane & 15)) * MXT2_PITCH;
|
||||
|
||||
/* acc: the current split's chain; v: the splits' running total (SPLIT only); tmp: the open
|
||||
* 32-block, whose first WMMA starts from the zero accumulator rather than a cleared tmp. */
|
||||
v8f acc[TM][TN], tmp[TM][TN], v[SPLIT ? TM : 1][SPLIT ? TN : 1];
|
||||
const v8f zero = (v8f)0.f;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) acc[i][j] = zero;
|
||||
if constexpr (SPLIT) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) v[i][j] = zero;
|
||||
}
|
||||
|
||||
halo_u32x4 ra[PD][AL], rw[PD][WL];
|
||||
unsigned re[PD][WL];
|
||||
float rs[PD];
|
||||
/* Every load is unconditional (a fetch past the last slab re-reads it): a load issued on one
|
||||
* path only makes the wait-count pass assume the worst at the merge, an s_waitcnt vmcnt(0) at
|
||||
* the top of every slab that drains the whole ring. */
|
||||
const int nk = K / MXT2_BK;
|
||||
/* Both operands go through the ring: the load counter retires in order, so an activation
|
||||
* fetched nearer than the weight would make each slab's wait on it drain the ring too. */
|
||||
auto fetch = [&](int d, int kt) {
|
||||
const int kc = kt < nk ? kt : nk - 1, k = kc * MXT2_BK;
|
||||
const char* ab = APLANE ? (const char*)(Adq + k) : (const char*)(A + k);
|
||||
const char* wb = (const char*)W + (size_t)kc * 4 * 32 * 4;
|
||||
const unsigned char* eb = Ws + (size_t)(k / HALO_MXT_GROUP) * ldws;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) ra[d][i] = *(const halo_u32x4*)(ab + aoff[i]);
|
||||
/* rows past BM read row 0's and never publish it */
|
||||
if constexpr (ABLK) rs[d] = *(const float*)((const char*)(As + (k >> 7)) + soff);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) {
|
||||
/* A 64-wide tile's upper threads repeat the lower half's chunk; only the lower half stores. */
|
||||
rw[d][i] = *(const halo_u32x4*)(wb + woff[i]);
|
||||
re[d][i] = *(const unsigned*)(eb + eoff[i]);
|
||||
}
|
||||
};
|
||||
|
||||
#pragma unroll
|
||||
for (int d = 0; d < PD; ++d) fetch(d, d);
|
||||
const int fps = Ks / HALO_MXT_GROUP; // folds a split
|
||||
int fc = 0;
|
||||
|
||||
/* One slab: stage it from ring slot d, then refill the slot PD slabs ahead and run the WMMAs. */
|
||||
auto slab = [&](const int d, const int kt) {
|
||||
/* No code motion across slabs: the scheduler would otherwise unpack later slabs' ring
|
||||
* words early and hold them (spilling past 256 VGPRs at a 16-row tile). */
|
||||
__builtin_amdgcn_sched_barrier(0);
|
||||
lds_barrier();
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) {
|
||||
if (ACN % 256 && tid + 256 * i >= ACN) break;
|
||||
if constexpr (APLANE) {
|
||||
*(halo_u32x4*)adst[i] = ra[d][i];
|
||||
} else {
|
||||
const v16bf f = mxt_deq16_exact((const uint32_t*)&ra[d][i]);
|
||||
const halo_u32x4* q = (const halo_u32x4*)&f;
|
||||
*(halo_u32x4*)adst[i] = q[0];
|
||||
*(halo_u32x4*)(adst[i] + 8) = q[1];
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
if (WCH < 256 && tid >= WCH) break;
|
||||
const int ed = (int)((re[d][i] >> (8 * q)) & 0xFF) - (int)((wref4[i] >> (8 * q)) & 0xFF);
|
||||
union { uint32_t u[4]; halo_u32x4 v; } pk;
|
||||
mxt_frag8(rw[d][i][q], ed, pk.u);
|
||||
*(halo_u32x4*)(wdst[i] + q * MXT2_PITCH) = pk.v;
|
||||
}
|
||||
if constexpr (ABLK) {
|
||||
/* Row r at its accumulator slot's order: fragment r / 16, half r & 1, slot (r & 15) / 2,
|
||||
* so a lane's eight fold scales are two 16-byte reads. */
|
||||
if (tid < BM) sS[(tid & ~15) + (tid & 1) * 8 + ((tid & 15) >> 1)] = rs[d];
|
||||
}
|
||||
lds_barrier();
|
||||
fetch(d, kt + PD);
|
||||
#pragma unroll
|
||||
for (int s = 0; s < MXT2_BK / 16; ++s) {
|
||||
v16bf af[TM], bf[TN];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) af[i] = fragP(fa + i * 16 * MXT2_PITCH + s * 16);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) bf[j] = fragP(fw + j * 16 * MXT2_PITCH + s * 16);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) {
|
||||
if (PART && i >= live) break;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) tmp[i][j] = halo::mma(af[i], bf[j], (s & 1) ? tmp[i][j] : zero);
|
||||
}
|
||||
__builtin_amdgcn_sched_group_barrier(0x100, TM + TN, 0); /* DS reads */
|
||||
__builtin_amdgcn_sched_group_barrier(0x008, TM * TN, 0); /* WMMA */
|
||||
if (s & 1) {
|
||||
/* A 32-block closed: m64's fold. */
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) {
|
||||
if (PART && i >= live) break;
|
||||
v8f asv = (v8f)1.f;
|
||||
if constexpr (ABLK) asv = *(const v8f*)&sS[(wm * TM + i) * 16 + (lane >> 4) * 8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const float as = asv[e]; /* row 2e + (lane >> 4) of the fragment (accRow) */
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
float f = rf[j];
|
||||
if constexpr (ABLK) f *= as;
|
||||
acc[i][j][e] = fmaf(tmp[i][j][e], f, acc[i][j][e]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if constexpr (SPLIT) {
|
||||
/* The split's last fold: its chain joins the total, in split order. */
|
||||
if (++fc == fps) {
|
||||
fc = 0;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
v[i][j] += acc[i][j];
|
||||
acc[i][j] = zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
int kt0 = 0;
|
||||
for (; kt0 + PD <= nk; kt0 += PD) {
|
||||
#pragma unroll
|
||||
for (int d = 0; d < PD; ++d) slab(d, kt0 + d);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int d = 0; d < PD - 1; ++d)
|
||||
if (kt0 + d < nk) slab(d, kt0 + d);
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
const int n = n0 + (wn * TN + j) * 16 + (lane & 15);
|
||||
if (n >= N) continue;
|
||||
const int mb = m0 + (wm * TM + i) * 16;
|
||||
const v8f r = SPLIT ? v[SPLIT ? i : 0][SPLIT ? j : 0] : acc[i][j];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int m = mb + accRow(lane, e);
|
||||
if (m < M) C[(size_t)m * ldc + n] = (__hip_bfloat16)(ABLK ? r[e] : r[e] * As[m]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* The activation plane fits the op's scratch up to this size; past it (a long prefill band at a
|
||||
* wide K) the kernel decodes while staging instead, rather than the program reserving the plane. */
|
||||
#define MXT2_PLANE_CAP (256ll << 20)
|
||||
|
||||
/* Launch one part. `Ks` is the split length (K for one split). The prefill band picks the tile by
|
||||
* the row's `tn` tunable (2: 64 x 64, 4: 128 x 128); 0 is halo_gemm_bf16_nt_tiled's rule, the
|
||||
* 128 x 128 tile once its grid reaches 32 blocks. The two tiles' bytes are the same, so the tuner
|
||||
* chooses on time alone. The decode band (M <= 64, the plane present) takes a 1 x 8 wave tile
|
||||
* one to four row fragments tall. */
|
||||
static int mxt2_launch(const unsigned char* A, const uint16_t* Adq, const float* As,
|
||||
const unsigned char* W, const unsigned char* Ws, const unsigned char* Wref,
|
||||
__hip_bfloat16* C, int M, int K, int N, int lda, bool ablk, int as_rs,
|
||||
int ldws, int ldc, int tn, int Ks, hipStream_t st) {
|
||||
#define MXT2_GO(WMW, TM, TN, PD, P, B, S, PT) hipLaunchKernelGGL( \
|
||||
(halo_gemm_mxfp4a8_tiled2_kernel<WMW, TM, TN, PD, P, B, S, PT>), grid, dim3(256), 0, st, A, \
|
||||
Adq, As, W, Ws, Wref, C, M, K, N, lda, as_rs, ldws, ldc, Ks)
|
||||
/* The decode band: SPLIT at any split count (one included), whole row tiles. */
|
||||
#define MXT2_AB(WMW, TM, TN, PD, P) do { \
|
||||
if (ablk) MXT2_GO(WMW, TM, TN, PD, P, true, true, false); \
|
||||
else MXT2_GO(WMW, TM, TN, PD, P, false, true, false); } while (0)
|
||||
/* The prefill band: one split always; `part` when the M edge cuts the last row of blocks. */
|
||||
#define MXT2_AB1(WMW, TM, TN, PD, P) do { \
|
||||
if (part) { if (ablk) MXT2_GO(WMW, TM, TN, PD, P, true, false, true); \
|
||||
else MXT2_GO(WMW, TM, TN, PD, P, false, false, true); } \
|
||||
else { if (ablk) MXT2_GO(WMW, TM, TN, PD, P, true, false, false); \
|
||||
else MXT2_GO(WMW, TM, TN, PD, P, false, false, false); } } while (0)
|
||||
if (M > 16 && M <= 64 && Adq) {
|
||||
/* The decode band: a 1 x 8 wave tile 32 or 48 rows tall and 128 wide, deep in the ring; at
|
||||
* 49..64 rows the 2 x 4 one 64 square, whose accumulators leave room for the occupancy the
|
||||
* WMMAs then need. Measured on gfx1151 against each other (34816 x 5120: 769 us at 18 rows,
|
||||
* 956 at 36, 1140 at 64). */
|
||||
const int mt = (M + 15) / 16;
|
||||
if (mt == 2) {
|
||||
const dim3 grid((unsigned)((N + 127) / 128), 1);
|
||||
MXT2_AB(1, 2, 1, 4, true);
|
||||
} else if (mt == 3) {
|
||||
const dim3 grid((unsigned)((N + 127) / 128), 1);
|
||||
MXT2_AB(1, 3, 1, 4, true);
|
||||
} else {
|
||||
const dim3 grid((unsigned)((N + 63) / 64), 1);
|
||||
MXT2_AB(2, 2, 1, 1, true);
|
||||
}
|
||||
} else {
|
||||
const long long g128 = (long long)((N + 127) / 128) * ((M + 127) / 128);
|
||||
const bool big = tn == 4 || (tn != 2 && g128 >= 32);
|
||||
const int bt = big ? 128 : 64;
|
||||
const bool part = M % bt != 0;
|
||||
const dim3 grid((unsigned)((N + bt - 1) / bt), (unsigned)((M + bt - 1) / bt));
|
||||
if (big) { if (Adq) MXT2_AB1(2, 4, 2, 1, true); else MXT2_AB1(2, 4, 2, 1, false); }
|
||||
else { if (Adq) MXT2_AB1(2, 2, 1, 1, true); else MXT2_AB1(2, 2, 1, 1, false); }
|
||||
}
|
||||
#undef MXT2_AB1
|
||||
#undef MXT2_AB
|
||||
#undef MXT2_GO
|
||||
return hipGetLastError() == hipSuccess ? 0 : -5;
|
||||
}
|
||||
|
||||
/* Every part of a gemm_nt_q MXFP4 launch through mxt2_launch at split length K / sk. The
|
||||
* activation plane is decoded into the op's scratch when it fits (else each block decodes while
|
||||
* staging). */
|
||||
static int mxt2_run(const RadArgs* a, RadStream s, const GemmOps& g, const MxParts& mp,
|
||||
int as_group, int as_rs, int tn, int sk) {
|
||||
const long long plane = g.M * g.K * 2;
|
||||
uint16_t* adq = (a->scratch && a->scratch_bytes >= plane) ? (uint16_t*)a->scratch : nullptr;
|
||||
const long kb = (long)((g.K + 127) / 128);
|
||||
hipStream_t st = (hipStream_t)s;
|
||||
for (int p = 0; p < mp.n; ++p) {
|
||||
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
|
||||
const int lda = (int)(mp.lda ? mp.lda : g.K);
|
||||
const unsigned char* ap = (const unsigned char*)halo_addr(g.a) + p * g.K;
|
||||
if (adq) {
|
||||
const long long total = g.M * (g.K / 16);
|
||||
hipLaunchKernelGGL(mxt2_adq_kernel, dim3((unsigned)((total + 255) / 256)), dim3(256), 0,
|
||||
st, ap, adq, (int)g.M, (int)g.K, lda);
|
||||
}
|
||||
if (mxt2_launch(ap, adq, (const float*)(halo_addr(g.ascale) + p * kb * 4),
|
||||
(const unsigned char*)halo_addr(g.b) + n0 * g.K / 2,
|
||||
(const unsigned char*)halo_addr(g.bscale) + n0,
|
||||
(const unsigned char*)halo_addr(g.bref) + n0,
|
||||
(__hip_bfloat16*)(halo_addr(g.y) + n0 * 2), (int)g.M, (int)g.K, (int)np,
|
||||
lda, as_group == 128, as_rs, (int)g.N, (int)g.N, tn, (int)(g.K / sk), st))
|
||||
return HALO_NO(RAD_E_DEVICE);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* nt_m64's bytes at `sk` splits, past one row tile of the decode band: the gemv rows at the gemv
|
||||
* split law's SK (halo_gemm_mxfp4a8_gemv.hip) and the decode rows at one split
|
||||
* (halo_gemm_mxfp4a8_decode.hip). RAD_E_UNSUPPORTED when this kernel does not take the shape or
|
||||
* the scratch holds no plane (the caller then runs its own kernel). */
|
||||
int halo_mxfp4a8_tiled_split(const RadArgs* a, RadStream s, const GemmOps& g, const MxParts& mp,
|
||||
int as_group, int as_rs, int sk) {
|
||||
if (g.M > 64 || sk < 1 || g.K % MXT2_BK || g.K % ((long long)sk * HALO_MXT_GROUP) ||
|
||||
!a->scratch || a->scratch_bytes < g.M * g.K * 2)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
return mxt2_run(a, s, g, mp, as_group, as_rs, 0, sk);
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
// For a partitioned weight (mx_parts), each part's activation copy is decoded and multiplied in
|
||||
// turn. The `tn` tunable now picks the tile (see mxt2_launch); it never changes the bytes.
|
||||
extern "C" int halo_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 HALO_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale) return HALO_NO(RAD_E_INVAL);
|
||||
if (!g.bref) return HALO_NO(RAD_E_INVAL);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.K % HALO_MXT_KUNIT) return HALO_NO(RAD_E_SHAPE);
|
||||
int as_group = 0, as_rs = 1;
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return mxt2_run(a, s, g, mp, as_group, as_rs, (int)halo_geti_or(a, "tn", 0), 1);
|
||||
}
|
||||
|
||||
/* The row's scratch: the exact bf16 activation plane, M * K * 2, at the band's widest M, while it
|
||||
* fits MXT2_PLANE_CAP (one plane serves every part: parts run in order on the op's stream). */
|
||||
extern "C" int64_t halo_rad_gemm_mxfp4a8_tiled_plane_scratch(const RadArgs* a) {
|
||||
const long long M = halo_geti_or(a, "M", 0), K = halo_geti_or(a, "K", 0);
|
||||
if (M < 1 || K < 1) return 0;
|
||||
const long long b = M * K * 2;
|
||||
return b <= MXT2_PLANE_CAP ? b : 0;
|
||||
}
|
||||
|
||||
/* The fp8 fragment plane halo_mxfp4a8_tile_a writes, in whole 16-row fragments: what the
|
||||
* w4a8i8/w5a8i8 tiled rows size with this hook (the mxfp4 row itself now asks for
|
||||
* halo_rad_gemm_mxfp4a8_tiled_plane_scratch). */
|
||||
extern "C" int64_t halo_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs* a) {
|
||||
const long long M = halo_geti_or(a, "M", 0), K = halo_geti_or(a, "K", 0);
|
||||
return (int64_t)halo_mxfp4a8_tile_a_bytes((int)M, (int)K);
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
/* Derived from libr4d/r4d_gemm_bf16_nt_bias.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_nt_bias.hip - gemm_bf16_nt_bias_tiled: biased GEMM C = res + act(A @ W^T + bias)
|
||||
// over 64-deep K tiles, the K tail staged as zeros (halo_gemm_bf16_nt_tiled's tile, with the
|
||||
// epilogue libr4d's row promises):
|
||||
//
|
||||
// t = bf16(acc + bias); if act: t = bf16(act(t)); if res: t = bf16(res + t)
|
||||
//
|
||||
// three RNE roundings in the store, as the unfused chain's tensors would round. The f32
|
||||
// accumulation order is the kernel's own (the row's tolerance allows it); what is pinned is
|
||||
// the roundings and the activation forms (gelu erf, gelu_tanh). `res` may be the output
|
||||
// itself: each element is read by the lane that overwrites it.
|
||||
#include "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <cmath>
|
||||
|
||||
#define NB_BK 64 // K per staged tile: four WMMA k steps
|
||||
#define NB_PITCH (NB_BK + 8)
|
||||
#define NB_WM 2 // waves over M
|
||||
#define NB_WN 4 // waves over N
|
||||
|
||||
__device__ __forceinline__ float nb_act(int act, float t) {
|
||||
if (act == 1) return 0.5f * t * (1.0f + erff(t * 0.70710678118654752f));
|
||||
if (act == 2) {
|
||||
const float u = 0.7978845608028654f * (t + 0.044715f * t * t * t);
|
||||
return 0.5f * t * (1.0f + tanhf(u));
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
// TM x TN WMMA tiles a wave; BM = 2*TM*16, BN = 4*TN*16.
|
||||
template <int TM, int TN>
|
||||
__global__ __launch_bounds__(256) void halo_gemm_nt_bias_kernel(
|
||||
const unsigned short* __restrict__ A, const unsigned short* __restrict__ W,
|
||||
const void* __restrict__ Bias, const unsigned short* __restrict__ Res,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N,
|
||||
int lda, int ldw, int ldc, int ldr, int act, int bias_f32, int has_res) {
|
||||
constexpr int BM = NB_WM * TM * 16, BN = NB_WN * TN * 16;
|
||||
constexpr int CPR = NB_BK / 8; // 16-byte chunks a staged row
|
||||
constexpr int AL = BM * CPR / 256, WL = BN * CPR / 256;
|
||||
static_assert(AL >= 1 && WL >= 1 && BM * CPR % 256 == 0 && BN * CPR % 256 == 0,
|
||||
"a tile is whole 16-byte chunks for every thread");
|
||||
__shared__ __attribute__((aligned(16))) unsigned short sA[BM * NB_PITCH];
|
||||
__shared__ __attribute__((aligned(16))) unsigned short sW[BN * NB_PITCH];
|
||||
|
||||
const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31;
|
||||
const int wm = wave / NB_WN, wn = wave % NB_WN;
|
||||
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;
|
||||
|
||||
unsigned aoff[AL], woff[WL];
|
||||
unsigned short* adst[AL];
|
||||
unsigned short* wdst[WL];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) {
|
||||
const int c = tid + 256 * i, rr = c / CPR, e = (c % CPR) * 8;
|
||||
const int gr = m0 + rr < M ? m0 + rr : M - 1;
|
||||
aoff[i] = (unsigned)gr * (unsigned)lda + (unsigned)e;
|
||||
adst[i] = sA + rr * NB_PITCH + e;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) {
|
||||
const int c = tid + 256 * i, rr = c / CPR, e = (c % CPR) * 8;
|
||||
const int gr = n0 + rr < N ? n0 + rr : N - 1;
|
||||
woff[i] = (unsigned)gr * (unsigned)ldw + (unsigned)e;
|
||||
wdst[i] = sW + rr * NB_PITCH + e;
|
||||
}
|
||||
|
||||
const unsigned short* fa = sA + (wm * TM * 16 + (lane & 15)) * NB_PITCH;
|
||||
const unsigned short* fw = sW + (wn * TN * 16 + (lane & 15)) * NB_PITCH;
|
||||
|
||||
v8f acc[TM][TN];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) acc[i][j] = (v8f)(0.f);
|
||||
|
||||
const int nk = (K + NB_BK - 1) / NB_BK;
|
||||
// A staged chunk is eight elements; chunks starting past K stage zeros. K is a multiple
|
||||
// of 8, so a chunk is whole or absent.
|
||||
auto load_tile = [&](int kt, halo_u32x4* ra, halo_u32x4* rw) {
|
||||
const unsigned k0 = (unsigned)kt * NB_BK;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) {
|
||||
const int c = tid + 256 * i, e = (c % CPR) * 8;
|
||||
ra[i] = (k0 + (unsigned)e < (unsigned)K)
|
||||
? *(const halo_u32x4*)(A + aoff[i] + k0) : (halo_u32x4)0u;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) {
|
||||
const int c = tid + 256 * i, e = (c % CPR) * 8;
|
||||
rw[i] = (k0 + (unsigned)e < (unsigned)K)
|
||||
? *(const halo_u32x4*)(W + woff[i] + k0) : (halo_u32x4)0u;
|
||||
}
|
||||
};
|
||||
|
||||
halo_u32x4 ra[AL], rw[WL];
|
||||
load_tile(0, ra, rw);
|
||||
|
||||
for (int kt = 0; kt < nk; ++kt) {
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int i = 0; i < AL; ++i) *(halo_u32x4*)adst[i] = ra[i];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WL; ++i) *(halo_u32x4*)wdst[i] = rw[i];
|
||||
__syncthreads();
|
||||
if (kt + 1 < nk) load_tile(kt + 1, ra, rw);
|
||||
#pragma unroll
|
||||
for (int s = 0; s < NB_BK / 16; ++s) {
|
||||
v16bf af[TM], bf[TN];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) af[i] = fragP(fa + i * 16 * NB_PITCH + s * 16);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) bf[j] = fragP(fw + j * 16 * NB_PITCH + s * 16);
|
||||
#pragma unroll
|
||||
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]);
|
||||
__builtin_amdgcn_sched_group_barrier(0x100, TM + TN, 0); /* DS reads */
|
||||
__builtin_amdgcn_sched_group_barrier(0x008, TM * TN, 0); /* WMMA */
|
||||
}
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
const int n = n0 + (wn * TN + j) * 16 + (lane & 15);
|
||||
const int mb = m0 + (wm * TM + i) * 16;
|
||||
float bv = 0.f;
|
||||
if (n < N)
|
||||
bv = bias_f32 ? ((const float*)Bias)[n]
|
||||
: bf16_to_f32(((const unsigned short*)Bias)[n]);
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int m = mb + accRow(lane, e);
|
||||
if (n < N && m < M) {
|
||||
float t = bf16_to_f32(f32_to_bf16(acc[i][j][e] + bv));
|
||||
if (act) t = bf16_to_f32(f32_to_bf16(nb_act(act, t)));
|
||||
if (has_res)
|
||||
t = bf16_to_f32(f32_to_bf16(bf16_to_f32(Res[(size_t)m * ldr + n]) + t));
|
||||
C[(size_t)m * ldc + n] = (__hip_bfloat16)t;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int gemm_nt_bias_launch(long a, long w, long bias, long res, long c, int M, int K, int N,
|
||||
int lda, int ldw, int ldc, int ldr, int act, int bias_f32,
|
||||
int has_res, long stream) {
|
||||
if (M < 1 || N < 1 || K < 8 || (K % 8)) return -1;
|
||||
if ((long long)M * lda >= (1ll << 32) || (long long)N * ldw >= (1ll << 32)) return -1;
|
||||
const long long g = (long long)((N + 127) / 128) * ((M + 127) / 128);
|
||||
const int bt = g >= 32 ? 128 : 64;
|
||||
dim3 grid((N + bt - 1) / bt, (M + bt - 1) / bt), block(256);
|
||||
auto Ap = (const unsigned short*)a; auto Wp = (const unsigned short*)w;
|
||||
auto Rp = (const unsigned short*)res; auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define NB_LAUNCH(TM, TN) hipLaunchKernelGGL((halo_gemm_nt_bias_kernel<TM, TN>), grid, block, 0, \
|
||||
st, Ap, Wp, (const void*)bias, Rp, Cp, M, K, N, lda, ldw, ldc, ldr, act, bias_f32, has_res)
|
||||
if (bt == 128) NB_LAUNCH(4, 2); else NB_LAUNCH(2, 1);
|
||||
#undef NB_LAUNCH
|
||||
return (int)hipGetLastError();
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
extern "C" int halo_rad_gemm_nt_bias(const RadArgs* a, RadStream s) {
|
||||
enum { GF_A = 0, GF_W, GF_BIAS, GF_RES, GF_Y };
|
||||
const RadTensor* A = halo_opt(a, GF_A);
|
||||
const RadTensor* W = halo_opt(a, GF_W);
|
||||
const RadTensor* B = halo_opt(a, GF_BIAS);
|
||||
const RadTensor* R = halo_opt(a, GF_RES);
|
||||
const RadTensor* Y = halo_opt(a, GF_Y);
|
||||
if (!A || !W || !B || !Y) return HALO_NO(RAD_E_INVAL);
|
||||
if (A->dtype != RAD_BF16 || W->dtype != RAD_BF16 || Y->dtype != RAD_BF16)
|
||||
return HALO_NO(RAD_E_DTYPE);
|
||||
if (B->dtype != RAD_F32 && B->dtype != RAD_BF16) return HALO_NO(RAD_E_DTYPE);
|
||||
const bool has_res = R && R->data;
|
||||
if (has_res && R->dtype != RAD_BF16) return HALO_NO(RAD_E_DTYPE);
|
||||
if (!halo_contig(W) || !halo_contig(B)) return HALO_NO(RAD_E_STRIDE);
|
||||
|
||||
const char* act_s = halo_gets(a, "act");
|
||||
int act = 0;
|
||||
if (act_s && *act_s) {
|
||||
if (!std::strcmp(act_s, "gelu")) act = 1;
|
||||
else if (!std::strcmp(act_s, "gelu_tanh")) act = 2;
|
||||
else if (std::strcmp(act_s, "none")) return HALO_NO(RAD_E_SCHEMA);
|
||||
}
|
||||
const char* dt = halo_gets(a, "dtype");
|
||||
if (dt && *dt && std::strcmp(dt, "bf16")) return HALO_NO(RAD_E_DTYPE);
|
||||
|
||||
const long long K = halo_geti_or(a, "K", halo_dim(W, (int)W->rank - 1));
|
||||
const long long N = halo_geti_or(a, "N", K > 0 ? halo_numel(W) / K : 0);
|
||||
if (K <= 0 || N <= 0 || halo_numel(W) < N * K || halo_numel(B) < N)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
long long M = 0, Ma = 0, Mw = 0, Mr2 = 0;
|
||||
const long long ldc = halo_rows_pitch(Y, N, &M);
|
||||
const long long lda = halo_rows_pitch(A, K, &Ma);
|
||||
const long long ldw = halo_rows_pitch(W, K, &Mw);
|
||||
const long long ldr = has_res ? halo_rows_pitch(R, N, &Mr2) : 0;
|
||||
if (ldc < 0 || lda < 0 || ldw < 0 || ldr < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || Ma < M || Mw < N || (has_res && Mr2 < M)) return HALO_NO(RAD_E_SHAPE);
|
||||
if (!halo_aligned(A->data, 16)) return HALO_NO(RAD_E_ALIGN);
|
||||
|
||||
const int e = gemm_nt_bias_launch(halo_addr(A), halo_addr(W), halo_addr(B),
|
||||
has_res ? halo_addr(R) : 0, halo_addr(Y),
|
||||
(int)M, (int)K, (int)N, (int)lda, (int)ldw, (int)ldc,
|
||||
(int)ldr, act, B->dtype == RAD_F32, has_res ? 1 : 0,
|
||||
(long)(uintptr_t)s);
|
||||
return e == 0 ? RAD_OK : HALO_NO(e < 0 ? RAD_E_SHAPE : RAD_E_DEVICE);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// halo_gemm_nt_f32.hip - gemm_nt_f32_bf16: the F32 routing and index gate projection.
|
||||
// C[M, N] f32 = X[M, K] bf16 @ W[N, K] f32^T, pitched rows on both sides.
|
||||
//
|
||||
// The accumulation order is part of the row's contract (the selftest compares byte for byte
|
||||
// with the host arithmetic): lane l folds k = l, l + 32, ... with fmaf, then an xor butterfly
|
||||
// over 16, 8, 4, 2, 1 closes the wave. Any tiling must keep that order, so the kernel is one
|
||||
// wave per output element; the shapes (N <= 512, K <= 16384, small M) make that the right
|
||||
// size anyway.
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_common.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace {
|
||||
|
||||
__global__ void __launch_bounds__(32) gemm_nt_f32_kernel(const uint16_t* __restrict__ x,
|
||||
const float* __restrict__ w,
|
||||
float* __restrict__ y,
|
||||
int K, long ldx, long ldw, long ldy) {
|
||||
const int m = (int)blockIdx.y;
|
||||
const int n = (int)blockIdx.x;
|
||||
const int lane = (int)threadIdx.x;
|
||||
const uint16_t* xr = x + (long)m * ldx;
|
||||
const float* wr = w + (long)n * ldw;
|
||||
float acc = 0.0f;
|
||||
for (int k = lane; k < K; k += 32)
|
||||
acc = fmaf(bf16_to_f32(xr[k]), wr[k], acc);
|
||||
#pragma unroll
|
||||
for (int mask = 16; mask; mask >>= 1) acc += __shfl_xor(acc, mask);
|
||||
if (lane == 0) y[(long)m * ldy + n] = acc;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
extern "C" int halo_rad_gemm_nt_f32(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* X = halo_opt(a, 0);
|
||||
const RadTensor* W = halo_opt(a, 1);
|
||||
const RadTensor* Y = halo_opt(a, 2);
|
||||
if (!X || !W || !Y) return HALO_NO(RAD_E_INVAL);
|
||||
if (X->dtype != RAD_BF16 || W->dtype != RAD_F32 || Y->dtype != RAD_F32)
|
||||
return HALO_NO(RAD_E_DTYPE);
|
||||
const char* dt = halo_gets(a, "dtype");
|
||||
if (dt && *dt && std::strcmp(dt, "bf16")) return HALO_NO(RAD_E_DTYPE);
|
||||
|
||||
const long long K = halo_geti_or(a, "K", halo_dim(W, (int)W->rank - 1));
|
||||
const long long N = halo_geti_or(a, "N", K > 0 ? halo_numel(W) / K : 0);
|
||||
if (K <= 0 || N <= 0 || halo_numel(W) < N * K) return HALO_NO(RAD_E_SHAPE);
|
||||
long long M = 0, Mx = 0;
|
||||
const long long ldy = halo_rows_pitch(Y, N, &M);
|
||||
const long long ldx = halo_rows_pitch(X, K, &Mx);
|
||||
long long Mw = 0;
|
||||
const long long ldw = halo_rows_pitch(W, K, &Mw);
|
||||
if (ldy < 0 || ldx < 0 || ldw < 0) return HALO_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || Mx < M || Mw < N) return HALO_NO(RAD_E_SHAPE);
|
||||
if (M > 65535 || N > 0x7fffffffll) return HALO_NO(RAD_E_SHAPE);
|
||||
|
||||
dim3 grid((unsigned)N, (unsigned)M);
|
||||
hipLaunchKernelGGL((gemm_nt_f32_kernel), grid, 32, 0, (hipStream_t)stream,
|
||||
(const uint16_t*)halo_p(X), (const float*)halo_p(W), (float*)halo_p(Y),
|
||||
(int)K, ldx, ldw, ldy);
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
/* Derived from libr4d/r4d_gemm_w2a8_nt_m64.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_w2a8_nt.hip - halo_gemm_w2a8_nt: 2-bit-weight, 8-bit-activation skinny GEMM, the
|
||||
// DFlash2 draft head. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, A quantised per row, W an unsigned
|
||||
// 2-bit code with an f16 scale and an integer zero per (row, 128 K).
|
||||
//
|
||||
// The weight keeps libr4d's fragment order byte for byte (halo_layout.cpp's w2_slot): within a
|
||||
// (16-row tile, 128 K block), lane r = n % 16 holds eight dwords -- (lh, d) in {0,1} x {0..3} --
|
||||
// whose 2-bit fields are the row's 128 codes. For one 16-wide k step u a lane needs exactly
|
||||
// the two dwords (lh = 0, 1) at d = u/2: field 4*(e%4) + (e/4) + 2*(u%2) of dword lh=(j%8)/4
|
||||
// is code j, with e = (j/8)*4 + (j%4). Sixteen shifts unpack the step; the integer zero is
|
||||
// folded into the byte (code - zero in [-15, 3] is an exact int8), so the iu8 WMMA accumulates
|
||||
// the corrected product directly and no activation group sums are needed -- the same integer
|
||||
// libr4d's asum correction forms, in the same order.
|
||||
//
|
||||
// The activation is quant_act_i8's pre-shuffled plane, read as halo_gemm_w8a8_nt_m64 reads it:
|
||||
// one cross-half exchange reassembles the gfx11 fragment's consecutive sixteen K.
|
||||
#include "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
// Not structural (grid.y tiles M, rows are clamped); a sanity bound only.
|
||||
#define HALO_GEMM_W2A8_MAX_M 32768
|
||||
#define WAVE32 32
|
||||
|
||||
typedef int v8i __attribute__((ext_vector_type(8)));
|
||||
typedef float v8f __attribute__((ext_vector_type(8)));
|
||||
typedef int v4i __attribute__((ext_vector_type(4)));
|
||||
typedef unsigned uint2v __attribute__((ext_vector_type(2)));
|
||||
|
||||
typedef __attribute__((address_space(1))) const uint2v* halo_ga2;
|
||||
|
||||
/* The activation fragment, as halo_gemm_w8a8_nt_m64 reads it. */
|
||||
__device__ __forceinline__ v4i frag_step(unsigned d0, unsigned d1, int lane) {
|
||||
const unsigned p0 = (unsigned)__shfl_xor((int)d0, 16);
|
||||
const unsigned p1 = (unsigned)__shfl_xor((int)d1, 16);
|
||||
const bool hi = lane >> 4;
|
||||
v4i r;
|
||||
r[0] = (int)(hi ? p0 : d0);
|
||||
r[1] = (int)(hi ? d0 : p0);
|
||||
r[2] = (int)(hi ? p1 : d1);
|
||||
r[3] = (int)(hi ? d1 : p1);
|
||||
return r;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v4i fragA8w(halo_ga2 p, int u, int lane) {
|
||||
const uint2v w = p[2 * u];
|
||||
return frag_step(w[0], w[1], lane);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v8i mmai8(v4i a, v4i b, v8i c) {
|
||||
return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, a, true, b, c, false);
|
||||
}
|
||||
|
||||
/* The lane's eight dwords of (tile t, group kb): (lh = 0, d = 0..3) and (lh = 1, d = 0..3), each
|
||||
* run contiguous, so two 16-byte loads. */
|
||||
__device__ __forceinline__ void loadW2(const unsigned* __restrict__ Wq, int t, int kb, int lane,
|
||||
int kpb, uint4& lo, uint4& hi) {
|
||||
const size_t base = ((size_t)(t * kpb + kb) * WAVE32 + (lane & 15)) * 4;
|
||||
lo = *(const uint4*)(Wq + base);
|
||||
hi = *(const uint4*)(Wq + base + 64);
|
||||
}
|
||||
|
||||
/* One k step's weight fragment: the lane's two dwords at d = u/2, sixteen 2-bit fields
|
||||
* unpacked and zero-corrected into the fragment's bytes. Fragment dword d takes fields
|
||||
* 4q + h (+1 for d >= 2) of w0 (d even) or w1 (d odd) into byte q, h = 2 (u & 1): the four codes
|
||||
* of a dword sit at one shift, so it is a shift and a mask. The zero comes off every byte at once
|
||||
* through a bias: `zb` is 0x80 - zero in each byte (zero is 0..15), so 0x80 + code - zero neither
|
||||
* carries nor borrows, and the xor leaves code - zero as the int8 the byte loop wrote. */
|
||||
__device__ __forceinline__ v4i fragW2(const uint4& lo, const uint4& hi, int u, unsigned zb) {
|
||||
const int dsel = u >> 1;
|
||||
const unsigned w0 = dsel == 0 ? lo.x : dsel == 1 ? lo.y : dsel == 2 ? lo.z : lo.w;
|
||||
const unsigned w1 = dsel == 0 ? hi.x : dsel == 1 ? hi.y : dsel == 2 ? hi.z : hi.w;
|
||||
const int s = (u & 1) * 4;
|
||||
constexpr unsigned M = 0x03030303u, B = 0x80808080u;
|
||||
v4i r4;
|
||||
r4[0] = (int)((((w0 >> s) & M) + zb) ^ B);
|
||||
r4[1] = (int)((((w1 >> s) & M) + zb) ^ B);
|
||||
r4[2] = (int)((((w0 >> (s + 2)) & M) + zb) ^ B);
|
||||
r4[3] = (int)((((w1 >> (s + 2)) & M) + zb) ^ B);
|
||||
return r4;
|
||||
}
|
||||
|
||||
#define HALO_W2A8_BOUNDS(MT, NPW) ((MT) * (NPW) >= 8 ? 256 : ((MT) * (NPW) >= 4 ? 512 : 1024))
|
||||
|
||||
template <int MT, int NPW>
|
||||
__global__ __launch_bounds__(HALO_W2A8_BOUNDS(MT, NPW)) void halo_gemm_w2a8_kernel(
|
||||
const signed char* __restrict__ A, const float* __restrict__ Ascale,
|
||||
const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) {
|
||||
extern __shared__ float red[];
|
||||
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
const int nt0 = (blockIdx.x * WV + col_local) * NPW;
|
||||
const int n0 = nt0 * 16;
|
||||
const int mt0 = blockIdx.y * MT;
|
||||
const int Ks = K / SK;
|
||||
const int groups = Ks / HALO_GEMM_W2A8_GROUP;
|
||||
const int kbase = ksplit * Ks;
|
||||
const int kpb = K / HALO_GEMM_W2A8_GROUP; /* 128-blocks a weight row */
|
||||
const int nsz = kpb;
|
||||
|
||||
v8f acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
if (n0 < N) {
|
||||
halo_ga2 pa[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
int r = (mt0 + i) * 16 + (lane & 15);
|
||||
r = r < M - 1 ? r : M - 1;
|
||||
const size_t off = (size_t)r * K + kbase + 8 * (lane >> 4);
|
||||
pa[i] = (halo_ga2)(const uint2v*)(A + off);
|
||||
}
|
||||
const int ntlast = N / 16 - 1;
|
||||
int tt[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) tt[j] = (nt0 + j) < ntlast ? (nt0 + j) : ntlast;
|
||||
|
||||
for (int g = 0; g < groups; g++) {
|
||||
const int kb = kbase / HALO_GEMM_W2A8_GROUP + g;
|
||||
float sc[NPW];
|
||||
unsigned zb[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const unsigned d = Ws[((size_t)(tt[j] * nsz + kb)) * 16 + (lane & 15)];
|
||||
sc[j] = __half2float(__ushort_as_half((unsigned short)(d & 0xffffu)));
|
||||
const int zero = (int)(-__half2float(__ushort_as_half((unsigned short)(d >> 16))) - 1024.0f);
|
||||
zb[j] = 0x80808080u - (unsigned)zero * 0x01010101u;
|
||||
}
|
||||
uint4 wlo[NPW], whi[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) loadW2(Wq, tt[j], kb, lane, kpb, wlo[j], whi[j]);
|
||||
v8i g_acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int u = 0; u < 8; u++) {
|
||||
v4i afrag[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) afrag[i] = fragA8w(pa[i], u, lane);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const v4i bfrag = fragW2(wlo[j], whi[j], u, zb[j]);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
g_acc[j][i] = (u == 0) ? mmai8(afrag[i], bfrag, (v8i)(0))
|
||||
: mmai8(afrag[i], bfrag, g_acc[j][i]);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#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]);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] += HALO_GEMM_W2A8_GROUP / 8;
|
||||
}
|
||||
}
|
||||
|
||||
const int ncols = WV * NPW;
|
||||
const int nthreads = WV * SK * WAVE32;
|
||||
if (SK == 1) {
|
||||
if (n0 >= N) return;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int n = (nt0 + j) * 16 + (lane & 15);
|
||||
if (n >= N) continue;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
const int mb = (mt0 + i) * 16;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) {
|
||||
const int m = mb + accRow(lane, e);
|
||||
if (m < M) C[(size_t)m * N + n] = (__hip_bfloat16)(acc[j][i][e] * Ascale[m]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int slot = ((col_local * NPW + j) * SK + ksplit) * 256;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) red[slot + e * WAVE32 + lane] = acc[j][i][e];
|
||||
}
|
||||
__syncthreads();
|
||||
for (int idx = tid; idx < ncols * 256; idx += nthreads) {
|
||||
const int col = idx >> 8, off = idx & 255;
|
||||
float v = 0.f;
|
||||
for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off];
|
||||
const int l = off & 31;
|
||||
const int n = (blockIdx.x * ncols + col) * 16 + (l & 15);
|
||||
const int m = (mt0 + i) * 16 + accRow(l, off >> 5);
|
||||
if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)(v * Ascale[m]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void gemm_w2a8_impl(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
|
||||
int WV, int SK, int MB, int NPW, long stream) {
|
||||
if (M < 1 || M > HALO_GEMM_W2A8_MAX_M)
|
||||
throw std::runtime_error("r4d gemm_w2a8_nt: M out of range");
|
||||
if (N % 16) throw std::runtime_error("r4d gemm_w2a8_nt: N must be a multiple of 16");
|
||||
if (K % (SK * HALO_GEMM_W2A8_GROUP))
|
||||
throw std::runtime_error("r4d gemm_w2a8_nt: K must be divisible by SK*group");
|
||||
if (WV * SK * WAVE32 > HALO_W2A8_BOUNDS(MB, NPW))
|
||||
throw std::runtime_error("r4d gemm_w2a8_nt: WV*SK*32 exceeds this tile'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 && NPW != 8)
|
||||
throw std::runtime_error("r4d gemm_w2a8_nt: NPW must be 1, 2, 4 or 8");
|
||||
const int ntiles = N / 16, mtiles = (M + 15) / 16;
|
||||
const int ncols = WV * NPW;
|
||||
dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32);
|
||||
size_t smem = (size_t)ncols * SK * 256 * sizeof(float);
|
||||
if (smem > 64 * 1024) throw std::runtime_error("r4d gemm_w2a8_nt: WV*NPW*SK too large");
|
||||
auto Ap = (const signed char*)a;
|
||||
auto Sp = (const float*)ascale;
|
||||
auto Wp = (const unsigned*)wq;
|
||||
auto Zp = (const unsigned*)ws;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH2(MT, NP) hipLaunchKernelGGL((halo_gemm_w2a8_kernel<MT, NP>), \
|
||||
grid, block, smem, st, Ap, Sp, Wp, Zp, Cp, M, K, N, WV, SK)
|
||||
#define LAUNCH2_MB4(NP) switch (MB) { \
|
||||
case 1: LAUNCH2(1, NP); break; \
|
||||
case 2: LAUNCH2(2, NP); break; \
|
||||
case 3: LAUNCH2(3, NP); break; \
|
||||
case 4: LAUNCH2(4, NP); break; \
|
||||
default: throw std::runtime_error("r4d gemm_w2a8_nt: MB unsupported"); }
|
||||
#define LAUNCH2_MB2(NP) switch (MB) { \
|
||||
case 1: LAUNCH2(1, NP); break; \
|
||||
case 2: LAUNCH2(2, NP); break; \
|
||||
default: throw std::runtime_error("r4d gemm_w2a8_nt: MB*NPW > 8 would spill"); }
|
||||
#define LAUNCH2_MB1(NP) switch (MB) { \
|
||||
case 1: LAUNCH2(1, NP); break; \
|
||||
default: throw std::runtime_error("r4d gemm_w2a8_nt: MB*NPW > 8 would spill"); }
|
||||
#define LAUNCH2_NPW switch (NPW) { \
|
||||
case 1: LAUNCH2_MB4(1); break; \
|
||||
case 2: LAUNCH2_MB4(2); break; \
|
||||
case 4: LAUNCH2_MB2(4); break; \
|
||||
case 8: LAUNCH2_MB1(8); break; \
|
||||
default: throw std::runtime_error("r4d gemm_w2a8_nt: NPW must be 1, 2, 4 or 8"); }
|
||||
LAUNCH2_NPW;
|
||||
#undef LAUNCH2_NPW
|
||||
#undef LAUNCH2_MB1
|
||||
#undef LAUNCH2_MB2
|
||||
#undef LAUNCH2_MB4
|
||||
#undef LAUNCH2
|
||||
}
|
||||
|
||||
/* libr4d's raw signature (halo.h, C linkage). The zero point is folded into the int8 fragment
|
||||
* bytes here, so `asum` is not read, and the load hint `NT` has no gfx1151 form. */
|
||||
extern "C" void halo_gemm_w2a8_nt(long a, long ascale, long wq, long ws, long asum, long c,
|
||||
int M, int K, int N, int WV, int SK, int MB, int NPW, int NT,
|
||||
long stream) {
|
||||
(void)asum; (void)NT;
|
||||
gemm_w2a8_impl(a, ascale, wq, ws, c, M, K, N, WV, SK, MB, NPW, stream);
|
||||
}
|
||||
static int halo_gemm_w2a8_nt_max_m(void) { return HALO_GEMM_W2A8_MAX_M; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
extern "C" int halo_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 HALO_NO(RAD_E_SHAPE);
|
||||
if (g.M > halo_gemm_w2a8_nt_max_m()) return HALO_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale) return HALO_NO(RAD_E_INVAL);
|
||||
Cfg c;
|
||||
/* With the tile count, an untuned split is the smallest that fills the part: at the draft
|
||||
* head's N (a vocabulary, ~15500 tiles) that is no split, 1.9x faster on gfx1151 than the
|
||||
* largest legal one (20 at K = 2560), which leaves a wave one scale group. */
|
||||
rc = cfg_for(a, g.K, g.M, HALO_GEMM_W2A8_GROUP, BR_W2A8, &c, g.N / 16);
|
||||
if (rc != RAD_OK) return rc;
|
||||
HALO_TRY("gemm_w2a8_nt",
|
||||
gemm_w2a8_impl(halo_addr(g.a), halo_addr(g.ascale), halo_addr(g.b),
|
||||
halo_addr(g.bscale), halo_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw,
|
||||
(long)(uintptr_t)s));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The raw-pointer query libr4d exports beside the row (halo.h). */
|
||||
extern "C" int halo_gemm_w2a8_nt_group(void) { return HALO_GEMM_W2A8_GROUP; }
|
||||
@@ -0,0 +1,315 @@
|
||||
/* Derived from libr4d/r4d_gemm_w4a16_nt_m64.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_w4a16_nt_m64.hip - halo_gemm_w4a16_nt_m64: 4-bit-weight skinny GEMM for M up to 64,
|
||||
// gfx1151. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C, fp32 accumulate.
|
||||
//
|
||||
// The decomposition of halo_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).
|
||||
//
|
||||
// f16, not bf16: `0x6400 | n` is exactly the f16 for 1024 + n, so eight v_perm_b32 turn two
|
||||
// dwords of eight nibbles (this lane's and its cross-half partner's; see dequant) into a
|
||||
// 16x16x16 fragment, and the zero point is subtracted with v_pk_add_f16. RDNA has no packed
|
||||
// bf16 arithmetic, so in bf16 that subtract would be one instruction an element instead of one
|
||||
// a pair. The WMMA inputs are exact; the group scale is applied to the f32 accumulator.
|
||||
//
|
||||
// On libr4d's part the f16 WMMA is the slowest matrix instruction and this kernel owns only
|
||||
// the small-M band, the int8 form (halo_gemm_w4a8_nt_m64) taking the same packed weight at
|
||||
// larger M; where the crossover falls on gfx1151 is a tuning measurement, not an inheritance.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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 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) (halo_gdn_wmma.h)
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// Quantiser: per output channel, per group of HALO_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 "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define HALO_GEMM_W4_MAX_M 64
|
||||
#define HALO_GEMM_W4_KPB 64 // K per packed block: 4 k steps, 16 bytes per lane
|
||||
#define WAVE32 32
|
||||
|
||||
typedef _Float16 v16h __attribute__((ext_vector_type(16)));
|
||||
typedef unsigned uint4v __attribute__((ext_vector_type(4)));
|
||||
|
||||
// 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 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 loads stay global_load, not flat_load (on gfx12 a flat load also
|
||||
// increments dscnt). See halo_gemm_bf16_nt_m64.hip for why the element type is a scalar.
|
||||
typedef __attribute__((address_space(1))) const uint4v* halo_gw4;
|
||||
typedef __attribute__((address_space(1))) const unsigned long long* halo_gu2;
|
||||
typedef __attribute__((address_space(1))) const unsigned* halo_gu1;
|
||||
|
||||
/* gfx11 fragment: the row's whole 16-wide k run, 32 contiguous bytes, where the gfx12 form was
|
||||
* two 8-byte halves sixteen bytes apart. The pointer step is 32 bytes either way. */
|
||||
__device__ __forceinline__ v16h fragA(halo_gu2 p, int u) {
|
||||
union { unsigned long long w[4]; v16h f; } x;
|
||||
x.w[0] = p[4 * u];
|
||||
x.w[1] = p[4 * u + 1];
|
||||
x.w[2] = p[4 * u + 2];
|
||||
x.w[3] = p[4 * u + 3];
|
||||
return x.f;
|
||||
}
|
||||
|
||||
// One dword of eight nibbles -> eight f16 values (four packed pairs), before the zero point is
|
||||
// subtracted. 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).
|
||||
|
||||
// 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__ void dequant_pairs(unsigned w, unsigned* u) {
|
||||
const unsigned K64 = 0x64646464u;
|
||||
// The stored nibble is two's complement, which halo_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;
|
||||
u[0] = __builtin_amdgcn_perm(K64, t0, 0x05010400u); // nibbles 0, 2
|
||||
u[1] = __builtin_amdgcn_perm(K64, t0, 0x05030402u); // nibbles 4, 6
|
||||
u[2] = __builtin_amdgcn_perm(K64, t1, 0x05010400u); // nibbles 1, 3
|
||||
u[3] = __builtin_amdgcn_perm(K64, t1, 0x05030402u); // nibbles 5, 7
|
||||
}
|
||||
|
||||
/* The stored weight keeps libr4d's gfx12 fragment order byte for byte. For one k step a lane's
|
||||
* dword holds K quarters (0,2) in the low half-wave and (1,3) in the high half-wave for the same
|
||||
* row, each unpacked as [quarter, quarter+2] pairs, so one cross-half exchange and a pair
|
||||
* interleave reassemble the gfx11 fragment's consecutive sixteen K. nz holds -(1024 + zero) in
|
||||
* both halves. */
|
||||
__device__ __forceinline__ v16h dequant(unsigned w, __half2 nz, int lane) {
|
||||
const unsigned pw = (unsigned)__shfl_xor((int)w, 16);
|
||||
const bool hi = lane >> 4;
|
||||
unsigned lo[4], hd[4];
|
||||
dequant_pairs(hi ? pw : w, lo); // K quarters 0 and 2, as [q0 pairs][q2 pairs]
|
||||
dequant_pairs(hi ? w : pw, hd); // K quarters 1 and 3
|
||||
union { unsigned u[8]; __half2 h2[8]; v16h f; } x;
|
||||
x.u[0] = lo[0]; x.u[1] = lo[1]; x.u[2] = hd[0]; x.u[3] = hd[1];
|
||||
x.u[4] = lo[2]; x.u[5] = lo[3]; x.u[6] = hd[2]; x.u[7] = hd[3];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; i++) x.h2[i] = __hadd2(x.h2[i], nz);
|
||||
return x.f;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v8f mmah(v16h a, v16h b, v8f c) {
|
||||
return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c);
|
||||
}
|
||||
|
||||
// MT = row tiles per block, as in the bf16 kernel.
|
||||
template <int MT, int NPW, bool NT>
|
||||
__global__ __launch_bounds__(1024) void halo_gemm_w4a16_nt_m64_kernel(
|
||||
const unsigned short* __restrict__ A, const unsigned* __restrict__ Wq,
|
||||
const unsigned* __restrict__ Wsz, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int WV, int SK) {
|
||||
extern __shared__ float red[]; // WV*NPW*SK*256 floats: a 16x16 tile per (column, split)
|
||||
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
const int nt0 = (blockIdx.x * WV + col_local) * NPW;
|
||||
const int n0 = nt0 * 16;
|
||||
const int mt0 = blockIdx.y * MT;
|
||||
const int Ks = K / SK;
|
||||
const int groups = Ks / HALO_GEMM_W4_GROUP; // groups this split owns
|
||||
const int kbase = ksplit * Ks;
|
||||
|
||||
v8f acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
if (n0 < N) {
|
||||
// Activation rows are clamped, not masked; results past M are never stored.
|
||||
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;
|
||||
halo_gu2 pa[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] = (halo_gu2)(const unsigned long long*)(A + aoff[i]);
|
||||
|
||||
// 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 / HALO_GEMM_W4_KPB; // packed blocks in a full row of tiles
|
||||
const int nsz = K / HALO_GEMM_W4_GROUP; // (scale, zero) dwords per row of tiles
|
||||
halo_gw4 pw[NPW];
|
||||
halo_gu1 ps[NPW];
|
||||
const int ntlast = N / 16 - 1;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
// 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] = (halo_gw4)(const uint4v*)(Wq) +
|
||||
(size_t)(t * kpb + kbase / HALO_GEMM_W4_KPB) * WAVE32 + lane;
|
||||
// Quantizer parameters: 16 distinct dwords per group, read by the 16 lanes that own the rows.
|
||||
ps[j] = (halo_gu1)(const unsigned*)(Wsz) +
|
||||
(size_t)(t * nsz + kbase / HALO_GEMM_W4_GROUP) * 16 + (lane & 15);
|
||||
}
|
||||
|
||||
const int bpg = HALO_GEMM_W4_GROUP / HALO_GEMM_W4_KPB; // packed blocks per group
|
||||
|
||||
for (int g = 0; g < groups; g++) {
|
||||
float sc[NPW];
|
||||
__half2 nz[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const unsigned sz = ps[j][(size_t)g * 16];
|
||||
sc[j] = __half2float(__ushort_as_half((unsigned short)(sz & 0xFFFFu)));
|
||||
nz[j] = __half2half2(__ushort_as_half((unsigned short)(sz >> 16)));
|
||||
}
|
||||
|
||||
// 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++) {
|
||||
uint4v wv[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const size_t o = (size_t)(g * bpg + b) * WAVE32;
|
||||
wv[j] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int s = 0; s < 4; s++) {
|
||||
const int u = b * 4 + s;
|
||||
v16h afrag[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) afrag[i] = fragA(pa[i], u); // loaded once, spent NPW times
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const v16h bfrag = dequant(wv[j][s], nz[j], lane);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
g_acc[j][i] = u == 0 ? mmah(afrag[i], bfrag, (v8f)(0.f))
|
||||
: mmah(afrag[i], bfrag, g_acc[j][i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) acc[j][i][e] = fmaf(g_acc[j][i][e], sc[j], acc[j][i][e]);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] += (HALO_GEMM_W4_GROUP / 16) * 4;
|
||||
}
|
||||
}
|
||||
|
||||
// Split-K reduction and store as in halo_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
|
||||
for (int i = 0; i < MT; i++) {
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int slot = ((col_local * NPW + j) * SK + ksplit) * 256;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) red[slot + e * WAVE32 + lane] = acc[j][i][e];
|
||||
}
|
||||
__syncthreads();
|
||||
for (int idx = tid; idx < ncols * 256; idx += nthreads) {
|
||||
const int col = idx >> 8, off = idx & 255;
|
||||
float v = 0.f;
|
||||
for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off];
|
||||
const int l = off & 31;
|
||||
const int n = (blockIdx.x * ncols + col) * 16 + (l & 15);
|
||||
const int m = (mt0 + i) * 16 + accRow(l, off >> 5);
|
||||
if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void halo_gemm_w4a16_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) {
|
||||
if (M < 1 || M > HALO_GEMM_W4_MAX_M)
|
||||
throw std::runtime_error("r4d gemm_w4a16_nt_m64: M must be 1..64");
|
||||
if (N % 16) throw std::runtime_error("r4d gemm_w4a16_nt_m64: N must be a multiple of 16");
|
||||
if (K % (SK * HALO_GEMM_W4_GROUP))
|
||||
throw std::runtime_error("r4d gemm_w4a16_nt_m64: K must be divisible by SK*128");
|
||||
if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_w4a16_nt_m64: threads/block > 1024");
|
||||
if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w4a16_nt_m64: MB must be 1..4");
|
||||
if (NPW != 1 && NPW != 4) throw std::runtime_error("r4d gemm_w4a16_nt_m64: NPW must be 1 or 4");
|
||||
const int ntiles = N / 16, mtiles = (M + 15) / 16;
|
||||
const int ncols = WV * NPW;
|
||||
dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32);
|
||||
size_t smem = (size_t)ncols * SK * 256 * sizeof(float);
|
||||
if (smem > 64 * 1024) throw std::runtime_error("r4d gemm_w4a16_nt_m64: WV*NPW*SK too large");
|
||||
auto Ap = (const unsigned short*)a;
|
||||
auto Wp = (const unsigned*)wq;
|
||||
auto Sp = (const unsigned*)wsz;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH(MT, NP, TT) hipLaunchKernelGGL((halo_gemm_w4a16_nt_m64_kernel<MT, NP, TT>), grid, \
|
||||
block, smem, st, Ap, Wp, Sp, Cp, M, K, N, WV, SK)
|
||||
#define LAUNCH_MB(NP, TT) switch (MB) { \
|
||||
case 1: LAUNCH(1, NP, TT); break; \
|
||||
case 2: LAUNCH(2, NP, TT); break; \
|
||||
case 3: LAUNCH(3, NP, TT); break; \
|
||||
case 4: LAUNCH(4, NP, TT); break; \
|
||||
default: throw std::runtime_error("r4d gemm_w4a16_nt_m64: MB unsupported"); }
|
||||
if (NPW == 1) {
|
||||
if (NT) { LAUNCH_MB(1, true); } else { LAUNCH_MB(1, false); }
|
||||
} else {
|
||||
if (NT) { LAUNCH_MB(4, true); } else { LAUNCH_MB(4, false); }
|
||||
}
|
||||
#undef LAUNCH_MB
|
||||
#undef LAUNCH
|
||||
}
|
||||
|
||||
int halo_gemm_w4a16_nt_m64_max_m(void) { return HALO_GEMM_W4_MAX_M; }
|
||||
int halo_gemm_w4a16_nt_m64_group(void) { return HALO_GEMM_W4_GROUP; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in halo_gemm_args.h; see libhalo/halo_args.h.
|
||||
/* ------------------------------------------------------------------ f16-activation grids */
|
||||
|
||||
extern "C" int halo_rad_gemm_w4a16_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 HALO_NO(RAD_E_SHAPE);
|
||||
/* Any other activation dtype would read plausible but wrong numbers. */
|
||||
if (g.a->dtype != RAD_F16) return HALO_NO(RAD_E_DTYPE);
|
||||
if (g.M > halo_gemm_w4a16_nt_m64_max_m()) return HALO_NO(RAD_E_SHAPE);
|
||||
const int group = halo_gemm_w4a16_nt_m64_group();
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, g.M, group, BR_FLAT, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
HALO_TRY("gemm_w4a16_nt_m64",
|
||||
halo_gemm_w4a16_nt_m64(halo_addr(g.a), halo_addr(g.b), halo_addr(g.bscale), halo_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt,
|
||||
(long)(uintptr_t)s));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
/* Derived from libr4d/r4d_gemm_w4a8_nt_m64.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_w4a8_nt_m64.hip - halo_gemm_w4a8_nt_m64: 4-bit-weight, 8-bit-activation skinny GEMM for
|
||||
// M up to 64, gfx1151. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with A quantised per row.
|
||||
//
|
||||
// Complements halo_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
|
||||
//
|
||||
// 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)
|
||||
//
|
||||
// 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 weight is shared byte for byte with halo_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.
|
||||
//
|
||||
// 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).
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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 "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include "halo_chain.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
// 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 HALO_GEMM_W4A8_MAX_M 8192
|
||||
// HALO_GEMM_W4A8_GROUP comes from halo_common.h; see the note there.
|
||||
#define HALO_GEMM_W4A8_KPB 64 // K per packed block: 4 k steps, 16 bytes per lane
|
||||
#define WAVE32 32
|
||||
|
||||
typedef int v8i __attribute__((ext_vector_type(8)));
|
||||
typedef float v4f __attribute__((ext_vector_type(4)));
|
||||
typedef int v2i __attribute__((ext_vector_type(2)));
|
||||
typedef int v4i __attribute__((ext_vector_type(4)));
|
||||
typedef unsigned uint4v __attribute__((ext_vector_type(4)));
|
||||
|
||||
typedef __attribute__((address_space(1))) const uint4v* halo_gw4;
|
||||
typedef __attribute__((address_space(1))) const unsigned* halo_gh1;
|
||||
typedef unsigned uint2v __attribute__((ext_vector_type(2)));
|
||||
typedef __attribute__((address_space(1))) const uint2v* halo_ga2;
|
||||
|
||||
/* Both operands keep libr4d's gfx12 fragment order byte for byte: the weight by its relayout
|
||||
* (shared with halo_gemm_w4a16_nt_m64), the activation by the quantiser that wrote it. For one
|
||||
* k step a lane's bytes hold K quarters (0,2) in the low half-wave and (1,3) in the high
|
||||
* half-wave for the same row, so one cross-half exchange per dword reassembles the gfx11
|
||||
* fragment's consecutive sixteen K. */
|
||||
__device__ __forceinline__ v4i frag_step(unsigned d0, unsigned d1, int lane) {
|
||||
const unsigned p0 = (unsigned)__shfl_xor((int)d0, 16);
|
||||
const unsigned p1 = (unsigned)__shfl_xor((int)d1, 16);
|
||||
const bool hi = lane >> 4;
|
||||
v4i r;
|
||||
r[0] = (int)(hi ? p0 : d0);
|
||||
r[1] = (int)(hi ? d0 : p0);
|
||||
r[2] = (int)(hi ? p1 : d1);
|
||||
r[3] = (int)(hi ? d1 : p1);
|
||||
return r;
|
||||
}
|
||||
|
||||
// A fragments from the pre-permuted plane: eight contiguous bytes per k step.
|
||||
__device__ __forceinline__ v4i fragA8(halo_ga2 p, int u, int lane) {
|
||||
const uint2v w = p[2 * u];
|
||||
return frag_step(w[0], w[1], lane);
|
||||
}
|
||||
|
||||
// The whole dequant of one dword: two ands and a shift. The result's dwords hold the dword's
|
||||
// eight codes as [first K quarter][third K quarter] of its step.
|
||||
__device__ __forceinline__ v2i dequant8(unsigned w) {
|
||||
v2i r;
|
||||
r[0] = (int)((w << 4) & 0xF0F0F0F0u);
|
||||
r[1] = (int)(w & 0xF0F0F0F0u);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* One step's B fragment: exchange the packed dword across halves, unpack both, interleave the
|
||||
* quarter dwords into consecutive K. */
|
||||
__device__ __forceinline__ v4i dequant_step(unsigned w, int lane) {
|
||||
const unsigned pw = (unsigned)__shfl_xor((int)w, 16);
|
||||
const bool hi = lane >> 4;
|
||||
const v2i lo = dequant8(hi ? pw : w);
|
||||
const v2i hd = dequant8(hi ? w : pw);
|
||||
v4i r;
|
||||
r[0] = lo[0]; r[1] = hd[0]; r[2] = lo[1]; r[3] = hd[1];
|
||||
return r;
|
||||
}
|
||||
|
||||
// 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(v4i a, v4i b, v8i c) {
|
||||
return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, a, BSIGNED, b, c, false);
|
||||
}
|
||||
|
||||
// __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 HALO_W4A8_BOUNDS(NPW) ((NPW) >= 8 ? 256 : ((NPW) >= 4 ? 512 : 1024))
|
||||
|
||||
// CHAIN brackets the body with the chained launch's wait and add (halo_chain.h); every block runs
|
||||
// to the end. The two kernels below are the plain form and the chained one (halo_r4dchain*).
|
||||
template <int MT, int NPW, bool NT, bool ASYM, bool CHAIN>
|
||||
__device__ __forceinline__ void halo_gemm_w4a8_nt_m64_body(
|
||||
const signed char* __restrict__ A, const float* __restrict__ Ascale,
|
||||
const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws,
|
||||
const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int WV, int SK) {
|
||||
if (CHAIN) halo_chain_wait();
|
||||
extern __shared__ float red[];
|
||||
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
const int nt0 = (blockIdx.x * WV + col_local) * NPW;
|
||||
const int n0 = nt0 * 16;
|
||||
const int mt0 = blockIdx.y * MT;
|
||||
const int Ks = K / SK;
|
||||
const int groups = Ks / HALO_GEMM_W4A8_GROUP;
|
||||
const int kbase = ksplit * Ks;
|
||||
|
||||
v8f acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
// 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 into 0..M-1, never masked; the store discards rows past M. A is int8, so the
|
||||
// row stride is K bytes.
|
||||
halo_ga2 pa[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
int r = (mt0 + i) * 16 + (lane & 15);
|
||||
r = r < M - 1 ? r : M - 1;
|
||||
const size_t off = (size_t)r * K + kbase + 8 * (lane >> 4);
|
||||
pa[i] = (halo_ga2)(const uint2v*)(A + off);
|
||||
}
|
||||
|
||||
const int kpb = K / HALO_GEMM_W4A8_KPB;
|
||||
const int nsz = K / HALO_GEMM_W4A8_GROUP;
|
||||
halo_gw4 pw[NPW];
|
||||
halo_gh1 ps[NPW];
|
||||
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] = (halo_gw4)(const uint4v*)(Wq) +
|
||||
(size_t)(t * kpb + kbase / HALO_GEMM_W4A8_KPB) * WAVE32 + lane;
|
||||
ps[j] = (halo_gh1)(const unsigned*)(Ws) +
|
||||
(size_t)(t * nsz + kbase / HALO_GEMM_W4A8_GROUP) * 16 + (lane & 15);
|
||||
}
|
||||
|
||||
const int bpg = HALO_GEMM_W4A8_GROUP / HALO_GEMM_W4A8_KPB;
|
||||
|
||||
for (int g = 0; g < groups; g++) {
|
||||
float sc[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
sc[j] = __half2float(__ushort_as_half(
|
||||
(unsigned short)(ps[j][(size_t)g * 16] & 0xFFFFu)));
|
||||
|
||||
// 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) {
|
||||
#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 + accRow(lane, e) on this
|
||||
// part: the lane's eight rows stride by two through the tile, where libr4d's are
|
||||
// contiguous. Asum is [G][Mpad]; four v4f loads cover the tile's sixteen rows and the
|
||||
// lane picks its strided eight from registers. The 64-byte aligned base is Mpad (a
|
||||
// multiple of 16). 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 / HALO_GEMM_W4A8_GROUP + g) * Mpad;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
// Clamped: MB may exceed the number of M tiles (MB=4 with M=9 is legal), and an
|
||||
// unclamped Asum read could fault.
|
||||
int rb = (mt0 + i) * 16;
|
||||
rb = rb < Mpad - 16 ? rb : Mpad - 16;
|
||||
const v4f* pv = (const v4f*)(Asum + gi + rb);
|
||||
float av[16];
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 4; t++) {
|
||||
const v4f v = pv[t];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 4; e++) av[4 * t + e] = v[e];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) asum[i][e] = av[2 * e + (lane >> 4)];
|
||||
}
|
||||
}
|
||||
|
||||
v8i g_acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++) {
|
||||
uint4v wv[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const size_t o = (size_t)(g * bpg + b) * WAVE32;
|
||||
wv[j] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int s = 0; s < 4; s++) {
|
||||
const int u = b * 4 + s;
|
||||
v4i afrag[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) afrag[i] = fragA8(pa[i], u, lane);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const v4i bfrag = dequant_step(wv[j][s], lane);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
g_acc[j][i] = (u == 0) ? mmai<!ASYM>(afrag[i], bfrag, (v8i)(0))
|
||||
: mmai<!ASYM>(afrag[i], bfrag, g_acc[j][i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) {
|
||||
float t = (float)g_acc[j][i][e];
|
||||
if (ASYM) t -= z16[j] * asum[i][e];
|
||||
acc[j][i][e] = fmaf(t, sc[j], acc[j][i][e]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] += HALO_GEMM_W4A8_GROUP / 8;
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
for (int i = 0; i < MT; i++) {
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int slot = ((col_local * NPW + j) * SK + ksplit) * 256;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) red[slot + e * WAVE32 + lane] = acc[j][i][e];
|
||||
}
|
||||
__syncthreads();
|
||||
for (int idx = tid; idx < ncols * 256; idx += nthreads) {
|
||||
const int col = idx >> 8, off = idx & 255;
|
||||
float v = 0.f;
|
||||
for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off];
|
||||
const int l = off & 31;
|
||||
const int n = (blockIdx.x * ncols + col) * 16 + (l & 15);
|
||||
const int m = (mt0 + i) * 16 + accRow(l, off >> 5);
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
if (CHAIN) halo_chain_done();
|
||||
}
|
||||
|
||||
#define HALO_W4A8_PARAMS const signed char* __restrict__ A, const float* __restrict__ Ascale, \
|
||||
const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws, \
|
||||
const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK
|
||||
template <int MT, int NPW, bool NT, bool ASYM>
|
||||
__global__ __launch_bounds__(HALO_W4A8_BOUNDS(NPW)) void halo_gemm_w4a8_nt_m64_kernel(HALO_W4A8_PARAMS) {
|
||||
halo_gemm_w4a8_nt_m64_body<MT, NPW, NT, ASYM, false>(A, Ascale, Wq, Ws, Asum, C, M, K, N, WV, SK);
|
||||
}
|
||||
template <int MT, int NPW, bool NT, bool ASYM>
|
||||
__global__ __launch_bounds__(HALO_W4A8_BOUNDS(NPW)) void halo_r4dchain_gemm_w4a8_nt_m64(HALO_W4A8_PARAMS) {
|
||||
halo_gemm_w4a8_nt_m64_body<MT, NPW, NT, ASYM, true>(A, Ascale, Wq, Ws, Asum, C, M, K, N, WV, SK);
|
||||
}
|
||||
#undef HALO_W4A8_PARAMS
|
||||
|
||||
static void halo_gemm_w4a8_impl(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,
|
||||
bool asym, long stream, bool chain = false) {
|
||||
if (M < 1 || M > HALO_GEMM_W4A8_MAX_M)
|
||||
throw std::runtime_error("r4d gemm_w4a8_nt_m64: M out of range");
|
||||
if (N % 16) throw std::runtime_error("r4d gemm_w4a8_nt_m64: N must be a multiple of 16");
|
||||
if (K % (SK * HALO_GEMM_W4A8_GROUP))
|
||||
throw std::runtime_error("r4d gemm_w4a8_nt_m64: K must be divisible by SK*group");
|
||||
if (WV * SK * WAVE32 > HALO_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");
|
||||
const int ntiles = N / 16, mtiles = (M + 15) / 16;
|
||||
const int ncols = WV * NPW;
|
||||
dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32);
|
||||
size_t smem = (size_t)ncols * SK * 256 * sizeof(float);
|
||||
if (smem > 64 * 1024) throw std::runtime_error("r4d gemm_w4a8_nt_m64: WV*NPW*SK too large");
|
||||
auto Ap = (const signed char*)a;
|
||||
auto Sp = (const float*)ascale;
|
||||
auto Wp = (const unsigned*)wq;
|
||||
auto Zp = (const unsigned*)ws;
|
||||
auto Up = (const float*)asum;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH(MT, NP, TT, AS) do { if (chain) \
|
||||
hipLaunchKernelGGL((halo_r4dchain_gemm_w4a8_nt_m64<MT, NP, TT, AS>), \
|
||||
grid, block, smem, st, Ap, Sp, Wp, Zp, Up, Cp, M, K, N, WV, SK); else \
|
||||
hipLaunchKernelGGL((halo_gemm_w4a8_nt_m64_kernel<MT, NP, TT, AS>), \
|
||||
grid, block, smem, st, Ap, Sp, Wp, Zp, Up, Cp, M, K, N, WV, SK); } while (0)
|
||||
#define LAUNCH_MB(NP, TT, AS) switch (MB) { \
|
||||
case 1: LAUNCH(1, NP, TT, AS); break; \
|
||||
case 2: LAUNCH(2, NP, TT, AS); break; \
|
||||
case 3: LAUNCH(3, NP, TT, AS); break; \
|
||||
case 4: LAUNCH(4, NP, TT, AS); break; \
|
||||
default: throw std::runtime_error("r4d gemm_w4a8_nt_m64: MB unsupported"); }
|
||||
#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: 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 {
|
||||
if (NT) { LAUNCH_NPW(true, false); } else { LAUNCH_NPW(false, false); }
|
||||
}
|
||||
#undef LAUNCH_NPW
|
||||
#undef LAUNCH_MB
|
||||
#undef LAUNCH
|
||||
}
|
||||
|
||||
void halo_gemm_w4a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
|
||||
int WV, int SK, int MB, int NPW, int NT, long stream) {
|
||||
halo_gemm_w4a8_impl(a, ascale, wq, ws, 0, c, M, K, N, WV, SK, MB, NPW, NT, false, stream);
|
||||
}
|
||||
|
||||
// Asymmetric grid: the nibble is read unsigned and the zero point is corrected with the per-row
|
||||
// per-group activation sums from halo_quant_act_i8_asum. `asum` is [K/group][Mpad] float,
|
||||
// Mpad = ceil(M/16)*16 (see the kernel). Allocate it zeroed.
|
||||
void halo_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");
|
||||
halo_gemm_w4a8_impl(a, ascale, wq, ws, asum, c, M, K, N, WV, SK, MB, NPW, NT, true, stream);
|
||||
}
|
||||
|
||||
int halo_gemm_w4a8_nt_m64_max_m(void) { return HALO_GEMM_W4A8_MAX_M; }
|
||||
int halo_gemm_w4a8_nt_m64_group(void) { return HALO_GEMM_W4A8_GROUP; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in halo_gemm_args.h; see libhalo/halo_args.h.
|
||||
/* ------------------------------------------------------------------ int8-activation grids */
|
||||
|
||||
/* The multi-user verify heights (33 to 64 rows: five to eight users of a DFlash2 verify, 8 rows a
|
||||
* user). The law's point there covers every row tile in one block at one N tile a wave (mb = all,
|
||||
* npw = 1), which re-reads the activation once a 16-column tile and holds MT accumulators a wave;
|
||||
* on 4x R9700 (one card, the 31B's per-card trunk shapes, every point byte-identical to the law's)
|
||||
* it ran a layer's four GEMMs in 259 us at 64 rows against 157 us here:
|
||||
*
|
||||
* q|k|v 3584x5376 o_proj 5376x2048 gate_up 10752x5376 down 5376x5376
|
||||
* 40 rows law 46.4 27.4 67.1 36.4
|
||||
* here 22.0 (mb1 npw2) 21.1 (mb1 npw2) 58.8 (mb1 npw4) 30.8 (mb1 npw2)
|
||||
* 48 rows law 31.4 30.4 71.9 42.4
|
||||
* here 22.2 21.2 58.9 31.6
|
||||
* 56 rows law 56.8 35.0 94.2 62.4
|
||||
* here 24.0 (mb1 npw2) 22.3 (mb2 npw1) 69.0 (mb2 npw4) 43.0 (mb1 npw2)
|
||||
* 64 rows law 58.6 37.3 97.6 65.2
|
||||
* here 24.7 22.7 69.6 44.0
|
||||
*
|
||||
* Neither axis moves a byte: the split stays the law's (a point whose wider block cannot hold it
|
||||
* is not taken, since a smaller split would regroup the K partials), and every output element
|
||||
* keeps its accumulation order. Only where neither `mb` nor `npw` was tuned. */
|
||||
static void multi_user_point(const RadArgs* a, long long M, long long N, long long K, Cfg* c) {
|
||||
if (M <= 32 || M > 64) return;
|
||||
HaloGemmCfg cv;
|
||||
halo_cfg_gemm(a, &cv);
|
||||
if (cv.mb > 0 || cv.npw > 1) return;
|
||||
int mb, npw;
|
||||
if (M <= 48) { mb = 1; npw = N >= 8192 ? 4 : 2; }
|
||||
else if (N >= 8192) { mb = 2; npw = 4; }
|
||||
else if (K <= 2048) { mb = 2; npw = 1; }
|
||||
else { mb = 1; npw = 2; }
|
||||
if (c->wv * c->sk * WAVE32 > block_bound(BR_NPW, mb, npw)) return;
|
||||
if ((size_t)c->wv * npw * c->sk * 256 * sizeof(float) > 64 * 1024) return;
|
||||
c->mb = mb;
|
||||
c->npw = npw;
|
||||
}
|
||||
|
||||
/* The asymmetric grid is selected by `dtype`, not by the presence of a_sum (see is_asym). */
|
||||
|
||||
extern "C" int halo_rad_gemm_w4a8_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 HALO_NO(RAD_E_SHAPE);
|
||||
if (g.M > halo_gemm_w4a8_nt_m64_max_m()) return HALO_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale) return HALO_NO(RAD_E_INVAL);
|
||||
const int group = halo_gemm_w4a8_nt_m64_group();
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, g.M, group, BR_NPW, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
multi_user_point(a, g.M, g.N, g.K, &c);
|
||||
|
||||
/* the engine's chained launch (RadKernelChainFn), at decode heights only */
|
||||
const bool chain = halo_geti_or(a, "chain", 0) != 0 && g.M <= 64;
|
||||
if (is_asym(a)) {
|
||||
if (!g.asum) return HALO_NO(RAD_E_INVAL); /* the entry point throws "asum is required" */
|
||||
HALO_TRY("gemm_w4a8_asym_nt_m64",
|
||||
halo_gemm_w4a8_impl(halo_addr(g.a), halo_addr(g.ascale), halo_addr(g.b),
|
||||
halo_addr(g.bscale), halo_addr(g.asum), halo_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw,
|
||||
c.nt, true, (long)(uintptr_t)s, chain));
|
||||
return RAD_OK;
|
||||
}
|
||||
HALO_TRY("gemm_w4a8_nt_m64",
|
||||
halo_gemm_w4a8_impl(halo_addr(g.a), halo_addr(g.ascale), halo_addr(g.b),
|
||||
halo_addr(g.bscale), 0, halo_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt,
|
||||
false, (long)(uintptr_t)s, chain));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
/* Derived from libr4d/r4d_gemm_w4a8_tiled.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_w4a8_tiled.hip - halo_gemm_w4a8_tiled: the W4A8 GEMM for prefill batches.
|
||||
//
|
||||
// halo_gemm_w4a8_nt_m64 covers at most 64 rows per block, so at M=4096 each of 64 M-blocks re-reads
|
||||
// the weight slice and it holds a flat ~105 TF/s. The target is the block-fp8 prefill GEMM
|
||||
// (~204 TF/s on the same shapes).
|
||||
//
|
||||
// Tile shape from traffic: a BM x BN tile reads M/BM copies of the weight and N/BN of the
|
||||
// activation. For gate_proj at M=4096 (~600 GB/s DRAM, ~1049 GB/s from the 64 MB MALL):
|
||||
//
|
||||
// 64 x 128 (skinny) 4352 blocks 2.85 GB 2.7 ms
|
||||
// 128 x 256 1088 blocks 1.43 GB 1.4 ms
|
||||
// 256 x 256 544 blocks 1.07 GB 1.0 ms
|
||||
//
|
||||
// 256x256 needs TM=TN=4 per wave, but the group loop keeps the int32 and float accumulators live
|
||||
// together (256 VGPRs), so TM*TN <= 8 and the tile is 128 x 256.
|
||||
//
|
||||
// BK is half the scale group, double-buffered. A single buffer at BK = the group exposes every
|
||||
// global-load latency and is slower than the skinny kernel: the loop is latency-bound. Double
|
||||
// buffering must stay under 32 KB of LDS to fit two workgroups per CU; at BK = 64 it is 8 KB of A
|
||||
// and 8 KB of W per buffer. The int32 accumulator carries across the two iterations of a group.
|
||||
//
|
||||
// Padding A's LDS row stride is slower at M = 4096 (one extra dword per row exceeds 32 KB and
|
||||
// drops a CU to one workgroup); the XOR swizzle below avoids the bank conflicts instead.
|
||||
//
|
||||
// Layouts are the skinny kernel's: the packed weight is in WMMA fragment order (lane L of a
|
||||
// (tile, k-block) owns dwords [4L, 4L+3] of a 128-dword run), so staging is a contiguous copy, and
|
||||
// the quantiser pre-shuffles the activation within each k step. Both kernels share one weight and
|
||||
// one activation.
|
||||
#include "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h" // accRow: the gfx11 accumulator row mapping
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define HALO_TILED_KPB 64
|
||||
|
||||
typedef int v2i_t __attribute__((ext_vector_type(2)));
|
||||
typedef int v4i_t __attribute__((ext_vector_type(4)));
|
||||
typedef int v8i_t __attribute__((ext_vector_type(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)));
|
||||
|
||||
// BSIGNED=false reads the unpacked byte as 16*nibble (0..240) instead of 16*twos(nibble): the
|
||||
// asymmetric grid, whose per-group zero is corrected with a row sum of the activation.
|
||||
template <bool BSIGNED>
|
||||
__device__ __forceinline__ v8i_t tmmai(v4i_t a, v4i_t b, v8i_t c) {
|
||||
return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, a, BSIGNED, b, c, false);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v2i_t tdequant8(unsigned w) {
|
||||
v2i_t r;
|
||||
r[0] = (int)((w << 4) & 0xF0F0F0F0u);
|
||||
r[1] = (int)(w & 0xF0F0F0F0u);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* The weight keeps libr4d's fragment order in LDS ([tile][lane][4 steps]): a lane's dword for a
|
||||
* step holds K quarters (0,2) in the low half-wave and (1,3) in the high, so the gfx11 fragment
|
||||
* unpacks this lane's dword and its cross-half partner's and interleaves the quarter dwords. */
|
||||
__device__ __forceinline__ v4i_t tdequant_step(unsigned w, unsigned pw, int lane) {
|
||||
const bool hi = lane >> 4;
|
||||
const v2i_t lo = tdequant8(hi ? pw : w);
|
||||
const v2i_t hd = tdequant8(hi ? w : pw);
|
||||
v4i_t r;
|
||||
r[0] = lo[0]; r[1] = hd[0]; r[2] = lo[1]; r[3] = hd[1];
|
||||
return r;
|
||||
}
|
||||
|
||||
// WM x WN waves, each owning TM x TN WMMA tiles. BM = WM*TM*16, BN = WN*TN*16. UNR k blocks are
|
||||
// unrolled per scale group.
|
||||
//
|
||||
// The symmetric grid seeds each group's WMMA accumulator with 0x4B400000 (the magic bias), which
|
||||
// removes the int32 -> float conversion from the group fold. For |x| < 2^22,
|
||||
//
|
||||
// float(x) == __uint_as_float(0x4B400000 + x) - 12582912.0f
|
||||
//
|
||||
// since 0x4B400000 is 1.5*2^23 with unit mantissa steps. A group's int32 sum is at most
|
||||
// 128 * 127 * 128 = 2,080,768. The -12582912*s per group is summed per column and subtracted once
|
||||
// at the end. The asymmetric grid converts plainly: with the bias, z16, the row sums and csum on top
|
||||
// of 128 accumulator registers, it spills.
|
||||
// No minimum-occupancy bound: libr4d's 8 waves a SIMD caps a lane at 192 VGPRs on gfx1151 and
|
||||
// spilled most arms (the 4x2 tile 158-165 slots); unbounded, the arms run 1.1-2.4x faster.
|
||||
// PART: as in halo_gemm_w8a8_tiled.hip, the waves of the M-cut last row of blocks skip the WMMAs
|
||||
// and folds of their padding fragments; only a ragged M's launch instantiates it.
|
||||
template <int WM, int WN, int TM, int TN, int ASYM, int UNR, bool PART = false>
|
||||
__global__ __launch_bounds__(WM * WN * 32) void halo_gemm_w4a8_tiled_kernel(
|
||||
const signed char* __restrict__ A, const float* __restrict__ Ascale,
|
||||
const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws,
|
||||
const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C, int M, int K, int N) {
|
||||
constexpr int BK = 64; // half a scale group
|
||||
constexpr int GRP = HALO_GEMM_W4A8_GROUP;
|
||||
constexpr int BM = WM * TM * 16, BN = WN * TN * 16;
|
||||
constexpr int NTILE = BN / 16;
|
||||
constexpr int AW = BM * BK / 4; // A dwords per buffer
|
||||
constexpr int WW = NTILE * 128; // W dwords per buffer (BK == KPB, so one run)
|
||||
constexpr bool BIAS = !ASYM;
|
||||
|
||||
__shared__ unsigned lds_a[2][AW];
|
||||
__shared__ unsigned lds_w[2][WW];
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int wm = wave / WN, wn = wave % WN;
|
||||
// Groups of 8 activation bands, M fastest (halo_gemm_bf16_nt_tiled's order), so the bands of a
|
||||
// column block share its weight through the cache.
|
||||
constexpr unsigned kGroupM = 8;
|
||||
const unsigned per = kGroupM * gridDim.x, lin = blockIdx.y * gridDim.x + blockIdx.x;
|
||||
const unsigned first = lin / per * kGroupM, rr = lin % per;
|
||||
const unsigned gm = min(gridDim.y - first, kGroupM);
|
||||
const int m0 = (int)(first + rr % gm) * BM, bx = (int)(rr / gm), n0 = bx * BN;
|
||||
const int live = PART ? __builtin_amdgcn_readfirstlane(
|
||||
min(TM, max(0, (M + 15) / 16 - (m0 / 16 + wm * TM))))
|
||||
: TM;
|
||||
const int kpb = K / HALO_TILED_KPB, nsz = K / GRP;
|
||||
constexpr int NT_ = WM * WN * 32;
|
||||
|
||||
v8f_t acc[TN][TM];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) acc[j][i] = (v8f_t)(0.f);
|
||||
v8i_t g[TN][TM];
|
||||
float csum[TN];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++) csum[j] = 0.f;
|
||||
unsigned scv[TN];
|
||||
|
||||
// XOR swizzle instead of padding (padding would exceed 32 KB and drop a CU to one workgroup).
|
||||
// A row is BK/4 = 16 dwords over 32 banks, so the sixteen lanes of a fragment read (differing
|
||||
// only in the row) would collide. Bank = (r*16 + (c ^ mask)) % 32, so the row only contributes
|
||||
// its low bit: `(r & 7) << 1` leaves rows r and r+8 colliding (2-way conflict on every A read),
|
||||
// while `((r >> 1) & 7) << 1` is conflict-free. Both stay inside the row ((row & 15) << 1 would
|
||||
// reach 30 and corrupt the next row) and even (for ds_load_b64 alignment). The A LDS read is about
|
||||
// a third of the kernel at decode tiles. The asymmetric kernel keeps the 8-row form.
|
||||
#define ASW(r, c) ((r) * (BK / 4) + ((c) ^ ((((ASYM ? (r) : ((r) >> 1)) & 7) << 1))))
|
||||
|
||||
// Prefetch into registers, compute off the other buffer, then commit to LDS, so the load wait
|
||||
// lands after the WMMA work (a prefetch that writes LDS directly would stall the compute; >2x).
|
||||
// A staging may be ragged (a predicate on the last pass), so BM need not be a multiple of the
|
||||
// workgroup width (e.g. BM = 80, 112).
|
||||
constexpr int APT = (AW + NT_ - 1) / NT_, WPT = WW / NT_;
|
||||
constexpr bool APAD = (AW % NT_) != 0;
|
||||
unsigned ra[APT], rw[WPT > 0 ? WPT : 1];
|
||||
// The weight moves as one global_load_b128 and one ds_store_b128 per thread where that tiles the
|
||||
// block (four threads cover a 16-dword row), else as dwords.
|
||||
constexpr int WPT4 = (WW / 4) / NT_;
|
||||
constexpr bool W128 = WPT4 > 0 && (WW / 4) % NT_ == 0;
|
||||
u4v_t rw4[WPT4 > 0 ? WPT4 : 1];
|
||||
static_assert(W128 || (WPT > 0 && WW % NT_ == 0), "no W staging path tiles this block shape");
|
||||
// Global indices are 32-bit: a 64-bit address costs four extra instructions per load.
|
||||
auto issue = [&](int kk) {
|
||||
if (W128) {
|
||||
#pragma unroll
|
||||
for (int x = 0; x < WPT4; x++) {
|
||||
const int t = tid + x * NT_, tl = t / 32, off4 = t % 32;
|
||||
rw4[x] = *(const u4v_t*)(Wq + (unsigned)(((n0 / 16 + tl) * kpb + kk / HALO_TILED_KPB) *
|
||||
128 + off4 * 4));
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int x = 0; x < APT; x++) {
|
||||
const int t = tid + x * NT_, r = t / (BK / 4), c = t % (BK / 4);
|
||||
if (APAD && t >= AW) continue;
|
||||
const int mm = m0 + r < M ? m0 + r : M - 1;
|
||||
ra[x] = *(const unsigned*)(A + (unsigned)(mm * K + kk + c * 4));
|
||||
}
|
||||
#pragma unroll
|
||||
for (int x = 0; x < WPT && !W128; x++) {
|
||||
const int t = tid + x * NT_, tl = t / 128, off = t % 128;
|
||||
rw[x] = Wq[(unsigned)(((n0 / 16 + tl) * kpb + kk / HALO_TILED_KPB) * 128 + off)];
|
||||
}
|
||||
};
|
||||
auto commit = [&](int buf) {
|
||||
if (W128) {
|
||||
#pragma unroll
|
||||
for (int x = 0; x < WPT4; x++) *(u4v_t*)(lds_w[buf] + (tid + x * NT_) * 4) = rw4[x];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int x = 0; x < APT; x++) {
|
||||
const int t = tid + x * NT_, r = t / (BK / 4), c = t % (BK / 4);
|
||||
if (APAD && t >= AW) continue;
|
||||
lds_a[buf][ASW(r, c)] = ra[x];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int x = 0; x < WPT && !W128; x++) lds_w[buf][tid + x * NT_] = rw[x];
|
||||
};
|
||||
// The group's scale dword: the f16 scale, and for the asymmetric grid the f16 of -(1024 + zero)
|
||||
// in the high half. 32-bit index: the table has at most (N/16)*(K/GRP)*16 elements.
|
||||
#define HALO_WS(g_, j_) Ws[(unsigned)(((n0 / 16 + wn * TN + (j_)) * nsz + (g_)) * 16 + (lane & 15))]
|
||||
|
||||
issue(0);
|
||||
commit(0);
|
||||
__syncthreads();
|
||||
|
||||
// Unroll the K loop over the group (UNR = GRP/BK) so the group-boundary tests are compile-time per
|
||||
// copy; a dynamic branch around the epilogue stops the scheduler interleaving it with the WMMA.
|
||||
// Worth several percent.
|
||||
for (int kg = 0, it = 0; kg < K; kg += BK * UNR) {
|
||||
#pragma unroll
|
||||
for (int h = 0; h < UNR; h++, it++) {
|
||||
const int k0 = kg + h * BK;
|
||||
const int buf = it & 1;
|
||||
if (k0 + BK < K) issue(k0 + BK); // loads in flight across the WMMA work below
|
||||
|
||||
const bool first_half = (k0 % GRP) == 0;
|
||||
// Fetch the group scale at the start of the group. Every wave reaches the boundary on the same
|
||||
// k0, so a load at the point of use stalls them all at once. Keep the raw dword and convert at
|
||||
// the group close: converting here would put the wait right after the load.
|
||||
if ((k0 % GRP) == 0) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
scv[j] = HALO_WS(k0 / GRP, j);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int u = 0; u < BK / 16; u++) {
|
||||
v4i_t af[TM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) {
|
||||
/* The A tile is staged row-major: the fragment is four consecutive LDS dwords. */
|
||||
const int row = (wm * TM + i) * 16 + (lane & 15);
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; d++)
|
||||
af[i][d] = (int)lds_a[buf][ASW(row, u * 4 + d)];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++) {
|
||||
const u4v_t wv = *(const u4v_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 128 + lane * 4);
|
||||
const u4v_t pv = *(const u4v_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 128 + (lane ^ 16) * 4);
|
||||
const v4i_t bf = tdequant_step(wv[u], pv[u], lane);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) {
|
||||
if (PART && i >= live) continue; // wave-uniform: padding fragments past M
|
||||
g[j][i] = (first_half && u == 0)
|
||||
? tmmai<!ASYM>(af[i], bf, (v8i_t)(BIAS ? 0x4B400000 : 0))
|
||||
: tmmai<!ASYM>(af[i], bf, g[j][i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((k0 + BK) % GRP == 0) { // the group closed: fold it into the float acc
|
||||
float sc[TN];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
sc[j] = __half2float(__ushort_as_half((unsigned short)(scv[j] & 0xFFFFu)));
|
||||
if (BIAS) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++) csum[j] += sc[j];
|
||||
}
|
||||
// Asymmetric grid: the group contributes s * (sum_k a_k q_k - z * sum_k a_k), using the
|
||||
// per-row per-group activation sums from halo_quant_act_i8_asum, laid out [G][Mpad] so a
|
||||
// lane's eight rows (m0 + (wm*TM+i)*16 + accRow(lane, e)) are gathered below. The zero is the
|
||||
// scale dword's high half, the f16 of -(1024 + z) (exact). One extra fma per element; the
|
||||
// loop is i-outer so only one tile's eight sums are live.
|
||||
float z16[TN];
|
||||
if (ASYM) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++) {
|
||||
const float nz = __half2float(__ushort_as_half((unsigned short)(scv[j] >> 16)));
|
||||
z16[j] = 16.f * (-nz - 1024.f);
|
||||
}
|
||||
}
|
||||
const int Mpad = ((M + 15) / 16) * 16;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) {
|
||||
if (PART && i >= live) continue;
|
||||
float as[8];
|
||||
if (ASYM) {
|
||||
/* The lane's eight rows stride by two through the tile on this part: load the
|
||||
* tile's sixteen sums and pick from registers. */
|
||||
int rb = m0 + (wm * TM + i) * 16;
|
||||
rb = rb < Mpad - 16 ? rb : Mpad - 16; // rows past M are stored away, not read
|
||||
const v4f_t* pv = (const v4f_t*)(Asum + (size_t)(k0 / GRP) * Mpad + rb);
|
||||
float av[16];
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 4; t++) {
|
||||
const v4f_t v = pv[t];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 4; e++) av[4 * t + e] = v[e];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) as[e] = av[2 * e + (lane >> 4)];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) {
|
||||
float v = BIAS ? __uint_as_float((unsigned)g[j][i][e]) : (float)g[j][i][e];
|
||||
if (ASYM) v = fmaf(-z16[j], as[e], v);
|
||||
acc[j][i][e] = fmaf(v, sc[j], acc[j][i][e]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (k0 + BK < K) commit(buf ^ 1); // the wait for those loads lands here
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
#undef HALO_WS
|
||||
#undef ASW
|
||||
|
||||
if (BIAS) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++) {
|
||||
const float d = -12582912.0f * csum[j];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) acc[j][i][e] += d;
|
||||
}
|
||||
}
|
||||
|
||||
// The flat predicated store beat LDS transposes (bf16 or packed dwords) and hand-hoisted Ascale /
|
||||
// row-offset variants: the epilogue is not bandwidth-bound (a cache-resident output takes the same
|
||||
// time), and with j innermost the stores stride the register file and share one guard.
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) {
|
||||
const int n = n0 + (wn * TN + j) * 16 + (lane & 15);
|
||||
const int m = m0 + (wm * TM + i) * 16 + accRow(lane, e);
|
||||
if (n < N && m < M)
|
||||
// 0.0625 undoes the 16 from the unpack's high-nibble placement.
|
||||
C[(size_t)m * N + n] = (__hip_bfloat16)(acc[j][i][e] * Ascale[m] * 0.0625f);
|
||||
}
|
||||
}
|
||||
|
||||
// CANPART: this arm instantiates the PART kernel for a ragged M (the default arm only).
|
||||
template <int WM, int WN, int TM, int TN, int ASYM, int UNR, bool CANPART = false>
|
||||
static void halo_tiled_launch(long a, long ascale, long wq, long ws, long asum, long c, int M, int K,
|
||||
int N, long stream) {
|
||||
constexpr int BM = WM * TM * 16, BN = WN * TN * 16;
|
||||
if (N % BN)
|
||||
throw std::runtime_error("r4d gemm_w4a8_tiled: N is not a multiple of this variant's block");
|
||||
dim3 grid(N / BN, (M + BM - 1) / BM), block(WM * WN * 32);
|
||||
if (CANPART && M % BM)
|
||||
hipLaunchKernelGGL((halo_gemm_w4a8_tiled_kernel<WM, WN, TM, TN, ASYM, UNR, CANPART>), grid,
|
||||
block, 0, (hipStream_t)stream, (const signed char*)a, (const float*)ascale,
|
||||
(const unsigned*)wq, (const unsigned*)ws, (const float*)asum,
|
||||
(__hip_bfloat16*)c, M, K, N);
|
||||
else
|
||||
hipLaunchKernelGGL((halo_gemm_w4a8_tiled_kernel<WM, WN, TM, TN, ASYM, UNR>), grid, block, 0,
|
||||
(hipStream_t)stream, (const signed char*)a, (const float*)ascale,
|
||||
(const unsigned*)wq, (const unsigned*)ws, (const float*)asum,
|
||||
(__hip_bfloat16*)c, M, K, N);
|
||||
}
|
||||
|
||||
static void halo_gemm_w4a8_tiled_impl(long a, long ascale, long wq, long ws, long asum, long c,
|
||||
int M, int K, int N, long stream, int variant, bool asym) {
|
||||
if (N % 256) throw std::runtime_error("r4d gemm_w4a8_tiled: N must be a multiple of 256");
|
||||
if (K % HALO_GEMM_W4A8_GROUP)
|
||||
throw std::runtime_error("r4d gemm_w4a8_tiled: K must be a multiple of the scale group");
|
||||
if (M < 1) throw std::runtime_error("r4d gemm_w4a8_tiled: M must be positive");
|
||||
// The unroll covers exactly one scale group: less leaves the boundary dynamic (~10% slower), more
|
||||
// doubles live ranges (over 2x slower). The K check above makes every K a whole number of them.
|
||||
static_assert(HALO_GEMM_W4A8_GROUP % HALO_TILED_KPB == 0, "the scale group must be whole k blocks");
|
||||
constexpr int UNRG = HALO_GEMM_W4A8_GROUP / HALO_TILED_KPB;
|
||||
#define HALO_TILED_LAUNCH(...) \
|
||||
halo_tiled_launch<__VA_ARGS__>(a, ascale, wq, ws, asum, c, M, K, N, stream)
|
||||
// The unroll loses on the asymmetric path (186 VGPRs), so it keeps UNR = 1, and it has one tile.
|
||||
if (asym) {
|
||||
HALO_TILED_LAUNCH(2, 8, 4, 2, 1, 1);
|
||||
return;
|
||||
}
|
||||
// The arms tile_bmbn in halo_rows.cpp lists, each with the (BM, BN) it records there. 512-thread
|
||||
// tiles are <2, 8, TM, TN> (or <1, 16, ...> for an odd BM at BN 256); at 256 threads <1, 8, TM, 1>
|
||||
// gives BM = 16*TM for any TM, so the block can be the smallest multiple of 16 covering M.
|
||||
// Staging constrains shapes (W needs WM | 4*TN, A needs WN | 8*TM).
|
||||
switch (variant) {
|
||||
case 6: HALO_TILED_LAUNCH(2, 8, 2, 2, 0, UNRG); break; // BM 64, BN 256
|
||||
case 10: HALO_TILED_LAUNCH(2, 8, 3, 2, 0, UNRG); break; // BM 96, BN 256
|
||||
case 12: HALO_TILED_LAUNCH(2, 8, 3, 1, 0, UNRG); break; // BM 96, BN 128
|
||||
case 57: HALO_TILED_LAUNCH(2, 8, 5, 1, 0, UNRG); break; // BM 160, BN 128
|
||||
case 59: HALO_TILED_LAUNCH(2, 8, 4, 1, 0, UNRG, true); break; // BM 128, BN 128
|
||||
case 114: HALO_TILED_LAUNCH(1, 8, 5, 1, 0, UNRG); break; // BM 80, BN 128
|
||||
case 124: HALO_TILED_LAUNCH(1, 8, 4, 1, 0, UNRG); break; // BM 64, BN 128
|
||||
case 125: HALO_TILED_LAUNCH(1, 8, 7, 1, 0, UNRG); break; // BM 112, BN 128
|
||||
case 126: HALO_TILED_LAUNCH(1, 8, 10, 1, 0, UNRG); break; // BM 160, BN 128
|
||||
case 128: HALO_TILED_LAUNCH(1, 8, 2, 1, 0, UNRG); break; // BM 32, BN 128
|
||||
case 129: HALO_TILED_LAUNCH(1, 8, 3, 1, 0, UNRG); break; // BM 48, BN 128
|
||||
case 138: HALO_TILED_LAUNCH(1, 16, 3, 1, 0, UNRG); break; // BM 48, BN 256
|
||||
case 139: HALO_TILED_LAUNCH(1, 16, 7, 1, 0, UNRG); break; // BM 112, BN 256
|
||||
case 146: HALO_TILED_LAUNCH(1, 8, 9, 1, 0, UNRG); break; // BM 144, BN 128
|
||||
case 900: HALO_TILED_LAUNCH(2, 8, 8, 1, 0, UNRG); break; // BM 256, BN 128 (prefill arm 14)
|
||||
// The untuned default is arm 59's tile, 2x8 waves of 4x1 tiles: on gfx1151 the 4x2 tile
|
||||
// libr4d defaults to (BM 128 x BN 256) holds 128 accumulators a lane and runs at 15-19 TFLOP/s
|
||||
// against 28-30 here (--perfw8 sweep at N 16384 K 5120 M 2048, N 5120 K 17408 / 5120 M 512).
|
||||
// Every arm accumulates each output over K in the same order, so the bytes do not move.
|
||||
default: HALO_TILED_LAUNCH(2, 8, 4, 1, 0, UNRG, true); break;
|
||||
}
|
||||
#undef HALO_TILED_LAUNCH
|
||||
}
|
||||
|
||||
void halo_gemm_w4a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
|
||||
long stream, int variant) {
|
||||
halo_gemm_w4a8_tiled_impl(a, ascale, wq, ws, 0, c, M, K, N, stream, variant, false);
|
||||
}
|
||||
|
||||
// Asymmetric grid: the nibble is read unsigned and the per-group zero is corrected with the per-row
|
||||
// per-group activation sums from halo_quant_act_i8_asum ([K/group][Mpad], Mpad = ceil(M/16)*16).
|
||||
void halo_gemm_w4a8_asym_tiled(long a, long ascale, long wq, long ws, long asum, long c, int M,
|
||||
int K, int N, long stream, int variant) {
|
||||
if (!asum) throw std::runtime_error("r4d gemm_w4a8_asym_tiled: asum is required");
|
||||
halo_gemm_w4a8_tiled_impl(a, ascale, wq, ws, asum, c, M, K, N, stream, variant, true);
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in halo_gemm_args.h; see libhalo/halo_args.h.
|
||||
/* ------------------------------------------------------------------ the large-M kernels
|
||||
*
|
||||
* These take one opaque tile variant; see tile_ok in halo_gemm_args.h for the N % BN check. */
|
||||
|
||||
extern "C" int halo_rad_gemm_w4a8_tiled(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (!g.ascale) return HALO_NO(RAD_E_INVAL);
|
||||
if (g.N % 256) return HALO_NO(RAD_E_SHAPE); /* the entry point throws on this */
|
||||
if (g.K % HALO_GEMM_W4A8_GROUP) return HALO_NO(RAD_E_SHAPE);
|
||||
HaloTileCfg tv;
|
||||
halo_cfg_tiled(a, &tv);
|
||||
const HaloTileCfg* t = &tv;
|
||||
rc = tile_ok(t, g.N);
|
||||
if (rc != RAD_OK) return rc;
|
||||
|
||||
if (is_asym(a)) {
|
||||
if (!g.asum) return HALO_NO(RAD_E_INVAL);
|
||||
HALO_TRY("gemm_w4a8_asym_tiled",
|
||||
halo_gemm_w4a8_asym_tiled(halo_addr(g.a), halo_addr(g.ascale), halo_addr(g.b),
|
||||
halo_addr(g.bscale), halo_addr(g.asum), halo_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, (long)(uintptr_t)s,
|
||||
t->variant));
|
||||
return RAD_OK;
|
||||
}
|
||||
HALO_TRY("gemm_w4a8_tiled",
|
||||
halo_gemm_w4a8_tiled(halo_addr(g.a), halo_addr(g.ascale), halo_addr(g.b), halo_addr(g.bscale),
|
||||
halo_addr(g.y), (int)g.M, (int)g.K, (int)g.N, (long)(uintptr_t)s,
|
||||
t->variant));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The prefill row: the same packed weight and pre-shuffled activation as the tiled row, so on
|
||||
* gfx1151 it runs on the tiled kernel above. Each prefill arm names a (BM, BN); arms sharing a
|
||||
* shape share the tiled arm of that shape. */
|
||||
extern "C" int halo_rad_gemm_w4a8_prefill(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (!g.ascale) return HALO_NO(RAD_E_INVAL);
|
||||
if (g.N % 256) return HALO_NO(RAD_E_SHAPE);
|
||||
if (g.K % HALO_GEMM_W4A8_GROUP) return HALO_NO(RAD_E_SHAPE);
|
||||
if (is_asym(a)) return HALO_NO(RAD_E_INVAL); /* no asymmetric prefill grid in libr4d either */
|
||||
HaloTileCfg pv;
|
||||
halo_cfg_prefill(a, &pv);
|
||||
const HaloTileCfg* t = &pv;
|
||||
rc = tile_ok(t, g.N);
|
||||
if (rc != RAD_OK) return rc;
|
||||
int variant = 0; /* BM 128 x BN 256, the default shape */
|
||||
if (t->bm == 64 && t->bn == 256) variant = 6;
|
||||
else if (t->bm == 96 && t->bn == 256) variant = 10;
|
||||
else if (t->bm == 128 && t->bn == 128) variant = 59;
|
||||
else if (t->bm == 256 && t->bn == 128) variant = 900;
|
||||
HALO_TRY("gemm_w4a8_prefill",
|
||||
halo_gemm_w4a8_tiled(halo_addr(g.a), halo_addr(g.ascale), halo_addr(g.b), halo_addr(g.bscale),
|
||||
halo_addr(g.y), (int)g.M, (int)g.K, (int)g.N, (long)(uintptr_t)s,
|
||||
variant));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The raw-pointer prefill entry libr4d exports beside the rows (halo.h): on gfx1151 the
|
||||
* prefill arms run on the tiled kernel, as the prefill row above does. Negative codes,
|
||||
* as libr4d's: -1 a null pointer, -2 a non-positive extent, -4 a K not a whole scale
|
||||
* group or an N the tile cannot take, -6 the launch failed. */
|
||||
extern "C" void halo_gemm_w4a8_prefill(long a, long ascale, long wq, long ws, long c, int M,
|
||||
int K, int N, long stream, int variant) {
|
||||
if (!a || !ascale || !wq || !ws || !c || M <= 0 || K <= 0 || N <= 0) return;
|
||||
if ((K % HALO_GEMM_W4A8_GROUP) || (N % 256)) return;
|
||||
/* libr4d's prefill arms name (BM, BN) like the tiled arms but number them
|
||||
* differently; map by shape, as the prefill row above does. The remaining
|
||||
* prefill arms are BM 128 x BN 256 with option bits, the tiled default. */
|
||||
int tv = 0;
|
||||
switch (variant) {
|
||||
case 8: case 13: tv = 6; break; /* BM 64, BN 256 */
|
||||
case 9: tv = 10; break; /* BM 96, BN 256 */
|
||||
case 10: tv = 59; break; /* BM 128, BN 128 */
|
||||
case 14: tv = 900; break; /* BM 256, BN 128 */
|
||||
default: tv = 0; break; /* BM 128, BN 256 */
|
||||
}
|
||||
halo_gemm_w4a8_tiled(a, ascale, wq, ws, c, M, K, N, stream, tv);
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
/* Derived from libr4d/r4d_gemm_w5a16_nt_m64.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_w5a16_nt_m64.hip - halo_gemm_w5a16_nt_m64: 5-bit-weight skinny GEMM for M up to 64,
|
||||
// gfx1151. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C, fp32 accumulate.
|
||||
//
|
||||
// halo_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 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
|
||||
//
|
||||
// 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. 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 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 halo_gemm_args.h) as one launch per part.
|
||||
#include "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define HALO_GEMM_W4_MAX_M 64
|
||||
#define HALO_GEMM_W4_KPB 64 // K per packed block: 4 k steps, 16 bytes per lane
|
||||
#define WAVE32 32
|
||||
|
||||
typedef _Float16 v16h __attribute__((ext_vector_type(16)));
|
||||
typedef unsigned uint4v __attribute__((ext_vector_type(4)));
|
||||
|
||||
// NT and NPW: see halo_gemm_w4a16_nt_m64.hip. Only NPW 1 and 4 are instantiated.
|
||||
|
||||
// Address-space-qualified so loads stay global_load, not flat_load (on gfx12 a flat load also
|
||||
// increments dscnt). See halo_gemm_bf16_nt_m64.hip for why the element type is a scalar.
|
||||
typedef __attribute__((address_space(1))) const uint4v* halo_gw4;
|
||||
typedef __attribute__((address_space(1))) const unsigned long long* halo_gu2;
|
||||
typedef __attribute__((address_space(1))) const unsigned* halo_gu1;
|
||||
|
||||
/* gfx11 fragment: the row's whole 16-wide k run, 32 contiguous bytes, where the gfx12 form was
|
||||
* two 8-byte halves sixteen bytes apart. The pointer step is 32 bytes either way. */
|
||||
__device__ __forceinline__ v16h fragA(halo_gu2 p, int u) {
|
||||
union { unsigned long long w[4]; v16h f; } x;
|
||||
x.w[0] = p[4 * u];
|
||||
x.w[1] = p[4 * u + 1];
|
||||
x.w[2] = p[4 * u + 2];
|
||||
x.w[3] = p[4 * u + 3];
|
||||
return x.f;
|
||||
}
|
||||
|
||||
// Do not fold the group scale into the B fragment; see halo_gemm_w4a16_nt_m64.hip.
|
||||
|
||||
// One dword of eight nibbles plus the byte of their fifth bits -> eight f16 values (four packed
|
||||
// pairs), before the zero point is subtracted. 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). 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;
|
||||
}
|
||||
__device__ __forceinline__ void dequant5_pairs(unsigned w, unsigned hb, unsigned* u) {
|
||||
const unsigned K64 = 0x64646464u;
|
||||
const unsigned t0 = (w & 0x0F0F0F0Fu) | spread16(hb & 15u);
|
||||
const unsigned t1 = ((w >> 4) & 0x0F0F0F0Fu) | spread16(hb >> 4);
|
||||
u[0] = __builtin_amdgcn_perm(K64, t0, 0x05010400u); // elements 0, 1
|
||||
u[1] = __builtin_amdgcn_perm(K64, t0, 0x05030402u); // elements 2, 3
|
||||
u[2] = __builtin_amdgcn_perm(K64, t1, 0x05010400u); // elements 4, 5
|
||||
u[3] = __builtin_amdgcn_perm(K64, t1, 0x05030402u); // elements 6, 7
|
||||
}
|
||||
|
||||
/* The stored weight keeps libr4d's gfx12 fragment order byte for byte, fifth-bit plane included:
|
||||
* its byte per step travels with the nibble dword it belongs to. One cross-half exchange of each
|
||||
* and a pair interleave reassemble the gfx11 fragment, as in halo_gemm_w4a16_nt_m64.hip. nz holds
|
||||
* -(1024 + zero) in both halves. */
|
||||
__device__ __forceinline__ v16h dequant5(unsigned w, unsigned hb, __half2 nz, int lane) {
|
||||
const unsigned pw = (unsigned)__shfl_xor((int)w, 16);
|
||||
const unsigned phb = (unsigned)__shfl_xor((int)hb, 16);
|
||||
const bool hi = lane >> 4;
|
||||
unsigned lo[4], hd[4];
|
||||
dequant5_pairs(hi ? pw : w, hi ? phb : hb, lo);
|
||||
dequant5_pairs(hi ? w : pw, hi ? hb : phb, hd);
|
||||
union { unsigned u[8]; __half2 h2[8]; v16h f; } x;
|
||||
x.u[0] = lo[0]; x.u[1] = lo[1]; x.u[2] = hd[0]; x.u[3] = hd[1];
|
||||
x.u[4] = lo[2]; x.u[5] = lo[3]; x.u[6] = hd[2]; x.u[7] = hd[3];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; i++) x.h2[i] = __hadd2(x.h2[i], nz);
|
||||
return x.f;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v8f mmah(v16h a, v16h b, v8f c) {
|
||||
return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c);
|
||||
}
|
||||
|
||||
// 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 halo_gemm_w5a16_nt_m64_kernel(
|
||||
const unsigned short* __restrict__ A, const unsigned* __restrict__ Wq,
|
||||
const unsigned* __restrict__ Whi, const unsigned* __restrict__ Wsz,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK, int lda, int ldc) {
|
||||
extern __shared__ float red[]; // WV*NPW*SK*256 floats: a 16x16 tile per (column, split)
|
||||
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
const int nt0 = (blockIdx.x * WV + col_local) * NPW;
|
||||
const int n0 = nt0 * 16;
|
||||
const int mt0 = blockIdx.y * MT;
|
||||
const int Ks = K / SK;
|
||||
const int groups = Ks / HALO_GEMM_W4_GROUP; // groups this split owns
|
||||
const int kbase = ksplit * Ks;
|
||||
|
||||
v8f acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
if (n0 < N) {
|
||||
// Activation rows are clamped, not masked; results past M are never stored.
|
||||
unsigned aoff[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
aoff[i] = rowGo((unsigned)lda, (mt0 + i) * 16, M - 1, lane) + (unsigned)kbase;
|
||||
halo_gu2 pa[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] = (halo_gu2)(const unsigned long long*)(A + aoff[i]);
|
||||
|
||||
// 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 / HALO_GEMM_W4_KPB; // packed blocks in a full row of tiles
|
||||
const int nsz = K / HALO_GEMM_W4_GROUP; // (scale, zero) dwords per row of tiles
|
||||
halo_gw4 pw[NPW];
|
||||
halo_gu1 ph[NPW];
|
||||
halo_gu1 ps[NPW];
|
||||
const int ntlast = N / 16 - 1;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
// 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] = (halo_gw4)(const uint4v*)(Wq) +
|
||||
(size_t)(t * kpb + kbase / HALO_GEMM_W4_KPB) * WAVE32 + lane;
|
||||
// Fifth-bit plane: one dword per lane per packed block (unused when !HI).
|
||||
ph[j] = (halo_gu1)(const unsigned*)(HI ? Whi : Wq) +
|
||||
(size_t)(t * kpb + kbase / HALO_GEMM_W4_KPB) * WAVE32 + lane;
|
||||
// Quantiser parameters: 16 dwords per group, read by the 16 lanes that own the rows.
|
||||
ps[j] = (halo_gu1)(const unsigned*)(Wsz) +
|
||||
(size_t)(t * nsz + kbase / HALO_GEMM_W4_GROUP) * 16 + (lane & 15);
|
||||
}
|
||||
|
||||
const int bpg = HALO_GEMM_W4_GROUP / HALO_GEMM_W4_KPB; // packed blocks per group
|
||||
|
||||
for (int g = 0; g < groups; g++) {
|
||||
float sc[NPW];
|
||||
__half2 nz[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const unsigned sz = ps[j][(size_t)g * 16];
|
||||
sc[j] = __half2float(__ushort_as_half((unsigned short)(sz & 0xFFFFu)));
|
||||
nz[j] = __half2half2(__ushort_as_half((unsigned short)(sz >> 16)));
|
||||
}
|
||||
|
||||
// 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++) {
|
||||
uint4v wv[NPW];
|
||||
unsigned hv[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const size_t o = (size_t)(g * bpg + b) * WAVE32;
|
||||
wv[j] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o];
|
||||
hv[j] = HI ? (NT ? __builtin_nontemporal_load(&ph[j][o]) : ph[j][o]) : 0u;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int s = 0; s < 4; s++) {
|
||||
const int u = b * 4 + s;
|
||||
v16h afrag[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) afrag[i] = fragA(pa[i], u); // loaded once, spent NPW times
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const v16h bfrag = dequant5(wv[j][s], (hv[j] >> (8 * s)) & 0xFFu, nz[j], lane);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
g_acc[j][i] = u == 0 ? mmah(afrag[i], bfrag, (v8f)(0.f))
|
||||
: mmah(afrag[i], bfrag, g_acc[j][i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) acc[j][i][e] = fmaf(g_acc[j][i][e], sc[j], acc[j][i][e]);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] += (HALO_GEMM_W4_GROUP / 16) * 4;
|
||||
}
|
||||
}
|
||||
|
||||
// Split-K reduction and store as in halo_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
|
||||
for (int i = 0; i < MT; i++) {
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int slot = ((col_local * NPW + j) * SK + ksplit) * 256;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) red[slot + e * WAVE32 + lane] = acc[j][i][e];
|
||||
}
|
||||
__syncthreads();
|
||||
for (int idx = tid; idx < ncols * 256; idx += nthreads) {
|
||||
const int col = idx >> 8, off = idx & 255;
|
||||
float v = 0.f;
|
||||
for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off];
|
||||
const int l = off & 31;
|
||||
const int n = (blockIdx.x * ncols + col) * 16 + (l & 15);
|
||||
const int m = (mt0 + i) * 16 + accRow(l, off >> 5);
|
||||
if (n < N && m < M) C[(size_t)m * ldc + n] = (__hip_bfloat16)v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void halo_gemm_w5a16_nt_m64(long a, long wq, long whi, long wsz, long c, int M, int K, int N,
|
||||
int WV, int SK, int MB, int NPW, int NT, long stream, int lda, int ldc,
|
||||
bool hi5) {
|
||||
if (!lda) lda = K;
|
||||
if (!ldc) ldc = N;
|
||||
if (M < 1 || M > HALO_GEMM_W4_MAX_M)
|
||||
throw std::runtime_error("r4d gemm_w5a16_nt_m64: M must be 1..64");
|
||||
if (N % 16) throw std::runtime_error("r4d gemm_w5a16_nt_m64: N must be a multiple of 16");
|
||||
if (K % (SK * HALO_GEMM_W4_GROUP))
|
||||
throw std::runtime_error("r4d gemm_w5a16_nt_m64: K must be divisible by SK*128");
|
||||
if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_w5a16_nt_m64: threads/block > 1024");
|
||||
if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w5a16_nt_m64: MB must be 1..4");
|
||||
if (NPW != 1 && NPW != 4) throw std::runtime_error("r4d gemm_w5a16_nt_m64: NPW must be 1 or 4");
|
||||
const int ntiles = N / 16, mtiles = (M + 15) / 16;
|
||||
const int ncols = WV * NPW;
|
||||
dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32);
|
||||
size_t smem = (size_t)ncols * SK * 256 * sizeof(float);
|
||||
if (smem > 64 * 1024) throw std::runtime_error("r4d gemm_w5a16_nt_m64: WV*NPW*SK too large");
|
||||
auto Ap = (const unsigned short*)a;
|
||||
auto Wp = (const unsigned*)wq;
|
||||
auto Hp = (const unsigned*)whi;
|
||||
auto Sp = (const unsigned*)wsz;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH(MT, NP, TT) do { \
|
||||
if (hi5) hipLaunchKernelGGL((halo_gemm_w5a16_nt_m64_kernel<MT, NP, TT, true>), grid, block, smem, \
|
||||
st, Ap, Wp, Hp, Sp, Cp, M, K, N, WV, SK, lda, ldc); \
|
||||
else hipLaunchKernelGGL((halo_gemm_w5a16_nt_m64_kernel<MT, NP, TT, false>), grid, block, smem, \
|
||||
st, Ap, Wp, Hp, Sp, Cp, M, K, N, WV, SK, lda, ldc); } while (0)
|
||||
#define LAUNCH_MB(NP, TT) switch (MB) { \
|
||||
case 1: LAUNCH(1, NP, TT); break; \
|
||||
case 2: LAUNCH(2, NP, TT); break; \
|
||||
case 3: LAUNCH(3, NP, TT); break; \
|
||||
case 4: LAUNCH(4, NP, TT); break; \
|
||||
default: throw std::runtime_error("r4d gemm_w5a16_nt_m64: MB unsupported"); }
|
||||
if (NPW == 1) {
|
||||
if (NT) { LAUNCH_MB(1, true); } else { LAUNCH_MB(1, false); }
|
||||
} else {
|
||||
if (NT) { LAUNCH_MB(4, true); } else { LAUNCH_MB(4, false); }
|
||||
}
|
||||
#undef LAUNCH_MB
|
||||
#undef LAUNCH
|
||||
}
|
||||
|
||||
int halo_gemm_w5a16_nt_m64_max_m(void) { return HALO_GEMM_W4_MAX_M; }
|
||||
int halo_gemm_w5a16_nt_m64_group(void) { return HALO_GEMM_W4_GROUP; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in halo_gemm_args.h; see libhalo/halo_args.h.
|
||||
/* ------------------------------------------------------------------ f16-activation grids */
|
||||
|
||||
static int w5_dispatch(const RadArgs* a, RadStream s, bool hi5) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N % 16) return HALO_NO(RAD_E_SHAPE);
|
||||
/* Any other activation dtype would read plausible but wrong numbers. */
|
||||
if (g.a->dtype != RAD_F16) return HALO_NO(RAD_E_DTYPE);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.K % HALO_GEMM_W4_GROUP) return HALO_NO(RAD_E_SHAPE);
|
||||
const int group = halo_gemm_w5a16_nt_m64_group();
|
||||
// Rows past 64 run as chunks of 64, each a pass over the weight.
|
||||
const long long mc = std::min<long long>(g.M, halo_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 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. */
|
||||
HaloGemmCfg tuned;
|
||||
halo_cfg_gemm(a, &tuned);
|
||||
if (tuned.mb <= 0) c.mb = std::min<long long>(4, (mc + 15) / 16);
|
||||
const long long Ntot = g.N, K = g.K, lda = mp.lda ? mp.lda : g.K;
|
||||
const long long nsz = K / HALO_GEMM_W4_GROUP;
|
||||
for (int p = 0; p < mp.n; ++p) {
|
||||
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
|
||||
for (long long m0 = 0; m0 < g.M; m0 += mc) {
|
||||
const long long mm = std::min<long long>(mc, g.M - m0);
|
||||
HALO_TRY("gemm_w5a16_nt_m64",
|
||||
halo_gemm_w5a16_nt_m64(
|
||||
halo_addr(g.a) + (m0 * lda + p * K) * 2,
|
||||
halo_addr(g.b) + n0 * K / 2, /* the nibble plane */
|
||||
hi5 ? halo_addr(g.b) + Ntot * K / 2 + n0 * K / 8 : 0L, /* the fifth-bit plane */
|
||||
halo_addr(g.bscale) + (n0 / 16) * nsz * 16 * 4,
|
||||
halo_addr(g.y) + (m0 * Ntot + n0) * 2,
|
||||
(int)mm, (int)K, (int)np, c.wv, c.sk, c.mb, c.npw, c.nt, (long)(uintptr_t)s,
|
||||
(int)lda, (int)Ntot, hi5));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_gemm_w5a16_m64(const RadArgs* a, RadStream s) { return w5_dispatch(a, s, true); }
|
||||
/* ...and the plain 4-bit asymmetric grid (z-lab's int4), whose blob is the nibble plane alone. */
|
||||
extern "C" int halo_rad_gemm_w4a16asym_m64(const RadArgs* a, RadStream s) { return w5_dispatch(a, s, false); }
|
||||
@@ -0,0 +1,277 @@
|
||||
/* Derived from libr4d/r4d_gemm_w8a16_nt_m64.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_w8a16_nt_m64.hip - halo_gemm_w8a16_nt_m64: 8-bit-weight skinny GEMM for M up to 64,
|
||||
// gfx1151. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C, fp32 accumulate.
|
||||
//
|
||||
// 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 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.
|
||||
//
|
||||
// Structure matches halo_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.
|
||||
//
|
||||
// Dequant: `0x6400 | b` is exactly the f16 for 1024 + b for b in 0..255, so eight v_perm_b32 turn
|
||||
// four 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 stored bytes remain libr4d's fragment order; dequant8_step exchanges K quarters across the
|
||||
// wave's halves to form this part's consecutive-K fragment (see there).
|
||||
//
|
||||
// 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 halo_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)).
|
||||
//
|
||||
// Quantiser: asymmetric, per output channel, per group of HALO_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 "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define HALO_GEMM_W8_MAX_M 64
|
||||
#define HALO_GEMM_W8_KPB 32 // K per packed block: 2 k steps, 16 bytes per lane
|
||||
#define WAVE32 32
|
||||
|
||||
typedef _Float16 v16h __attribute__((ext_vector_type(16)));
|
||||
typedef unsigned uint4v __attribute__((ext_vector_type(4)));
|
||||
|
||||
typedef __attribute__((address_space(1))) const uint4v* halo_gw4;
|
||||
typedef __attribute__((address_space(1))) const unsigned long long* halo_gu2;
|
||||
typedef __attribute__((address_space(1))) const unsigned* halo_gu1;
|
||||
|
||||
/* gfx11 fragment: the row's whole 16-wide k run, 32 contiguous bytes, where the gfx12 form was
|
||||
* two 8-byte halves sixteen bytes apart. The pointer step is 32 bytes either way. */
|
||||
__device__ __forceinline__ v16h fragA8(halo_gu2 p, int u) {
|
||||
union { unsigned long long w[4]; v16h f; } x;
|
||||
x.w[0] = p[4 * u];
|
||||
x.w[1] = p[4 * u + 1];
|
||||
x.w[2] = p[4 * u + 2];
|
||||
x.w[3] = p[4 * u + 3];
|
||||
return x.f;
|
||||
}
|
||||
|
||||
// Four dwords of four consecutive-K bytes -> one 16x16x16 f16 B fragment, minus the zero point.
|
||||
// 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__ v16h dequant8(unsigned w0, unsigned w1, unsigned w2, unsigned w3,
|
||||
__half2 nz) {
|
||||
const unsigned K64 = 0x64646464u;
|
||||
const unsigned d[4] = { w0, w1, w2, w3 };
|
||||
union { unsigned u[8]; __half2 h2[8]; v16h f; } x;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; i++) {
|
||||
x.u[2 * i] = __builtin_amdgcn_perm(K64, d[i], 0x05010400u);
|
||||
x.u[2 * i + 1] = __builtin_amdgcn_perm(K64, d[i], 0x05030402u);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; i++) x.h2[i] = __hadd2(x.h2[i], nz);
|
||||
return x.f;
|
||||
}
|
||||
|
||||
/* The stored weight keeps libr4d's gfx12 fragment order byte for byte. For one k step a lane's
|
||||
* two dwords hold K quarters (0,2) in the low half-wave and (1,3) in the high half-wave for the
|
||||
* same row, so one cross-half exchange per dword reassembles the gfx11 fragment's consecutive
|
||||
* sixteen K in order. */
|
||||
__device__ __forceinline__ v16h dequant8_step(unsigned w0, unsigned w1, __half2 nz, int lane) {
|
||||
const unsigned p0 = (unsigned)__shfl_xor((int)w0, 16);
|
||||
const unsigned p1 = (unsigned)__shfl_xor((int)w1, 16);
|
||||
const bool hi = lane >> 4;
|
||||
return dequant8(hi ? p0 : w0, hi ? w0 : p0, hi ? p1 : w1, hi ? w1 : p1, nz);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v8f mmah8(v16h a, v16h b, v8f c) {
|
||||
return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c);
|
||||
}
|
||||
|
||||
template <int MT, int NPW, bool NT>
|
||||
__global__ __launch_bounds__(1024) void halo_gemm_w8a16_nt_m64_kernel(
|
||||
const unsigned short* __restrict__ A, const unsigned* __restrict__ Wq,
|
||||
const unsigned* __restrict__ Wsz, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int WV, int SK) {
|
||||
extern __shared__ float red8[]; // WV*NPW*SK*256 floats: a 16x16 tile per (column, split)
|
||||
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
const int nt0 = (blockIdx.x * WV + col_local) * NPW;
|
||||
const int n0 = nt0 * 16;
|
||||
const int mt0 = blockIdx.y * MT;
|
||||
const int Ks = K / SK;
|
||||
const int groups = Ks / HALO_GEMM_W8_GROUP;
|
||||
const int kbase = ksplit * Ks;
|
||||
|
||||
v8f acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
if (n0 < N) {
|
||||
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;
|
||||
halo_gu2 pa[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] = (halo_gu2)(const unsigned long long*)(A + aoff[i]);
|
||||
|
||||
const int kpb = K / HALO_GEMM_W8_KPB; // packed blocks in a full row of tiles
|
||||
const int nsz = K / HALO_GEMM_W8_GROUP; // (scale, zero) dwords per row of tiles
|
||||
halo_gw4 pw[NPW];
|
||||
halo_gu1 ps[NPW];
|
||||
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] = (halo_gw4)(const uint4v*)(Wq) +
|
||||
(size_t)(t * kpb + kbase / HALO_GEMM_W8_KPB) * WAVE32 + lane;
|
||||
ps[j] = (halo_gu1)(const unsigned*)(Wsz) +
|
||||
(size_t)(t * nsz + kbase / HALO_GEMM_W8_GROUP) * 16 + (lane & 15);
|
||||
}
|
||||
|
||||
const int bpg = HALO_GEMM_W8_GROUP / HALO_GEMM_W8_KPB; // packed blocks per group
|
||||
|
||||
for (int g = 0; g < groups; g++) {
|
||||
float sc[NPW];
|
||||
__half2 nz[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const unsigned sz = ps[j][(size_t)g * 16];
|
||||
sc[j] = __half2float(__ushort_as_half((unsigned short)(sz & 0xFFFFu)));
|
||||
nz[j] = __half2half2(__ushort_as_half((unsigned short)(sz >> 16)));
|
||||
}
|
||||
|
||||
v8f g_acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++) {
|
||||
uint4v wv[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const size_t o = (size_t)(g * bpg + b) * WAVE32;
|
||||
wv[j] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int s = 0; s < 2; s++) {
|
||||
const int u = b * 2 + s;
|
||||
v16h afrag[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) afrag[i] = fragA8(pa[i], u);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const v16h bfrag = dequant8_step(wv[j][2 * s], wv[j][2 * s + 1], nz[j], lane);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
g_acc[j][i] = u == 0 ? mmah8(afrag[i], bfrag, (v8f)(0.f))
|
||||
: mmah8(afrag[i], bfrag, g_acc[j][i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) acc[j][i][e] = fmaf(g_acc[j][i][e], sc[j], acc[j][i][e]);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] += (HALO_GEMM_W8_GROUP / 16) * 4;
|
||||
}
|
||||
}
|
||||
|
||||
const int ncols = WV * NPW;
|
||||
const int nthreads = WV * SK * WAVE32;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int slot = ((col_local * NPW + j) * SK + ksplit) * 256;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) red8[slot + e * WAVE32 + lane] = acc[j][i][e];
|
||||
}
|
||||
__syncthreads();
|
||||
for (int idx = tid; idx < ncols * 256; idx += nthreads) {
|
||||
const int col = idx >> 8, off = idx & 255;
|
||||
float v = 0.f;
|
||||
for (int s = 0; s < SK; s++) v += red8[(col * SK + s) * 256 + off];
|
||||
const int l = off & 31;
|
||||
const int n = (blockIdx.x * ncols + col) * 16 + (l & 15);
|
||||
const int m = (mt0 + i) * 16 + accRow(l, off >> 5);
|
||||
if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void halo_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) {
|
||||
// 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 * HALO_GEMM_W8_GROUP))
|
||||
throw std::runtime_error("r4d gemm_w8a16_nt_m64: K must be divisible by SK*128");
|
||||
if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_w8a16_nt_m64: threads/block > 1024");
|
||||
if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w8a16_nt_m64: MB must be 1..4");
|
||||
if (NPW != 1 && NPW != 2 && NPW != 4)
|
||||
throw std::runtime_error("r4d gemm_w8a16_nt_m64: NPW must be 1, 2 or 4");
|
||||
const int ntiles = N / 16, mtiles = (M + 15) / 16;
|
||||
const int ncols = WV * NPW;
|
||||
dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32);
|
||||
size_t smem = (size_t)ncols * SK * 256 * sizeof(float);
|
||||
if (smem > 64 * 1024) throw std::runtime_error("r4d gemm_w8a16_nt_m64: WV*NPW*SK too large");
|
||||
auto Ap = (const unsigned short*)a;
|
||||
auto Wp = (const unsigned*)wq;
|
||||
auto Sp = (const unsigned*)wsz;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH8(MT, NP, TT) hipLaunchKernelGGL((halo_gemm_w8a16_nt_m64_kernel<MT, NP, TT>), grid, \
|
||||
block, smem, st, Ap, Wp, Sp, Cp, M, K, N, WV, SK)
|
||||
#define LAUNCH8_MB(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; \
|
||||
default: throw std::runtime_error("r4d gemm_w8a16_nt_m64: MB unsupported"); }
|
||||
if (NPW == 1) {
|
||||
if (NT) { LAUNCH8_MB(1, true); } else { LAUNCH8_MB(1, false); }
|
||||
} else if (NPW == 2) {
|
||||
if (NT) { LAUNCH8_MB(2, true); } else { LAUNCH8_MB(2, false); }
|
||||
} else {
|
||||
if (NT) { LAUNCH8_MB(4, true); } else { LAUNCH8_MB(4, false); }
|
||||
}
|
||||
#undef LAUNCH8_MB
|
||||
#undef LAUNCH8
|
||||
}
|
||||
|
||||
int halo_gemm_w8a16_nt_m64_max_m(void) { return HALO_GEMM_W8_MAX_M; }
|
||||
int halo_gemm_w8a16_nt_m64_group(void) { return HALO_GEMM_W8_GROUP; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in halo_gemm_args.h; see libhalo/halo_args.h.
|
||||
extern "C" int halo_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 HALO_NO(RAD_E_SHAPE);
|
||||
/* Any other activation dtype would read plausible but wrong numbers. */
|
||||
if (g.a->dtype != RAD_F16) return HALO_NO(RAD_E_DTYPE);
|
||||
if (g.M > halo_gemm_w8a16_nt_m64_max_m()) return HALO_NO(RAD_E_SHAPE);
|
||||
const int group = halo_gemm_w8a16_nt_m64_group();
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, g.M, group, BR_FLAT, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
HALO_TRY("gemm_w8a16_nt_m64",
|
||||
halo_gemm_w8a16_nt_m64(halo_addr(g.a), halo_addr(g.b), halo_addr(g.bscale), halo_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt,
|
||||
(long)(uintptr_t)s));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
/* Derived from libr4d/r4d_gemm_w8a8_nt_m64.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_w8a8_nt_m64.hip - halo_gemm_w8a8_nt_m64: 8-bit-weight, 8-bit-activation skinny GEMM for
|
||||
// M up to a prefill chunk, gfx1151. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, A quantised per row and
|
||||
// W per (row, 128-wide group).
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// It is halo_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.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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 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: 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 "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h"
|
||||
#include "halo_chain.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
// Not structural (grid.y tiles M, rows are clamped); a sanity bound only.
|
||||
#define HALO_GEMM_W8A8_MAX_M 32768
|
||||
#define HALO_GEMM_W8A8_KPB 32 // K per packed block: 2 k steps, 16 bytes per lane
|
||||
#define WAVE32 32
|
||||
|
||||
typedef int v8i __attribute__((ext_vector_type(8)));
|
||||
typedef float v4f __attribute__((ext_vector_type(4)));
|
||||
typedef int v4i __attribute__((ext_vector_type(4)));
|
||||
typedef unsigned uint4v __attribute__((ext_vector_type(4)));
|
||||
typedef unsigned uint2v __attribute__((ext_vector_type(2)));
|
||||
|
||||
typedef __attribute__((address_space(1))) const uint4v* halo_gw8;
|
||||
typedef __attribute__((address_space(1))) const unsigned short* halo_gs2;
|
||||
typedef __attribute__((address_space(1))) const uint2v* halo_ga2;
|
||||
|
||||
/* Both operands keep libr4d's gfx12 fragment order byte for byte: the weight by its relayout,
|
||||
* the activation by the quantiser that wrote it, one permutation serving both. For one k step a
|
||||
* lane's two dwords hold K quarters (0,2) in the low half-wave and (1,3) in the high half-wave
|
||||
* for the same row, so one cross-half exchange per dword reassembles the gfx11 fragment's
|
||||
* consecutive sixteen K. */
|
||||
__device__ __forceinline__ v4i frag_step(unsigned d0, unsigned d1, int lane) {
|
||||
const unsigned p0 = (unsigned)__shfl_xor((int)d0, 16);
|
||||
const unsigned p1 = (unsigned)__shfl_xor((int)d1, 16);
|
||||
const bool hi = lane >> 4;
|
||||
v4i r;
|
||||
r[0] = (int)(hi ? p0 : d0);
|
||||
r[1] = (int)(hi ? d0 : p0);
|
||||
r[2] = (int)(hi ? p1 : d1);
|
||||
r[3] = (int)(hi ? d1 : p1);
|
||||
return r;
|
||||
}
|
||||
|
||||
// The A fragment, as halo_gemm_w4a8_nt_m64 reads it.
|
||||
__device__ __forceinline__ v4i fragA8w(halo_ga2 p, int u, int lane) {
|
||||
const uint2v w = p[2 * u];
|
||||
return frag_step(w[0], w[1], lane);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v8i mmai8(v4i a, v4i b, v8i c) {
|
||||
return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, a, true, b, c, false);
|
||||
}
|
||||
|
||||
// __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 HALO_W8A8_BOUNDS(MT, NPW) ((MT) * (NPW) >= 8 ? 256 : ((MT) * (NPW) >= 4 ? 512 : 1024))
|
||||
|
||||
// The body; the plain kernel and its chained form (halo_chain.h) wrap it below. Its early returns
|
||||
// sit after its last barrier, so every block still reaches the wrapper's add.
|
||||
template <int MT, int NPW, bool NT>
|
||||
__device__ __forceinline__ void halo_gemm_w8a8_nt_m64_body(
|
||||
const signed char* __restrict__ A, const float* __restrict__ Ascale,
|
||||
const unsigned* __restrict__ Wq, const unsigned short* __restrict__ Ws,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) {
|
||||
extern __shared__ float red[];
|
||||
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
const int nt0 = (blockIdx.x * WV + col_local) * NPW;
|
||||
const int n0 = nt0 * 16;
|
||||
const int mt0 = blockIdx.y * MT;
|
||||
const int Ks = K / SK;
|
||||
const int groups = Ks / HALO_GEMM_W8A8_GROUP;
|
||||
const int kbase = ksplit * Ks;
|
||||
|
||||
v8f acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
if (n0 < N) {
|
||||
// Rows clamped into 0..M-1, never masked; the store discards rows past M. A is int8, so the
|
||||
// row stride is K bytes.
|
||||
halo_ga2 pa[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
int r = (mt0 + i) * 16 + (lane & 15);
|
||||
r = r < M - 1 ? r : M - 1;
|
||||
const size_t off = (size_t)r * K + kbase + 8 * (lane >> 4);
|
||||
pa[i] = (halo_ga2)(const uint2v*)(A + off);
|
||||
}
|
||||
|
||||
const int kpb = K / HALO_GEMM_W8A8_KPB;
|
||||
const int nsz = K / HALO_GEMM_W8A8_GROUP;
|
||||
halo_gw8 pw[NPW];
|
||||
halo_gs2 ps[NPW];
|
||||
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] = (halo_gw8)(const uint4v*)(Wq) +
|
||||
(size_t)(t * kpb + kbase / HALO_GEMM_W8A8_KPB) * WAVE32 + lane;
|
||||
ps[j] = (halo_gs2)(const unsigned short*)(Ws) +
|
||||
(size_t)(t * nsz + kbase / HALO_GEMM_W8A8_GROUP) * 16 + (lane & 15);
|
||||
}
|
||||
|
||||
const int bpg = HALO_GEMM_W8A8_GROUP / HALO_GEMM_W8A8_KPB;
|
||||
|
||||
for (int g = 0; g < groups; g++) {
|
||||
float sc[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
sc[j] = __half2float(__ushort_as_half(ps[j][(size_t)g * 16]));
|
||||
|
||||
v8i g_acc[NPW][MT];
|
||||
// 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.
|
||||
v4i afg[2 * (HALO_GEMM_W8A8_GROUP / HALO_GEMM_W8A8_KPB)][MT];
|
||||
#pragma unroll
|
||||
for (int u = 0; u < 2 * bpg; u++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
afg[u][i] = fragA8w(pa[i], u, lane);
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++) {
|
||||
uint4v wv[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const size_t o = (size_t)(g * bpg + b) * WAVE32;
|
||||
wv[j] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o];
|
||||
}
|
||||
// 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;
|
||||
v4i afrag[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) afrag[i] = afg[u][i];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
// The sixteen weight bytes are the fragment, once exchanged across halves.
|
||||
const v4i bfrag = frag_step(wv[j][2 * s], wv[j][2 * s + 1], lane);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
g_acc[j][i] = (u == 0) ? mmai8(afrag[i], bfrag, (v8i)(0))
|
||||
: mmai8(afrag[i], bfrag, g_acc[j][i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#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]);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] += HALO_GEMM_W8A8_GROUP / 8;
|
||||
}
|
||||
}
|
||||
|
||||
// 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: 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
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int n = (nt0 + j) * 16 + (lane & 15);
|
||||
if (n >= N) continue;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
const int mb = (mt0 + i) * 16;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) {
|
||||
const int m = mb + accRow(lane, e);
|
||||
if (m < M) C[(size_t)m * N + n] = (__hip_bfloat16)(acc[j][i][e] * Ascale[m]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int slot = ((col_local * NPW + j) * SK + ksplit) * 256;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) red[slot + e * WAVE32 + lane] = acc[j][i][e];
|
||||
}
|
||||
__syncthreads();
|
||||
for (int idx = tid; idx < ncols * 256; idx += nthreads) {
|
||||
const int col = idx >> 8, off = idx & 255;
|
||||
float v = 0.f;
|
||||
for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off];
|
||||
const int l = off & 31;
|
||||
const int n = (blockIdx.x * ncols + col) * 16 + (l & 15);
|
||||
const int m = (mt0 + i) * 16 + accRow(l, off >> 5);
|
||||
if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)(v * Ascale[m]);
|
||||
}
|
||||
}
|
||||
}
|
||||
template <int MT, int NPW, bool NT>
|
||||
__global__ __launch_bounds__(HALO_W8A8_BOUNDS(MT, NPW)) void halo_gemm_w8a8_nt_m64_kernel(
|
||||
const signed char* __restrict__ A, const float* __restrict__ Ascale,
|
||||
const unsigned* __restrict__ Wq, const unsigned short* __restrict__ Ws,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) {
|
||||
halo_gemm_w8a8_nt_m64_body<MT, NPW, NT>(A, Ascale, Wq, Ws, C, M, K, N, WV, SK);
|
||||
}
|
||||
template <int MT, int NPW, bool NT>
|
||||
__global__ __launch_bounds__(HALO_W8A8_BOUNDS(MT, NPW)) void halo_r4dchain_gemm_w8a8_nt_m64(
|
||||
const signed char* __restrict__ A, const float* __restrict__ Ascale,
|
||||
const unsigned* __restrict__ Wq, const unsigned short* __restrict__ Ws,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) {
|
||||
halo_chain_wait();
|
||||
halo_gemm_w8a8_nt_m64_body<MT, NPW, NT>(A, Ascale, Wq, Ws, C, M, K, N, WV, SK);
|
||||
halo_chain_done();
|
||||
}
|
||||
|
||||
/* `chain`: the chained form (the plugin entry, where the row resolved with `chain`). */
|
||||
static void gemm_w8a8_m64_impl(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
|
||||
int WV, int SK, int MB, int NPW, int NT, long stream, bool chain);
|
||||
|
||||
void halo_gemm_w8a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
|
||||
int WV, int SK, int MB, int NPW, int NT, long stream) {
|
||||
gemm_w8a8_m64_impl(a, ascale, wq, ws, c, M, K, N, WV, SK, MB, NPW, NT, stream, false);
|
||||
}
|
||||
|
||||
static void gemm_w8a8_m64_impl(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
|
||||
int WV, int SK, int MB, int NPW, int NT, long stream, bool chain) {
|
||||
if (M < 1 || M > HALO_GEMM_W8A8_MAX_M)
|
||||
throw std::runtime_error("r4d gemm_w8a8_nt_m64: M out of range");
|
||||
if (N % 16) throw std::runtime_error("r4d gemm_w8a8_nt_m64: N must be a multiple of 16");
|
||||
if (K % (SK * HALO_GEMM_W8A8_GROUP))
|
||||
throw std::runtime_error("r4d gemm_w8a8_nt_m64: K must be divisible by SK*group");
|
||||
if (WV * SK * WAVE32 > HALO_W8A8_BOUNDS(MB, NPW))
|
||||
throw std::runtime_error("r4d gemm_w8a8_nt_m64: WV*SK*32 exceeds this tile's launch bound");
|
||||
// cfg_for (halo_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;
|
||||
const int ncols = WV * NPW;
|
||||
dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32);
|
||||
size_t smem = (size_t)ncols * SK * 256 * sizeof(float);
|
||||
if (smem > 64 * 1024) throw std::runtime_error("r4d gemm_w8a8_nt_m64: WV*NPW*SK too large");
|
||||
auto Ap = (const signed char*)a;
|
||||
auto Sp = (const float*)ascale;
|
||||
auto Wp = (const unsigned*)wq;
|
||||
auto Zp = (const unsigned short*)ws;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH8(MT, NP, TT) hipLaunchKernelGGL((chain ? halo_r4dchain_gemm_w8a8_nt_m64<MT, NP, TT> \
|
||||
: halo_gemm_w8a8_nt_m64_kernel<MT, NP, TT>), \
|
||||
grid, block, smem, st, Ap, Sp, Wp, Zp, Cp, M, K, N, WV, SK)
|
||||
// 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; \
|
||||
default: throw std::runtime_error("r4d gemm_w8a8_nt_m64: MB unsupported"); }
|
||||
#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 > 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 > 8 would spill"); }
|
||||
#define LAUNCH8_NPW(TT) switch (NPW) { \
|
||||
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"); }
|
||||
if (NT) { LAUNCH8_NPW(true); } else { LAUNCH8_NPW(false); }
|
||||
#undef LAUNCH8_NPW
|
||||
#undef LAUNCH8_MB1
|
||||
#undef LAUNCH8_MB2
|
||||
#undef LAUNCH8_MB4
|
||||
#undef LAUNCH8
|
||||
}
|
||||
|
||||
int halo_gemm_w8a8_nt_m64_max_m(void) { return HALO_GEMM_W8A8_MAX_M; }
|
||||
int halo_gemm_w8a8_nt_m64_group(void) { return HALO_GEMM_W8A8_GROUP; }
|
||||
int halo_gemm_w8a8_nt_m64_kpb(void) { return HALO_GEMM_W8A8_KPB; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in halo_gemm_args.h; see libhalo/halo_args.h.
|
||||
extern "C" int halo_rad_gemm_w8a8_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 HALO_NO(RAD_E_SHAPE);
|
||||
if (g.M > halo_gemm_w8a8_nt_m64_max_m()) return HALO_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale) return HALO_NO(RAD_E_INVAL);
|
||||
const int group = halo_gemm_w8a8_nt_m64_group();
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, g.M, group, BR_MBNPW, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
/* the engine's chained launch (RadKernelChainFn), at decode heights only */
|
||||
const bool chain = halo_geti_or(a, "chain", 0) != 0 && g.M <= 64;
|
||||
HALO_TRY("gemm_w8a8_nt_m64",
|
||||
gemm_w8a8_m64_impl(halo_addr(g.a), halo_addr(g.ascale), halo_addr(g.b),
|
||||
halo_addr(g.bscale), halo_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt,
|
||||
(long)(uintptr_t)s, chain));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
/* Derived from libr4d/r4d_gemm_w8a8_tiled.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_w8a8_tiled.hip - halo_gemm_w8a8_tiled: the W8A8 GEMM for prefill batches.
|
||||
//
|
||||
// halo_gemm_w4a8_tiled with the weight radix doubled: the inner loop, double buffering, XOR swizzle
|
||||
// and magic-bias epilogue are that kernel's, and staging copies the weight's bytes to LDS in
|
||||
// `[tile][lane*8 + u*2]` order instead of unpacking nibbles.
|
||||
//
|
||||
// At prefill the promotion to eight bits is nearly free: the kernel is matrix-bound and the WMMA
|
||||
// count does not depend on the radix, while twice the weight and LDS bytes are amortised over BM
|
||||
// rows. (A skinny kernel would re-read the weight M/(16*MB) times.)
|
||||
//
|
||||
// The packed layout is halo_gemm_w8a8_nt_m64's: a lane owns 16 bytes of a 32-column block, staged
|
||||
// with coalesced global_load_b128 to `lane*8 + kh*4` dwords of the tile's LDS run. One weight feeds
|
||||
// both kernels. The scale plane is f16 only: a symmetric 8-bit grid has no zero point.
|
||||
//
|
||||
#include "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h" // accRow: the gfx11 accumulator row mapping
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define HALO_TILED8_KPB 32 // packed block: 32 columns, 16 bytes a lane
|
||||
// BK = 32, not the 4-bit kernel's 64: at BK = 64 the 64x256 tile needs 40960 B of LDS (one
|
||||
// workgroup per CU); BK = 32 needs 20480 B (three), worth several percent on down_proj at every
|
||||
// prefill M despite twice the barriers per scale group.
|
||||
#define HALO_TILED8_BK 32
|
||||
|
||||
typedef int v2i8_t __attribute__((ext_vector_type(2)));
|
||||
typedef int v4i8_t __attribute__((ext_vector_type(4)));
|
||||
typedef int v8i8_t __attribute__((ext_vector_type(8)));
|
||||
typedef float v8f8_t __attribute__((ext_vector_type(8)));
|
||||
typedef unsigned u4v8_t __attribute__((ext_vector_type(4)));
|
||||
|
||||
// WM x WN waves, each owning TM x TN WMMA tiles. BM = WM*TM*16, BN = WN*TN*16. UNR k blocks are
|
||||
// unrolled per scale group. The accumulator carries the magic bias of halo_gemm_w4a8_tiled.hip:
|
||||
// for |x| < 2^22, float(x) == __uint_as_float(0x4B400000 + x) - 12582912.0f.
|
||||
//
|
||||
// `Asum` is always null (an 8-bit grid here is symmetric). The slot keeps the 4-bit kernel's
|
||||
// argument layout: dropping it changes the generated code of the tuned tiles.
|
||||
// No minimum-occupancy bound: libr4d's 8 waves a SIMD caps a lane at 192 VGPRs on gfx1151 and
|
||||
// spilled most arms (the 4x2 tile 158-165 slots); unbounded, the arms run 1.1-2.4x faster.
|
||||
// PART: the grid's last row of blocks is cut by M, and its waves skip the WMMAs and folds of their
|
||||
// padding fragments past M (wave-uniform; those rows are never stored). Only the launch for a
|
||||
// ragged M instantiates it, so whole-band grids run the unguarded kernel.
|
||||
template <int WM, int WN, int TM, int TN, int UNR, bool PART = false>
|
||||
__global__ __launch_bounds__(WM * WN * 32) void halo_gemm_w8a8_tiled_kernel(
|
||||
const signed char* __restrict__ A, const float* __restrict__ Ascale,
|
||||
const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws,
|
||||
const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C, int M, int K, int N) {
|
||||
constexpr int BK = HALO_TILED8_BK;
|
||||
constexpr int GRP = HALO_GEMM_W8A8_GROUP;
|
||||
constexpr int BM = WM * TM * 16, BN = WN * TN * 16;
|
||||
constexpr int NTILE = BN / 16;
|
||||
constexpr int AW = BM * BK / 4; // A dwords per buffer
|
||||
constexpr int WW = NTILE * BK * 4; // W dwords per buffer: NTILE*16 rows x BK bytes
|
||||
|
||||
__shared__ unsigned lds_a[2][AW];
|
||||
__shared__ unsigned lds_w[2][WW];
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int wm = wave / WN, wn = wave % WN;
|
||||
// halo_gemm_bf16_nt_tiled's block order: groups of 8 activation bands, M fastest, so the bands
|
||||
// of one column block run together and share its weight through the cache -- a ragged last band
|
||||
// then re-reads the weight from L2, not from DRAM after every other band is done.
|
||||
constexpr unsigned kGroupM = 8;
|
||||
const unsigned per = kGroupM * gridDim.x, lin = blockIdx.y * gridDim.x + blockIdx.x;
|
||||
const unsigned first = lin / per * kGroupM, rr = lin % per;
|
||||
const unsigned gm = min(gridDim.y - first, kGroupM);
|
||||
const int m0 = (int)(first + rr % gm) * BM, bx = (int)(rr / gm), n0 = bx * BN;
|
||||
const int live = PART ? __builtin_amdgcn_readfirstlane(
|
||||
min(TM, max(0, (M + 15) / 16 - (m0 / 16 + wm * TM))))
|
||||
: TM;
|
||||
const int kpb = K / HALO_TILED8_KPB, nsz = K / GRP;
|
||||
constexpr int NT_ = WM * WN * 32;
|
||||
|
||||
v8f8_t acc[TN][TM];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) acc[j][i] = (v8f8_t)(0.f);
|
||||
v8i8_t g[TN][TM];
|
||||
float csum[TN];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++) csum[j] = 0.f;
|
||||
unsigned scv[TN];
|
||||
|
||||
// XOR swizzle of the A rows instead of padding, separating rows r >> 1 (see
|
||||
// halo_gemm_w4a8_tiled.hip). The XOR must stay inside a row of BK/4 = 8 dwords, so the mask is
|
||||
// derived from BK and steps by 2 for ds_load_b64 alignment.
|
||||
#define ASW_M2 ((BK / 8) - 1)
|
||||
#define ASW(r, c) ((r) * (BK / 4) + ((c) ^ ((((r) >> 1) & ASW_M2) << 1)))
|
||||
|
||||
// Prefetch into registers, compute off the other buffer, then commit to LDS, so the load wait
|
||||
// lands after the WMMA work (a prefetch that writes LDS directly would stall the compute; >2x).
|
||||
// Both stagings may be ragged (a predicate on the last pass), so the tile need not divide the
|
||||
// workgroup width (e.g. BM = 80, 112; at BK = 32 the NTILE*32 weight chunks).
|
||||
constexpr int APT = (AW + NT_ - 1) / NT_;
|
||||
constexpr bool APAD = (AW % NT_) != 0;
|
||||
unsigned ra[APT];
|
||||
constexpr int WWP = NTILE * BK; // 16-byte weight chunks per buffer
|
||||
constexpr int WPTU = (WWP + NT_ - 1) / NT_;
|
||||
constexpr bool WPAD = (WWP % NT_) != 0;
|
||||
u4v8_t rwu[WPTU];
|
||||
// Global indices into A are 32-bit: a 64-bit address costs four extra instructions per load.
|
||||
auto issue = [&](int kk) {
|
||||
// Sixteen bytes per thread, copied unchanged. A lane owns 16 bytes of a 32-column packed
|
||||
// block; at BK = 64 `kh` would pick one of two blocks 512 bytes apart. Coalesced across the
|
||||
// wave.
|
||||
#pragma unroll
|
||||
for (int x = 0; x < WPTU; x++) {
|
||||
const int t = tid + x * NT_;
|
||||
if (WPAD && t >= WWP) continue;
|
||||
const int tl = t / BK, rem = t % BK, kh = rem / 32, ln = rem % 32;
|
||||
rwu[x] = *((const u4v8_t*)Wq +
|
||||
(size_t)(((n0 / 16 + tl) * kpb + kk / HALO_TILED8_KPB + kh) * 32 + ln));
|
||||
}
|
||||
#pragma unroll
|
||||
for (int x = 0; x < APT; x++) {
|
||||
const int t = tid + x * NT_, r = t / (BK / 4), c = t % (BK / 4);
|
||||
if (APAD && t >= AW) continue;
|
||||
const int mm = m0 + r < M ? m0 + r : M - 1;
|
||||
ra[x] = *(const unsigned*)(A + (unsigned)(mm * K + kk + c * 4));
|
||||
}
|
||||
};
|
||||
auto commit = [&](int buf) {
|
||||
#pragma unroll
|
||||
for (int x = 0; x < WPTU; x++) {
|
||||
const int t = tid + x * NT_;
|
||||
if (WPAD && t >= WWP) continue;
|
||||
const int tl = t / BK, rem = t % BK, kh = rem / 32, ln = rem % 32;
|
||||
// [tile][lane][u][2] dwords: a lane's 16 bytes are k steps 2*kh and 2*kh+1, four
|
||||
// consecutive dwords at `ln*8 + kh*4`, one ds_store_b128.
|
||||
*(u4v8_t*)(lds_w[buf] + (size_t)tl * (BK * 4) + ln * (BK / 8) + kh * 4) = rwu[x];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int x = 0; x < APT; x++) {
|
||||
const int t = tid + x * NT_, r = t / (BK / 4), c = t % (BK / 4);
|
||||
if (APAD && t >= AW) continue;
|
||||
lds_a[buf][ASW(r, c)] = ra[x];
|
||||
}
|
||||
};
|
||||
|
||||
issue(0);
|
||||
commit(0);
|
||||
__syncthreads();
|
||||
|
||||
// Unroll the K loop over the group (UNR = GRP/BK) so the group-boundary tests are compile-time per
|
||||
// copy; a dynamic branch around the epilogue stops the scheduler interleaving it with the WMMA.
|
||||
// Worth several percent.
|
||||
for (int kg = 0, it = 0; kg < K; kg += BK * UNR) {
|
||||
#pragma unroll
|
||||
for (int h = 0; h < UNR; h++, it++) {
|
||||
const int k0 = kg + h * BK;
|
||||
const int buf = it & 1;
|
||||
if (k0 + BK < K) issue(k0 + BK); // loads in flight across the WMMA work below
|
||||
|
||||
const bool first_half = (k0 % GRP) == 0;
|
||||
// Fetch the group scale at the start of the group, so the waves do not all stall on it at the
|
||||
// fold; keep the raw bits and convert at the group close. 32-bit index: the table has at most
|
||||
// (N/16)*(K/GRP)*16 elements.
|
||||
if ((k0 % GRP) == 0) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
scv[j] = (unsigned)((const unsigned short*)Ws)[(unsigned)(((n0 / 16 + wn * TN + j) * nsz +
|
||||
k0 / GRP) * 16 + (lane & 15))];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int u = 0; u < BK / 16; u++) {
|
||||
v4i8_t af[TM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) {
|
||||
/* The A tile is staged row-major, so the gfx11 fragment is the row's sixteen
|
||||
* consecutive bytes: four dwords, each through the row XOR swizzle. */
|
||||
const int row = (wm * TM + i) * 16 + (lane & 15);
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; d++)
|
||||
af[i][d] = (int)lds_a[buf][ASW(row, u * 4 + d)];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++) {
|
||||
/* The W tile keeps libr4d's fragment order in LDS ([tile][lane][u][2] dwords): a
|
||||
* lane's two dwords hold K quarters (0,2) in the low half-wave and (1,3) in the high,
|
||||
* so the gfx11 fragment takes the cross-half partner's staged dwords too. */
|
||||
const unsigned* lw = lds_w[buf] + (size_t)(wn * TN + j) * (BK * 4) + lane * (BK / 8) + u * 2;
|
||||
const unsigned* pw = lds_w[buf] + (size_t)(wn * TN + j) * (BK * 4) + (lane ^ 16) * (BK / 8) + u * 2;
|
||||
const bool hi = lane >> 4;
|
||||
v4i8_t bf;
|
||||
bf[0] = (int)(hi ? pw[0] : lw[0]);
|
||||
bf[1] = (int)(hi ? lw[0] : pw[0]);
|
||||
bf[2] = (int)(hi ? pw[1] : lw[1]);
|
||||
bf[3] = (int)(hi ? lw[1] : pw[1]);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) {
|
||||
if (PART && i >= live) continue; // wave-uniform: padding fragments past M
|
||||
g[j][i] = (first_half && u == 0)
|
||||
? __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(
|
||||
true, af[i], true, bf, (v8i8_t)(0x4B400000), false)
|
||||
: __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(
|
||||
true, af[i], true, bf, g[j][i], false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((k0 + BK) % GRP == 0) { // the group closed: fold it into the float acc
|
||||
float sc[TN];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
sc[j] = __half2float(__ushort_as_half((unsigned short)(scv[j] & 0xFFFFu)));
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++) csum[j] += sc[j];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) {
|
||||
if (PART && i >= live) continue;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++)
|
||||
acc[j][i][e] = fmaf(__uint_as_float((unsigned)g[j][i][e]), sc[j], acc[j][i][e]);
|
||||
}
|
||||
}
|
||||
if (k0 + BK < K) commit(buf ^ 1); // the wait for those loads lands here
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
#undef ASW
|
||||
#undef ASW_M2
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++) {
|
||||
const float d = -12582912.0f * csum[j];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) acc[j][i][e] += d;
|
||||
}
|
||||
|
||||
// The flat predicated store, as in the 4-bit kernel.
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) {
|
||||
const int n = n0 + (wn * TN + j) * 16 + (lane & 15);
|
||||
const int m = m0 + (wm * TM + i) * 16 + accRow(lane, e);
|
||||
if (n < N && m < M)
|
||||
// No 1/16 here, unlike the 4-bit kernel: an 8-bit code is the byte itself, with no
|
||||
// high-nibble factor to undo.
|
||||
C[(size_t)m * N + n] = (__hip_bfloat16)(acc[j][i][e] * Ascale[m]);
|
||||
}
|
||||
}
|
||||
|
||||
// CANPART: this arm instantiates the PART kernel for a ragged M (the default arm; the tuned arms
|
||||
// keep one kernel each).
|
||||
template <int WM, int WN, int TM, int TN, int UNR, bool CANPART = false>
|
||||
static void halo_tiled8_launch(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
|
||||
long stream) {
|
||||
constexpr int BM = WM * TM * 16, BN = WN * TN * 16;
|
||||
// An 8-bit weight doubles the staged bytes.
|
||||
static_assert(2 * (BM * HALO_TILED8_BK / 4 + (BN / 16) * HALO_TILED8_BK * 4) * sizeof(unsigned) <=
|
||||
64 * 1024, "this tile needs more than 64 KB of LDS");
|
||||
if (N % BN)
|
||||
throw std::runtime_error("r4d gemm_w8a8_tiled: N is not a multiple of this variant's block");
|
||||
dim3 grid(N / BN, (M + BM - 1) / BM), block(WM * WN * 32);
|
||||
if (CANPART && M % BM)
|
||||
hipLaunchKernelGGL((halo_gemm_w8a8_tiled_kernel<WM, WN, TM, TN, UNR, CANPART>), grid, block, 0,
|
||||
(hipStream_t)stream, (const signed char*)a, (const float*)ascale,
|
||||
(const unsigned*)wq, (const unsigned*)ws, nullptr, (__hip_bfloat16*)c, M, K,
|
||||
N);
|
||||
else
|
||||
hipLaunchKernelGGL((halo_gemm_w8a8_tiled_kernel<WM, WN, TM, TN, UNR>), grid, block, 0,
|
||||
(hipStream_t)stream, (const signed char*)a, (const float*)ascale,
|
||||
(const unsigned*)wq, (const unsigned*)ws, nullptr, (__hip_bfloat16*)c, M, K,
|
||||
N);
|
||||
}
|
||||
|
||||
void halo_gemm_w8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
|
||||
long stream, int variant) {
|
||||
if (N % 256) throw std::runtime_error("r4d gemm_w8a8_tiled: N must be a multiple of 256");
|
||||
if (K % HALO_GEMM_W8A8_GROUP)
|
||||
throw std::runtime_error("r4d gemm_w8a8_tiled: K must be a multiple of the scale group");
|
||||
if (M < 1) throw std::runtime_error("r4d gemm_w8a8_tiled: M must be positive");
|
||||
// The unroll covers exactly one scale group (GRP/BK steps); see halo_gemm_w4a8_tiled.hip. The K
|
||||
// check above makes every K a whole number of them.
|
||||
static_assert(HALO_GEMM_W8A8_GROUP % HALO_TILED8_BK == 0, "the scale group must be whole k steps");
|
||||
constexpr int UNRG = HALO_GEMM_W8A8_GROUP / HALO_TILED8_BK;
|
||||
#define HALO_TILED8_LAUNCH(...) \
|
||||
halo_tiled8_launch<__VA_ARGS__>(a, ascale, wq, ws, c, M, K, N, stream)
|
||||
// The arms tile_bmbn in halo_rows.cpp lists, with the (BM, BN) it records for each.
|
||||
switch (variant) {
|
||||
case 6: HALO_TILED8_LAUNCH(2, 8, 2, 2, UNRG); break; // BM 64, BN 256
|
||||
case 10: HALO_TILED8_LAUNCH(2, 8, 3, 2, UNRG); break; // BM 96, BN 256
|
||||
case 12: HALO_TILED8_LAUNCH(2, 8, 3, 1, UNRG); break; // BM 96, BN 128
|
||||
case 57: HALO_TILED8_LAUNCH(2, 8, 5, 1, UNRG); break; // BM 160, BN 128
|
||||
case 59: HALO_TILED8_LAUNCH(2, 8, 4, 1, UNRG, true); break; // BM 128, BN 128
|
||||
case 114: HALO_TILED8_LAUNCH(1, 8, 5, 1, UNRG); break; // BM 80, BN 128
|
||||
case 124: HALO_TILED8_LAUNCH(1, 8, 4, 1, UNRG); break; // BM 64, BN 128
|
||||
case 125: HALO_TILED8_LAUNCH(1, 8, 7, 1, UNRG); break; // BM 112, BN 128
|
||||
case 126: HALO_TILED8_LAUNCH(1, 8, 10, 1, UNRG); break; // BM 160, BN 128
|
||||
case 128: HALO_TILED8_LAUNCH(1, 8, 2, 1, UNRG); break; // BM 32, BN 128
|
||||
case 129: HALO_TILED8_LAUNCH(1, 8, 3, 1, UNRG); break; // BM 48, BN 128
|
||||
case 138: HALO_TILED8_LAUNCH(1, 16, 3, 1, UNRG); break; // BM 48, BN 256
|
||||
case 139: HALO_TILED8_LAUNCH(1, 16, 7, 1, UNRG); break; // BM 112, BN 256
|
||||
case 146: HALO_TILED8_LAUNCH(1, 8, 9, 1, UNRG); break; // BM 144, BN 128
|
||||
// The untuned default is arm 59's tile (BM 128 x BN 128): 32-34 TFLOP/s on gfx1151 against
|
||||
// 15-19 for libr4d's 4x2 default (see halo_gemm_w4a8_tiled.hip); the bytes are the same.
|
||||
default: HALO_TILED8_LAUNCH(2, 8, 4, 1, UNRG, true); break;
|
||||
}
|
||||
#undef HALO_TILED8_LAUNCH
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in halo_gemm_args.h; see libhalo/halo_args.h.
|
||||
extern "C" int halo_rad_gemm_w8a8_tiled(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (!g.ascale) return HALO_NO(RAD_E_INVAL);
|
||||
if (is_asym(a)) return HALO_NO(RAD_E_UNSUPPORTED);
|
||||
if (g.N % 256) return HALO_NO(RAD_E_SHAPE);
|
||||
if (g.K % HALO_GEMM_W8A8_GROUP) return HALO_NO(RAD_E_SHAPE);
|
||||
HaloTileCfg tv;
|
||||
halo_cfg_tiled(a, &tv);
|
||||
const HaloTileCfg* t = &tv;
|
||||
rc = tile_ok(t, g.N);
|
||||
if (rc != RAD_OK) return rc;
|
||||
HALO_TRY("gemm_w8a8_tiled",
|
||||
halo_gemm_w8a8_tiled(halo_addr(g.a), halo_addr(g.ascale), halo_addr(g.b), halo_addr(g.bscale),
|
||||
halo_addr(g.y), (int)g.M, (int)g.K, (int)g.N, (long)(uintptr_t)s,
|
||||
t->variant));
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
/* Derived from libr4d/r4d_gemm_wpa8i8_tiled.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_gemm_wpa8i8_tiled.hip - gemm_w4a8i8_tiled / gemm_w5a8i8_tiled: the 4- and 5-bit
|
||||
// asymmetric weight x int8 activation GEMM for prefill row counts (ParoQuant int4 / int5).
|
||||
// C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with dequant = scale[n][k/128] * (code - zero[n][k/128]),
|
||||
// the activation int8 with an f32 scale per (row, part, 128 of K).
|
||||
//
|
||||
// The tile machinery is halo_gemm_w4a8_tiled's (128 x 256 blocks, the weight's packed dwords
|
||||
// staged through LDS, the activation staged row-major so a fragment is four consecutive
|
||||
// dwords); what differs is the fragment and the fold:
|
||||
// * the weight byte is (code - zero), formed in the fragment by libr4d's three-op SWAR
|
||||
// subtract, ((codes | 0x80808080) - zero) ^ 0x80808080 per dword -- exact for codes and
|
||||
// zeros in 0..31, so the iu8 WMMA accumulates the corrected product in int32;
|
||||
// * BITS 5 takes the code's fifth bit from the plane after the nibbles (one dword per
|
||||
// (n-tile, 64 of K, lane); byte s = k step s, bit e = fragment element e), spread into
|
||||
// bit 4 of each byte as halo_gemm_w5a16_nt_m64 spreads it;
|
||||
// * the fold is per (row, group): acc += g * (w_scale[col] * a_scale[row][g]).
|
||||
// A partitioned weight (pb1/pb2) is one launch per part over windows of the planes (mx_parts).
|
||||
#include "halo.h"
|
||||
#include "halo_gemm_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_gdn_wmma.h" // accRow: the gfx11 accumulator row mapping
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define HALO_WPT_KPB 64
|
||||
|
||||
typedef int v2i_t __attribute__((ext_vector_type(2)));
|
||||
typedef int v4i_t __attribute__((ext_vector_type(4)));
|
||||
typedef int v8i_t __attribute__((ext_vector_type(8)));
|
||||
typedef float v8f_t __attribute__((ext_vector_type(8)));
|
||||
typedef unsigned u4v_t __attribute__((ext_vector_type(4)));
|
||||
|
||||
__device__ __forceinline__ v8i_t wpt_mmai(v4i_t a, v4i_t b, v8i_t c) {
|
||||
return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, a, true, b, c, false);
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v2i_t wpt_dequant8(unsigned w) {
|
||||
v2i_t r;
|
||||
r[0] = (int)((w << 4) & 0xF0F0F0F0u);
|
||||
r[1] = (int)(w & 0xF0F0F0F0u);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Four code bytes (0..31) with the zero in every byte -> the four bytes of (code - zero). */
|
||||
__device__ __forceinline__ unsigned wpt_sub_zero(unsigned codes4, unsigned zz) {
|
||||
return ((codes4 | 0x80808080u) - zz) ^ 0x80808080u;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ unsigned wpt_spread16(unsigned n) { // 4 bits -> bit 4 of each byte
|
||||
return ((n * 0x00204081u) & 0x01010101u) << 4;
|
||||
}
|
||||
|
||||
/* The fragment from this lane's dword and its cross-half partner's, as in
|
||||
* halo_gemm_w4a8_tiled, with the zero subtracted per byte. */
|
||||
__device__ __forceinline__ v4i_t wpt_step(unsigned w, unsigned pw, int lane, int zero) {
|
||||
const bool hi = lane >> 4;
|
||||
const v2i_t lo = wpt_dequant8(hi ? pw : w);
|
||||
const v2i_t hd = wpt_dequant8(hi ? w : pw);
|
||||
const unsigned zz = (unsigned)zero * 0x01010101u;
|
||||
v4i_t r;
|
||||
r[0] = (int)wpt_sub_zero((unsigned)(lo[0] >> 4) & 0x0F0F0F0Fu, zz);
|
||||
r[1] = (int)wpt_sub_zero((unsigned)(hd[0] >> 4) & 0x0F0F0F0Fu, zz);
|
||||
r[2] = (int)wpt_sub_zero((unsigned)(lo[1] >> 4) & 0x0F0F0F0Fu, zz);
|
||||
r[3] = (int)wpt_sub_zero((unsigned)(hd[1] >> 4) & 0x0F0F0F0Fu, zz);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* BITS 5: hb (this lane's) and phb (the partner's) are the fifth-bit bytes of the two dwords.
|
||||
* Fragment dword d takes its fifth bits from hb's low nibble (d < 2: nibbles 2b) or high
|
||||
* nibble (d >= 2: nibbles 2b+1), as halo_gemm_w5a16_nt_m64's dequant5_pairs reads them. */
|
||||
__device__ __forceinline__ v4i_t wpt_step5(unsigned w, unsigned pw, unsigned hb, unsigned phb,
|
||||
int lane, int zero) {
|
||||
const bool hi = lane >> 4;
|
||||
const v2i_t lo = wpt_dequant8(hi ? pw : w);
|
||||
const v2i_t hd = wpt_dequant8(hi ? w : pw);
|
||||
const unsigned ahb = hi ? phb : hb, bhb = hi ? hb : phb;
|
||||
const unsigned zz = (unsigned)zero * 0x01010101u;
|
||||
v4i_t r;
|
||||
r[0] = (int)wpt_sub_zero(((unsigned)(lo[0] >> 4) & 0x0F0F0F0Fu) | wpt_spread16(ahb & 15u), zz);
|
||||
r[1] = (int)wpt_sub_zero(((unsigned)(hd[0] >> 4) & 0x0F0F0F0Fu) | wpt_spread16(bhb & 15u), zz);
|
||||
r[2] = (int)wpt_sub_zero(((unsigned)(lo[1] >> 4) & 0x0F0F0F0Fu) | wpt_spread16(ahb >> 4), zz);
|
||||
r[3] = (int)wpt_sub_zero(((unsigned)(hd[1] >> 4) & 0x0F0F0F0Fu) | wpt_spread16(bhb >> 4), zz);
|
||||
return r;
|
||||
}
|
||||
|
||||
// WM x WN waves, each owning TM x TN WMMA tiles. BM = WM*TM*16, BN = WN*TN*16. UNR k blocks
|
||||
// (half-groups of 64) are unrolled per scale group of 128.
|
||||
template <int WM, int WN, int TM, int TN, int BITS, int UNR>
|
||||
__global__ __launch_bounds__(WM * WN * 32) void halo_gemm_wpa8i8_tiled_kernel(
|
||||
const signed char* __restrict__ A, const float* __restrict__ Ascale,
|
||||
const unsigned* __restrict__ Wq, const unsigned* __restrict__ Whi,
|
||||
const unsigned* __restrict__ Ws, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int lda, int as_rs, int n0g, int nend) {
|
||||
constexpr int BK = 64; // half a scale group
|
||||
constexpr int GRP = HALO_GEMM_W4A8_GROUP;
|
||||
constexpr int BM = WM * TM * 16, BN = WN * TN * 16;
|
||||
constexpr int NTILE = BN / 16;
|
||||
constexpr int AW = BM * BK / 4; // A dwords per buffer
|
||||
constexpr int WW = NTILE * 128; // W dwords per buffer
|
||||
constexpr int HW = NTILE * 32; // fifth-bit dwords per buffer
|
||||
|
||||
__shared__ unsigned lds_a[2][AW];
|
||||
__shared__ unsigned lds_w[2][WW];
|
||||
__shared__ unsigned lds_h[2][HW];
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int wm = wave / WN, wn = wave % WN;
|
||||
const int m0 = blockIdx.y * BM, n0 = n0g + blockIdx.x * BN;
|
||||
const int kpb = K / HALO_WPT_KPB, nsz = K / GRP;
|
||||
const int ntlast = N / 16 - 1;
|
||||
constexpr int NT_ = WM * WN * 32;
|
||||
|
||||
v8f_t acc[TN][TM];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) acc[j][i] = (v8f_t)(0.f);
|
||||
v8i_t g[TN][TM];
|
||||
unsigned scv[TN];
|
||||
int zero[TN];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++) { scv[j] = 0; zero[j] = 0; }
|
||||
|
||||
#define ASW(r, c) ((r) * (BK / 4) + ((c) ^ ((((r) >> 1) & 7) << 1)))
|
||||
|
||||
constexpr int APT = (AW + NT_ - 1) / NT_, WPT = WW / NT_;
|
||||
constexpr bool APAD = (AW % NT_) != 0;
|
||||
unsigned ra[APT], rw[WPT > 0 ? WPT : 1];
|
||||
constexpr int WPT4 = (WW / 4) / NT_;
|
||||
constexpr bool W128 = WPT4 > 0 && (WW / 4) % NT_ == 0;
|
||||
u4v_t rw4[WPT4 > 0 ? WPT4 : 1];
|
||||
constexpr int HPT = (HW + NT_ - 1) / NT_;
|
||||
unsigned rh[HPT > 0 ? HPT : 1];
|
||||
static_assert(W128 || (WPT > 0 && WW % NT_ == 0), "no W staging path tiles this block shape");
|
||||
auto issue = [&](int kk) {
|
||||
if (W128) {
|
||||
#pragma unroll
|
||||
for (int x = 0; x < WPT4; x++) {
|
||||
const int t = tid + x * NT_, tl = t / 32, off4 = t % 32;
|
||||
const int tg = (n0 / 16 + tl) < ntlast ? (n0 / 16 + tl) : ntlast;
|
||||
rw4[x] = *(const u4v_t*)(Wq + (unsigned)((tg * kpb + kk / HALO_WPT_KPB) * 128 + off4 * 4));
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int x = 0; x < APT; x++) {
|
||||
const int t = tid + x * NT_, r = t / (BK / 4), c = t % (BK / 4);
|
||||
if (APAD && t >= AW) continue;
|
||||
const int mm = m0 + r < M ? m0 + r : M - 1;
|
||||
ra[x] = *(const unsigned*)(A + (size_t)mm * lda + kk + c * 4);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int x = 0; x < WPT && !W128; x++) {
|
||||
const int t = tid + x * NT_, tl = t / 128, off = t % 128;
|
||||
const int tg = (n0 / 16 + tl) < ntlast ? (n0 / 16 + tl) : ntlast;
|
||||
rw[x] = Wq[(unsigned)((tg * kpb + kk / HALO_WPT_KPB) * 128 + off)];
|
||||
}
|
||||
if (BITS == 5) {
|
||||
#pragma unroll
|
||||
for (int x = 0; x < HPT; x++) {
|
||||
const int t = tid + x * NT_;
|
||||
if (t >= HW) continue;
|
||||
const int tl = t / 32, ln = t % 32;
|
||||
const int tg = (n0 / 16 + tl) < ntlast ? (n0 / 16 + tl) : ntlast;
|
||||
rh[x] = Whi[(unsigned)((tg * kpb + kk / HALO_WPT_KPB) * 32 + ln)];
|
||||
}
|
||||
}
|
||||
};
|
||||
auto commit = [&](int buf) {
|
||||
if (W128) {
|
||||
#pragma unroll
|
||||
for (int x = 0; x < WPT4; x++) *(u4v_t*)(lds_w[buf] + (tid + x * NT_) * 4) = rw4[x];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int x = 0; x < APT; x++) {
|
||||
const int t = tid + x * NT_, r = t / (BK / 4), c = t % (BK / 4);
|
||||
if (APAD && t >= AW) continue;
|
||||
lds_a[buf][ASW(r, c)] = ra[x];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int x = 0; x < WPT && !W128; x++) lds_w[buf][tid + x * NT_] = rw[x];
|
||||
if (BITS == 5) {
|
||||
#pragma unroll
|
||||
for (int x = 0; x < HPT; x++) {
|
||||
const int t = tid + x * NT_;
|
||||
if (t < HW) lds_h[buf][t] = rh[x];
|
||||
}
|
||||
}
|
||||
};
|
||||
#define HALO_WS(g_, j_) Ws[(unsigned)((((n0 / 16 + wn * TN + (j_)) < ntlast ? (n0 / 16 + wn * TN + (j_)) : ntlast) * nsz + (g_)) * 16 + (lane & 15))]
|
||||
|
||||
issue(0);
|
||||
commit(0);
|
||||
__syncthreads();
|
||||
|
||||
for (int kg = 0, it = 0; kg < K; kg += BK * UNR) {
|
||||
#pragma unroll
|
||||
for (int h = 0; h < UNR; h++, it++) {
|
||||
const int k0 = kg + h * BK;
|
||||
const int buf = it & 1;
|
||||
if (k0 + BK < K) issue(k0 + BK);
|
||||
|
||||
const bool first_half = (k0 % GRP) == 0;
|
||||
if (first_half) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++) {
|
||||
scv[j] = HALO_WS(k0 / GRP, j);
|
||||
zero[j] = (int)(-__half2float(__ushort_as_half((unsigned short)(scv[j] >> 16))) - 1024.0f);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int u = 0; u < BK / 16; u++) {
|
||||
v4i_t af[TM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) {
|
||||
const int row = (wm * TM + i) * 16 + (lane & 15);
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; d++)
|
||||
af[i][d] = (int)lds_a[buf][ASW(row, u * 4 + d)];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++) {
|
||||
const u4v_t wv = *(const u4v_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 128 + lane * 4);
|
||||
const u4v_t pv = *(const u4v_t*)(lds_w[buf] + (size_t)(wn * TN + j) * 128 + (lane ^ 16) * 4);
|
||||
v4i_t bf;
|
||||
if (BITS == 5) {
|
||||
const unsigned hbw = lds_h[buf][(wn * TN + j) * 32 + lane];
|
||||
const unsigned hbp = lds_h[buf][(wn * TN + j) * 32 + (lane ^ 16)];
|
||||
bf = wpt_step5(wv[u], pv[u], (hbw >> (8 * u)) & 0xffu, (hbp >> (8 * u)) & 0xffu,
|
||||
lane, zero[j]);
|
||||
} else {
|
||||
bf = wpt_step(wv[u], pv[u], lane, zero[j]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++)
|
||||
g[j][i] = (first_half && u == 0) ? wpt_mmai(af[i], bf, (v8i_t)(0))
|
||||
: wpt_mmai(af[i], bf, g[j][i]);
|
||||
}
|
||||
}
|
||||
|
||||
if ((k0 + BK) % GRP == 0) { // the group closed: fold it into the float acc
|
||||
float sc[TN];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
sc[j] = __half2float(__ushort_as_half((unsigned short)(scv[j] & 0xFFFFu)));
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++) {
|
||||
float as[8];
|
||||
const int rb = m0 + (wm * TM + i) * 16;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) {
|
||||
int m = rb + 2 * e + (lane >> 4);
|
||||
m = m < M ? m : M - 1;
|
||||
as[e] = Ascale[(size_t)m * as_rs + k0 / GRP];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++)
|
||||
acc[j][i][e] = fmaf((float)g[j][i][e], sc[j] * as[e], acc[j][i][e]);
|
||||
}
|
||||
}
|
||||
if (k0 + BK < K) commit(buf ^ 1);
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
#undef HALO_WS
|
||||
#undef ASW
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) {
|
||||
const int n = n0 + (wn * TN + j) * 16 + (lane & 15);
|
||||
const int m = m0 + (wm * TM + i) * 16 + accRow(lane, e);
|
||||
if (n < nend && m < M)
|
||||
C[(size_t)m * N + n] = (__hip_bfloat16)acc[j][i][e];
|
||||
}
|
||||
}
|
||||
|
||||
template <int BITS>
|
||||
static void wpa8i8_launch(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
|
||||
int lda, int as_rs, int n0, int n1, long stream) {
|
||||
constexpr int BM = 128, BN = 128;
|
||||
const unsigned* Whi = BITS == 5 ? (const unsigned*)wq + (size_t)N * K / 8 : nullptr;
|
||||
dim3 grid((n1 - n0 + BN - 1) / BN, (M + BM - 1) / BM), block(512);
|
||||
hipLaunchKernelGGL((halo_gemm_wpa8i8_tiled_kernel<4, 4, 2, 2, BITS, 2>), grid, block, 0,
|
||||
(hipStream_t)stream, (const signed char*)a, (const float*)ascale,
|
||||
(const unsigned*)wq, Whi, (const unsigned*)ws, (__hip_bfloat16*)c,
|
||||
M, K, N, lda, as_rs, n0, n1);
|
||||
if (hipGetLastError() != hipSuccess)
|
||||
throw std::runtime_error("r4d gemm_wpa8i8_tiled: launch failed");
|
||||
}
|
||||
|
||||
template <int BITS>
|
||||
static int rad_wpa8i8_tiled(const RadArgs* a, RadStream s, const char* dtype) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (!g.ascale) return HALO_NO(RAD_E_INVAL);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
if (rc != RAD_OK) return rc;
|
||||
const char* dt = halo_gets(a, "dtype");
|
||||
if (!dt || std::strcmp(dt, dtype)) return HALO_NO(RAD_E_DTYPE);
|
||||
if ((g.K % 128) || (g.N % 16)) return HALO_NO(RAD_E_SHAPE);
|
||||
const long long PK = mp.lda > 0 ? mp.lda : g.K; // activation row pitch (elements)
|
||||
const int PG = (int)(PK / 128); // scale groups a row, all parts
|
||||
for (int p = 0; p < mp.n; ++p) {
|
||||
HALO_TRY("gemm_wpa8i8_tiled",
|
||||
wpa8i8_launch<BITS>(halo_addr(g.a) + (long)p * g.K,
|
||||
halo_addr(g.ascale) + (long)p * (g.K / 128) * (long)sizeof(float),
|
||||
halo_addr(g.b), halo_addr(g.bscale), halo_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, (int)PK, PG,
|
||||
(int)mp.n0[p], (int)mp.n1[p], (long)(uintptr_t)s));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int halo_rad_gemm_w4a8i8_tiled(const RadArgs* a, RadStream s) {
|
||||
return rad_wpa8i8_tiled<4>(a, s, "w4a8i8_asym");
|
||||
}
|
||||
extern "C" int halo_rad_gemm_w5a8i8_tiled(const RadArgs* a, RadStream s) {
|
||||
return rad_wpa8i8_tiled<5>(a, s, "w5a8i8");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,173 @@
|
||||
/* Derived from libr4d/r4d_givens_dense.hip by the libhalo rename transform (2026-10-26),
|
||||
* then ported to gfx1151; see libhalo/README.md. */
|
||||
// halo_givens_dense.hip -- ParoQuant's rotation as a dense per-group matrix on the matrix
|
||||
// cores: out[m][j] = sum_i T[j][i] * (x[m][i] / D[i]) per 128-column group, then the
|
||||
// sequential producer's quantiser (int8 at amax / 127, E4M3 at amax / 448).
|
||||
//
|
||||
// The gfx1151 fragment layout is the attention kernels' (halo_dt16.h): a lane holds all
|
||||
// sixteen k of a run, the accumulator's column is lane & 15 (here the output row m) and
|
||||
// its element e is output column j = 2e + (lane>>4). So where the gfx12 kernel reads eight
|
||||
// T values and eight activation values a step, this one reads sixteen of each: the A
|
||||
// fragment is T row (lane & 15) at the step's sixteen i, the B fragment the activation
|
||||
// row's sixteen i divided by D and rounded to f16. A row's 128 outputs sit in lanes col
|
||||
// and col + 16 (the two j parities), so the amax closes with the same 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.
|
||||
#include "halo.h"
|
||||
#include "halo_args.h"
|
||||
#include "halo_common.h"
|
||||
#include "halo_wmma.h"
|
||||
#include "halo_fp8_wmma.h"
|
||||
#include "halo_q8.h"
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t kGroup = 128;
|
||||
constexpr uint32_t kThreads = 128;
|
||||
constexpr uint32_t kWaves = kThreads / 32;
|
||||
constexpr uint32_t kTStride = kGroup + 8; // T row pitch in f16: 16 B pad for conflict-free b128
|
||||
static_assert(kThreads == kGroup, "a thread stages one channel scale of the group (invd[tid])");
|
||||
|
||||
template <bool I8>
|
||||
__global__ __launch_bounds__(kThreads) void givens_dense_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ tdense, const float* __restrict__ rscale,
|
||||
uint8_t* __restrict__ q, float* __restrict__ s, uint32_t M, uint32_t K, uint32_t nkb, uint32_t x_ld,
|
||||
uint32_t q_ld, uint32_t s_ld) {
|
||||
__shared__ uint16_t Tl[kGroup * kTStride];
|
||||
__shared__ float invd[kGroup];
|
||||
const uint32_t gp = blockIdx.x, part = gp / nkb, g = gp % nkb;
|
||||
const uint32_t tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
|
||||
// all sixteen loads in flight before the first LDS store: the staging is latency, not bandwidth
|
||||
const uint4* tg = (const uint4*)(tdense + (size_t)gp * kGroup * kGroup);
|
||||
constexpr uint32_t kStage = kGroup * kGroup / 8 / kThreads;
|
||||
uint4 tv[kStage];
|
||||
#pragma unroll
|
||||
for (uint32_t k = 0; k < kStage; ++k) tv[k] = tg[tid + k * kThreads];
|
||||
#pragma unroll
|
||||
for (uint32_t k = 0; k < kStage; ++k) {
|
||||
const uint32_t i = tid + k * kThreads, j = i / (kGroup / 8), c = i % (kGroup / 8);
|
||||
*(uint4*)&Tl[j * kTStride + c * 8] = tv[k];
|
||||
}
|
||||
invd[tid] = 1.0f / rscale[(size_t)part * K + g * kGroup + tid];
|
||||
__syncthreads();
|
||||
|
||||
const uint32_t h = lane >> 4, col = lane & 15;
|
||||
const uint32_t Mt = (M + 15) >> 4;
|
||||
const uint32_t step = gridDim.y * kWaves;
|
||||
for (uint32_t tile = blockIdx.y * kWaves + wave; tile < Mt; tile += step) {
|
||||
uint32_t m = tile * 16 + col;
|
||||
const bool live = m < M;
|
||||
if (!live) m = M - 1;
|
||||
const uint16_t* xr = x + (size_t)m * x_ld + g * kGroup;
|
||||
v8f acc[8];
|
||||
#pragma unroll
|
||||
for (int jt = 0; jt < 8; ++jt) acc[jt] = (v8f)(0.f);
|
||||
#pragma unroll
|
||||
for (uint32_t ks = 0; ks < 8; ++ks) {
|
||||
const uint32_t c0 = ks * 16;
|
||||
// The B fragment: this row's sixteen activation values at the step, / D, to f16.
|
||||
const uint4 r0 = *(const uint4*)(xr + c0);
|
||||
const uint4 r1 = *(const uint4*)(xr + c0 + 8);
|
||||
const uint32_t w[4] = { r0.x, r0.y, r0.z, r0.w };
|
||||
const uint32_t w2[4] = { r1.x, r1.y, r1.z, r1.w };
|
||||
union { uint32_t u[8]; v16hf f; } bfq;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 16; ++e) {
|
||||
const uint32_t wd = e < 8 ? w[e >> 1] : w2[(e >> 1) & 3];
|
||||
const uint32_t b = (wd >> (16 * (e & 1))) & 0xFFFFu;
|
||||
const float v = __uint_as_float(b << 16) * invd[c0 + e];
|
||||
const _Float16 hv = (_Float16)fminf(fmaxf(v, -65504.0f), 65504.0f);
|
||||
uint16_t hb;
|
||||
__builtin_memcpy(&hb, &hv, 2);
|
||||
if ((e & 1) == 0) bfq.u[e >> 1] = hb;
|
||||
else bfq.u[e >> 1] |= (uint32_t)hb << 16;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int jt = 0; jt < 8; ++jt) {
|
||||
const v16hf af = *(const v16hf*)&Tl[(jt * 16 + col) * kTStride + c0];
|
||||
acc[jt] = halo::mma(af, bfq.f, acc[jt]);
|
||||
}
|
||||
}
|
||||
float amax = 0.0f;
|
||||
#pragma unroll
|
||||
for (int jt = 0; jt < 8; ++jt)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) amax = fmaxf(amax, fabsf(acc[jt][e]));
|
||||
amax = fmaxf(amax, __shfl_xor(amax, 16));
|
||||
const float sc = amax > 0.0f ? amax * (1.0f / q8_top<I8>()) : 1.0f;
|
||||
const float inv = 1.0f / sc;
|
||||
if (!live) continue;
|
||||
if (h == 0) s[(size_t)m * s_ld + (size_t)part * nkb + g] = sc;
|
||||
uint8_t* qr = q + (size_t)m * q_ld + (size_t)part * K + g * kGroup;
|
||||
// Element e of tile jt is output column jt*16 + 2e + h: four consecutive e of one
|
||||
// parity pack as q8_pack4's four values, stored at the strided columns.
|
||||
#pragma unroll
|
||||
for (int jt = 0; jt < 8; ++jt) {
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const float v = acc[jt][e];
|
||||
const uint32_t code = I8
|
||||
? (uint32_t)(uint8_t)(int8_t)(int)rintf(fminf(fmaxf(v * inv, -127.0f), 127.0f))
|
||||
: halo_fp8::f32_to_e4m3(fminf(fmaxf(v * inv, -448.0f), 448.0f));
|
||||
qr[jt * 16 + 2 * e + h] = (uint8_t)code;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// x [M][K] bf16, `x_ld` elements a row (0 = K)
|
||||
// tdense [parts * K/128][128][128] f16, T[j][i] of each (part, group)
|
||||
// rscale [parts][K] f32, the factor the stored row was multiplied by
|
||||
// q [M][parts * K] int8 or E4M3, `q_ld` elements a row (0 = parts * K)
|
||||
// s [M][parts * K/128] f32, `s_ld` elements a row (0 = parts * K/128)
|
||||
enum { GD_X = 0, GD_T = 1, GD_RSCALE = 2, GD_Q = 3, GD_S = 4 };
|
||||
|
||||
extern "C" int halo_rad_givens_dense_quant(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* x = halo_opt(a, GD_X);
|
||||
const RadTensor* t = halo_opt(a, GD_T);
|
||||
const RadTensor* rs = halo_opt(a, GD_RSCALE);
|
||||
const RadTensor* q = halo_opt(a, GD_Q);
|
||||
const RadTensor* sc = halo_opt(a, GD_S);
|
||||
if (!x || !t || !rs || !q || !sc) return HALO_NO(RAD_E_INVAL);
|
||||
if (x->rank < 2 || q->rank != 2 || sc->rank != 2 || t->rank != 2 || rs->rank != 2)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
if (t->dtype != RAD_F16 || rs->dtype != RAD_F32) return HALO_NO(RAD_E_DTYPE);
|
||||
// `out` names the quantiser and q's dtype must be it: a mismatch is refused, not read from q
|
||||
const char* out = halo_gets(a, "out");
|
||||
const bool i8 = q->dtype == RAD_I8;
|
||||
if (!i8 && q->dtype != RAD_F8E4M3) return HALO_NO(RAD_E_DTYPE);
|
||||
if (!out || std::strcmp(out, i8 ? "i8" : "fp8") != 0) return HALO_NO(RAD_E_DTYPE);
|
||||
const long long M = x->shape[0], K = halo_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1);
|
||||
const long long parts = halo_geti_or(a, "parts", 1), nkb = K / kGroup;
|
||||
if (halo_geti_or(a, "group", kGroup) != (long long)kGroup || K % kGroup || parts < 1)
|
||||
return HALO_NO(RAD_E_SHAPE);
|
||||
if (q->shape[0] != M || q->shape[1] != parts * K) return HALO_NO(RAD_E_SHAPE);
|
||||
if (sc->shape[0] != M || sc->shape[1] != parts * nkb) return HALO_NO(RAD_E_SHAPE);
|
||||
// tdense is a packed blob: its byte count is the layout hook's ([parts * K, 128] f16), not a shape to check
|
||||
if (rs->shape[0] != parts || rs->shape[1] != K) return HALO_NO(RAD_E_SHAPE);
|
||||
if (!halo_aligned(t->data, 16) || !halo_aligned(x->data, 16) || !halo_aligned(q->data, 8))
|
||||
return HALO_NO(RAD_E_ALIGN);
|
||||
const long long xp = halo_row_pitch(x), qp = halo_row_pitch(q), sp = halo_row_pitch(sc);
|
||||
if (xp < 0 || qp < 0 || sp < 0 || (xp * 2) % 16) return HALO_NO(RAD_E_STRIDE);
|
||||
const long long mt = (M + 15) / 16;
|
||||
const uint32_t gy = (uint32_t)std::max<long long>(1, (mt + 4 * kWaves - 1) / (4 * kWaves));
|
||||
const dim3 grid((uint32_t)(parts * nkb), gy);
|
||||
if (i8)
|
||||
givens_dense_kernel<true><<<grid, dim3(kThreads), 0, (hipStream_t)stream>>>(
|
||||
(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);
|
||||
else
|
||||
givens_dense_kernel<false><<<grid, dim3(kThreads), 0, (hipStream_t)stream>>>(
|
||||
(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);
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
Loaded 100 of 452 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user