merge origin/main: the upstream LoRA-runtime refactor beneath the ref2va port

Merges upstream 1.10.0 (152 commits: the LoRA acquire/runtime refactor, the
form-1 LTX-2 scheduler family, guidance terms + negative prompts, decoder
selection, input_reference, new architectures) into the ref2va port branch.
Resolution rule throughout: keep BOTH feature sets; ABI numbering follows
upstream (RAD_ABI_VERSION 26, RAD_FORMAT_VER 2), with the port's video fields
unioned into RadVideoGenBatch/RadVideoGenDecl and abi_layout_table.h
regenerated from the live table.

Notable reconciliations:
  * videos.cpp: the task grammars are disjoint by capability -- keyframe tasks
    (i2va/l2va/flash-attn l2va/fl2va) are recognized only when decl.encodes,
    so upstream models keep refusing them as unknown tasks; input_reference,
    the LoRA tag/field pipeline, and the guidance/negative_prompt rendering
    coexist with refs/ref2va; the prompt put() helper hoisted to block scope
    for the media branch.
  * video_schedule(): upstream's (steps, video_tokens, refine) keeps its
    positional slots; the port's shift_video/shift_audio overrides move to the
    tail so upstream's schedule tests call unchanged.
  * r4d_selftest conv3d cases: the port's sp/st/causal/down/refl geometry and
    upstream's tpad/tpre fold into one reference (ft = causal ? 2 : tpad==2 ?
    2+tpre : 1); rms_mod rows keep the port's i8/fp8 quant modes alongside
    upstream's wadd/norm_once/norm parameters.
  * tests/oot_plugins.sh: the per-plugin cmake --install gains a --prefix
    staging dir -- plugin .so files still land in the absolute
    RAD_PLUGIN_INSTALL_HOME, but libr4d now also installs r4d_selftest to a
    relative bin/, which needs no root.

Host ctest: 112/113 (mm_test's webp gap pre-exists this merge); r4d_selftest,
engine_e2e, oot_plugins, abi_layout, all LoRA tests green.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
gearwave00001andClaude committed 2026-10-22 18:38:04 -05:00
commit a1a75da7e9
415 files changed
+78837 -5310

No files matched your search

+18
View File
@@ -44,6 +44,8 @@ set(R4D_UNITS
# Gemma 4 dense sliding window: head_dim 256, 2 queries per KV head, windowed decode and
# prefill.
"r4d_attn_paged_h256_gqa2|"
# Gemma 3 sliding window: head_dim 128, 2 queries per KV head, windowed decode and prefill.
"r4d_attn_paged_h128_gqa2w|"
# Eight queries per KV head, one body instantiated at head_dim 256 (the routed 35B-A3B) and 128
# (MiniCPM5-2B).
"r4d_attn_paged_gqa8|"
@@ -79,6 +81,7 @@ set(R4D_UNITS
# decoder's patch unfold, tiles, stitch and rotary positions, and the soundtrack decoder's
# alias-free SnakeBeta.
"r4d_video|"
"r4d_ltx|"
# A video latent upscaler: the 3x3x3 convolution as an implicit GEMM over voxel rows, the group
# norm, the temporal depthwise convolution, the per-frame bilinear resize, the patch fold and the
# re-noise.
@@ -101,6 +104,13 @@ set(R4D_UNITS
# launches behind one entry point: the mix depends on every column of the low-rank waist, so it
# needs a grid-wide barrier.
"r4d_hc_bf16|"
"r4d_mhc|"
"r4d_glm|"
"r4d_dsa|"
"r4d_mla|"
"r4d_kda|"
"r4d_moe_mxfp4|"
"r4d_fp8_f32scale|"
"r4d_ngram_ids|"
"r4d_ple_gate_bf16|"
"r4d_ple_conv_bf16|"
@@ -151,6 +161,10 @@ set(R4D_UNITS
"r4d_quant_act_i8|"
"r4d_rmsnorm_quant_i8|"
"r4d_qkv_norm_rope|"
# A batch's context lengths less a runtime trim (the 31B's per-slice prefill attention).
"r4d_kv_len_trim|"
# A weight read into the on-die cache beside a collective (the prefetch op).
"r4d_prefetch|"
"r4d_gelu_mul_quant_i8|"
"r4d_had_quant_act_i8|"
"r4d_rmsnorm_had_quant_i8|"
@@ -213,6 +227,10 @@ add_executable(r4d_selftest ${CMAKE_CURRENT_SOURCE_DIR}/r4d_selftest.cpp)
target_link_libraries(r4d_selftest PRIVATE radiance::abi ${CMAKE_DL_LIBS} ${RAD_HIP_RUNTIME})
target_include_directories(r4d_selftest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
set_target_properties(r4d_selftest PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
# Installed beside the tools, so the image can run the rows' own card checks without a build tree:
# r4d_selftest /opt/radiance/share/radiance/kernels/libr4d.so [--case <row>]
# The collective cases need every card of the box in the container.
install(TARGETS r4d_selftest RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
# C++17: at C++20 clang tightens the address-space check on
# __builtin_amdgcn_global_load_tr_b128_v8i16 in r4d_common.h. Kernel cost figures are for C++17.
+105 -10
View File
@@ -65,6 +65,23 @@ struct R4DArgs {
// null.
const int* cu_q; // (num_seqs+1,) int32 device, or null for a uniform q_len
int total_q; // rows of q/out; ignored unless cu_q is set
// ---- Views the split-KV decode kernel reads (r4d_attn_decode_h256_gqa6.hip); every other
// kernel leaves them at zero and reads q dense with one cache head per query group.
//
// `q_ld` is the element distance between q rows, 0 for dense (q_heads * head_dim): the q part
// of a fused [q|k|v] projection read where it lies (attn_paged_qrow). A multiple of 4.
//
// `kv_rep` maps query groups onto cache heads: group g (q heads g*GQA .. g*GQA+GQA-1) reads
// cache head g / kv_rep, and the descales are per cache head. kv_heads then counts the groups
// (q_heads / GQA) and the cache holds kv_heads / kv_rep heads. 0 or 1 is one head a group. It
// runs a gqa of GQA * kv_rep on the kernel compiled for GQA, whose workgroup holds at most 64
// rows of q_len * GQA: the 31B's DFlash drafter, gqa 8 at a block of 16, on the gqa-4 kernel.
long q_ld;
int kv_rep;
// The engine's chained launch (RadKernelChainFn, r4d_chain.h): the decode path launches its
// chained forms. fill_paged sets it from the resolved `chain` parameter.
int chain;
};
// Rows of q and out. The split-KV scratch is laid out by dense query row, so the host sizing hook
@@ -89,6 +106,9 @@ int r4d_attn_decode_h256_gqa6_bf16kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa4_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa4_bf16kv (const R4DArgs* a, hipStream_t stream);
long r4d_attn_decode_h128_gqa4_scratch_bytes(const R4DArgs* a);
// ...with R4DArgs::kv_rep and q_ld read: a gqa of 4 * kv_rep over a cache of kv_heads / kv_rep.
int r4d_attn_decode_h128_gqa4_rep_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa4_rep_bf16kv (const R4DArgs* a, hipStream_t stream);
// Bytes of split-KV partial buffer one decode launch of this shape needs. Independent of the cache
// dtype: the partials are f16 either way.
long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a);
@@ -100,6 +120,15 @@ int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_bf16kv (const R4DArgs* a, hipStream_t stream);
long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a);
/* Gemma 3 sliding window (r4d_attn_paged_h128_gqa2w.hip): head_dim 128, gqa 2, window >= 1. */
int r4d_attn_prefill_h128_gqa2w_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_prefill_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa2w_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa2w_bf16kv (const R4DArgs* a, hipStream_t stream);
long r4d_attn_decode_h128_gqa2w_scratch_bytes(const R4DArgs* a);
// ...with q at R4DArgs::q_ld (attn_paged_qrow).
int r4d_attn_decode_h256_gqa2_qld_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_qld_bf16kv (const R4DArgs* a, hipStream_t stream);
// The geometry the attention kernels above are compiled for, so a caller can check a model
// before the first launch.
void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows);
@@ -230,7 +259,8 @@ int r4d_gdn_recurrent_update_k128_v128_bf16_fp32state(
// zeroed words, a handshake and a slot-parity counter per block of capacity (r4d_ar_seq.h).
enum { R4D_AR_HANDLE_BYTES = 64 };
// IPC scratch helpers, startup-only: alloc returns the device pointer and writes the IPC handle
// (up to HANDLE_BYTES) into out_handle.
// (up to HANDLE_BYTES) into out_handle. A refused export (beside another engine on the same cards)
// leaves it zeroed with *out_len 0: libr4d's ranks are threads of one process and share the pointer.
long r4d_ar_ipc_alloc(long size, int finegrained, char* out_handle, int* out_len);
// Strided peer (or local) device-to-device copy through the copy engines; pitches and width in
// bytes, height in rows. Returns 0 or -100 - hipError_t.
@@ -302,7 +332,8 @@ void r4d_ar_wht6_dims(int* group, int* bits, int* chunk_elems); // rotated-6-bit
void r4d_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, long nblocks,
long nthreads, long drain, long acq);
long nthreads, long drain, long acq, long dpitch,
long spitch);
// ---- all-reduce: one-shot, push, 4 or 8 ranks over P2P -------------------------------------
// The same algorithm at width (r4d_ar_oneshot_Nrank_exact.hip). Peer arguments are in ascending
@@ -336,7 +367,8 @@ void r4d_ar_gather_3rank(long peer_scratch0, long peer_scratch1, long peer_flags
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 drain, long acq, long pub, long dpitch,
long spitch);
void r4d_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,
@@ -380,11 +412,15 @@ void r4d_ar_wide_dims(int* max_blocks, int* nb_design, int* max_peers);
// rank s (fp32, ascending rank order), then gathered. Sends 2*(ws-1)/ws*N bytes per rank in two
// hops, for sizes where the one-shot's (ws-1)*N send is too heavy. Shards are as even as the word
// count allows (the first n16 % ws take one more word), so the message need not divide by the
// rank count. Regions A and B sit at 0 and the longest shard, so the slot stride must hold twice
// that. Above the bound below the caller falls back to the one-shot; it only guards the kernel's
// int word offsets (2^28 elements is 2^26 words at fp32). A lower bound would send large prefill
// rank count. At 8 ranks `shard_weights` (8 ints, or null for the even split) sizes the shards per
// rank instead (r4d_ar_shards.h); every rank must pass the same weights. Regions A and B sit at 0
// and the longest shard, so the slot stride must hold twice that. `pieces` (8 ranks, 1 to
// R4D_AR_TS_MAX_PIECES, the same on every rank) pipelines each block's words in that many runs so
// phase 1 of one run and phase 2 of the previous share the link; 1 is the unpipelined kernel.
// Above the bound below the caller falls back to the one-shot; it only guards the kernel's int
// word offsets (2^28 elements is 2^26 words at fp32). A lower bound would send large prefill
// chunks (e.g. 8192 tokens at Gemma 4's 2816 width, 23M-46M elements) to the one-shot.
enum { R4D_AR_TWOSHOT_WIDE_MAX_ELEMS = 268435456 };
enum { R4D_AR_TWOSHOT_WIDE_MAX_ELEMS = 268435456, R4D_AR_TS_MAX_PIECES = 16 };
void r4d_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,
@@ -395,7 +431,18 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee
long my_scratch, long my_flags, long seq_ctrs,
long slot_stride16, long inp, long out, long n_elem, long dtype,
long rank, long stream, long nblocks, long nthreads, long drain,
long acq, long pub, long gate, long gate_ctr);
long acq, long pub, long gate, long gate_ctr, long chain);
// The four-rank exact two-shot with both pushes coded losslessly at ~12.2 bits a bf16 value (the
// same bytes out; r4d_ar_twoshot_Nrank_exact.hip). r4d_ar_twoshot_coded_ok says whether a message
// and slot fit the coded form: bf16, shards of whole 256-value waves, two coded regions a slot.
int r4d_ar_twoshot_coded_ok(long n_elem, long dtype, long world, long slot_stride16);
void r4d_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);
void r4d_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,
@@ -403,7 +450,13 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee
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);
long nblocks, long nthreads, long drain, long acq, long pub,
const int* shard_weights, long pieces, long timeline,
long form);
// `form` is R4D_AR8_FORM_* (r4d_ar_shards.h), the same on every rank: lockstep, ring or split,
// all with the same bits. `timeline`, a diagnostic, is 0 or a device buffer of nblocks * R4D_AR_TL_WORDS int64 that every
// block of the eight-rank two-shot fills with wall-clock stamps (r4d_ar_wide.h): its start, each
// handshake's arrival and release, its end. r4d_selftest --perfar8 with --timeline reads it.
// The tiered int8 wire on both two-shot hops (r4d_ar_twoshot_Nrank_ti8.hip; codec in
// r4d_ar_ti8.h), 3 or 4 ranks. Int8 groups of 32 with an fp16 scale and a per-group record
// (T1 plain, T2 top-1-exact, T3 wht32), 38 bytes/group; tiering is deterministic and
@@ -631,6 +684,10 @@ void r4d_moe_gemm_pin_down_dec(int pin);
// (refused likewise, and below 512 rows, whose scratch is not sized for their weight planes).
// All bit-identical; r4d_selftest compares their bytes.
void r4d_hc_read_pin_prefill(int form);
// Test hook: pins the MLA matrix row's key load. 0 is the launcher's rule (sixteen-byte vectors
// wherever the cache rows are aligned to them), 1 the element-wise load the rule falls back to.
// Bit-identical; r4d_selftest compares them and --perfmla times both.
void r4d_mla_matrix_pin_form(int form);
// Test hook: records the function each launch dispatches into `fns[0..cap)`, in order, until the
// next call, and returns how many launches the previous recording saw (which may exceed its cap).
// Null `fns` stops recording. r4d_selftest uses it to show that a pinned form dispatches a kernel
@@ -697,6 +754,15 @@ int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, long s, int
int q_ld, int s_ld, long stream);
int r4d_gated_quant_fp8(long gu, long y, long q, long s, int M, int n, int mode,
int gu_ld, int y_ld, int q_ld, int s_ld, long stream);
// The two above with had_quant_act_i8g's quantiser on the pass instead (the `_had_quant_i8g`
// forms): the width-128 Hadamard, then int8 codes at amax / 127 per (row, 128), for a weight at
// i8a8h. `q` is int8, `n` a multiple of 128, and `y` keeps the unrotated bf16 value. The codes
// are the producer + had_quant_act_i8g pair's bytes.
int r4d_rmsnorm_had_quant_i8g(long x, long res, long w, long y, long q, long s, int M, int n,
float eps, float wadd, int w_f32, int x_ld, int r_ld, int y_ld,
int q_ld, int s_ld, long stream);
int r4d_gated_had_quant_i8g(long gu, long y, long q, long s, int M, int n, int mode,
int gu_ld, int y_ld, int q_ld, int s_ld, long stream);
// The activation is rounded to bf16 before the product, matching the unfused `sigmoid` then `mul`
// pair with a bf16 buffer between them.
// The same epilogue with the gate in a different buffer from what it scales, as in gated
@@ -720,8 +786,17 @@ int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flag
int M, int n, float eps, float wadd, int w_f32,
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq, int wire,
long loc_pack, long loc_scale_off);
long loc_pack, long loc_scale_off, long wp = 0);
int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void);
// Its rotated int8 form, as r4d_rmsnorm_had_quant_i8g: the reduction and the norm unchanged, the
// norm's pass quantised by had_quant_act_i8g's rule. No post-norm.
int r4d_ar_rmsnorm_had_quant_i8g(long peer_scratch, long my_scratch, long peer_flags,
long my_flags, long seq_ctrs, long slot_stride16,
long x, long res, long w, long y, long q, long s,
int M, int n, float eps, float wadd, int w_f32,
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq, int wire,
long loc_pack, long loc_scale_off);
// The same IPC with the sandwich-norm junction after it (r4d_rmsnorm_quant_i8.hip): post-norm of
// the reduced `x` (`wp`), the residual add, the [1] scalar (`sc`), the norm (`w`) and the w4a8
@@ -731,6 +806,22 @@ int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags
long sc, int sc_f32, long y, long q, long s, int M, int n, float eps,
float wadd, int w_f32, int r_ld, int y_ld, long stream, int nblocks,
int drain, int acq);
// ...and at four ranks, on the wide family's transport: r4d_ar_oneshot_4rank_exact's IPC
// arguments (peers in ascending rank, this rank's own, the counters, the slot stride), `pub`, the
// engine's link gate with the instance's landed counter (0 for none; r4d_ar_seq.h), and, with
// `tail_nbt` blocks (positive), the standalone two-shot on that many with the junction as its tail,
// counting on the two words at `tail_ctr` (ar_rmsnorm_quant_i8_tail_kernel). With `sp` 1 or 2 the
// all-reduce split around the junction instead (ar_rmsnorm_quant_i8_sp_kernel): q and S on every
// row, the residual on this rank's rows (every row at 2), `x` left as it came.
int r4d_ar_rmsnorm_quant_i8_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 x, long res, long w, long wp, long sc,
int sc_f32, long y, long q, long s, int M, int n, float eps,
float wadd, int w_f32, int r_ld, int y_ld, int rank,
long stream, int nblocks, int drain, int acq, int pub,
long gate, long gate_ctr, long tail_ctr, int tail_nbt,
int chain, int sp);
// ---- sampling ----------------------------------------------------------------------------------
//
@@ -853,6 +944,7 @@ int r4d_binary_bf16(long a, long b, long y, int M, int n, int op,
int a_ld, int b_ld, int y_ld, long stream);
int r4d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long stream);
int r4d_fill_f32(long y, int M, int n, int y_ld, float value, long stream);
// y[.., i] = silu(gu[.., i]) * gu[.., n + i]. The gate is the first half, the order rad-convert
// fuses gate_proj and up_proj in.
int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream);
@@ -878,6 +970,9 @@ int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
// that compares neighbouring probabilities. K must be a multiple of 8.
int r4d_logits_gemm_bf16(long a, long w, long c, int M, int K, int N, int a_ld, int c_ld,
long stream);
// The same bytes from a wave per four vocabulary columns; K must be 4096.
int r4d_logits_gemm_bf16_cols(long a, long w, long c, int M, int K, int N, int a_ld, int c_ld,
long stream);
// Scatter into kv_cache[n_blocks, kv_heads, block_size, 2*head_dim]: K at [.., d], V at
// [.., head_dim + d], slot decomposing as block = slot / block_size, offset = slot % block_size.
int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim, int kv_heads,
+536 -61
View File
@@ -20,6 +20,8 @@
#include "r4d_args.h"
#include "r4d.h"
#include "r4d_ar_shards.h"
#include "r4d_ar_links.h"
#include <condition_variable>
#include <cstdio>
@@ -33,6 +35,8 @@
static_assert(R4D_AR_TWOSHOT_WIDE_MAX_ELEMS == 268435456,
"r4d_rows.cpp restates this bound; libr4d changed it");
static_assert(R4D_MAX_RANKS == 8, "the 8-rank entry point names exactly seven peers");
static_assert((long long)R4D_AR8_MIN_ELEMS_MAX == (long long)R4D_AR_TWOSHOT_WIDE_MAX_ELEMS,
"r4d_ar_shards.h restates the two-shot band's top");
/* ------------------------------------------------------------------ throw conversion
*
@@ -68,6 +72,16 @@ struct Rendezvous {
long flags [R4D_MAX_RANKS] = { 0 };
long seq [R4D_MAX_RANKS] = { 0 };
int dev [R4D_MAX_RANKS] = { 0 };
/* What each rank read for the eight-rank two-shot: settings that must agree, and its own
* card's link, which the weights are derived from. */
struct Ar8Seen {
int mode = 0;
int w[R4D_MAX_RANKS] = { 0 };
int pieces = 0;
long long weights_min = 0, pieces_min = 0;
int form = 0;
R4DArLink link;
} ar8[R4D_MAX_RANKS];
int failed = 0;
};
@@ -111,6 +125,18 @@ struct ArInst {
* each card reaches over its own link (see build). */
int host = 0;
long gate_ctr = 0; /* the blocks that have seen their peer's bytes land (r4d_ar_seq.h) */
/* The eight-rank two-shot's per-rank shard weights (r4d_ar_shards.h), fixed at build so the
* scratch was sized for them and a recorded launch keeps its table. */
int shard_weighted = 0;
int shard_w[R4D_MAX_RANKS] = { 0 };
/* Its piece count (RADIANCE_AR8_PIECES), 0 for the size rule (r4d_ar8_auto_pieces); a launch's
* `pieces` parameter overrides it. */
int pieces = 0;
/* Messages under these sizes (elements) run even and in one piece, whatever is configured. */
long long weights_min = R4D_AR8_MIN_ELEMS_DEFAULT;
long long pieces_min = R4D_AR8_MIN_ELEMS_DEFAULT;
/* Its form (RADIANCE_AR8_FORM); a launch's `form` parameter overrides it. */
int form = R4D_AR8_FORM_LOCKSTEP;
};
/* A parameter that may be declared as a range: init gets one band's frozen geometry, and buffers
@@ -127,6 +153,191 @@ long long pgeti_hi(const RadParam* p, int n_p, const char* k, long long dflt) {
long align16(long v) { return (v + 15) & ~15L; }
/* RADIANCE_AR8_SHARD_WEIGHTS, read at every eight-rank build so a process can change it between
* instances: unset or "auto" derives the weights from the links by r4d_ar_weights_from_rates,
* "duplex" from the same links by r4d_ar_weights_duplex, "off" keeps the shards even, eight
* integers set them. Anything else is "off", with one warning. */
enum { AR8_EVEN = 0, AR8_SET = 1, AR8_AUTO = 2, AR8_DUPLEX = 3 };
int ar8_weights_mode(int* w) {
const char* e = std::getenv(R4D_AR8_SHARD_WEIGHTS_ENV);
if (!e || !*e || !std::strcmp(e, "auto")) return AR8_AUTO;
if (!std::strcmp(e, "duplex")) return AR8_DUPLEX;
if (!std::strcmp(e, "off")) return AR8_EVEN;
if (r4d_ar_shard_weights_parse(e, 8, w)) return AR8_SET;
static std::once_flag said;
std::call_once(said, [e] {
std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs auto, off or eight non-negative "
"integers, comma-separated, sum > 0, or duplex); eight-rank two-shot shards "
"stay even\n",
R4D_AR8_SHARD_WEIGHTS_ENV, e);
});
return AR8_EVEN;
}
/* This rank's card's slowest PCIe hop, from sysfs by the runtime's bus id. */
bool ar8_own_link(R4DArLink* l) {
int dev = 0;
char bus[64] = { 0 };
if (hipGetDevice(&dev) != hipSuccess ||
hipDeviceGetPCIBusId(bus, (int)sizeof bus, dev) != hipSuccess)
return false;
unsigned dom = 0, b = 0, d = 0, f = 0;
if (std::sscanf(bus, "%x:%x:%x.%x", &dom, &b, &d, &f) != 4) return false;
char bdf[32];
std::snprintf(bdf, sizeof bdf, "%04x:%02x:%02x.%x", dom, b, d, f);
return r4d_ar_link_bottleneck("", bdf, l);
}
/* RADIANCE_AR8_PIECES and the two size floors, read like the weights. */
int ar8_pieces() {
const char* e = std::getenv(R4D_AR8_PIECES_ENV);
if (!e || !*e) return 0;
long long v = 0;
if (!r4d_ar_parse_count(e, R4D_AR_TS_MAX_PIECES, &v) || v < 1) {
static std::once_flag said;
std::call_once(said, [e] {
std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs 1..%d); the eight-rank "
"two-shot takes its piece count from the message size\n",
R4D_AR8_PIECES_ENV, e, (int)R4D_AR_TS_MAX_PIECES);
});
return 0;
}
return (int)v;
}
long long ar8_min_elems(const char* name, std::once_flag* said) {
const char* e = std::getenv(name);
if (!e || !*e) return R4D_AR8_MIN_ELEMS_DEFAULT;
long long v = 0;
if (!r4d_ar_parse_count(e, R4D_AR8_MIN_ELEMS_MAX, &v)) {
std::call_once(*said, [name, e] {
std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs 0..%d elements); using %d\n",
name, e, (int)R4D_AR8_MIN_ELEMS_MAX,
(int)R4D_AR8_MIN_ELEMS_DEFAULT);
});
return R4D_AR8_MIN_ELEMS_DEFAULT;
}
return v;
}
/* RADIANCE_AR8_FORM: lockstep (or unset), ring or split. Anything else is lockstep, with one
* warning. */
int ar8_form() {
const char* e = std::getenv(R4D_AR8_FORM_ENV);
if (!e || !*e) return R4D_AR8_FORM_LOCKSTEP;
const int f = r4d_ar8_form_parse(e);
if (f >= 0) return f;
static std::once_flag said;
std::call_once(said, [e] {
std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs lockstep, ring or split); the "
"eight-rank two-shot runs in lockstep\n", R4D_AR8_FORM_ENV, e);
});
return R4D_AR8_FORM_LOCKSTEP;
}
/* The eight-rank two-shot's choice for one message, a function of its size and the instance
* alone: a recorded launch keeps the table and piece count it was recorded with, and replays of
* the same size agree with it. */
const int* ar8_weights_for(const ArInst* in, long numel) {
return in->shard_weighted && numel >= in->weights_min ? in->shard_w : nullptr;
}
long long ar8_pieces_for(const ArInst* in, long numel, long long asked) {
if (numel < in->pieces_min) return 1;
return asked > 0 ? asked : r4d_ar8_auto_pieces(numel);
}
/* The eight-rank two-shot's settings, agreed before anything is sized: each rank publishes what
* it read and its own card's link, and after one barrier every rank derives the same weights from
* the same eight entries. Settings that differ between ranks would cut the message at different
* words or take different handshake steps; all ranks compare the same entries, so all refuse
* together. */
int ar8_settle(ArInst* in, int rank, int world) {
static std::once_flag said_w, said_p, said_links, said_unknown, said_set;
Rendezvous::Ar8Seen me;
me.mode = ar8_weights_mode(me.w);
me.pieces = ar8_pieces();
me.weights_min = ar8_min_elems(R4D_AR8_SHARD_WEIGHTS_MIN_ENV, &said_w);
me.pieces_min = ar8_min_elems(R4D_AR8_PIECES_MIN_ENV, &said_p);
me.form = ar8_form();
if ((me.mode == AR8_AUTO || me.mode == AR8_DUPLEX) && !ar8_own_link(&me.link))
me.link = R4DArLink();
{
std::lock_guard<std::mutex> lk(g_rv.m);
g_rv.ar8[rank] = me;
}
const int rc = rv_barrier(world);
if (rc != RAD_OK) return rc;
const Rendezvous::Ar8Seen* all = g_rv.ar8;
for (int r = 0; r < world; ++r)
if (all[r].mode != me.mode || std::memcmp(all[r].w, me.w, sizeof(me.w)) ||
all[r].pieces != me.pieces || all[r].weights_min != me.weights_min ||
all[r].pieces_min != me.pieces_min || all[r].form != me.form) {
std::fprintf(stderr, "[r4d] ranks %d and %d read different eight-rank two-shot "
"settings (%s, %s and their _MIN_ELEMS, %s)\n", rank, r,
R4D_AR8_SHARD_WEIGHTS_ENV, R4D_AR8_PIECES_ENV, R4D_AR8_FORM_ENV);
return RAD_E_STATE;
}
in->pieces = me.pieces;
in->weights_min = me.weights_min;
in->pieces_min = me.pieces_min;
in->form = me.form;
if (me.form != R4D_AR8_FORM_LOCKSTEP) {
static std::once_flag said_form;
const int f = me.form;
std::call_once(said_form, [f] {
std::fprintf(stderr, "[r4d] eight-rank two-shot form: %s (%s)\n",
f == R4D_AR8_FORM_RING ? "ring" : "split", R4D_AR8_FORM_ENV);
});
}
int w[R4D_MAX_RANKS] = { 0 };
if (me.mode == AR8_SET) {
std::memcpy(w, me.w, sizeof(w));
std::call_once(said_set, [&w] {
std::fprintf(stderr, "[r4d] eight-rank two-shot shards weighted "
"%d,%d,%d,%d,%d,%d,%d,%d (%s)\n", w[0], w[1], w[2], w[3], w[4], w[5],
w[6], w[7], R4D_AR8_SHARD_WEIGHTS_ENV);
});
} else if (me.mode == AR8_AUTO || me.mode == AR8_DUPLEX) {
double gbs[R4D_MAX_RANKS] = { 0 };
for (int r = 0; r < world; ++r) gbs[r] = r4d_ar_link_gbs(all[r].link);
const bool known = me.mode == AR8_DUPLEX ? r4d_ar_weights_duplex(gbs, world, w)
: r4d_ar_weights_from_rates(gbs, world, w);
if (!known) {
std::call_once(said_unknown, [all, world] {
std::string who;
for (int r = 0; r < world; ++r)
if (r4d_ar_link_gbs(all[r].link) <= 0.0) who += " " + std::to_string(r);
std::fprintf(stderr, "[r4d] eight-rank two-shot: no PCIe link speed in sysfs for "
"rank%s; shards stay even\n", who.c_str());
});
return RAD_OK;
}
const bool duplex = me.mode == AR8_DUPLEX;
std::call_once(said_links, [all, world, duplex, &w] {
std::string l;
for (int r = 0; r < world; ++r) {
char one[96];
std::snprintf(one, sizeof one, "%s r%d %.1f GT/s x%d %.1f GB/s w%d",
r ? "," : "", r, all[r].link.gts, all[r].link.width,
r4d_ar_link_gbs(all[r].link), w[r]);
l += one;
}
std::fprintf(stderr, "[r4d] eight-rank two-shot shard weights from the slowest PCIe "
"hop of each card%s:%s\n", duplex ? " (duplex)" : "", l.c_str());
});
bool same = true;
for (int r = 1; r < world; ++r) same = same && w[r] == w[0];
if (same) return RAD_OK; /* equal links: the even split, on the unweighted path */
} else {
return RAD_OK;
}
in->shard_weighted = 1;
std::memcpy(in->shard_w, w, sizeof(in->shard_w));
return RAD_OK;
}
/* Sequence counter allocation in words: 2 * nbw (r4d_ar_seq.h), then r4d_ar_link_landed's block
* counter, padded to a cache line. */
long kSeqWords(long nbw) { return 2L * nbw + 32; }
@@ -136,7 +347,9 @@ long kSeqWords(long nbw) { return 2L * nbw + 32; }
* One sizing rule for the whole family: a slot holds a full message. The one-shots need exactly
* that; the two-shot's two regions (2 * message / world_size) and the tiered-int8 wire's two
* images (2 * ceil(shard/32) * 38 bytes) are smaller. RadInitFn is not told which row resolved,
* so sizing for the maximum avoids reconstructing which kernel this instance serves.
* so sizing for the maximum avoids reconstructing which kernel this instance serves. The one
* exception is a weighted eight-rank two-shot whose largest weight is over half the sum: its two
* regions of the longest shard outgrow a message, and the slot grows to hold them.
*
* Cost: at a 4096-token chunk on a 5120-wide residual, 40 MiB a slot and 80 MiB for the pair. One
* set serves every op with the same (rank, world, dtype, bound); see the cache below. */
@@ -153,6 +366,19 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
in->max_numel = (long)max_numel;
in->slot_bytes = align16((long)max_numel * in->esize);
in->slot16 = in->slot_bytes / 16;
if (world == 8) {
const int rc8 = ar8_settle(in, rank, world);
if (rc8 != RAD_OK) return rc8;
}
if (in->shard_weighted) {
const long need16 =
2 * r4d_ar_shard_max_bound((long)max_numel * in->esize / 16, 8, in->shard_w);
/* Sized only if some message this instance carries is weighted. */
if (max_numel >= in->weights_min && need16 > in->slot16) {
in->slot16 = need16;
in->slot_bytes = need16 * 16;
}
}
int maxb = 0, nb_design = 0, max_peers = 0;
if (world == 2) {
@@ -163,11 +389,29 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
}
if (maxb <= 0) return RAD_E_DEVICE;
in->max_blocks = maxb;
/* R4D_AR_MAX_BLOCKS: a ceiling on every collective's block count, for two engines sharing one
* set of cards. Each block of a collective spins until its twin on the peer card has pushed, and
* a prefill-sized ar_rmsnorm_quant_fp8 launches up to 256 blocks of 16 waves, twice what an
* R9700 holds. One engine survives that (both cards dispatch blocks in the same order, so the
* lowest unfinished block is resident on both); two engines do not: one engine's spinning blocks
* fill a card while their twins wait behind the other engine's kernel on the peer card, which
* waits for a slot on the full card. Not capped: the hyper-connection gathers of the MoE paths
* (r4d_ar_gather_hc_write without its inverse scratch, r4d_ar_hc_write_wht6), whose LDS table
* needs a minimum block count, which may exceed the ceiling (dense models do not use them).
* Two TP2 engines on two R9700s (Qwen3.8-27B and Gemma 3 27B) hung within a minute of
* concurrent prefill; MES then failed to evict the queues and the failed reset froze the
* host. Capped in both engines so that their spinners together cannot
* fill a card, the cycle cannot close. The flag and counter arrays keep their full size (maxb);
* only the launch counts shrink, and each element's sum is the same. Unset, nothing changes. */
if (const char* e = std::getenv("R4D_AR_MAX_BLOCKS")) {
const int cap = std::atoi(e);
if (cap > 0 && cap < in->max_blocks) in->max_blocks = cap;
}
/* Launch ceilings: 24 at two ranks, the library's design count at width. The compressed
* 2-rank wire uses up to 48, set at its own call site: it moves three eighths of the bytes, so
* it needs more blocks to saturate the link. */
in->nb_cap = (world == 2) ? 24 : (nb_design > 0 ? nb_design : maxb);
if (in->nb_cap > maxb) in->nb_cap = maxb;
if (in->nb_cap > in->max_blocks) in->nb_cap = in->max_blocks;
/* Slots: one per (parity, source rank) at width; two at world 2, where there is one remote
* writer. Flags: one word per (block, source rank) at width, one per block at world 2.
@@ -190,7 +434,9 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
* changes: kernels touch other ranks only through those two, so no card addresses another's
* VRAM. A message then crosses two links instead of one; only rows requiring device.p2p == 0
* take this path (r4d_rows.cpp). Sequence counters stay in VRAM, since only their own rank
* reads them. */
* reads them, and coarse-grained: only this rank's kernels touch them, with device- and
* agent-scope atomics, which then complete in L2 rather than past it -- the first returning
* atomic of every launch (r4d_ar_seq_take) is on the push's path. */
R4D_TRY("ar_ipc_alloc",
if (hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE;
if (host) {
@@ -200,7 +446,7 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen);
fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen);
}
sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 1, handle, &hlen));
sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen));
/* This rank's own packed copy, for the rotated 6-bit wire only: the reduce must fold exactly
* the bytes it sent. The 6-bit payload is 3/8 of the bf16 message and the scales 1/64, so half
@@ -229,7 +475,9 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
/* Peer access is per context, so each rank enables its own, after the publish barrier where
* peer device ordinals are known. A host can expose more HIP devices than ranks (e.g. an
* integrated GPU), so the ordinal comes from the peer rather than the rank. */
* integrated GPU), so the ordinal comes from the peer rather than the rank. A peer on this
* rank's own card needs none (the runtime refuses to enable it): r4d_selftest runs eight ranks
* on one card that way, each on its own stream. */
int j = 0;
for (int r = 0; r < world; ++r) {
if (r == rank) continue;
@@ -237,7 +485,8 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
in->peer_scratch[j] = g_rv.scratch[r];
in->peer_flags[j] = g_rv.flags[r];
++j;
if (!host) R4D_TRY("ar_ipc_enable_peer", r4d_ar_ipc_enable_peer((long)g_rv.dev[r]));
if (!host && g_rv.dev[r] != dev)
R4D_TRY("ar_ipc_enable_peer", r4d_ar_ipc_enable_peer((long)g_rv.dev[r]));
}
/* Second barrier: no rank may launch until every rank has enabled peer access, or the first
@@ -393,11 +642,11 @@ extern "C" int r4d_rad_ar_ln_host_init(const RadParam* p, int n_p, int rank, int
return ar_ln_init(p, n_p, rank, world, 1, out);
}
/* The four-rank ar_hc_write and ar_gather_hc_write. The key is {rank, 4, bf16, M_hi * n}, shared
* with a standalone all_reduce band only where the bounds agree. Either way is safe on one stream:
* every wide kernel advances the instance's seq counters once per all-reduce and writes only its
* (parity, source) slot (r4d_ar_wide.h), so ops on one instance interleave in any order all ranks
* share. Exact wire only; `wire` 6 is refused. */
/* The four-rank ar_hc_write, ar_gather_hc_write and ar_rmsnorm_quant_i8 (the norm declares no
* `wire`). The key is {rank, 4, bf16, M_hi * n}, shared with a standalone all_reduce band only where
* the bounds agree. Either way is safe on one stream: every wide kernel advances the instance's seq
* counters once per all-reduce and writes only its (parity, source) slot (r4d_ar_wide.h), so ops on
* one instance interleave in any order all ranks share. Exact wire only; `wire` 6 is refused. */
static int ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world, int host,
void** out) {
if (!out) return RAD_E_INVAL;
@@ -456,6 +705,32 @@ static int nb_for(long words16, int max_nb) {
return (int)nb;
}
/* The four-rank exact two-shot at decode and verify heights (the one-shot row's band from ts_min,
* the junction's tail form, the two-shot row up to kTsDecodeShard words a shard), over the words of
* one shard: one block per 2688 words, floor 2, ceiling 8 (and max_nb). A two-shot takes two
* handshakes, each a PCIe round trip a block, so a block more costs more than its share of the
* bytes saves until the shards are large. One per 672 (the rule before 2026-10-19) launched 16
* blocks at 64 rows of 5376, where the multi-user verify runs (8 users x DFlash2's 8 rows): on 4x
* R9700, one launch at a time on the real payload, 64 rows took 85.6 us at 16 blocks against 75.3
* at 4, 32 rows 58.9 at 16 / 47.1 at 8 against 44.2 at 4, 128 rows 143.5 at 16 against 137.9 at 8;
* 8 rows (two blocks either way) 19.6. The block count moves no byte: every word is folded by one
* thread in ascending rank order whatever the grid. */
/* The chained two-shot (r4d_chain.h) where the row resolved with `chain`, for a decode-sized
* message only (64 rows of an 8192-wide residual): DFlash2's verify-height reductions. */
static long ar_chain(const RadArgs* a, long numel) {
return r4d_geti_or(a, "chain", 0) != 0 && numel <= 64L * 8192L ? 1L : 0L;
}
static constexpr long kTsDecodeShard = 43008; /* 256 rows of 5376 at tp 4 */
static int nb_for_shard(long shard16, int max_nb) {
long nb = shard16 / 2688;
if (nb < 2) nb = 2;
if (nb > 8) nb = 8;
if (nb > max_nb) nb = max_nb;
if (nb > shard16) nb = shard16 > 0 ? shard16 : 1;
return (int)nb;
}
/* Shared front half of every all-reduce launch: find the instance, check the message against
* init's sizing, resolve the tuned point. Every kernel of the family is safe in place (`y` absent
* or equal to `x`); each entry point says why. */
@@ -494,12 +769,22 @@ static int ar_setup(const RadArgs* a, ArCall* c, int shard_nb) {
c->pub = cfgv.pub;
const long words16 = (long)n * in->esize / 16;
const long basis = shard_nb ? words16 / in->world : words16;
long basis = shard_nb ? words16 / in->world : words16;
if (shard_nb && ar8_weights_for(in, n)) {
long off[R4D_MAX_RANKS + 1];
basis = r4d_ar_shard_table(words16, in->world, in->shard_w, off);
}
/* The two-shots move shards, so they use the smaller basis and a tighter ceiling; the
* full-message rule over-launches across the mid band. */
int cap = in->nb_cap;
if (shard_nb && cap > 24) cap = 24;
c->nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(basis, cap);
/* Every block handshakes with all seven peers at eight ranks; past eight blocks the extra
* flag rounds cost more than the added reduce bandwidth (8 against 16 blocks measured up to 3 %
* faster from 2097152 elements on). */
if (shard_nb && in->world == 8 && cap > 8) cap = 8;
/* a decode-sized shard takes the decode rule (nb_for_shard), a prompt-sized one nb_for's */
c->nblocks = cfgv.nblocks > 0 ? cfgv.nblocks
: (shard_nb && basis <= kTsDecodeShard) ? nb_for_shard(basis, cap) : nb_for(basis, cap);
if (c->nblocks > in->max_blocks) c->nblocks = in->max_blocks;
return RAD_OK;
}
@@ -517,7 +802,7 @@ extern "C" void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long
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 gate, long gate_ctr, long dpitch, long spitch, long chain);
extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2,
long peer_scratch3, long peer_scratch4, long peer_scratch5,
long peer_scratch6, long peer_flags0, long peer_flags1,
@@ -526,11 +811,14 @@ extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long
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 pub, long dpitch, long spitch);
/* Not ar_setup: an all-gather's output is world_size times its input. */
/* Not ar_setup: an all-gather's output is world_size times its input. With `row`, `y` may also be
* the leading world_size * row columns of a wider buffer and `x` a row-wide window of one
* (docs/OPS.md); `*dpitch_out` and `*spitch_out` are then their row pitches in elements, else 0. */
static int ar_gather_wide_setup(const RadArgs* a, int ws, const ArInst** out_in, ArCall* c,
long long* row_out) {
long long* row_out, long long* dpitch_out,
long long* spitch_out) {
const ArInst* in = (const ArInst*)(a ? a->instance : nullptr);
if (!in) return RAD_E_STATE; /* init did not run: a core sequencing bug */
if (in->world != ws) return RAD_E_SHAPE; /* the peer bundle is compiled for this width */
@@ -538,7 +826,6 @@ static int ar_gather_wide_setup(const RadArgs* a, int ws, const ArInst** out_in,
const RadTensor* x = r4d_opt(a, AR_X);
const RadTensor* y = r4d_opt(a, AR_Y);
if (!x || !y) return RAD_E_INVAL; /* the gather has no in-place form */
if (!r4d_contig(x) || !r4d_contig(y)) return RAD_E_STRIDE;
if (y->data == x->data) return RAD_E_INVAL;
const long n = (long)r4d_numel(x);
@@ -548,6 +835,27 @@ static int ar_gather_wide_setup(const RadArgs* a, int ws, const ArInst** out_in,
const long long row = r4d_pgeti_or(a->p, a->n_p, "row", 0);
if (row < 0 || (row > 0 && (n % row || (row * in->esize) % 16))) return RAD_E_SHAPE;
/* A row-interleaved gather's [rows][world * row] may sit in the leading columns of a wider
* buffer, the pitch in whole 16-byte words: rows land at that pitch, the rest of each row is
* left alone. */
long long dpitch = 0;
if (!r4d_contig(y)) {
const long long p = r4d_row_pitch(y);
if (row <= 0 || y->rank != 2 || p <= 0 || y->shape[1] != (int64_t)row * in->world ||
(p * in->esize) % 16)
return RAD_E_STRIDE;
dpitch = p;
}
/* Likewise x may be [rows][row] read at a wider pitch: a rank's window of a row it computed
* wider (a split linear's block-aligned superset, arch/common/rad_block_dflash2.h). */
long long spitch = 0;
if (!r4d_contig(x)) {
const long long p = r4d_row_pitch(x);
if (row <= 0 || x->rank != 2 || p <= 0 || x->shape[1] != (int64_t)row ||
(p * in->esize) % 16)
return RAD_E_STRIDE;
spitch = p;
}
if (((long long)n * in->esize) % 16) return RAD_E_ALIGN;
if (!r4d_aligned(x->data, 16) || !r4d_aligned(y->data, 16)) return RAD_E_ALIGN;
@@ -569,43 +877,46 @@ static int ar_gather_wide_setup(const RadArgs* a, int ws, const ArInst** out_in,
c->acq = cfgv.acq;
c->pub = cfgv.pub;
*row_out = row;
*dpitch_out = dpitch;
*spitch_out = spitch;
return RAD_OK;
}
extern "C" int r4d_rad_ar_gather_2rank(const RadArgs* a, RadStream s) {
const ArInst* in = nullptr;
ArCall c;
long long row = 0;
int rc = ar_gather_wide_setup(a, 2, &in, &c, &row);
long long row = 0, dpitch = 0, spitch = 0;
int rc = ar_gather_wide_setup(a, 2, &in, &c, &row, &dpitch, &spitch);
if (rc != RAD_OK) return rc;
R4D_TRY("ar_gather_2rank",
r4d_ar_gather_2rank(in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags,
in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank,
(long)row, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain,
c.acq));
c.acq, (long)dpitch, (long)spitch));
return RAD_OK;
}
extern "C" int r4d_rad_ar_gather_3rank(const RadArgs* a, RadStream s) {
const ArInst* in = nullptr;
ArCall c;
long long row = 0;
int rc = ar_gather_wide_setup(a, 3, &in, &c, &row);
long long row = 0, dpitch = 0, spitch = 0;
int rc = ar_gather_wide_setup(a, 3, &in, &c, &row, &dpitch, &spitch);
if (rc != RAD_OK) return rc;
R4D_TRY("ar_gather_3rank",
r4d_ar_gather_3rank(in->peer_scratch[0], in->peer_scratch[1],
in->peer_flags[0], in->peer_flags[1],
in->my_scratch, in->my_flags, in->my_seq, in->slot16,
c.inp, c.out, c.numel, in->dtype, in->rank, (long)row,
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub));
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub,
(long)dpitch, (long)spitch));
return RAD_OK;
}
extern "C" int r4d_rad_ar_gather_4rank(const RadArgs* a, RadStream s) {
const ArInst* in = nullptr;
ArCall c;
long long row = 0;
int rc = ar_gather_wide_setup(a, 4, &in, &c, &row);
long long row = 0, dpitch = 0, spitch = 0;
int rc = ar_gather_wide_setup(a, 4, &in, &c, &row, &dpitch, &spitch);
if (rc != RAD_OK) return rc;
/* One handshake, placement after it local: the release is the one-shot's. */
const long gate = link_gate(a), early = in->host ? 0L : gate;
@@ -615,15 +926,16 @@ extern "C" int r4d_rad_ar_gather_4rank(const RadArgs* a, RadStream s) {
in->my_scratch, in->my_flags, in->my_seq, in->slot16,
c.inp, c.out, c.numel, in->dtype, in->rank, (long)row,
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub,
early, early ? in->gate_ctr : 0L));
early, early ? in->gate_ctr : 0L, (long)dpitch, (long)spitch,
ar_chain(a, c.numel)));
return early ? RAD_LINK_ENDED : RAD_OK;
}
extern "C" int r4d_rad_ar_gather_8rank(const RadArgs* a, RadStream s) {
const ArInst* in = nullptr;
ArCall c;
long long row = 0;
int rc = ar_gather_wide_setup(a, 8, &in, &c, &row);
long long row = 0, dpitch = 0, spitch = 0;
int rc = ar_gather_wide_setup(a, 8, &in, &c, &row, &dpitch, &spitch);
if (rc != RAD_OK) return rc;
R4D_TRY("ar_gather_8rank",
r4d_ar_gather_8rank(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2],
@@ -634,7 +946,8 @@ extern "C" int r4d_rad_ar_gather_8rank(const RadArgs* a, RadStream s) {
in->peer_flags[6],
in->my_scratch, in->my_flags, in->my_seq, in->slot16,
c.inp, c.out, c.numel, in->dtype, in->rank, (long)row,
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub));
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub,
(long)dpitch, (long)spitch));
return RAD_OK;
}
@@ -742,6 +1055,32 @@ extern "C" int r4d_rad_ar_oneshot_4rank_exact(const RadArgs* a, RadStream s) {
if (rc != RAD_OK) return rc;
if (c.in->world != 4) return RAD_E_SHAPE;
const ArInst* in = c.in;
/* From `ts_min` elements, the exact two-shot on this instance: the same fold per element, so
* the same bytes, for half the bytes a rank (a 16-row verify's message, 516 KiB a card at
* 3x, is what the link waits on). It shares the wide family's flags, counters and slots, and
* a shard pair fits any slot that holds the whole message. */
const long ts_min = r4d_cfg_ar_ts_min(a);
const long words16 = c.numel * in->esize / 16;
if (ts_min > 0 && c.numel >= ts_min && words16 % in->world == 0 &&
2 * (c.numel * in->esize) / in->world <= in->slot_bytes &&
c.numel <= R4D_AR_TWOSHOT_WIDE_MAX_ELEMS) {
R4dArCfg cfgv;
r4d_cfg_ar(a, &cfgv);
int nb = cfgv.nblocks > 0 ? cfgv.nblocks
: nb_for_shard(words16 / in->world,
in->nb_cap > 24 ? 24 : in->nb_cap);
if (nb > in->max_blocks) nb = in->max_blocks;
const long gate = link_gate(a), early = in->host ? 0L : gate;
R4D_TRY("ar_oneshot_4rank_exact (two-shot)",
r4d_ar_twoshot_4rank_exact(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2],
in->peer_flags[0], in->peer_flags[1], in->peer_flags[2],
in->my_scratch, in->my_flags, in->my_seq, in->slot16,
c.inp, c.out, c.numel, in->dtype, in->rank,
(long)(uintptr_t)s, nb, c.nthreads, c.drain, c.acq,
c.pub, early, early ? in->gate_ctr : 0L,
ar_chain(a, c.numel)));
return early ? RAD_LINK_ENDED : RAD_OK;
}
/* The wide release, the two-rank family's rule: over P2P the kernel ends the engine's hold
* itself once the peers' pushes have landed (the kernel after the handshake is local VRAM
* traffic); through the host mailbox the reduce reads the bytes across the link, so early
@@ -819,6 +1158,25 @@ extern "C" int r4d_rad_ar_twoshot_4rank_exact(const RadArgs* a, RadStream s) {
if (words16 % c.in->world) return RAD_E_SHAPE;
if (2 * (c.numel * c.in->esize) / c.in->world > c.in->slot_bytes) return RAD_E_SCRATCH;
const ArInst* in = c.in;
/* A reduction beside compute (overlap 1) carries its pushes coded at ~12.2 bits a bf16 value
* (r4d_ar_twoshot_Nrank_exact.hip, the coded form), at 4 blocks of 1024 threads, wherever the
* message fits that form; the same bytes either way. The 31B's prefill (4x R9700, a
* 5033-token prompt): 5724 -> 5949 tok/s (+3.9%), every reply identical; 8 x 512 gave +2.1%,
* 16 x 256 +1.3%, 6 x 1024 -1.9% (the blocks crowd the GEMM beside them). `coded` 0, a launch
* parameter no declaration carries, keeps the plain wire: r4d_selftest's plain arm. */
const bool lane = r4d_geti_or(a, "overlap", 0) == 1;
if (lane && r4d_geti_or(a, "coded", 1) != 0 &&
r4d_ar_twoshot_coded_ok(c.numel, in->dtype, 4, in->slot16)) {
const long gate = link_gate(a), early = in->host ? 0L : gate;
R4D_TRY("ar_twoshot_4rank_exact (coded)",
r4d_ar_twoshot_4rank_exact_coded(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2],
in->peer_flags[0], in->peer_flags[1], in->peer_flags[2],
in->my_scratch, in->my_flags, in->my_seq, in->slot16,
c.inp, c.out, c.numel, in->rank, (long)(uintptr_t)s,
4, 1024, c.drain, c.acq, c.pub, early,
early ? in->gate_ctr : 0L, ar_chain(a, c.numel)));
return early ? RAD_LINK_ENDED : RAD_OK;
}
/* The kernel ends the hold after its second handshake (its reduce is fused with the phase-2
* push); through the host mailbox early stays 0 and the engine releases by barrier. */
const long gate = link_gate(a), early = in->host ? 0L : gate;
@@ -828,7 +1186,8 @@ extern "C" int r4d_rad_ar_twoshot_4rank_exact(const RadArgs* a, RadStream s) {
in->my_scratch, in->my_flags, in->my_seq, in->slot16,
c.inp, c.out, c.numel, in->dtype, in->rank,
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq,
c.pub, early, early ? in->gate_ctr : 0L));
c.pub, early, early ? in->gate_ctr : 0L,
ar_chain(a, c.numel)));
return early ? RAD_LINK_ENDED : RAD_OK;
}
@@ -838,10 +1197,22 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) {
if (rc != RAD_OK) return rc;
if (c.in->world != 8) return RAD_E_SHAPE;
if (c.numel > R4D_AR_TWOSHOT_WIDE_MAX_ELEMS) return RAD_E_SHAPE;
const long words16 = c.numel * c.in->esize / 16;
if (words16 % c.in->world) return RAD_E_SHAPE;
if (2 * (c.numel * c.in->esize) / c.in->world > c.in->slot_bytes) return RAD_E_SCRATCH;
const ArInst* in = c.in;
const int* weights = ar8_weights_for(in, c.numel);
/* Even shards keep the four-rank rule (whole words a rank); weighted ones are uneven anyway. */
const long words16 = c.numel * in->esize / 16;
if (!weights && words16 % in->world) return RAD_E_SHAPE;
long off[R4D_MAX_RANKS + 1];
const long sh_max = r4d_ar_shard_table(words16, in->world, weights, off);
if (2 * sh_max * 16 > in->slot_bytes) return RAD_E_SCRATCH;
/* Pieces only move the handshakes; the regions stay at 0 and sh_max, so scratch is as above. */
const long long asked = r4d_pgeti_or(a->p, a->n_p, "pieces", in->pieces);
if (asked < 0 || asked > R4D_AR_TS_MAX_PIECES) return RAD_E_INVAL;
const long long pieces = ar8_pieces_for(in, c.numel, asked);
/* A diagnostic: a device buffer of nblocks * R4D_AR_TL_WORDS int64 stamps (r4d.h). */
const long long timeline = r4d_pgeti_or(a->p, a->n_p, "timeline", 0);
const long long form = r4d_pgeti_or(a->p, a->n_p, "form", in->form);
if (form < R4D_AR8_FORM_LOCKSTEP || form > R4D_AR8_FORM_SPLIT) return RAD_E_INVAL;
R4D_TRY("ar_twoshot_8rank_exact",
r4d_ar_twoshot_8rank_exact(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2],
in->peer_scratch[3], in->peer_scratch[4], in->peer_scratch[5],
@@ -852,7 +1223,7 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) {
in->my_scratch, in->my_flags, in->my_seq, in->slot16,
c.inp, c.out, c.numel, in->dtype, in->rank,
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq,
c.pub));
c.pub, weights, (long)pieces, (long)timeline, (long)form));
return RAD_OK;
}
@@ -932,7 +1303,7 @@ extern "C" int r4d_rad_ar_twoshot_4rank_ti8(const RadArgs* a, RadStream s) {
/* ------------------------------------------------------------------ the fused all-reduce + norm */
enum { AL_X = 0, AL_RESID, AL_W, AL_Q, AL_SCALE, AL_OUTBF16 };
enum { AL_X = 0, AL_RESID, AL_W, AL_Q, AL_SCALE, AL_OUTBF16, AL_WPOST };
extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) {
const ArInst* in = (const ArInst*)(a ? a->instance : nullptr);
@@ -985,6 +1356,7 @@ extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) {
* shim's count equal to the kernel's. */
int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(M * K * 2 / 16, in->max_blocks);
if (nblocks > (int)M) nblocks = (int)M;
if (nblocks > in->max_blocks) nblocks = in->max_blocks; // a tuned count under R4D_AR_MAX_BLOCKS too
/* LDS floor on the block count. The compressed wire stages every row a block owns, so a count
* chosen for the push alone can exceed LDS (at K = 5120, more than two rows per block). Raise
* the count to the kernel's floor; refuse shapes no count within the flag capacity serves.
@@ -1014,7 +1386,9 @@ extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) {
* chooses it as the standalone `all_reduce` row would (lossy wire allowed, group tiles the message,
* size above --tp-wire-min-kb), and both ranks decide on the same T. A wire-6 chunk that would
* straddle a row is refused as a shape. */
extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
/* `hi8`: ar_rmsnorm_had_quant_i8g, the same with had_quant_act_i8g's quantiser on the norm's pass
* (int8 codes, K whole 128s, no post-norm). */
static int rad_ar_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) {
const ArInst* in = (const ArInst*)(a ? a->instance : nullptr);
if (!in) return RAD_E_STATE;
if (in->world != 2) return RAD_E_SHAPE;
@@ -1025,8 +1399,15 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
const RadTensor* q = r4d_opt(a, AL_Q);
const RadTensor* sc = r4d_opt(a, AL_SCALE);
const RadTensor* ob = r4d_opt(a, AL_OUTBF16);
/* ar_rmsnorm_quant_fp8's optional post-norm (Gemma 3's sandwich); ar_ln_had_quant_i8 has no
* seventh operand, and this function serves only the fp8 op and its rotated int8 twin. */
const RadTensor* wpo = r4d_opt(a, AL_WPOST);
if (!x || !w || !q || !sc) return RAD_E_INVAL;
if (hi8 && q->dtype != RAD_I8) return RAD_E_DTYPE;
if (hi8 && wpo) return RAD_E_UNSUPPORTED;
if (!r4d_contig(w)) return RAD_E_STRIDE;
if (wpo && (!rs || !r4d_contig(wpo) || r4d_numel(wpo) != r4d_numel(w) || wpo->dtype != w->dtype))
return RAD_E_SHAPE;
/* Rank 2 everywhere, as in rmsnorm_quant_fp8: a norm has a gain per channel, so flattening
* everything after dim 0 into the row would put one gain across several heads. */
@@ -1041,6 +1422,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
const long long grp = r4d_quant_act_fp8_group();
const long long nkb = (K + grp - 1) / grp;
if (r4d_geti_or(a, "group", grp) != grp) return RAD_E_SHAPE;
if (hi8 && K % grp) return RAD_E_SHAPE;
if (r4d_numel(w) != K) return RAD_E_SHAPE;
if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return RAD_E_DTYPE;
if (q->shape[0] != M || q->shape[1] != K) return RAD_E_SHAPE;
@@ -1066,6 +1448,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
/* This rank's packed-half side buffer exists for every bf16 instance; missing means a
* broken init. */
if (!in->locpack) return RAD_E_STATE;
if (wpo) return RAD_E_UNSUPPORTED; // the post-norm is the exact wire's only
}
R4dArCfg cfgv;
@@ -1095,17 +1478,34 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
if (nblocks > in->max_blocks) nblocks = in->max_blocks;
if (nblocks < 1) nblocks = 1;
const int e = r4d_ar_rmsnorm_quant_fp8(
in->peer_scratch[0], in->my_scratch,
in->peer_flags[0], in->my_flags, in->my_seq,
in->slot16, r4d_addr(x), r4d_addr(rs), r4d_addr(w), r4d_addr(ob), r4d_addr(q),
r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32,
(int)rp, (int)yp, (int)qp, (int)sp,
(long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire,
in->locpack, in->slot_bytes / 2);
const int e = hi8
? r4d_ar_rmsnorm_had_quant_i8g(
in->peer_scratch[0], in->my_scratch,
in->peer_flags[0], in->my_flags, in->my_seq,
in->slot16, r4d_addr(x), r4d_addr(rs), r4d_addr(w), r4d_addr(ob), r4d_addr(q),
r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32,
(int)rp, (int)yp, (int)qp, (int)sp,
(long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire,
in->locpack, in->slot_bytes / 2)
: r4d_ar_rmsnorm_quant_fp8(
in->peer_scratch[0], in->my_scratch,
in->peer_flags[0], in->my_flags, in->my_seq,
in->slot16, r4d_addr(x), r4d_addr(rs), r4d_addr(w), r4d_addr(ob), r4d_addr(q),
r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32,
(int)rp, (int)yp, (int)qp, (int)sp,
(long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire,
in->locpack, in->slot_bytes / 2, wpo ? r4d_addr(wpo) : 0);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
return rad_ar_rmsnorm_quant(a, s, false);
}
extern "C" int r4d_rad_ar_rmsnorm_had_quant_i8g(const RadArgs* a, RadStream s) {
return rad_ar_rmsnorm_quant(a, s, true);
}
/* The all-reduce and the sandwich-norm junction after it, int8 out: exact `all_reduce` of `x`, then
* `rmsnorm_quant_i8` (post-norm of the reduced x, residual add, scalar, norm and the per-row int8
* quantiser the w4a8 skinny GEMM reads). Operands are rmsnorm_quant_i8's with `x` inout, since the
@@ -1113,18 +1513,22 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
* all-reduce. Width and block count as in ar_rmsnorm_quant_fp8. */
enum { AQ8_X = 0, AQ8_RES, AQ8_W, AQ8_Q, AQ8_S, AQ8_Y, AQ8_WP, AQ8_SC };
extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) {
const ArInst* in = (const ArInst*)(a ? a->instance : nullptr);
if (!in) return RAD_E_STATE;
if (in->world != 2) return RAD_E_SHAPE;
const RadTensor* x = r4d_opt(a, AQ8_X);
const RadTensor* rs = r4d_opt(a, AQ8_RES);
const RadTensor* w = r4d_opt(a, AQ8_W);
const RadTensor* q = r4d_opt(a, AQ8_Q);
const RadTensor* sc = r4d_opt(a, AQ8_S);
const RadTensor* ob = r4d_opt(a, AQ8_Y);
const RadTensor* wp = r4d_opt(a, AQ8_WP);
const RadTensor* sl = r4d_opt(a, AQ8_SC);
/* The operands and their rules, the same at every width. */
struct ArQ8Args {
const RadTensor *x = nullptr, *rs = nullptr, *w = nullptr, *q = nullptr, *sc = nullptr;
const RadTensor *ob = nullptr, *wp = nullptr, *sl = nullptr;
long long M = 0, K = 0, yp = 0, rp = 0;
};
static int ar_q8_args(const RadArgs* a, const ArInst* in, ArQ8Args* o) {
const RadTensor* x = o->x = r4d_opt(a, AQ8_X);
const RadTensor* rs = o->rs = r4d_opt(a, AQ8_RES);
const RadTensor* w = o->w = r4d_opt(a, AQ8_W);
const RadTensor* q = o->q = r4d_opt(a, AQ8_Q);
const RadTensor* sc = o->sc = r4d_opt(a, AQ8_S);
const RadTensor* ob = o->ob = r4d_opt(a, AQ8_Y);
const RadTensor* wp = o->wp = r4d_opt(a, AQ8_WP);
const RadTensor* sl = o->sl = r4d_opt(a, AQ8_SC);
if (!x || !w || !q || !sc) return RAD_E_INVAL;
if ((wp || sl) && !rs) return RAD_E_INVAL;
if (!r4d_contig(w) || (wp && !r4d_contig(wp))) return RAD_E_STRIDE;
@@ -1143,6 +1547,18 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) {
const long long xp = r4d_row_pitch(x), yp = ob ? r4d_row_pitch(ob) : 0, rp = rs ? r4d_row_pitch(rs) : 0;
if (xp != K || yp < 0 || rp < 0) return RAD_E_STRIDE; /* x is the message: tight */
if (r4d_geti_or(a, "wire", 0) != 0) return RAD_E_INVAL;
o->M = M; o->K = K; o->yp = yp; o->rp = rp;
return RAD_OK;
}
extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) {
const ArInst* in = (const ArInst*)(a ? a->instance : nullptr);
if (!in) return RAD_E_STATE;
if (in->world != 2) return RAD_E_SHAPE;
ArQ8Args v;
const int arc = ar_q8_args(a, in, &v);
if (arc != RAD_OK) return arc;
const long long M = v.M, K = v.K;
R4dArCfg cfgv;
r4d_cfg_ar(a, &cfgv);
@@ -1153,13 +1569,72 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) {
if (nblocks < 1) nblocks = 1;
const int e = r4d_ar_rmsnorm_quant_i8(
in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq,
in->slot16, r4d_addr(x), r4d_addr(rs), r4d_addr(w), r4d_addr(wp), r4d_addr(sl),
sl ? (sl->dtype == RAD_F32) : 0, r4d_addr(ob), r4d_addr(q), r4d_addr(sc), (int)M, (int)K,
(float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0), w->dtype == RAD_F32,
(int)rp, (int)yp, (long)(uintptr_t)s, nblocks, cfgv.drain, cfgv.acq);
in->slot16, r4d_addr(v.x), r4d_addr(v.rs), r4d_addr(v.w), r4d_addr(v.wp), r4d_addr(v.sl),
v.sl ? (v.sl->dtype == RAD_F32) : 0, r4d_addr(v.ob), r4d_addr(v.q), r4d_addr(v.sc), (int)M,
(int)K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0),
v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (long)(uintptr_t)s, nblocks, cfgv.drain,
cfgv.acq);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
/* The same at four ranks, on the wide family's one-shot transport (r4d_rmsnorm_quant_i8.hip's
* ar_rmsnorm_quant_i8_wide_kernel), the one ar_hc_write_4rank rides, with the junction as its
* epilogue. The operands and the norm's width are the two-rank form's. The block count is one per
* row, capped by the wide family's flag array in the launcher and by the instance here. The
* instance is the four-rank family's {rank, 4, bf16, M_hi * n} (ar_hc_wide_init), so it is a
* standalone all_reduce band's where the two bounds agree, which is safe on one stream for the
* reason that init gives. The plugin issues it only at one-shot heights: each rank sends three
* times the message, which the two-shot the standalone takes above them does not. */
extern "C" int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs* a, RadStream s) {
const ArInst* in = (const ArInst*)(a ? a->instance : nullptr);
if (!in) return RAD_E_STATE;
if (in->world != 4) return RAD_E_SHAPE;
if (in->dtype != 0) return RAD_E_DTYPE;
ArQ8Args v;
const int arc = ar_q8_args(a, in, &v);
if (arc != RAD_OK) return arc;
R4dArCfg cfgv;
r4d_cfg_ar(a, &cfgv);
/* The fence-free forms rest on fine-grained P2P scratch and a store drain; the host mailbox
* (pinned host memory, cached on the way) keeps both fences. */
if (in->host || cfgv.drain != 3) {
if (cfgv.pub == 2) cfgv.pub = 1;
if (cfgv.acq == 2) cfgv.acq = 0;
}
int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : (int)v.M;
if (nblocks > in->max_blocks) nblocks = in->max_blocks;
/* Above one-shot heights (the plugin's fold band at 5 rows and up), the `tail` axis's form:
* the standalone two-shot over words on the blocks the standalone all_reduce would take for
* this message (nb_for_shard), with the junction as its tail; its two counters are words of the
* instance's zeroed sequence allocation past the landed counter (r4d_ar_seq.h). P2P only. */
int tail_nbt = 0;
if (r4d_cfg_ar_tail(a) && v.M >= 5 && !in->host) {
const long words16 = (long)v.M * v.K / 8;
tail_nbt = nb_for_shard(words16 / in->world, in->nb_cap > 24 ? 24 : in->nb_cap);
if (tail_nbt > in->max_blocks) tail_nbt = in->max_blocks;
}
const long tail_ctr = in->my_seq + (2L * in->max_blocks + 8) * 4;
/* `sp` (0 unless asked): the all-reduce split around the junction, P2P only. The host mailbox
* runs the whole form, which leaves every byte the split one does. */
const long long sp = r4d_geti_or(a, "sp", 0);
if (sp < 0 || sp > 2) return RAD_E_INVAL;
/* The junction after the last handshake is local, so either form releases there. */
const long gate = link_gate(a), early = in->host ? 0L : gate;
const int e = r4d_ar_rmsnorm_quant_i8_4rank(
in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2],
in->peer_flags[0], in->peer_flags[1], in->peer_flags[2],
in->my_scratch, in->my_flags, in->my_seq, in->slot16,
r4d_addr(v.x), r4d_addr(v.rs), r4d_addr(v.w), r4d_addr(v.wp), r4d_addr(v.sl),
v.sl ? (v.sl->dtype == RAD_F32) : 0, r4d_addr(v.ob), r4d_addr(v.q), r4d_addr(v.sc),
(int)v.M, (int)v.K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0),
v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (int)in->rank, (long)(uintptr_t)s, nblocks,
cfgv.drain, cfgv.acq, cfgv.pub, early, early ? in->gate_ctr : 0L, tail_ctr, tail_nbt,
r4d_geti_or(a, "chain", 0) != 0 ? 1 : 0, in->host ? 0 : (int)sp);
if (e != 0) return RAD_E_SHAPE;
return early ? RAD_LINK_ENDED : RAD_OK;
}
/* The all-reduce with the gated residual write: `all_reduce` of `y`, then `hc_write` of the reduced
* `y` into `h`, in one kernel. A block whose output feeds a hyper-connection write skips its own
* collective when this runs.
+46 -17
View File
@@ -38,11 +38,20 @@ __device__ __forceinline__ unsigned int r4d_g_load_acq(const unsigned int* p) {
//
// The vocab-parallel sampler's merge reads one row of gathered candidates per position at a single
// row stride, which the concatenated form cannot express. Interleaving costs one division per word
// and saves a transpose launch.
__device__ __forceinline__ int r4d_g_dst(int k, int row16, int n16, int who) {
// 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 r4d_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 * (2 * row16) + who * row16 + c;
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 r4d_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
@@ -50,7 +59,8 @@ __device__ __forceinline__ int r4d_g_dst(int k, int row16, int n16, int who) {
__global__ void r4d_ar_gather_2rank_kernel(
const int4* __restrict__ in4, int4* peer_base, const int4* my_base, int4* __restrict__ out4,
unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs,
int n16, int slot_stride16, int rank, int row16, int drain, int acq, unsigned int nbw) {
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;
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
@@ -68,14 +78,20 @@ __global__ void r4d_ar_gather_2rank_kernel(
{
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];
int4 v0 = in4[r4d_g_src(k, row16, n16, sp16)], v1 = in4[r4d_g_src(k + nt, row16, n16, sp16)],
v2 = in4[r4d_g_src(k + 2 * nt, row16, n16, sp16)],
v3 = in4[r4d_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;
out4[r4d_g_dst(k, row16, n16, rank)] = v0;
out4[r4d_g_dst(k + nt, row16, n16, rank)] = v1;
out4[r4d_g_dst(k + 2 * nt, row16, n16, rank)] = v2;
out4[r4d_g_dst(k + 3 * nt, row16, n16, rank)] = v3;
out4[r4d_g_dst(k, row16, n16, rank, dp16)] = v0;
out4[r4d_g_dst(k + nt, row16, n16, rank, dp16)] = v1;
out4[r4d_g_dst(k + 2 * nt, row16, n16, rank, dp16)] = v2;
out4[r4d_g_dst(k + 3 * nt, row16, n16, rank, dp16)] = v3;
}
for (; k < end; k += nt) {
int4 v = in4[r4d_g_src(k, row16, n16, sp16)];
ps[k] = v;
out4[r4d_g_dst(k, row16, n16, rank, dp16)] = v;
}
for (; k < end; k += nt) { int4 v = in4[k]; ps[k] = v; out4[r4d_g_dst(k, row16, n16, rank)] = 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.
@@ -100,19 +116,19 @@ __global__ void r4d_ar_gather_2rank_kernel(
const int who = 1 - rank;
int k = start + tid;
for (; k + 3 * nt < end; k += 4 * nt) {
out4[r4d_g_dst(k, row16, n16, who)] = ms[k];
out4[r4d_g_dst(k + nt, row16, n16, who)] = ms[k + nt];
out4[r4d_g_dst(k + 2 * nt, row16, n16, who)] = ms[k + 2 * nt];
out4[r4d_g_dst(k + 3 * nt, row16, n16, who)] = ms[k + 3 * nt];
out4[r4d_g_dst(k, row16, n16, who, dp16)] = ms[k];
out4[r4d_g_dst(k + nt, row16, n16, who, dp16)] = ms[k + nt];
out4[r4d_g_dst(k + 2 * nt, row16, n16, who, dp16)] = ms[k + 2 * nt];
out4[r4d_g_dst(k + 3 * nt, row16, n16, who, dp16)] = ms[k + 3 * nt];
}
for (; k < end; k += nt) out4[r4d_g_dst(k, row16, n16, who)] = ms[k];
for (; k < end; k += nt) out4[r4d_g_dst(k, row16, n16, who, dp16)] = ms[k];
}
}
void r4d_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 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;
@@ -126,6 +142,19 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo
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;
@@ -139,5 +168,5 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo
r4d_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, (int)drain, (int)acq, nbw);
(int)slot_stride16, (int)rank, row16, dp16, sp16, (int)drain, (int)acq, nbw);
}
+81 -24
View File
@@ -20,6 +20,7 @@
// the peer arrays.
#include "r4d.h"
#include "r4d_ar_wide.h"
#include "r4d_chain.h"
#include <cstdint>
#include <stdexcept>
#include <string>
@@ -32,14 +33,15 @@ extern "C" void r4d_ar_gather_3rank(long peer_scratch0, long peer_scratch1,
long my_scratch, long my_flags, long seq_ctrs,
long slot_stride16, long inp, long out, long n_elem,
long dtype, long rank, long row_elems, long stream,
long nblocks, long nthreads, long drain, long acq, long pub);
long nblocks, long nthreads, long drain, long acq, long pub,
long dpitch, long spitch);
extern "C" void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2,
long peer_flags0, long peer_flags1, long peer_flags2,
long my_scratch, long my_flags, long seq_ctrs,
long slot_stride16, long inp, long out, long n_elem,
long dtype, long rank, long row_elems, long stream,
long nblocks, long nthreads, long drain, long acq, long pub,
long gate, long gate_ctr);
long gate, long gate_ctr, long dpitch, long spitch, long chain);
extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2,
long peer_scratch3, long peer_scratch4, long peer_scratch5,
long peer_scratch6, long peer_flags0, long peer_flags1,
@@ -48,25 +50,37 @@ extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long
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 pub, long dpitch, long spitch);
// Where a rank's words land: the 2-rank r4d_g_dst generalised to WS. Named differently because two
// __device__ definitions of one name in the two units would violate the ODR.
__device__ __forceinline__ int r4d_g_dst_ws(int k, int row16, int n16, int WS, int who) {
// `dp16` is the output's row pitch in words, WS * row16 when the gathered rows are tight.
__device__ __forceinline__ int r4d_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 * (WS * row16) + who * row16 + c;
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 r4d_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 (r4d_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>
__global__ void r4d_ar_gather_wide_kernel(
__device__ __forceinline__ void r4d_ar_gather_wide_body(
const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers,
const int4* __restrict__ my_base, int4* __restrict__ out4,
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs,
int n16, int slot_stride16, int rank, int row16, int drain, int acq, int pub,
long long* gate, unsigned int* gate_ctr) {
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).
@@ -95,14 +109,17 @@ __global__ void r4d_ar_gather_wide_kernel(
{
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];
const int4 v0 = in4[r4d_g_src_ws(k, row16, n16, sp16)];
const int4 v1 = in4[r4d_g_src_ws(k + nt, row16, n16, sp16)];
const int4 v2 = in4[r4d_g_src_ws(k + 2 * nt, row16, n16, sp16)];
const int4 v3 = in4[r4d_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[k];
const int4 v = in4[r4d_g_src_ws(k, row16, n16, sp16)];
#pragma unroll
for (int p = 0; p < NPEERS; ++p) ps[p][k] = v;
}
@@ -117,7 +134,7 @@ __global__ void r4d_ar_gather_wide_kernel(
r4d_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 and the loop is branch-free.
// 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)
@@ -127,20 +144,44 @@ __global__ void r4d_ar_gather_wide_kernel(
int k = start + tid;
if (RU == 2) {
for (; k + nt < end; k += 2 * nt) {
const int k0 = r4d_g_src_ws(k, row16, n16, sp16), k1 = r4d_g_src_ws(k + nt, row16, n16, sp16);
#pragma unroll
for (int r = 0; r < WS; ++r) {
out4[r4d_g_dst_ws(k, row16, n16, WS, r)] = src[r][k];
out4[r4d_g_dst_ws(k + nt, row16, n16, WS, r)] = src[r][k + nt];
out4[r4d_g_dst_ws(k, row16, n16, r, dp16)] = src[r][r == rank ? k0 : k];
out4[r4d_g_dst_ws(k + nt, row16, n16, r, dp16)] = src[r][r == rank ? k1 : k + nt];
}
}
}
for (; k < end; k += nt) {
const int k0 = r4d_g_src_ws(k, row16, n16, sp16);
#pragma unroll
for (int r = 0; r < WS; ++r)
out4[r4d_g_dst_ws(k, row16, n16, WS, r)] = src[r][k];
out4[r4d_g_dst_ws(k, row16, n16, r, dp16)] = src[r][r == rank ? k0 : k];
}
}
}
template <int WS>
__global__ void r4d_ar_gather_wide_kernel(
const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers,
const int4* __restrict__ my_base, int4* __restrict__ out4,
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs,
int n16, int slot_stride16, int rank, int row16, int dp16, int sp16, int drain, int acq,
int pub, long long* gate, unsigned int* gate_ctr) {
r4d_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 r4dchain_ar_gather_wide(
const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers,
const int4* __restrict__ my_base, int4* __restrict__ out4,
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs,
int n16, int slot_stride16, int rank, int row16, int dp16, int sp16, int drain, int acq,
int pub, long long* gate, unsigned int* gate_ctr) {
r4d_chain_wait();
r4d_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);
r4d_chain_done();
}
// --- host side ---
// `row_elems` is the row width in elements, 0 for plain concatenation. The entry point checks it
@@ -150,7 +191,8 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla
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 pub, long gate, long gate_ctr, long dpitch, long spitch,
bool chain = false) {
constexpr int NPEERS = WS - 1;
static_assert(NPEERS <= R4D_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound");
@@ -173,6 +215,20 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla
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 = R4D_AR_NB_DESIGN;
@@ -207,10 +263,10 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla
}
hipStream_t st = (hipStream_t)stream_i;
r4d_ar_gather_wide_kernel<WS><<<nb, nt, 0, st>>>(
(chain ? r4dchain_ar_gather_wide<WS> : r4d_ar_gather_wide_kernel<WS>)<<<nb, nt, 0, st>>>(
(const int4*)inp, peers, (const int4*)my_scratch, (int4*)out, (unsigned int*)my_flags,
(unsigned int*)seq_ctrs, n16, (int)slot_stride16, (int)rank, row16, (int)drain, (int)acq,
(int)pub, (long long*)gate, (unsigned int*)gate_ctr);
(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). */
@@ -218,13 +274,14 @@ void r4d_ar_gather_3rank(long peer_scratch0, long peer_scratch1,
long peer_flags0, long peer_flags1, long my_scratch,
long my_flags, long seq_ctrs, long slot_stride16, long inp, long out,
long n_elem, long dtype, long rank, long row_elems, long stream,
long nblocks, long nthreads, long drain, long acq, long pub) {
long nblocks, long nthreads, long drain, long acq, long pub, long 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);
0L, 0L, dpitch, spitch);
}
void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2,
@@ -232,12 +289,12 @@ void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scrat
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 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);
gate, gate_ctr, dpitch, spitch, chain != 0);
}
void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2,
@@ -247,7 +304,7 @@ void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scrat
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 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,
@@ -255,5 +312,5 @@ void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scrat
/* 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);
0L, 0L, dpitch, spitch);
}
+126
View File
@@ -0,0 +1,126 @@
#pragma once
// r4d_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 R4DArLink {
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 r4d_ar_link_gbs(const R4DArLink& 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 r4d_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 r4d_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 r4d_ar_link_bottleneck(const std::string& root, const std::string& bdf,
R4DArLink* 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;
R4DArLink best;
for (const fs::path& part : real) {
const std::string p = part.string();
if (!r4d_ar_is_bdf(p)) continue;
R4DArLink h;
h.bdf = p;
h.gts = std::strtod(r4d_ar_sysfs_line(devs + p + "/current_link_speed").c_str(), nullptr);
h.width = std::atoi(r4d_ar_sysfs_line(devs + p + "/current_link_width").c_str());
const double r = r4d_ar_link_gbs(h);
if (r <= 0.0) continue;
if (best.bdf.empty() || r < r4d_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 r4d_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;
}
// RADIANCE_AR8_SHARD_WEIGHTS=duplex: 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.
inline bool r4d_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;
}
+11 -3
View File
@@ -300,10 +300,18 @@ long r4d_ar_ipc_alloc(long size, int finegrained, char* out_handle, int* out_len
// 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. libr4d's ranks are threads of one process and share
// the pointer itself (r4d_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;
HIPOK(hipIpcGetMemHandle(&h, p));
std::memcpy(out_handle, &h, sizeof(h));
*out_len = (int)sizeof(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, R4D_AR_HANDLE_BYTES);
*out_len = 0;
}
return (long)p;
}
// r4d_p2p_copy2d as a kernel with a bounded workgroup count.
+7 -3
View File
@@ -33,17 +33,21 @@
// 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.
// 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 r4d_ar_seq_take(unsigned int* __restrict__ ctrs, unsigned int nbw,
unsigned int& s_seq, unsigned int& s_slot) {
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], 1u) + 1u;
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");
+136
View File
@@ -0,0 +1,136 @@
#pragma once
// r4d_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>
#define R4D_AR8_SHARD_WEIGHTS_ENV "RADIANCE_AR8_SHARD_WEIGHTS"
#define R4D_AR8_PIECES_ENV "RADIANCE_AR8_PIECES"
// The eight-rank two-shot's form (r4d_ar_twoshot_Nrank_exact.hip): lockstep (unset, the 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.
#define R4D_AR8_FORM_ENV "RADIANCE_AR8_FORM"
// Below these message sizes (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).
#define R4D_AR8_SHARD_WEIGHTS_MIN_ENV "RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS"
#define R4D_AR8_PIECES_MIN_ENV "RADIANCE_AR8_PIECES_MIN_ELEMS"
enum { R4D_AR8_FORM_LOCKSTEP = 0, R4D_AR8_FORM_RING = 1, R4D_AR8_FORM_SPLIT = 2 };
enum {
R4D_AR_SHARD_WEIGHT_MAX = 65535,
R4D_AR8_MIN_ELEMS_DEFAULT = 262144,
R4D_AR8_MIN_ELEMS_MAX = 268435456, // the two-shot band's top (r4d.h)
};
// The piece count when RADIANCE_AR8_PIECES is unset, 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 r4d_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 R4D_AR8_FORM_*; -1 for anything else.
inline int r4d_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;
}
// A non-negative decimal integer of at most `max`, nothing else.
inline bool r4d_ar_parse_count(const char* s, long long max, long long* out) {
if (!s || *s < '0' || *s > '9') return false;
long long v = 0;
while (*s >= '0' && *s <= '9') {
v = v * 10 + (*s++ - '0');
if (v > max) return false;
}
if (*s) return false;
*out = v;
return true;
}
// `ws` non-negative integers separated by commas, each at most R4D_AR_SHARD_WEIGHT_MAX, summing
// to more than zero; nothing else (no blanks, signs or trailing text).
inline bool r4d_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 > R4D_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 r4d_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 r4d_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 (r4d.h, `timeline`): per block R4D_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). R4D_AR_TL_BLOCKS is the wide family's block ceiling.
enum { R4D_AR_TL_WORDS = 2 + 2 * (16 + 1), R4D_AR_TL_BLOCKS = 64 };
+530 -77
View File
@@ -9,44 +9,86 @@
// to my out and every peer's slot[me] region B, flag 2s; assemble out from region B. Region A at
// 0, B at sh_max; the slot stride must hold 2*sh_max.
//
// Uneven shards: n16 words split into base = n16/ws words per shard, and the first n16 % ws shards
// take one more, so shard s starts at s*base + min(s, rem). At 4 and 8 ranks engine residuals
// divide evenly; at 3 they rarely do (a 2048-wide bf16 row is 256 words). Each word is the same
// fp32 fold in ascending rank order whoever owns it, so the bits match the one-shot's.
// The shard table (r4d_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 may be weighted per link
// (RADIANCE_AR8_SHARD_WEIGHTS); 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 (RADIANCE_AR8_PIECES, by default a count from
// the message size, r4d_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 (RADIANCE_AR8_FORM, the `form` parameter):
// * ring sends the first hop to the peers in ring order from rank + 1 instead of ascending, so
// at any moment each card receives from one peer rather than all seven from the same one;
// * 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 (r4d_ar_wide.h): it publishes in the 2*seq flag
// space plus the 2s-1 half-step and advances the per-block counter once per AR, so one buffer set
// can carry any mix of one-shot and two-shot launches. The slot stride must hold the largest
// requirement in the mix.
// 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 "r4d.h"
#include "r4d_ar_wide.h"
#include "r4d_ar_shards.h"
#include "r4d_chain.h"
#include <stdexcept>
#include <string>
template <typename T, int LANES, int WS>
__global__ void r4d_ar_twoshot_wide_exact_kernel(
static_assert(R4D_AR_TL_WORDS >= 4 + 2 * R4D_AR_TS_MAX_PIECES,
"a timeline holds the start, a stamp pair a handshake and the end");
template <int WS>
struct R4DArShardOff {
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 (r4d_chain.h); no block returns early.
template <typename T, int LANES, int WS, bool PIECED, int FORM, bool CHAIN>
__device__ __forceinline__ void r4d_ar_twoshot_wide_exact_body(
const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers,
const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags,
int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, int n16,
int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, R4DArShardOff<WS> sh,
int slot_stride16, int rank, int drain, int acq, int pub,
long long* gate, unsigned int* gate_ctr) {
long long* gate, unsigned int* gate_ctr, int pieces_arg, long long* tl_all) {
if (CHAIN) r4d_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 = r4d_ar_link_word(gate, (unsigned int)tid);
r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe
const unsigned int s = s_seq;
// 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)
r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot,
(unsigned int)(FORM == R4D_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 != R4D_AR8_FORM_SPLIT || 4 * pieces + 2 <= R4D_AR_TL_WORDS)
? tl_all + (size_t)b * R4D_AR_TL_WORDS : nullptr;
r4d_ar_tl_stamp(tl, 0);
// shard s = words [s*base + min(s, rem), +base + (s < rem)); sh_max is the longest one
const int base = n16 / WS, rem = n16 % WS;
const int sh_max = base + (rem ? 1 : 0);
#define R4D_TS_OFF(s) ((s) * base + ((s) < rem ? (s) : rem))
#define R4D_TS_LEN(s) (base + ((s) < rem ? 1 : 0))
const int sh_max = sh.sh_max;
#define R4D_TS_OFF(s) (sh.off[s])
#define R4D_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];
@@ -54,71 +96,388 @@ __global__ void r4d_ar_twoshot_wide_exact_kernel(
for (int p = 0; p < NPEERS; ++p)
pa[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16;
// ---- phase 1 push: my contribution to each peer-owned shard -> owner's region A
for (int p = 0; p < NPEERS; ++p) {
const int owner = peers.rank[p];
const int4* src = in4 + (size_t)R4D_TS_OFF(owner);
int4* dst = pa[p];
const int lim = w1 < R4D_TS_LEN(owner) ? w1 : R4D_TS_LEN(owner);
for (int k = w0 + tid; k < lim; k += nt) dst[k] = src[k];
}
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s - 1u, drain, acq, pub);
// ---- reduce my shard (fp32, ascending rank, own contribution from the input), and phase 2
// push: the reduced word goes to my out and every peer's region B in the same pass
const int4* src[WS];
#pragma unroll
for (int r = 0; r < WS; ++r)
src[r] = (r == rank) ? (in4 + (size_t)R4D_TS_OFF(rank))
: (my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16);
int4* my_out = out4 + (size_t)R4D_TS_OFF(rank);
const int my_lim = w1 < R4D_TS_LEN(rank) ? w1 : R4D_TS_LEN(rank);
for (int k = w0 + tid; k < my_lim; k += nt) {
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] += r4d_ar_to_f(pv[j]);
}
int4 o;
T* po = reinterpret_cast<T*>(&o);
#pragma unroll
for (int j = 0; j < LANES; ++j) r4d_ar_from_f(acc[j], po[j]);
my_out[k] = o;
#pragma unroll
for (int p = 0; p < NPEERS; ++p) pa[p][sh_max + k] = o; // region B
}
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s, drain, acq, pub);
/* The hold ends after the second handshake, not the first: the reduce above is fused with the
* phase-2 push (every reduced word goes to each peer's region B), so at the first handshake the
* link still carries this launch's phase-2 bytes. Here every phase-1 and phase-2 remote store
* has retired behind its flag store and every peer's pushes to this rank have been waited on;
* only the local assemble is left (r4d_ar_seq.h). */
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
// ---- assemble: every peer-owned shard from my region B copies
for (int p = 0; p < NPEERS; ++p) {
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)R4D_TS_OFF(owner);
const int lim = w1 < R4D_TS_LEN(owner) ? w1 : R4D_TS_LEN(owner);
for (int k = w0 + tid; k < lim; k += nt) dst[k] = srcB[k];
// 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 == R4D_AR8_FORM_LOCKSTEP ? i : (i + rank) % NPEERS;
const int owner = peers.rank[p];
const int4* s1 = in4 + (size_t)R4D_TS_OFF(owner);
int4* dst = pa[p];
const int lim = p1 < R4D_TS_LEN(owner) ? p1 : R4D_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 < R4D_TS_LEN(rank) ? p1 : R4D_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] += r4d_ar_to_f(pv[l]);
}
int4 o;
T* po = reinterpret_cast<T*>(&o);
#pragma unroll
for (int l = 0; l < LANES; ++l) r4d_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)R4D_TS_OFF(owner);
const int lim = p1 < R4D_TS_LEN(owner) ? p1 : R4D_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 != R4D_AR8_FORM_SPLIT) {
push1(0);
r4d_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);
r4d_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 (r4d_ar_seq.h). */
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
assemble(pieces - 1);
if (tl) {
__syncthreads();
r4d_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 (r4d_ar_seq.h). */
int n = 0;
auto tlp = [&]() { long long* p = tl ? tl + 1 + 2 * n : nullptr; ++n; return p; };
push1(0);
r4d_ar_publish<WS>(peers, b, rank, v0, drain, pub);
for (int j = 0; j < pieces; ++j) {
if (j + 1 < pieces) {
push1(j + 1);
r4d_ar_publish<WS>(peers, b, rank, v0 + 2u * (unsigned int)j + 1u, drain, pub);
}
r4d_ar_await<WS>(peers, my_flags, b, j == 0 ? v0 : v0 + 2u * (unsigned int)j - 1u, acq,
tlp());
reduce2(j);
r4d_ar_publish<WS>(peers, b, rank, v0 + 2u * (unsigned int)j + 2u, drain, pub);
if (j > 0) {
r4d_ar_await<WS>(peers, my_flags, b, v0 + 2u * (unsigned int)j, acq, tlp());
assemble(j - 1);
}
}
r4d_ar_await<WS>(peers, my_flags, b, v0 + 2u * (unsigned int)pieces, acq, tlp());
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
assemble(pieces - 1);
if (tl) {
__syncthreads();
r4d_ar_tl_stamp(tl, 1 + 2 * n);
}
}
#undef R4D_TS_OFF
#undef R4D_TS_LEN
if (CHAIN) r4d_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 r4d_arc_shfl(unsigned v, int src) {
return (unsigned)__builtin_amdgcn_ds_bpermute(src << 2, (int)v);
}
struct R4dArcEnc { 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__ R4dArcEnc r4d_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 = r4d_arc_shfl(emin, lane ^ s), b = r4d_arc_shfl(emax, lane ^ s);
const unsigned c = r4d_arc_shfl(bad, lane ^ s);
emin = a < emin ? a : emin; emax = b > emax ? b : emax; bad |= c;
}
R4dArcEnc 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 r4d_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 R4dArcRegion { unsigned* packed; unsigned* bases; int4* shadow; };
__host__ __device__ constexpr size_t r4d_arc_shadow_off(long SL) {
return ((size_t)12 * SL + (size_t)SL / 8 + 15) & ~(size_t)15;
}
__host__ __device__ constexpr size_t r4d_arc_region_bytes(long SL) {
return (r4d_arc_shadow_off(SL) + (size_t)16 * SL + 255) & ~(size_t)255;
}
__device__ __forceinline__ R4dArcRegion r4d_arc_region(const void* p, int SL) {
char* b = (char*)p;
return R4dArcRegion{(unsigned*)b, (unsigned*)(b + (size_t)12 * SL), (int4*)(b + r4d_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 r4d_arc_put(R4dArcRegion (&dst)[ND], int k0, const R4dArcEnc& 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 = r4d_arc_shfl(e.w[0], sl), a1 = r4d_arc_shfl(e.w[1], sl);
const unsigned a2 = r4d_arc_shfl(e.w[2], sl), vs = r4d_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 = r4d_arc_shfl(e.base, 0), b1 = r4d_arc_shfl(e.base, 8);
const unsigned b2 = r4d_arc_shfl(e.base, 16), b3 = r4d_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 r4d_arc_get(const R4dArcRegion& 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 = r4d_arc_shfl(ld[0], sl), a1 = r4d_arc_shfl(ld[1], sl);
const unsigned a2 = r4d_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 r4d_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 r4d_ar_twoshot_coded_body(
const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers,
const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags,
int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, int n16,
int slot_stride16, int rank, int drain, int acq, int pub,
long long* gate, unsigned int* gate_ctr) {
if (CHAIN) r4d_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 = r4d_ar_link_word(gate, (unsigned int)tid);
r4d_ar_seq_take(seq_ctrs, R4D_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 = r4d_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;
R4dArcRegion dst[1] = {r4d_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);
r4d_arc_put<1>(dst, k - lane, r4d_arc_enc(v, valid), v, valid);
}
}
r4d_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
R4dArcRegion srcA[WS], dstB[NPEERS];
#pragma unroll
for (int r = 0; r < WS; ++r)
srcA[r] = r4d_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] = r4d_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)) : r4d_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;
r4d_arc_put<NPEERS>(dstB, k0, r4d_arc_enc(o, valid), o, valid);
}
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s, drain, acq, pub);
r4d_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 R4dArcRegion src = r4d_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 = r4d_arc_get(src, k - lane, valid);
if (valid) dst[k] = v;
}
}
if (CHAIN) r4d_chain_done();
}
#define R4D_ARTS_PARAMS const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers, \
const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, \
int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, R4DArShardOff<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 R4D_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 r4d_ar_twoshot_wide_exact_kernel(R4D_ARTS_PARAMS) {
r4d_ar_twoshot_wide_exact_body<T, LANES, WS, PIECED, FORM, false>(R4D_ARTS_ARGS);
}
template <typename T, int LANES, int WS, bool PIECED, int FORM>
__global__ void r4dchain_ar_twoshot_wide_exact(R4D_ARTS_PARAMS) {
r4d_ar_twoshot_wide_exact_body<T, LANES, WS, PIECED, FORM, true>(R4D_ARTS_ARGS);
}
#undef R4D_ARTS_ARGS
#undef R4D_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 R4D_ARTC_PARAMS const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers, \
const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, \
int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, int n16, int slot_stride16, \
int rank, int drain, int acq, int pub, long long* gate, unsigned int* gate_ctr
#define R4D_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 r4d_ar_twoshot_coded_kernel(R4D_ARTC_PARAMS) {
r4d_ar_twoshot_coded_body<WS, false>(R4D_ARTC_ARGS);
}
template <int WS>
__global__ void r4dchain_ar_twoshot_coded(R4D_ARTC_PARAMS) {
r4d_ar_twoshot_coded_body<WS, true>(R4D_ARTC_ARGS);
}
#undef R4D_ARTC_ARGS
#undef R4D_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) {
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) +
@@ -133,11 +492,25 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags,
std::to_string(R4D_AR_TWOSHOT_WIDE_MAX_ELEMS) +
" elems); use the fallback path");
const long n16 = nbytes / 16;
if (n16 < WS)
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");
// the longest shard (the kernel's uneven split); regions A and B each hold one
const long sh_max = (n16 + WS - 1) / WS;
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] > R4D_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 = r4d_ar_shard_table(n16, WS, shard_weights, off);
R4DArShardOff<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 (" +
@@ -150,6 +523,16 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags,
int nt = (int)nthreads;
if (nt < 64) nt = 64;
if (nt > 1024) nt = 1024;
if (pieces < 1 || pieces > R4D_AR_TS_MAX_PIECES)
throw std::runtime_error("all_reduce: pieces " + std::to_string(pieces) + " outside 1.." +
std::to_string((int)R4D_AR_TS_MAX_PIECES));
if (form < R4D_AR8_FORM_LOCKSTEP || form > R4D_AR8_FORM_SPLIT ||
(WS != 8 && form != R4D_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);
R4DArWidePeers<int4, NPEERS> peers{};
for (int i = 0; i < NPEERS; ++i) {
@@ -175,17 +558,38 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags,
}
hipStream_t st = (hipStream_t)stream_i;
#define R4D_AR_TS_LAUNCH(T, LN) \
r4d_ar_twoshot_wide_exact_kernel<T, LN, WS><<<nb, nt, 0, st>>>( \
#define R4D_AR_TS_LAUNCH_F(T, LN, P, F) \
(chain ? r4dchain_ar_twoshot_wide_exact<T, LN, WS, P, F> \
: r4d_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, (int)n16, (int)slot_stride16, \
(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)
(unsigned int*)gate_ctr, np, (long long*)timeline)
#define R4D_AR_TS_LAUNCH_P(T, LN, P) \
do { \
if constexpr (WS == 8) { \
if (form == R4D_AR8_FORM_RING) \
R4D_AR_TS_LAUNCH_F(T, LN, P, R4D_AR8_FORM_RING); \
else if (form == R4D_AR8_FORM_SPLIT) \
R4D_AR_TS_LAUNCH_F(T, LN, P, R4D_AR8_FORM_SPLIT); \
else \
R4D_AR_TS_LAUNCH_F(T, LN, P, R4D_AR8_FORM_LOCKSTEP); \
} else { \
R4D_AR_TS_LAUNCH_F(T, LN, P, R4D_AR8_FORM_LOCKSTEP); \
} \
} while (0)
#define R4D_AR_TS_LAUNCH(T, LN) \
do { \
if (np > 1) R4D_AR_TS_LAUNCH_P(T, LN, true); \
else R4D_AR_TS_LAUNCH_P(T, LN, false); \
} while (0)
if (dtype == 0) R4D_AR_TS_LAUNCH(__hip_bfloat16, 8);
else if (dtype == 1) R4D_AR_TS_LAUNCH(__half, 8);
else if (dtype == 2) R4D_AR_TS_LAUNCH(float, 4);
else throw std::runtime_error("all_reduce: bad dtype");
#undef R4D_AR_TS_LAUNCH
#undef R4D_AR_TS_LAUNCH_P
#undef R4D_AR_TS_LAUNCH_F
}
void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long peer_flags0,
@@ -197,7 +601,8 @@ void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long pee
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);
dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L, nullptr,
1L, 0L, 0L);
}
void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2,
@@ -205,11 +610,56 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee
long my_scratch, long my_flags, long seq_ctrs,
long slot_stride16, long inp, long out, long n_elem, long dtype,
long rank, long stream, long nblocks, long nthreads, long drain,
long acq, long pub, long gate, long gate_ctr) {
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);
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 r4d_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 * r4d_arc_region_bytes(SL) <= (size_t)slot_stride16 * 16 ? 1 : 0;
}
void r4d_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 (!r4d_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 > R4D_AR_WIDE_MAX_BLOCKS) nb = R4D_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;
R4DArWidePeers<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 ? r4dchain_ar_twoshot_coded<WS> : r4d_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 r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2,
@@ -219,12 +669,15 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee
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) {
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);
dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L,
shard_weights, pieces, timeline, form);
}
+73 -4
View File
@@ -1,7 +1,8 @@
#pragma once
// r4d_ar_wide.h: shared transport of the wide (ws>2) all-reduce family. Every wide kernel
// (one-shot exact, two-shot exact, two-shot ti8) publishes in the 2*seq flag space (the two-shots
// add the 2s-1 half-step), advances seq_ctrs[b] once per AR, and lays scratch out as 2*ws slots of
// 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
// r4d_ar_seq.h, so seq_ctrs is 2 * R4D_AR_WIDE_MAX_BLOCKS words. The constants sizing the shared
// flag/seq/scratch set are defined only here so they cannot drift apart.
@@ -15,6 +16,7 @@
#include <stdexcept>
#include <string>
#include "r4d_ar_seq.h"
#include "r4d_ar_shards.h"
#define R4D_AR_SPIN_MAX 4000000000ULL
#define R4D_AR_WIDE_MAX_BLOCKS 64
@@ -53,7 +55,9 @@ __device__ __forceinline__ void r4d_ar_drain(int drain) {
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
}
// acq: 0 acquire-only fence (global_inv, no writeback half), 1 full threadfence_system,
// 2 none -- fine-grained scratch only.
// 2 none -- fine-grained scratch only. Every thread of the block runs it after the handshake, so at
// 0 or 1 that is one system-scope invalidate a wave. The P2P scratch is fine-grained (the reads
// bypass L2; r4d_ar_entry.hip's allocation says why), so 2 is the documented design there.
__device__ __forceinline__ void r4d_ar_acquire(int acq) {
if (acq == 1) __threadfence_system();
else if (acq != 2) __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "");
@@ -63,17 +67,31 @@ __device__ __forceinline__ void r4d_ar_acquire(int acq) {
// 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 (r4d_ar_tl_stamp).
template <int WS, typename S, int NPEERS>
__device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers<S, NPEERS>& peers,
unsigned int* __restrict__ my_flags, int b,
int rank, unsigned int val, int drain, int acq,
int pub) {
int pub, long long* tl = nullptr) {
r4d_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) {
if (pub == 2) {
// No release fence: the flags go out behind the data with nothing written back. Meant for
// a P2P instance with drain 3, on the reasoning that fine-grained scratch stores reach past
// L2. They do not: on 4x R9700 the readers saw stale scratch on nearly every element
// (r4d_selftest, 2026-10-17), so no tuned point selects pub 2 (tArQ84); it is kept only
// as the measured negative.
#pragma unroll
for (int p = 0; p < NPEERS; ++p)
r4d_ar_store_sys_rlx(&peers.flags[p][(size_t)b * WS + rank], val);
} else 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, "");
@@ -95,9 +113,60 @@ __device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers<S, NPEERS>
}
}
__syncthreads();
if (tl && tid == 0) tl[1] = (long long)wall_clock64();
r4d_ar_acquire(acq);
}
// The two halves of r4d_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 r4d_ar_publish(const R4DArWidePeers<S, NPEERS>& peers, int b,
int rank, unsigned int val, int drain, int pub) {
r4d_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)
r4d_ar_store_sys_rlx(&peers.flags[p][(size_t)b * WS + rank], val);
} else {
#pragma unroll
for (int p = 0; p < NPEERS; ++p)
r4d_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 r4d_ar_handshake's, stamped on entry and on release.
template <int WS, typename S, int NPEERS>
__device__ __forceinline__ void r4d_ar_await(const R4DArWidePeers<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)(r4d_ar_load_sys_rlx(f) - val) < 0) {
__builtin_amdgcn_s_sleep(2);
if (++z > R4D_AR_SPIN_MAX) __builtin_trap(); // lockstep violation
}
}
__syncthreads();
if (tl && tid == 0) tl[1] = (long long)wall_clock64();
r4d_ar_acquire(acq);
}
// The two-shot timeline (layout in r4d_ar_shards.h), one stamp of the device wall clock.
static_assert(R4D_AR_TL_BLOCKS == R4D_AR_WIDE_MAX_BLOCKS, "r4d_ar_shards.h restates the ceiling");
__device__ __forceinline__ void r4d_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.
+10
View File
@@ -357,8 +357,18 @@ void r4d_cfg_mxfp4_tiled(const RadArgs*, struct R4dMxTileCfg*);
void r4d_cfg_mxfp4_decode(const RadArgs*, struct R4dMxDecCfg*);
void r4d_cfg_split (const RadArgs*, struct R4dSplitCfg*);
void r4d_cfg_ar (const RadArgs*, struct R4dArCfg*);
/* Whether the four-rank fused junction takes its tail form from 5 rows (the row's `tail` axis). */
int r4d_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 r4d_cfg_ar_ts_min(const RadArgs*);
/* The prefetch's workgroup count (the row's `nb` axis). */
int r4d_cfg_prefetch_nb(const RadArgs*);
void r4d_cfg_topk (const RadArgs*, struct R4dTopkCfg*);
void r4d_cfg_mv (const RadArgs*, struct R4dMvCfg*);
/* 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 r4d_cfg_rmsq8_reg(const RadArgs*);
} /* extern "C" */
+26 -5
View File
@@ -39,8 +39,14 @@ enum { AP_Q = 0, AP_KV, AP_BT, AP_SEQ, AP_KDS, AP_VDS, AP_CU, AP_OUT };
* 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.
*/
static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) {
/* `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, R4DArgs* r, int expect_head_dim, long long row,
bool q_pitched = false) {
const RadTensor* q = r4d_opt(a, AP_Q);
const RadTensor* kv = r4d_opt(a, AP_KV);
const RadTensor* bt = r4d_opt(a, AP_BT);
@@ -72,8 +78,16 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim)
}
/* q and out are indexed as one dense [total_q, q_heads, head_dim] block; the kernel has no
* pitch argument for either. */
if (!r4d_contig(q) || !r4d_contig(o)) return R4D_NO(RAD_E_STRIDE);
* 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 && !r4d_contig(q)) {
q_ld = r4d_row_pitch(q);
if (q_ld < q_heads * head_dim || q_ld % 4) return R4D_NO(RAD_E_STRIDE);
} else if (!r4d_contig(q)) {
return R4D_NO(RAD_E_STRIDE);
}
if (!r4d_contig(o)) return R4D_NO(RAD_E_STRIDE);
if (o->shape[0] != total_q || r4d_numel(o) != total_q * q_heads * head_dim)
return R4D_NO(RAD_E_SHAPE);
if (su->shape[0] != num_seqs) return R4D_NO(RAD_E_SHAPE);
@@ -83,8 +97,8 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim)
* Each (block, head) slot must be dense, because the kernel walks it with vector loads. */
const long long block_size = kv->shape[2];
if (kv->stride[3] != 1) return R4D_NO(RAD_E_STRIDE);
if (kv->stride[2] != 2 * head_dim) return R4D_NO(RAD_E_STRIDE);
if (kv->shape[3] != 2 * head_dim) return R4D_NO(RAD_E_SHAPE);
if (kv->stride[2] != row) return R4D_NO(RAD_E_STRIDE);
if (kv->shape[3] != row) return R4D_NO(RAD_E_SHAPE);
/* 16-byte alignment for 128-bit loads. */
if (!r4d_aligned(q->data, 16) || !r4d_aligned(o->data, 16) || !r4d_aligned(kv->data, 16))
@@ -102,6 +116,7 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim)
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;
@@ -139,6 +154,7 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim)
/* Set by the caller from the tuned `splits`; 0 means libr4d's own split law. */
r->splits = 0;
r->chain = r4d_geti_or(a, "chain", 0) != 0 ? 1 : 0;
return RAD_OK;
}
@@ -150,4 +166,9 @@ static inline int split_of(const RadArgs* a) {
}
static inline int fill_paged(const RadArgs* a, R4DArgs* 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 /* R4D_ATTN_ARGS_H */
+164 -20
View File
@@ -15,6 +15,7 @@
#include "r4d_common.h"
#include "r4d_dt16.h"
#include "r4d_q8.h" // the gate quantiser's 8-bit codes: E4M3, or int8 (GQ == 2)
#include "r4d_chain.h"
#include <algorithm>
#include <type_traits>
@@ -52,6 +53,17 @@
// fragment for fp8, 16 for bf16), costing 2 or 4 x HEAD_DIM/16 VGPRs; PF = HEAD_DIM/16 would hold
// converted fragments and cost occupancy. Results are unchanged.
#define O_KRAW 16777216
// O_V4: the fp8_v4 cache (E4M3 K, int4 V in groups of 32 with an f16 scale), and with O_K6 the
// k6_v4 cache (int6 K, int4 V); a token's row layout is RadBuildCtx::kv_quant's (abi/rad_builder.h).
#define O_V4 33554432
#define O_K6 67108864
// The two views of R4DArgs (r4d.h), compiled in only where a row asks for them, since the h256
// instances sit at the 256-VGPR bound and a runtime pitch and head map spill there:
// QLD q rows at R4DArgs::q_ld (attn_paged_qrow), not dense.
// KVREP query group g reads cache head g / R4DArgs::kv_rep, descales per cache head.
// Neither changes the arithmetic.
#define O_QLD 134217728
#define O_KVREP 268435456
__host__ __device__ __forceinline__ int r4d_attn_tiles(int ctx, int tile) { return (ctx + tile - 1) / tile; }
__host__ __device__ __forceinline__ int r4d_attn_tps(int ctx, int tile, int splits) {
int t = r4d_attn_tiles(ctx, tile); return (t + splits - 1) / splits;
@@ -69,10 +81,12 @@ __host__ __device__ __forceinline__ int r4d_attn_used(int ctx, int tile, int spl
// WIN enables a sliding window (a.window positions ending at each row's causal limit). As a
// template parameter defaulting to 0, full attention compiles with no window code.
// The body: its blocks return early (empty slots, tiles past the window), so the chained form
// (r4d_chain.h) wraps it below rather than bracketing it in place.
template<int NWARPS, int TILE, int HEAD_DIM, int GQA, int BS, int KVP, int OPT,
int WIN = 0>
__global__ __launch_bounds__(NWARPS * 32)
void r4d_attn_decode_kernel(const R4DArgs a, int splits)
__device__ __forceinline__
void r4d_attn_decode_body(const R4DArgs& a, int splits)
{
constexpr int F16 = (OPT & O_F16) ? 1 : 0;
constexpr int MSKIP = (OPT & O_MSKIP) ? 1 : 0;
@@ -85,10 +99,22 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
constexpr int DOT2 = ((OPT & O_DOT2) && (OPT & O_F16)) ? 1 : 0;
constexpr int BTS = (OPT & O_BTS) ? 1 : 0;
constexpr int LDSB = (OPT & O_LDSB) ? 1 : 0;
constexpr int V8 = ((OPT & O_V8) && !KVP) ? 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 V8 = ((OPT & O_V8) && !KVP && !V4) ? 1 : 0;
static_assert(!V8 || (OPT & O_CONTIG), "the code tile is read in the contiguous layout");
constexpr int KRAW = ((OPT & O_KRAW) && !KLDS) ? 1 : 0;
static_assert(!KRAW || (OPT & O_CONTIG), "the raw K round reads the contiguous layout");
static_assert(!K6 || (!KLDS && (OPT & O_CONTIG) && !KRAW),
"k6_v4 K is widened from the paged cache, a lane's eight dims contiguous");
static_assert(!V4 || (OPT & O_F16), "fp8_v4 widens to f16");
constexpr int QLD = (OPT & O_QLD) ? 1 : 0;
constexpr int KVREP = (OPT & O_KVREP) ? 1 : 0;
typedef DT16<F16> D;
typedef typename D::frag frag16;
@@ -104,7 +130,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
// Up to three uint4 it fits in 255 VGPRs without spilling (two: +6-8% at depth; three, the
// 48-row shape q_len 8 x gqa 6 at NWARPS 3: a further 2-15%). At four or more (NWARPS 1-2, or a
// bf16 cache) it spills and loses ~10%, so the geometry gates it, not just the flag.
constexpr int GPREV = ((OPT & O_GPREV) && VREGS <= 3) ? 1 : 0;
constexpr int GPREV = ((OPT & O_GPREV) && VREGS <= 3 && !V4) ? 1 : 0;
constexpr float PSHIFT = D::SHIFT;
constexpr float PGROW = D::GROW;
@@ -119,6 +145,8 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
const int c = lane & 15, h = lane >> 4;
const int sp = blockIdx.x, kvh = blockIdx.y, seq = blockIdx.z;
// kvh is the query group; under KVREP the cache head it reads is kvh / kv_rep
const int kvc = KVREP ? kvh / a.kv_rep : kvh;
const int ctx = a.seqused_k[seq];
if (ctx <= 0) return;
@@ -147,13 +175,17 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
const int qhead = kvh * GQA + hi;
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 kdesc = a.k_descale
? a.k_descale[seq * (KVREP ? a.kv_heads / a.kv_rep : a.kv_heads) + kvc]
: 1.0f;
const float mul = a.scale * kdesc * 1.44269504089f;
frag16 qf[NKS];
{
const uint16_t* qp = (const uint16_t*)a.q
+ ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM;
const uint16_t* qp = QLD ? (const uint16_t*)a.q + (size_t)(qoff + qrow) * a.q_ld
+ (size_t)qhead * HEAD_DIM
: (const uint16_t*)a.q
+ ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM;
#pragma unroll
for (int t = 0; t < NKS; ++t) {
const uint2 l0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h : 4 * h));
@@ -185,6 +217,62 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
const int vg = lane >> 3, vj = lane & 7;
uint4 vreg[VREGS];
// ---- fp8_v4 / k6_v4: V's int4 codes into sV16 ([dim][key]) as the prefill kernel stages them
// (r4d_attn_prefill_h256_gqa6.hip: a key pair's 8 dims a thread, two code words and the pair's
// scale, widened with packed f16 into one dword a dim), fetched in the tile: no prefetch.
constexpr int NP4 = (TILE / 2) * (HEAD_DIM / 8);
constexpr int U4 = V4 ? (NP4 + NTHR - 1) / NTHR : 1;
uint32_t v4c[U4][2], v4s[U4];
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) {
int kk = min(k0 + 2 * kp + j, ctx - 1);
if (WIN && kk < wlo0) kk = wlo0;
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);
}
v4s[r] = sc[0] | (sc[1] << 16);
}
}
};
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);
// 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, v4s[r]);
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) {
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;
const uint32_t hi = __builtin_amdgcn_perm(m1, m0, sel) | 0x64006400u;
const h2 vl = (__builtin_bit_cast(h2, lo) - bias) * s2;
const h2 vh = (__builtin_bit_cast(h2, hi) - bias) * s2;
*(uint32_t*)(dst + (2 * b) * VSTR) = __builtin_bit_cast(uint32_t, vl);
*(uint32_t*)(dst + (2 * b + 1) * VSTR) = __builtin_bit_cast(uint32_t, vh);
}
}
}
};
auto fetchV = [&](int k0, const int* blks) {
#pragma unroll
for (int r = 0; r < VREGS; ++r) {
@@ -197,8 +285,8 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
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) * (2 * HEAD_DIM) + HEAD_DIM + d0;
+ (size_t)kvc * 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));
@@ -275,7 +363,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
if (WIN && kk < wlo0) kk = wlo0;
const int kb = BTS ? blk[(kk - k0) / BS] : bt[kk / BS];
const size_t o = (size_t)kb * a.kv_block_stride
+ (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * (2 * HEAD_DIM);
+ (size_t)kvc * a.kv_head_stride + (size_t)(kk % BS) * ROWB;
uint16_t* kd = &sK[key * KSTR];
uint32_t w4[4];
if (KVP) {
@@ -289,8 +377,8 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
*(uint2*)(kd + ch * 8 + 4) = make_uint2(w4[2], w4[3]);
}
}
if (!GPREV) fetchV(k0, blk);
storeV();
if constexpr (V4) { fetchV4(k0, blk); storeV4(); }
else { if (!GPREV) fetchV(k0, blk); storeV(); }
if (LDSB) lds_barrier(); else __syncthreads();
if (GPREV && ti + 1 < t_hi) fetchV(k0 + TILE, blkn);
@@ -302,7 +390,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
if (WIN && kk < wlo0) kk = wlo0;
const int kb = BTS ? blk[(kk - k0) / BS] : bt[kk / BS];
grow = (const uint8_t*)a.kv + ((size_t)kb * a.kv_block_stride
+ (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * (2 * HEAD_DIM))
+ (size_t)kvc * a.kv_head_stride + (size_t)(kk % BS) * ROWB)
* (KVP ? 2 : 1);
}
// A fragment's raw K: 8 elements of 1 byte (fp8) or 2 (bf16).
@@ -341,6 +429,15 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
}
kb[j] = D::mk(make_uint2(D::from_bf16w(l0.x), D::from_bf16w(l0.y)),
make_uint2(D::from_bf16w(h0.x), D::from_bf16w(h0.y)));
} else if constexpr (K6) {
// k6_v4: this lane's eight dims (16t + 8h ..) from their low nibbles, the
// chunk's high-bit word and the group's scale.
uint32_t w4[4];
const uint32_t sb = *(const uint16_t*)(grow + KSOFF + (t >> 1) * 2);
k6x8_to_f16x4w(*(const uint32_t*)(grow + 8 * t + 4 * h),
*(const uint32_t*)(grow + HEAD_DIM / 2 + 4 * t), h,
sb | (sb << 16), w4);
kb[j] = D::mk(make_uint2(w4[0], w4[1]), make_uint2(w4[2], w4[3]));
} else {
const uint8_t* kp = grow + 16 * t;
uint32_t w4[4];
@@ -504,6 +601,24 @@ __device__ __forceinline__ uint16_t r4d_gq_gate(uint16_t gb, uint16_t xb) {
}
__device__ __forceinline__ float r4d_gq_clamp(float v) { return fminf(fmaxf(v, -448.0f), 448.0f); }
// The plain decode kernel, and the chained one (r4dchain*, r4d_chain.h) over the same body.
template<int NWARPS, int TILE, int HEAD_DIM, int GQA, int BS, int KVP, int OPT,
int WIN = 0>
__global__ __launch_bounds__(NWARPS * 32)
void r4d_attn_decode_kernel(const R4DArgs a, int splits)
{
r4d_attn_decode_body<NWARPS, TILE, HEAD_DIM, GQA, BS, KVP, OPT, WIN>(a, splits);
}
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 r4dchain_attn_decode(const R4DArgs a, int splits)
{
r4d_chain_wait();
r4d_attn_decode_body<NWARPS, TILE, HEAD_DIM, GQA, BS, KVP, OPT, WIN>(a, splits);
r4d_chain_done();
}
// Vectorised merge, used by the h256 launcher whenever the split count fits a wave. Bit-identical
// to splitkv_combine_body below; only the thread map differs. One wave owns one output row and
// each lane HEAD_DIM/32 dims, so a segment is one 16-byte load per lane; a block carries JPB rows.
@@ -651,8 +766,9 @@ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DG
}
}
const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads);
const float vd = a.v_descale ? a.v_descale[seq * a.kv_heads + kvh] : 1.0f;
const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads); /* the query group */
const int krep = a.kv_rep > 1 ? a.kv_rep : 1; /* its cache head: kvh / krep */
const float vd = a.v_descale ? a.v_descale[seq * (a.kv_heads / krep) + kvh / krep] : 1.0f;
uint16_t ob[DPL];
#pragma unroll
for (int j = 0; j < DPL; ++j) {
@@ -672,6 +788,15 @@ void r4d_attn_splitkv_combine_vec_kernel(const R4DArgs a, int splits, int tile)
splitkv_combine_vec_body<HEAD_DIM, CHAINS, PF16, JPB, WIN, 0>(a, splits, tile,
R4DGateQuant{});
}
template<int HEAD_DIM, int CHAINS, int PF16, int JPB, int WIN = 0>
__global__ __launch_bounds__(32 * JPB)
void r4dchain_attn_splitkv_combine_vec(const R4DArgs a, int splits, int tile)
{
r4d_chain_wait();
splitkv_combine_vec_body<HEAD_DIM, CHAINS, PF16, JPB, WIN, 0>(a, splits, tile,
R4DGateQuant{});
r4d_chain_done();
}
template<int HEAD_DIM, int CHAINS, int PF16, int JPB, int WIN = 0, int GQ = 1>
__global__ __launch_bounds__(32 * JPB)
void r4d_attn_splitkv_combine_vec_gq_kernel(const R4DArgs a, int splits, int tile,
@@ -794,8 +919,9 @@ void splitkv_combine_body(const R4DArgs& a, int splits, int tile, const R4DGateQ
#pragma unroll
for (int i = 0; i < CHAINS; ++i) av += ch[i];
const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads);
const float vd = a.v_descale ? a.v_descale[seq * a.kv_heads + kvh] : 1.0f;
const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads); /* the query group */
const int krep = a.kv_rep > 1 ? a.kv_rep : 1; /* its cache head: kvh / krep */
const float vd = a.v_descale ? a.v_descale[seq * (a.kv_heads / krep) + kvh / krep] : 1.0f;
finish(f32_to_bf16(tot > 0.0f ? av * vd / tot : 0.0f));
}
@@ -805,6 +931,14 @@ void r4d_attn_splitkv_combine_kernel(const R4DArgs a, int splits, int tile)
{
splitkv_combine_body<HEAD_DIM, CHAINS, PF16, WIN, 0>(a, splits, tile, R4DGateQuant{});
}
template<int HEAD_DIM, int CHAINS, int PF16, int WIN = 0>
__global__ __launch_bounds__(HEAD_DIM)
void r4dchain_attn_splitkv_combine(const R4DArgs a, int splits, int tile)
{
r4d_chain_wait();
splitkv_combine_body<HEAD_DIM, CHAINS, PF16, WIN, 0>(a, splits, tile, R4DGateQuant{});
r4d_chain_done();
}
template<int HEAD_DIM, int CHAINS, int PF16, int WIN = 0, int GQ = 1>
__global__ __launch_bounds__(HEAD_DIM)
void r4d_attn_splitkv_combine_gq_kernel(const R4DArgs a, int splits, int tile,
@@ -882,9 +1016,13 @@ static int r4d_decode_launch_win(const R4DArgs* a, hipStream_t s) {
if (rows > 64) return -4;
const int nw = (rows + 15) / 16;
const int splits = r4d_decode_splits_win(a, TILE);
#define R4D_WIN_LAUNCH(NW) \
#define R4D_WIN_LAUNCH(NW) do { if (a->chain) \
hipLaunchKernelGGL((r4dchain_attn_decode<NW, TILE, HEAD_DIM, GQA, BS, KVP, OPT, 1>), \
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits); \
else \
hipLaunchKernelGGL((r4d_attn_decode_kernel<NW, TILE, HEAD_DIM, GQA, BS, KVP, OPT, 1>), \
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits)
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits); \
} while (0)
if (nw == 1) R4D_WIN_LAUNCH(1);
else if (nw == 2) R4D_WIN_LAUNCH(2);
else if (nw == 3) R4D_WIN_LAUNCH(3);
@@ -894,9 +1032,15 @@ static int r4d_decode_launch_win(const R4DArgs* a, hipStream_t s) {
if (e != hipSuccess) return -100 - (int)e;
const int jobs3 = r4d_q_total(*a) * a->q_heads;
if (splits <= 64 && jobs3 >= VECMIN)
if (splits <= 64 && jobs3 >= VECMIN && a->chain)
hipLaunchKernelGGL((r4dchain_attn_splitkv_combine_vec<HEAD_DIM, 4, PF16, JPB, 1>),
dim3((jobs3 + JPB - 1) / JPB), dim3(32 * JPB), 0, s, *a, splits, TILE);
else if (splits <= 64 && jobs3 >= VECMIN)
hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel<HEAD_DIM, 4, PF16, JPB, 1>),
dim3((jobs3 + JPB - 1) / JPB), dim3(32 * JPB), 0, s, *a, splits, TILE);
else if (a->chain)
hipLaunchKernelGGL((r4dchain_attn_splitkv_combine<HEAD_DIM, 4, PF16, 1>), dim3(jobs3),
dim3(HEAD_DIM), splits * sizeof(float), s, *a, splits, TILE);
else
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<HEAD_DIM, 4, PF16, 1>), dim3(jobs3),
dim3(HEAD_DIM), splits * sizeof(float), s, *a, splits, TILE);
+42 -32
View File
@@ -1,8 +1,9 @@
// R4D 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). bf16 in and out, f16 operands, f32 accumulate. Head
// widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair is a row.
// 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 (r4d_attn_vit_h72_bf16.hip): S^T = K.Q^T, so the wave32
// column-distributed accumulator gives each lane one query row, softmax state is lane-private, and
@@ -39,7 +40,8 @@ __global__ __launch_bounds__(NQB * GQA * DSPLIT * 32)
void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, float scale, int window, int wright,
int block, int cdiv, int causal, int q_ld, int k_ld, int v_ld, int o_ld)
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;
@@ -73,8 +75,9 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
const int dp = warp % DSPLIT;
const int g = (warp / DSPLIT) % GQA;
const int qbi = warp / (DSPLIT * GQA);
const int kvh = blockIdx.y, seq = blockIdx.z;
const int hq = kvh * GQA + g;
// 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;
@@ -302,21 +305,25 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
// 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) — an encoder's own heads
// h256 gqa2: 8 query blocks x 2 heads, tiles of 32 (LDS: 37 KiB)
// h256 gqa4: 4 query blocks x 4 heads, tiles of 32 (LDS: 37 KiB)
// h512 gqa4: 2 query blocks x 4 heads x 2 head halves, tiles of 16 (LDS: 57 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 r4d_attn_dense_launch(const void* q, const void* k, const void* v, void* o,
const void* cu, int num_seqs, int max_seqlen, int n_head_kv,
float scale, int window, int wright, int block, int cdiv,
int causal, int q_ld, int k_ld, int v_ld, int o_ld, hipStream_t s)
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, num_seqs);
dim3 grid((max_seqlen + BQ - 1) / BQ, n_head_kv * krep, num_seqs);
hipLaunchKernelGGL((r4d_attn_dense_kernel<HD, GQA, NQB, DSPLIT, TILE>), grid,
dim3(NQB * GQA * DSPLIT * 32), 0, s, (const uint16_t*)q, (const uint16_t*)k,
(const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, wright,
block, cdiv, causal, q_ld, k_ld, v_ld, o_ld);
block, cdiv, causal, q_ld, k_ld, v_ld, o_ld, krep);
const hipError_t e = hipGetLastError();
return e == hipSuccess ? 0 : -100 - (int)e;
}
@@ -339,32 +346,35 @@ extern "C" int r4d_attn_dense_bf16(const void* q, const void* k, const void* v,
return -4;
if (num_seqs <= 0 || max_seqlen <= 0) return 0;
if (wright == 0) wright = window;
const int gqa = n_head / n_head_kv;
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 r4d_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);
if (head_dim == 256 && gqa == 1)
return r4d_attn_dense_launch<256, 1, 8, 1, 32>(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);
if (head_dim == 256 && gqa == 2)
return r4d_attn_dense_launch<256, 2, 8, 1, 32>(q, k, v, o, cu_seqlens, num_seqs,
max_seqlen, n_head_kv, scale, window,
wright, block, cdiv, causal, q_ld, k_ld,
v_ld, o_ld, s);
if (head_dim == 256 && gqa == 4)
return r4d_attn_dense_launch<256, 4, 4, 1, 32>(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);
if (head_dim == 512 && gqa == 4)
return r4d_attn_dense_launch<512, 4, 2, 2, 16>(q, k, v, o, cu_seqlens, num_seqs,
max_seqlen, n_head_kv, scale, window,
wright, block, cdiv, causal, q_ld, k_ld,
v_ld, o_ld, s);
#define R4D_DENSE(HD, G, NQB, DS, T) \
return r4d_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: R4D_DENSE(256, 1, 8, 1, 32); /* an encoder's own heads */
case 2: R4D_DENSE(256, 2, 8, 1, 32);
case 4: R4D_DENSE(256, 4, 4, 1, 32);
case 8: R4D_DENSE(256, 8, 2, 1, 32);
default: return -1;
}
}
if (head_dim == 512) {
switch (gqa) {
case 2: R4D_DENSE(512, 2, 4, 2, 16);
case 4: R4D_DENSE(512, 4, 2, 2, 16);
case 8: R4D_DENSE(512, 8, 1, 2, 16);
default: return -1;
}
}
#undef R4D_DENSE
return -1;
}
+81 -19
View File
@@ -69,7 +69,8 @@ __global__ __launch_bounds__(NQB * GQA * 32)
void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const int8_t* __restrict__ gk8, const float* __restrict__ gks,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, int num_seqs, const int* __restrict__ used,
const int* __restrict__ cu, const int* __restrict__ cuk, int num_seqs,
const int* __restrict__ used,
const int* __restrict__ bt, int bt_pitch,
const uint16_t* __restrict__ kvc, int kv_heads,
float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld,
@@ -137,7 +138,10 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
if (slen <= 0 || q0 >= slen) return;
const int qlast = min(q0 + BQ, slen) - 1;
const int P = used ? used[seq] : 0;
const int ke = causal ? qlast + 1 : slen; // own keys any query here can see
// Own keys: beside the queries, or (`cuk`, attn_cross) a run of their own; a query sees key j
// of its run, counted from the run's start, when j <= its own row with `causal`.
const int ks0 = cuk ? cuk[seq] : s0, klen = cuk ? cuk[seq + 1] - ks0 : slen;
const int ke = causal ? min(qlast + 1, klen) : klen; // own keys any query here can see
const float mul = scale * 1.44269504089f;
const int qpos = q0 + qbi * 16 + c;
@@ -193,12 +197,12 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
// The K row of key `kk` of the current source; its V row is `vrow`.
auto krow = [&](bool pre, int kk) -> const uint16_t* {
if (!pre) return kbase + (long)(s0 + kk) * k_ld;
if (!pre) return kbase + (long)(ks0 + kk) * k_ld;
const int blk = btrow[kk / BS];
return kvc + ((long)(blk * kv_heads + kvh) * BS + (kk % BS)) * (2 * HD);
};
auto vrow = [&](bool pre, int kk) -> const uint16_t* {
if (!pre) return vbase + (long)(s0 + kk) * v_ld;
if (!pre) return vbase + (long)(ks0 + kk) * v_ld;
const int blk = btrow[kk / BS];
return kvc + ((long)(blk * kv_heads + kvh) * BS + (kk % BS)) * (2 * HD) + HD;
};
@@ -222,12 +226,12 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
if ((TILE * K8G) % NTHR == 0 || i < TILE * K8G) {
const int key = i / K8G, gg = i % K8G;
const int kk = (k0 + key < klim) ? k0 + key : klim - 1;
kr[p] = *(const uint4*)(gk8 + (long)(s0 + kk) * k8_ld + (long)kvh * HD + gg * 16);
kr[p] = *(const uint4*)(gk8 + (long)(ks0 + kk) * k8_ld + (long)kvh * HD + gg * 16);
}
}
if (tid < TILE) {
const int kk = (k0 + tid < klim) ? k0 + tid : klim - 1;
ksr = gks[(long)(s0 + kk) * ks_ld + kvh];
ksr = gks[(long)(ks0 + kk) * ks_ld + kvh];
}
} else {
#pragma unroll
@@ -243,7 +247,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
if constexpr (PV8) {
const int kk0 = k0 + (lgi / DG8) * 8 + vj;
const int kk = (kk0 < klim) ? kk0 : klim - 1;
const uint8_t* v8 = (const uint8_t*)gv + (long)(s0 + kk) * v_ld + (long)kvh * HD;
const uint8_t* v8 = (const uint8_t*)gv + (long)(ks0 + kk) * v_ld + (long)kvh * HD;
vr[0] = __builtin_bit_cast(uint4, load_tr_b128(v8 + (lgi % DG8) * 16));
} else {
#pragma unroll
@@ -597,7 +601,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
template<int HD, int GQA, int NQB, int TILE, bool I8, bool PV8>
static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, const float* ks,
const void* v, void* o, const int* cu,
const void* v, void* o, const int* cu, const int* cuk,
const int* used, const int* bt, int bt_pitch, const void* kvc,
int num_seqs, int max_q, int n_head_kv, float scale, int causal,
int q_ld, int k_ld, int k8_ld, int ks_ld, int v_ld, int o_ld,
@@ -609,14 +613,15 @@ static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, cons
hipLaunchKernelGGL((r4d_attn_ps_kernel<HD, GQA, NQB, TILE, I8, PV8>), grid,
dim3(NQB * GQA * 32), 0, s,
(const uint16_t*)q, (const uint16_t*)k, (const int8_t*)k8, ks,
(const uint16_t*)v, (uint16_t*)o, cu, num_seqs, used, bt, bt_pitch,
(const uint16_t*)v, (uint16_t*)o, cu, cuk, num_seqs, used, bt, bt_pitch,
(const uint16_t*)kvc, n_head_kv, scale, causal, q_ld, k_ld, k8_ld, ks_ld,
v_ld, o_ld, vs);
const hipError_t e = hipGetLastError();
return e == hipSuccess ? 0 : -100 - (int)e;
}
/* head_dim 128 at gqa 1, 2, 4 and 8. Null `used`/`bt`/`kvc` means no prefix (the dense form).
/* head_dim 128 at gqa 1, 2, 4 and 8, and 64 (an audio stream's heads) without a prefix or the
* int8 and fp8 forms. Null `used`/`bt`/`kvc` means no prefix (the dense form).
* `max_q` is the total query rows over all sequences and bounds the flat grid. Non-null `k8`
* selects the int8 Q.K form (own-key codes, `k8_ld` bytes per row; a scale per (row, head) in
* `ks`, `ks_ld` floats per row), gqa 1 only. Non-null `vs` selects the fp8 P.V form (`v` as E4M3
@@ -626,16 +631,34 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float
const int* used, const int* bt, int bt_pitch, const void* kvc,
int num_seqs, int max_q, int n_head, int n_head_kv, int head_dim,
float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld,
int v_ld, int o_ld, hipStream_t s, const float* vs = nullptr)
int v_ld, int o_ld, hipStream_t s, const float* vs = nullptr,
const int* cuk = nullptr)
{
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 (k8 && ((k8_ld & 15) || ((uintptr_t)k8 & 15) || !ks)) return -3;
if (num_seqs <= 0 || max_q <= 0) return 0;
const int gqa = n_head / n_head_kv;
if (head_dim == 64) {
if (k8 || vs || used || bt || kvc) return -1;
#define R4D_PS64(G, NQB) \
return r4d_attn_ps_launch<64, G, NQB, 64, false, false>(q, k, k8, ks, v, o, cu, cuk, used, \
bt, bt_pitch, kvc, num_seqs, \
max_q, n_head_kv, scale, causal, \
q_ld, k_ld, k8_ld, ks_ld, v_ld, \
o_ld, nullptr, s)
switch (gqa) {
case 1: R4D_PS64(1, 16);
case 2: R4D_PS64(2, 4);
case 4: R4D_PS64(4, 2);
case 8: R4D_PS64(8, 1);
default: return -1;
}
#undef R4D_PS64
}
if (head_dim != 128) return -1;
#define R4D_PS(G, NQB, T, I8) \
return r4d_attn_ps_launch<128, G, NQB, T, I8, false>(q, k, k8, ks, v, o, cu, used, bt, \
return r4d_attn_ps_launch<128, G, NQB, T, I8, false>(q, k, k8, ks, v, o, cu, cuk, used, bt, \
bt_pitch, kvc, num_seqs, max_q, \
n_head_kv, scale, causal, q_ld, k_ld, \
k8_ld, ks_ld, v_ld, o_ld, nullptr, s)
@@ -646,10 +669,10 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float
if (gqa != 1 || used || bt || kvc || (v_ld & 15) || ((uintptr_t)v & 15)) return -1;
if (k8)
return r4d_attn_ps_launch<128, 1, 16, 64, true, true>(
q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv,
q, k, k8, ks, v, o, cu, cuk, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv,
scale, causal, q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, vs, s);
return r4d_attn_ps_launch<128, 1, 16, 64, false, true>(
q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv, scale,
q, k, k8, ks, v, o, cu, cuk, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv, scale,
causal, q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, vs, s);
}
if (k8) {
@@ -791,8 +814,44 @@ extern "C" int r4d_rad_attn_dense_h128(const RadArgs* a, RadStream s) {
return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
}
// ============================================================== wide heads (attn_dense, h768 / h1152)
// Image decoder mid-block attention: one head up to 1152 wide over every latent pixel (16384 rows
/* attn_cross at head_dim 64 or 128: the dense kernel with each entry's keys a run of their own
* (`cu_k`), causal counting from each run's start. */
extern "C" int r4d_rad_attn_cross(const RadArgs* a, RadStream s) {
const RadTensor* q = r4d_opt(a, 0);
const RadTensor* k = r4d_opt(a, 1);
const RadTensor* v = r4d_opt(a, 2);
const RadTensor* cu = r4d_opt(a, 3);
const RadTensor* ck = r4d_opt(a, 4);
const RadTensor* o = r4d_opt(a, 5);
if (!q || !k || !v || !cu || !ck || !o) return R4D_NO(RAD_E_INVAL);
if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2 || !r4d_contig(ck) ||
r4d_numel(ck) < cu->shape[0])
return R4D_NO(RAD_E_SHAPE);
const long long hd = r4d_geti_or(a, "head_dim", 0), gqa = r4d_geti_or(a, "gqa", 1);
if ((hd != 64 && hd != 128) || gqa <= 0) return R4D_NO(RAD_E_SHAPE);
long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0;
long long to = 0, ho = 0, o_ld = 0;
if (!r4d_head_rows(q, hd, &total, &nh, &q_ld) ||
!r4d_head_rows(k, hd, &tk, &hk, &k_ld) ||
!r4d_head_rows(v, hd, &tv, &hv, &v_ld) ||
!r4d_head_rows(o, hd, &to, &ho, &o_ld))
return R4D_NO(RAD_E_STRIDE);
if (hk != hv || ho != nh || hk * gqa != nh || tk != tv || to < total) return R4D_NO(RAD_E_SHAPE);
const int num_seqs = (int)(cu->shape[0] - 1);
const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd));
const int e = r4d_attn_ps(q->data, k->data, nullptr, nullptr, v->data, o->data,
(const int*)cu->data, nullptr, nullptr, 0, nullptr, num_seqs,
(int)total, (int)nh, (int)hk, (int)hd, scale,
(int)r4d_geti_or(a, "causal", 0), (int)q_ld, (int)k_ld, 0, 0,
(int)v_ld, (int)o_ld, (hipStream_t)s, nullptr,
(const int*)ck->data);
if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE);
if (e == 0) return RAD_OK;
return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
}
// ============================================================== wide heads (attn_dense, h384 .. h1152)
// Image decoder mid-block attention: one head 384 to 1152 wide over every latent pixel (16384 rows
// at 2048 x 2048). A lane cannot hold a 1152-wide output row (576 accumulator VGPRs), so the head
// is split across the workgroup's eight waves: a wave owns HD/8 dims of the 16-query block.
//
@@ -945,7 +1004,8 @@ extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream s) {
if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL);
if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE);
const long long hd = r4d_geti_or(a, "head_dim", 0);
if ((hd != 768 && hd != 1152) || r4d_geti_or(a, "gqa", 1) != 1 || r4d_geti_or(a, "causal", 0) != 0 ||
if ((hd != 384 && hd != 512 && hd != 768 && hd != 1152) || r4d_geti_or(a, "gqa", 1) != 1 ||
r4d_geti_or(a, "causal", 0) != 0 ||
r4d_geti_or(a, "window", 0) != 0 || r4d_geti_or(a, "block", 0) != 0 ||
r4d_geti_or(a, "cu_div", 1) != 1)
return R4D_NO(RAD_E_UNSUPPORTED);
@@ -967,8 +1027,10 @@ extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream s) {
(const uint16_t*)q->data, (const uint16_t*)k->data, \
(const uint16_t*)v->data, (uint16_t*)o->data, (const int*)cu->data, \
num_seqs, scale, (int)q_ld, (int)k_ld, (int)v_ld, (int)o_ld)
if (hd == 768) R4D_WIDE(768);
else R4D_WIDE(1152);
if (hd == 384) R4D_WIDE(384);
else if (hd == 512) R4D_WIDE(512);
else if (hd == 768) R4D_WIDE(768);
else R4D_WIDE(1152);
#undef R4D_WIDE
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
+57 -10
View File
@@ -54,6 +54,12 @@ using std::max;
#ifndef R4D_ATTN_H256
#define R4D_ATTN_H256 1
#endif
/* The fp8_v4 and k6_v4 caches at head_dim 256 (RadBuildCtx::kv_quant), off unless the including
* unit serves a model whose plugin offers them: Qwen3.8-Flash-Next's QSA layers (gqa12, and gqa6
* at four ranks). The kernels are the h256/gqa6 templates' O_V4 / O_K6 forms. */
#ifndef R4D_ATTN_V4
#define R4D_ATTN_V4 0
#endif
#define GQ_JOIN_(a, b, c) a##b##c
#define GQ_JOIN(a, b, c) GQ_JOIN_(a, b, c)
#define GQ_SYM(pre, suf) GQ_JOIN(pre, R4D_ATTN_GQA, suf)
@@ -99,10 +105,11 @@ extern "C" long GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(const R4DArgs* a) {
return r4d_decode_scratch(a, r4d_decode_splits(a, G8_D_TILE), G8_D_OPT);
}
template <int HEAD_DIM, int KVP>
/* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (168
template <int HEAD_DIM, int KVP, int XOPT = 0>
/* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (184
* bytes) like any other kernel argument. Non-null `gq` adds the output gate and quantiser to the
* combine (attn_paged_gate_quant; R4DGateQuant in r4d_attn_decode_h256_gqa6.hip). */
* combine (attn_paged_gate_quant; R4DGateQuant in r4d_attn_decode_h256_gqa6.hip). `XOPT` adds
* option bits to the attention kernel's (O_V4, O_K6: the cache layout). */
static int g8_decode_launch(const R4DArgs* a, RadStream stream,
const R4DGateQuant* gq = nullptr) {
int emit_rc = RAD_OK;
@@ -115,12 +122,14 @@ static int g8_decode_launch(const R4DArgs* a, RadStream stream,
#define G8_LAUNCH(NW) \
emit_rc = R4D_EMIT(stream, (r4d_attn_decode_kernel<NW, G8_D_TILE, HEAD_DIM, G8_GQA, \
G8_BLOCK_SIZE, KVP, G8_D_OPT>), \
G8_BLOCK_SIZE, KVP, G8_D_OPT | XOPT>), \
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, *a, splits)
/* One-wave workgroups stage V as codes (O_V8): same conversion count, half the LDS. */
/* One-wave workgroups stage V as codes (O_V8): same conversion count, half the LDS. A v4
* cache stages V widened (the kernel drops O_V8 under O_V4). */
if (nw == 1)
emit_rc = R4D_EMIT(stream, (r4d_attn_decode_kernel<1, G8_D_TILE, HEAD_DIM, G8_GQA,
G8_BLOCK_SIZE, KVP, G8_D_OPT | O_V8>),
G8_BLOCK_SIZE, KVP,
G8_D_OPT | O_V8 | XOPT>),
dim3(splits, a->kv_heads, a->num_seqs), dim3(32), 0, *a, splits);
else if (nw == 2) G8_LAUNCH(2);
else if (nw == 3) G8_LAUNCH(3);
@@ -227,7 +236,9 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _bf16)(const RadArgs* a, Rad
* parameters and no tensors, so parameters come first and tensors are the fallback (see the
* h256/gqa6 dispatch). The size is the maximum over every sequence count up to max_seqs, because
* S * floor(128 / (kv_heads * S)) is not monotone in S. */
static int64_t g8_decode_scratch(const RadArgs* a, int head_dim) {
/* `row` is a token's bytes in a (block, head) page, 0 for the 16-bit and E4M3 caches' 2 * head_dim
* (fill_paged_row). */
static int64_t g8_decode_scratch(const RadArgs* a, int head_dim, long long row = 0) {
const int sp = split_of(a);
if (sp < 0) return R4D_NO(RAD_E_INVAL);
@@ -254,7 +265,7 @@ static int64_t g8_decode_scratch(const RadArgs* a, int head_dim) {
}
return worst;
}
const int rc = fill_paged(a, &r, head_dim);
const int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim);
if (rc != RAD_OK) return rc;
r.splits = sp;
return GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(&r);
@@ -271,10 +282,10 @@ extern "C" int64_t GQ_SYM(r4d_rad_attn_decode_h128_gqa, _scratch)(const RadArgs*
}
#endif
static int g8_decode_common(const RadArgs* a, R4DArgs* r, int head_dim) {
static int g8_decode_common(const RadArgs* a, R4DArgs* r, int head_dim, long long row = 0) {
const int sp = split_of(a);
if (sp < 0) return R4D_NO(RAD_E_INVAL);
const int rc = fill_paged(a, r, head_dim);
const int rc = fill_paged_row(a, r, head_dim, row > 0 ? row : 2LL * head_dim);
if (rc != RAD_OK) return rc;
r->splits = sp;
const int64_t need = GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(r);
@@ -380,3 +391,39 @@ extern "C" int GQ_SYM(r4d_rad_attn_decode_h128_gqa, _bf16)(const RadArgs* a, Rad
return g8_decode_launch<128, 1>(&r, s);
}
#endif
#if R4D_ATTN_H256 && R4D_ATTN_V4
/* ---- the fp8_v4 cache (a token's row 25 * 256 / 16 = 400 bytes: E4M3 K, int4 V, f16 scales) and
* the k6_v4 cache (352 bytes: int6 K, int4 V), prefill, decode and decode with the gate and
* quantiser in the merge. */
#define G8_V4_ENTRIES(TAG, ROWB, XOPT) \
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h256_gqa, _##TAG)(const RadArgs* a, RadStream s) { \
R4DArgs r; \
const int rc = fill_paged_row(a, &r, 256, ROWB); \
if (rc != RAD_OK) return rc; \
return g8_prefill_launch<256, G8_P_OPT_256 | (XOPT), 0>(&r, (hipStream_t)s); \
} \
extern "C" int64_t GQ_SYM(r4d_rad_attn_decode_h256_gqa, _##TAG##_scratch)(const RadArgs* a) { \
return g8_decode_scratch(a, 256, ROWB); \
} \
extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _##TAG)(const RadArgs* a, \
RadStream stream) { \
R4DArgs r; \
const int rc = g8_decode_common(a, &r, 256, ROWB); \
if (rc != RAD_OK) return rc; \
return g8_decode_launch<256, 0, (XOPT)>(&r, stream); \
} \
extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _##TAG)(const RadArgs* a, \
RadStream stream) { \
R4DArgs r; \
const int rc = g8_decode_common(a, &r, 256, ROWB); \
if (rc != RAD_OK) return rc; \
R4DGateQuant gq{}; \
const int gc = g8_gate_quant_args(a, r, &gq); \
if (gc != RAD_OK) return gc; \
return g8_decode_launch<256, 0, (XOPT)>(&r, stream, &gq); \
}
G8_V4_ENTRIES(fp8v4, 400, O_V4)
G8_V4_ENTRIES(k6v4, 352, O_V4 | O_K6)
#undef G8_V4_ENTRIES
#endif
+82
View File
@@ -0,0 +1,82 @@
// R4D 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 h256/gqa6 kernel templates with WIN = 1, as
// r4d_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 (r4d_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.
#include "r4d.h"
#include "r4d_attn_args.h"
#include "r4d_common.h"
#include <cmath>
#include <algorithm>
using std::max;
// The decode kernel uses helpers from the prefill unit, so prefill is included first. Both kernels
// are instantiated here with WIN = 1.
#include "r4d_attn_prefill_h256_gqa6.hip"
#include "r4d_attn_decode_h256_gqa6.hip"
#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
#define B_TILE 16 // decode: r4d_decode_launch_win (r4d_attn_decode_h256_gqa6.hip)
// The DFlash2 drafter's head_dim 128 windowed decode set (r4d_attn_paged_h128_gqa4.hip): K
// prefetch 2 and O_KRAW. Not separately tuned for gqa 2.
#define B_OPT 20207163
extern "C" long r4d_attn_decode_h128_gqa2w_scratch_bytes(const R4DArgs* a) {
return r4d_decode_scratch(a, r4d_decode_splits_win(a, B_TILE), B_OPT);
}
extern "C" int r4d_attn_decode_h128_gqa2w_fp8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 0>(a, s);
}
extern "C" int r4d_attn_decode_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 1>(a, s);
}
// ---- prefill ---------------------------------------------------------------------------------
// The windowless h128 prefill option set (r4d_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 R4DArgs* a, hipStream_t s) {
if (a->head_dim != B_HEAD_DIM || a->block_size != B_BLOCK_SIZE) return -1;
if (a->q_heads / a->kv_heads != B_GQA) return -2;
constexpr int BQ = (P_NWARPS * 16) / B_GQA;
dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs);
hipLaunchKernelGGL((r4d_attn_prefill_kernel<P_NWARPS, P_TILE, B_HEAD_DIM, B_GQA,
B_BLOCK_SIZE, KVP, P_OPT, 1>),
grid, dim3(P_NWARPS * 32), 0, s, *a);
CHK4();
return 0;
}
extern "C" int r4d_attn_prefill_h128_gqa2w_fp8kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch_h128_gqa2w<0>(a, s);
}
extern "C" int r4d_attn_prefill_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch_h128_gqa2w<1>(a, s);
}
/* Prefill RadArgs wrappers. Absent descales mean 1.0 (fill_paged leaves them null). The decode
* wrappers are in r4d_attn_paged_h256_gqa6.hip beside decode_common. */
extern "C" int r4d_rad_attn_prefill_h128_gqa2w_fp8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = fill_paged(a, &r, B_HEAD_DIM);
if (rc != RAD_OK) return rc;
return r4d_attn_prefill_h128_gqa2w_fp8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_prefill_h128_gqa2w_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = fill_paged(a, &r, B_HEAD_DIM);
if (rc != RAD_OK) return rc;
return r4d_attn_prefill_h128_gqa2w_bf16kv(&r, (hipStream_t)s);
}
+8
View File
@@ -37,3 +37,11 @@ extern "C" int r4d_attn_decode_h128_gqa4_fp8kv(const R4DArgs* a, hipStream_t s)
extern "C" int r4d_attn_decode_h128_gqa4_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 1>(a, s);
}
// The same over a cache holding each kv head once for kv_rep query groups (O_KVREP), q at
// R4DArgs::q_ld (O_QLD): gqa 8 on this gqa-4 kernel, under attn_paged_qrow.
extern "C" int r4d_attn_decode_h128_gqa4_rep_fp8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD | O_KVREP, 0>(a, s);
}
extern "C" int r4d_attn_decode_h128_gqa4_rep_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD | O_KVREP, 1>(a, s);
}
+2
View File
@@ -17,5 +17,7 @@
// pages at 4 (RadKVGroupDecl takes the block size from the resolved kernel). A row saying 16 here
// would refuse at issue rather than at declare.
#define G8_BLOCK_SIZE 4
// The fp8_v4 and k6_v4 caches (--kv-cache-dtype), which qwen4exp_fp8 offers for these layers.
#define R4D_ATTN_V4 1
#include "r4d_attn_paged_gqa8.hip"
+8
View File
@@ -36,6 +36,14 @@ extern "C" int r4d_attn_decode_h256_gqa2_fp8kv(const R4DArgs* a, hipStream_t s)
extern "C" int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 1>(a, s);
}
// The same with q at R4DArgs::q_ld (O_QLD), for attn_paged_qrow; its own instances, so the dense
// ones above keep their registers.
extern "C" int r4d_attn_decode_h256_gqa2_qld_fp8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD, 0>(a, s);
}
extern "C" int r4d_attn_decode_h256_gqa2_qld_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD, 1>(a, s);
}
// ---- prefill ---------------------------------------------------------------------------------
// The h256/gqa6 prefill option set but at K prefetch 4 (P_OPT there is 3954187); O_KWIDE is valid
+155 -11
View File
@@ -19,6 +19,7 @@
#include "r4d_attn_args.h"
#include "r4d_common.h"
#include <cmath>
#include <cstdlib>
#include <algorithm>
using std::max;
#include "r4d_attn_prefill_h256_gqa6.hip"
@@ -50,15 +51,31 @@ extern "C" void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max
#define P_OPT 3954187
// KVP: 0 = fp8 e4m3 cache, 1 = bf16 cache. Reached only through the two named wrappers below.
template <int KVP>
template <int KVP, int XOPT = 0>
static int prefill_launch(const R4DArgs* a, hipStream_t s) {
if (a->head_dim != A_HEAD_DIM || a->block_size != A_BLOCK_SIZE) return -1;
if (a->q_heads / a->kv_heads != A_GQA) return -2;
constexpr int BQ = (P_NWARPS * 16) / A_GQA;
dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs);
hipLaunchKernelGGL((r4d_attn_prefill_kernel<P_NWARPS, P_TILE, A_HEAD_DIM, A_GQA, A_BLOCK_SIZE,
KVP, P_OPT>),
grid, dim3(P_NWARPS * 32), 0, s, *a);
// R4D_ATTN_FP8: 0 = f16 (default), 1 = O_QK8, 2 = O_PV8, 3 = both; fp8, fp8_v4 and k6_v4 KV.
int fp8mode = 0;
if constexpr (KVP == 0) {
static const int m = [] { const char* e = getenv("R4D_ATTN_FP8"); return e ? atoi(e) : 0; }();
fp8mode = m;
}
#define P_LAUNCH(OPTX) \
hipLaunchKernelGGL((r4d_attn_prefill_kernel<P_NWARPS, P_TILE, A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, \
KVP, OPTX>), \
grid, dim3(P_NWARPS * 32), 0, s, *a)
if constexpr (KVP == 0) {
if (fp8mode == 3) P_LAUNCH(P_OPT | XOPT | O_QK8 | O_PV8);
else if (fp8mode == 2) P_LAUNCH(P_OPT | XOPT | O_PV8);
else if (fp8mode == 1) P_LAUNCH(P_OPT | XOPT | O_QK8);
else P_LAUNCH(P_OPT | XOPT);
} else {
P_LAUNCH(P_OPT | XOPT);
}
#undef P_LAUNCH
CHK();
return 0;
}
@@ -69,6 +86,12 @@ extern "C" int r4d_attn_prefill_h256_gqa6_fp8kv(const R4DArgs* a, hipStream_t s)
extern "C" int r4d_attn_prefill_h256_gqa6_bf16kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch<1>(a, s);
}
extern "C" int r4d_attn_prefill_h256_gqa6_fp8v4kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch<0, O_V4>(a, s);
}
extern "C" int r4d_attn_prefill_h256_gqa6_k6v4kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch<0, O_V4 | O_K6>(a, s);
}
// ---- decode ----------------------------------------------------------------------------------
#define D_TILE 16
@@ -90,7 +113,7 @@ extern "C" long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a) {
return r4d_decode_scratch(a, r4d_decode_splits(a, D_TILE), D_OPT);
}
template <int KVP>
template <int KVP, int XOPT = 0>
static int decode_launch(const R4DArgs* a, hipStream_t s) {
if (a->head_dim != A_HEAD_DIM || a->block_size != A_BLOCK_SIZE) return -1;
if (a->q_heads / a->kv_heads != A_GQA) return -2;
@@ -101,7 +124,7 @@ static int decode_launch(const R4DArgs* a, hipStream_t s) {
#define D_LAUNCH(NW) \
hipLaunchKernelGGL((r4d_attn_decode_kernel<NW, D_TILE, A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, \
KVP, D_OPT>), \
KVP, D_OPT | XOPT>), \
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits)
if (nw == 1) D_LAUNCH(1);
else if (nw == 2) D_LAUNCH(2);
@@ -138,6 +161,12 @@ extern "C" int r4d_attn_decode_h256_gqa6_fp8kv(const R4DArgs* a, hipStream_t s)
extern "C" int r4d_attn_decode_h256_gqa6_bf16kv(const R4DArgs* a, hipStream_t s) {
return decode_launch<1>(a, s);
}
extern "C" int r4d_attn_decode_h256_gqa6_fp8v4kv(const R4DArgs* a, hipStream_t s) {
return decode_launch<0, O_V4>(a, s);
}
extern "C" int r4d_attn_decode_h256_gqa6_k6v4kv(const R4DArgs* a, hipStream_t s) {
return decode_launch<0, O_V4 | O_K6>(a, s);
}
// ============================================================== the plugin ABI entry points
//
@@ -186,10 +215,15 @@ extern "C" int r4d_rad_attn_prefill_h256_bf16(const RadArgs* a, RadStream s) {
static int64_t decode_scratch_bytes_of(const R4DArgs* r, int which) {
if (which == 1) return (int64_t)r4d_attn_decode_h128_gqa4_scratch_bytes(r);
if (which == 2) return (int64_t)r4d_attn_decode_h256_gqa2_scratch_bytes(r);
if (which == 3) return (int64_t)r4d_attn_decode_h128_gqa2w_scratch_bytes(r);
return (int64_t)r4d_attn_decode_h256_gqa6_scratch_bytes(r);
}
static int64_t decode_scratch(const RadArgs* a, int head_dim, int which) {
/* `row`: a token's bytes in a (block, head) page (fill_paged_row), 0 for 2 * head_dim; `rep`: the
* launch maps each kv head onto `rep` query groups (R4DArgs::kv_rep), so the split law counts
* groups, gqa / rep of them a kv head; `q_pitched`: q may be a slice (attn_paged_qrow). */
static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long long row = 0,
int rep = 1, bool q_pitched = false) {
const int sp = split_of(a);
if (sp < 0) return R4D_NO(RAD_E_INVAL);
@@ -201,7 +235,8 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which) {
r.head_dim = head_dim;
r.q_heads = (int)n_head;
const long long gqa = r4d_geti_or(a, "gqa", 1);
r.kv_heads = (int)(gqa > 0 ? n_head / gqa : n_head);
r.kv_heads = (int)(gqa > 0 ? n_head / gqa : n_head) * rep;
r.kv_rep = rep;
r.num_seqs = (int)max_seqs;
r.q_len = (int)r4d_geti_or(a, "q_len", 1);
r.max_ctx = (int)r4d_geti_or(a, "max_ctx", 0);
@@ -219,8 +254,10 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which) {
return worst;
}
int rc = fill_paged(a, &r, head_dim);
int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim, q_pitched);
if (rc != RAD_OK) return rc;
r.kv_heads *= rep;
r.kv_rep = rep;
r.splits = sp;
return decode_scratch_bytes_of(&r, which);
}
@@ -233,11 +270,17 @@ extern "C" int64_t r4d_rad_attn_decode_h128_scratch(const RadArgs* a) {
return decode_scratch(a, 128, 1);
}
static int decode_common(const RadArgs* a, R4DArgs* r, int head_dim, int which) {
static int decode_common(const RadArgs* a, R4DArgs* r, int head_dim, int which, long long row = 0,
int rep = 1, bool q_pitched = false) {
const int sp = split_of(a);
if (sp < 0) return R4D_NO(RAD_E_INVAL);
int rc = fill_paged(a, r, head_dim);
int rc = fill_paged_row(a, r, head_dim, row > 0 ? row : 2LL * head_dim, q_pitched);
if (rc != RAD_OK) return rc;
/* a QLD instance reads q_ld whatever q is: dense is the pitch q_heads * head_dim */
if (q_pitched && r->q_ld == 0) r->q_ld = (long)r->q_heads * head_dim;
/* each cache head serves `rep` query groups: the kernel's grid and its gqa check count groups */
r->kv_heads *= rep;
r->kv_rep = rep;
r->splits = sp;
const int64_t need = decode_scratch_bytes_of(r, which);
if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH);
@@ -253,6 +296,48 @@ extern "C" int r4d_rad_attn_decode_h256_fp8(const RadArgs* a, RadStream s) {
return r4d_attn_decode_h256_gqa6_fp8kv(&r, (hipStream_t)s);
}
/* The fp8_v4 cache: a token's row is 25 * 256 / 16 = 400 bytes (E4M3 K, int4 V, f16 scales). */
extern "C" int r4d_rad_attn_prefill_h256_fp8v4(const RadArgs* a, RadStream s) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
int rc = fill_paged_row(a, &r, 256, 400);
if (rc != RAD_OK) return rc;
return r4d_attn_prefill_h256_gqa6_fp8v4kv(&r, (hipStream_t)s);
}
extern "C" int64_t r4d_rad_attn_decode_h256_v4_scratch(const RadArgs* a) {
return decode_scratch(a, 256, 0, 400);
}
extern "C" int r4d_rad_attn_decode_h256_fp8v4(const RadArgs* a, RadStream s) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
int rc = decode_common(a, &r, 256, 0, 400);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa6_fp8v4kv(&r, (hipStream_t)s);
}
/* The k6_v4 cache: a token's row is 22 * 256 / 16 = 352 bytes (int6 K, int4 V, f16 scales). */
extern "C" int r4d_rad_attn_prefill_h256_k6v4(const RadArgs* a, RadStream s) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
int rc = fill_paged_row(a, &r, 256, 352);
if (rc != RAD_OK) return rc;
return r4d_attn_prefill_h256_gqa6_k6v4kv(&r, (hipStream_t)s);
}
extern "C" int64_t r4d_rad_attn_decode_h256_k6_scratch(const RadArgs* a) {
return decode_scratch(a, 256, 0, 352);
}
extern "C" int r4d_rad_attn_decode_h256_k6v4(const RadArgs* a, RadStream s) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
int rc = decode_common(a, &r, 256, 0, 352);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa6_k6v4kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_decode_h256_bf16(const RadArgs* a, RadStream s) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
@@ -297,3 +382,62 @@ extern "C" int r4d_rad_attn_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s)
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa2_bf16kv(&r, (hipStream_t)s);
}
/* Gemma 3 sliding window (head_dim 128, gqa 2, window 1024) decode; its prefill entry points
* are in r4d_attn_paged_h128_gqa2w.hip. */
extern "C" int64_t r4d_rad_attn_decode_h128_gqa2w_scratch(const RadArgs* a) {
return decode_scratch(a, 128, 3);
}
extern "C" int r4d_rad_attn_decode_h128_gqa2w_fp8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 128, 3);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h128_gqa2w_fp8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_decode_h128_gqa2w_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 128, 3);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h128_gqa2w_bf16kv(&r, (hipStream_t)s);
}
/* The same decode under attn_paged_qrow: q read at its own row pitch (R4DArgs::q_ld), the sliding
* layers' q where Gemma 4 31B's fused q|k|v projection left it. Same kernel, same arithmetic. */
extern "C" int64_t r4d_rad_attn_qrow_decode_h256_gqa2_scratch(const RadArgs* a) {
return decode_scratch(a, 256, 2, 0, 1, true);
}
extern "C" int r4d_rad_attn_qrow_decode_h256_gqa2_fp8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 256, 2, 0, 1, true);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa2_qld_fp8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_qrow_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 256, 2, 0, 1, true);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa2_qld_bf16kv(&r, (hipStream_t)s);
}
/* Head_dim 128 at 8 queries per kv head, any window, causal or not, q_len up to 16, under
* attn_paged_qrow: the gqa-4 kernel with each kv head mapped onto two query groups
* (R4DArgs::kv_rep = 2), the 31B's DFlash drafter's attention over a cache that holds each kv head
* once. The workgroup holds q_len * 4 rows, so a block of 16 fits where gqa 8 (128 rows) does not;
* the two groups of a kv head read its blocks twice, as the copies they replace did. */
extern "C" int64_t r4d_rad_attn_qrow_h128_gqa8_scratch(const RadArgs* a) {
return decode_scratch(a, 128, 1, 0, 2, true);
}
extern "C" int r4d_rad_attn_qrow_h128_gqa8_fp8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 128, 1, 0, 2, true);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h128_gqa4_rep_fp8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_qrow_h128_gqa8_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 128, 1, 0, 2, true);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h128_gqa4_rep_bf16kv(&r, (hipStream_t)s);
}
+2
View File
@@ -19,5 +19,7 @@
// the pages at 4 (RadKVGroupDecl takes the block size from the resolved kernel). A row saying 16
// here would refuse at issue rather than at declare.
#define G8_BLOCK_SIZE 4
// The fp8_v4 and k6_v4 caches (--kv-cache-dtype), which qwen4exp_fp8 offers for these layers.
#define R4D_ATTN_V4 1
#include "r4d_attn_paged_gqa8.hip"
+118 -34
View File
@@ -42,6 +42,7 @@
#include "r4d_plugin.h"
#include "r4d_launch.h"
#include "r4d_chain.h"
#include "rad_plugin.h"
#if defined(__HIP_DEVICE_COMPILE__) && defined(__AMDGCN_WAVEFRONT_SIZE) && __AMDGCN_WAVEFRONT_SIZE != 32
@@ -232,8 +233,10 @@ __device__ void find_tile(const int* cu, int n_seq, int tile, int* s_scan, int*
}
/* ------------------------------------------------------------------ the attention kernel */
/* The body; attn_kernel and its chained form r4dchain_attn_window (r4d_chain.h) wrap it below,
* since its blocks return early. */
template <int HD, int GQA, bool KV8>
__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) {
__device__ __forceinline__ void attn_body(AttnArgs A) {
constexpr int R = Geo<HD>::R, BK = Geo<HD>::BK, RW = R / kWaves, BQ = R / GQA;
constexpr int NC = HD / 128; /* 4-element chunks a lane holds of a row */
constexpr int ESZ = KV8 ? 1 : 2;
@@ -499,15 +502,14 @@ __device__ __forceinline__ unsigned f16_bits(float f) {
if (f == f) f = __builtin_fminf(__builtin_fmaxf(f, -65504.0f), 65504.0f);
return (unsigned)__builtin_bit_cast(unsigned short, (_Float16)f);
}
__device__ __forceinline__ void fp8x16_f16(const uint4 w, unsigned (&h)[16]) {
const unsigned in[4] = {w.x, w.y, w.z, w.w};
#pragma unroll
for (int q = 0; q < 4; ++q) {
float f[4];
fp8x4(in[q], f);
#pragma unroll
for (int e = 0; e < 4; ++e) h[q * 4 + e] = f16_bits(f[e]);
}
/* Two f32 values exact in f16 as an f16 pair, `a` low: v_cvt_pkrtz on gfx12, f16_bits elsewhere
* (the host emulator), the same bits either way since neither rounds an exact value. */
__device__ __forceinline__ unsigned f16x2_exact(float a, float b) {
#if defined(__GFX12__)
return __builtin_bit_cast(unsigned, __builtin_amdgcn_cvt_pkrtz(a, b));
#else
return f16_bits(a) | f16_bits(b) << 16;
#endif
}
__device__ __forceinline__ void bf16x8_f16(const uint4 w, unsigned (&h)[8]) {
const unsigned in[4] = {w.x, w.y, w.z, w.w};
@@ -684,11 +686,17 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
const uint4 wb = (tok && kb1 >= lo && kb1 < hi) ? pv[j][1] : make_uint4(0u, 0u, 0u, 0u);
unsigned d[CW]; /* f16 pairs: key 2kp low, 2kp + 1 high */
if constexpr (KV8) {
unsigned ha[16], hb2[16];
fp8x16_f16(wa, ha);
fp8x16_f16(wb, hb2);
/* every e4m3 value is exact in f16 (|v| <= 448, subnormals 2^-9 up), so the
* pack's round-toward-zero and f16_bits' clamp leave the same bits */
const unsigned ia[4] = {wa.x, wa.y, wa.z, wa.w}, ib[4] = {wb.x, wb.y, wb.z, wb.w};
#pragma unroll
for (int e = 0; e < CW; ++e) d[e] = ha[e] | hb2[e] << 16;
for (int q = 0; q < 4; ++q) {
float fa[4], fb[4];
fp8x4(ia[q], fa);
fp8x4(ib[q], fb);
#pragma unroll
for (int e = 0; e < 4; ++e) d[q * 4 + e] = f16x2_exact(fa[e], fb[e]);
}
} else {
unsigned ha[8], hb2[8];
bf16x8_f16(wa, ha);
@@ -747,14 +755,26 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
/* ---- online softmax, row n: eight keys here, eight in lane ^ 16 */
float sv[8], mx = -__builtin_inff();
/* A tile wholly inside [lo, hi) and, causal, at or before the block's first position
* (every row's pos >= qbase) is visible to every valid row: the same scores, unmasked. */
const bool interior = window <= 0 && k0 >= lo && k0 + 16 <= hi && (!causal || k0 + 15 <= qbase);
if (interior) {
const bool vis = rval && tok;
#pragma unroll
for (int e = 0; e < 8; ++e) {
const int kk = k0 + 8 * h + e;
bool vis = rval && tok && kk >= lo && kk < hi;
if (causal) vis = vis && kk <= pos;
if (window > 0) vis = vis && (pos - kk < window) && (causal || kk - pos < window);
sv[e] = vis ? tot[e] * sscale : -__builtin_inff();
mx = __builtin_fmaxf(mx, sv[e]);
for (int e = 0; e < 8; ++e) {
sv[e] = vis ? tot[e] * sscale : -__builtin_inff();
mx = __builtin_fmaxf(mx, sv[e]);
}
} else {
#pragma unroll
for (int e = 0; e < 8; ++e) {
const int kk = k0 + 8 * h + e;
bool vis = rval && tok && kk >= lo && kk < hi;
if (causal) vis = vis && kk <= pos;
if (window > 0) vis = vis && (pos - kk < window) && (causal || kk - pos < window);
sv[e] = vis ? tot[e] * sscale : -__builtin_inff();
mx = __builtin_fmaxf(mx, sv[e]);
}
}
mx = __builtin_fmaxf(mx, shfl_xor(mx, 16));
const float mn = __builtin_fmaxf(m, mx);
@@ -773,10 +793,23 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
/* ---- O^T += V^T * P^T in f16: A = V^T rows (dim n of the chunk), keys 8h .. 8h + 7 */
const unsigned char* va = vb + (sl * kDQ + n) * VS + h * 16;
if constexpr (KV8) {
/* x * 1 = x, so a wave whose rows all kept their max skips the rescale. With an fp8
* cache that is ~4% at head_dim 512; with bf16 the split loop measured ~10% slower,
* so it keeps the fused one. */
if (__builtin_amdgcn_ballot_w32(corr != 1.0f) != 0) {
#pragma unroll
for (int mc = 0; mc < kDQ / 16; ++mc) {
oacc[mc] *= corr;
oacc[mc] = wmma_f16(__builtin_bit_cast(win_v8h, *(const uint4*)(va + mc * 16 * VS)), pf, oacc[mc]);
for (int mc = 0; mc < kDQ / 16; ++mc) oacc[mc] *= corr;
}
#pragma unroll
for (int mc = 0; mc < kDQ / 16; ++mc)
oacc[mc] = wmma_f16(__builtin_bit_cast(win_v8h, *(const uint4*)(va + mc * 16 * VS)), pf, oacc[mc]);
} else {
#pragma unroll
for (int mc = 0; mc < kDQ / 16; ++mc) {
oacc[mc] *= corr;
oacc[mc] = wmma_f16(__builtin_bit_cast(win_v8h, *(const uint4*)(va + mc * 16 * VS)), pf, oacc[mc]);
}
}
}
@@ -800,7 +833,7 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
* (kMaxSplit is 64), so the row max and denominator are one wave reduction each. Then one sweep
* over the splits that saw a key, four at a time, each lane accumulating its 4 * NC dims. */
template <int HD, int GQA>
__global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) {
__device__ __forceinline__ void merge_body(AttnArgs A) {
constexpr int R = Geo<HD>::R, NC = HD / 128;
static_assert(kMaxSplit <= 64, "two splits a lane");
const int tile = (int)blockIdx.x, kh = (int)blockIdx.y;
@@ -840,9 +873,9 @@ __global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) {
* (a written split, so 0 * finite). An empty split's accumulator is never read. */
uint64_t live = (uint64_t)__builtin_amdgcn_ballot_w32(w0 != 0.0f) |
((uint64_t)__builtin_amdgcn_ballot_w32(w1 != 0.0f) << 32);
while (live) {
int zi[4];
float wj[4];
/* Group g + 1's loads go out before group g's FMAs, so a group's wait overlaps the one
* before it instead of following it; the FMAs keep their order, so the bytes do too. */
auto take = [&](int (&zi)[4], float (&wj)[4]) {
#pragma unroll
for (int j = 0; j < 4; ++j) {
const bool have = live != 0;
@@ -851,13 +884,16 @@ __global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) {
wj[j] = readlane(zi[j] < 32 ? w0 : w1, zi[j] & 31);
if (!have) wj[j] = 0.0f;
}
float4 v[4][NC];
};
auto load = [&](const int (&zi)[4], float4 (&v)[4][NC]) {
#pragma unroll
for (int j = 0; j < 4; ++j) {
const float* pp = A.part + (base + (long long)zi[j] * R) * (HD + 4);
#pragma unroll
for (int c = 0; c < NC; ++c) v[j][c] = *(const float4*)(pp + c * 128 + lane * 4);
}
};
auto fold = [&](const float (&wj)[4], const float4 (&v)[4][NC]) {
#pragma unroll
for (int j = 0; j < 4; ++j)
#pragma unroll
@@ -867,6 +903,23 @@ __global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) {
acc[c][2] = __builtin_fmaf(wj[j], v[j][c].z, acc[c][2]);
acc[c][3] = __builtin_fmaf(wj[j], v[j][c].w, acc[c][3]);
}
};
if (live) {
int za[4], zb[4];
float wa[4], wb[4];
float4 va[4][NC], vb[4][NC];
take(za, wa);
load(za, va);
while (true) {
const bool more_b = live != 0;
if (more_b) { take(zb, wb); load(zb, vb); }
fold(wa, va);
if (!more_b) break;
const bool more_a = live != 0;
if (more_a) { take(za, wa); load(za, va); }
fold(wb, vb);
if (!more_a) break;
}
}
#pragma unroll
for (int c = 0; c < NC; ++c)
@@ -914,6 +967,25 @@ static constexpr int64_t scratch_need() {
return part_bytes<HD>() + (int64_t)kTinfoMax * 2 * (int64_t)sizeof(int);
}
/* The plain kernels and their chained forms (r4dchain*, RadKernelChainFn): the chained ones wait
* for the kernels before them on the queue in their prologue and count themselves in at the end. */
template <int HD, int GQA, bool KV8>
__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) { attn_body<HD, GQA, KV8>(A); }
template <int HD, int GQA, bool KV8>
__global__ __launch_bounds__(kThreads) void r4dchain_attn_window(AttnArgs A) {
r4d_chain_wait();
attn_body<HD, GQA, KV8>(A);
r4d_chain_done();
}
template <int HD, int GQA>
__global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { merge_body<HD, GQA>(A); }
template <int HD, int GQA>
__global__ __launch_bounds__(kThreads) void r4dchain_merge_window(AttnArgs A) {
r4d_chain_wait();
merge_body<HD, GQA>(A);
r4d_chain_done();
}
template <int HD, int GQA, bool KV8>
static int launch_attn(const RadArgs* a, RadStream stream) {
constexpr int R = Geo<HD>::R, BK = Geo<HD>::BK, BQ = R / GQA, ESZ = KV8 ? 1 : 2;
@@ -1084,11 +1156,23 @@ static int launch_attn(const RadArgs* a, RadStream stream) {
A.n_split = (int)ns;
hipStream_t s = (hipStream_t)stream;
R4D_KLAUNCH(R4D_KNAME(attn_kernel<HD, GQA, KV8>), dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns),
dim3(kThreads), s, A);
if (ns > 1)
R4D_KLAUNCH(R4D_KNAME(merge_kernel<HD, GQA>), dim3((unsigned)nt, (unsigned)kvh), dim3(kThreads),
s, A);
/* The chained forms where the row resolved with `chain` (a chainable row, RADIANCE_CHAIN), at
* decode heights only: the 31B's full layers at a verify. */
const bool chain = rad_args_geti_or(a, "chain", 0) != 0 && rows <= 64;
if (chain)
R4D_KLAUNCH(R4D_KNAME(r4dchain_attn_window<HD, GQA, KV8>),
dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), dim3(kThreads), s, A);
else
R4D_KLAUNCH(R4D_KNAME(attn_kernel<HD, GQA, KV8>),
dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), dim3(kThreads), s, A);
if (ns > 1) {
if (chain)
R4D_KLAUNCH(R4D_KNAME(r4dchain_merge_window<HD, GQA>), dim3((unsigned)nt, (unsigned)kvh),
dim3(kThreads), s, A);
else
R4D_KLAUNCH(R4D_KNAME(merge_kernel<HD, GQA>), dim3((unsigned)nt, (unsigned)kvh),
dim3(kThreads), s, A);
}
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
+196 -16
View File
@@ -29,6 +29,12 @@
#define O_F16 1
#define O_MSKIP 2
// QK8/PV8 (ported from radiance-vllm-mxfp4 r4d_radiance_extras.patch): Q and P as e4m3,
// K and V as e4m3 bytes in LDS, both matmuls as fp8 WMMA. Not with bf16 KV. On the fp8 cache (and
// fp8_v4's K) the bytes are the cache's own; k6_v4's K and the int4 V of fp8_v4/k6_v4 are widened
// to the value times its group scale and rounded once to e4m3 at staging.
#define O_QK8 32
#define O_PV8 64
#define O_FOLDQ 8
#define O_CONTIG 512
#define O_PF2 1024
@@ -53,6 +59,28 @@
// LDSB: an LDS-scoped barrier instead of __syncthreads() (lds_barrier() in r4d_common.h). The
// default fence invalidates the vector cache twice per tile, though only LDS needs ordering.
#define O_LDSB 2097152
// O_V4: the fp8_v4 cache, O_V4 | O_K6 the k6_v4 cache (see r4d_attn_decode_h256_gqa6.hip).
#define O_V4 33554432
#define O_K6 67108864
typedef int v2i32_r4d __attribute__((ext_vector_type(2))); // one fp8 WMMA operand (8 e4m3)
// pack 4 floats -> 4 e4m3 bytes in element order (RNE, saturating), 2 instructions
__device__ __forceinline__ uint32_t pk_fp8x4(float a, float b, float c, float d) {
const uint32_t w = __builtin_amdgcn_cvt_pk_fp8_f32(a, b, 0u, false);
return __builtin_amdgcn_cvt_pk_fp8_f32(c, d, w, true);
}
// two f16 dwords (four values in element order) -> four e4m3 bytes
__device__ __forceinline__ uint32_t pk_fp8x4_h(uint32_t lo, uint32_t hi) {
typedef _Float16 h2 __attribute__((ext_vector_type(2)));
const h2 a = __builtin_bit_cast(h2, lo), b = __builtin_bit_cast(h2, hi);
return pk_fp8x4((float)a[0], (float)a[1], (float)b[0], (float)b[1]);
}
// one f16 dword -> two e4m3 bytes in the low half
__device__ __forceinline__ uint32_t pk_fp8x2_h(uint32_t w) {
typedef _Float16 h2 __attribute__((ext_vector_type(2)));
const h2 a = __builtin_bit_cast(h2, w);
return (uint32_t)__builtin_amdgcn_cvt_pk_fp8_f32((float)a[0], (float)a[1], 0u, false) & 0xffffu;
}
// bf16 dword -> 16-bit dword in the target format, optionally scaled. Used once per kernel on Q.
template<class D, int FOLDQ, int F16>
@@ -75,11 +103,21 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
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 DOT2 = ((OPT & O_DOT2) && (OPT & O_F16)) ? 1 : 0;
constexpr int DOT2 = ((OPT & O_DOT2) && (OPT & O_F16) && !(OPT & O_PV8)) ? 1 : 0;
constexpr int BTS = (OPT & O_BTS) ? 1 : 0;
constexpr int GPREV = (OPT & O_GPREV) ? 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) && !V4) ? 1 : 0;
constexpr int LDSB = (OPT & O_LDSB) ? 1 : 0;
constexpr int KWIDE = (OPT & O_KWIDE) ? 1 : 0;
constexpr int QK8 = ((OPT & O_QK8) && !KVP) ? 1 : 0;
constexpr int PV8 = ((OPT & O_PV8) && !KVP) ? 1 : 0;
static_assert(!QK8 || KWIDE, "QK8 raw-byte staging is written for the wide K fetch");
typedef DT16<F16> D;
typedef typename D::frag frag16;
@@ -98,11 +136,16 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
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 = D::GROW;
constexpr float PGROW = PV8 ? 8.0f : D::GROW; // e4m3 max is 448 = 2^8.8
static_assert(!KWIDE || KPASS == 1, "the wide K fetch is one straight-line pass");
static_assert(!K6 || KWIDE, "k6_v4 K is staged sixteen dims a thread");
static_assert((!QK8 && !PV8) || CTG, "the 8-bit fragment maps are written for CONTIG");
__shared__ uint16_t sK[TILE * KSTR];
__shared__ uint16_t sV16[HEAD_DIM * VSTR];
constexpr int KSTR8 = HEAD_DIM + 8, VSTR8 = TILE + 8;
__shared__ uint16_t sK[QK8 ? (TILE * KSTR8 + 1) / 2 : TILE * KSTR];
__shared__ uint16_t sV16[PV8 ? (HEAD_DIM * VSTR8 + 1) / 2 : HEAD_DIM * VSTR];
uint8_t* const sK8 = (uint8_t*)sK;
uint8_t* const sV8 = (uint8_t*)sV16;
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
const int c = lane & 15, h = lane >> 4;
@@ -131,6 +174,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
const float mul = a.scale * kdesc * 1.44269504089f;
frag16 qf[NKS];
v2i32_r4d qf8[QK8 ? NKS : 1];
{
const uint16_t* qp = (const uint16_t*)a.q
+ ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM;
@@ -139,10 +183,19 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
// CONTIG reads the 8 dims as one run; the split map takes them 4+4.
const uint2 l0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h : 4 * h));
const uint2 h0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h + 4 : 8 + 4 * h));
qf[t] = D::mk(make_uint2(r4d_qcvt<D, FOLDQ, F16>(l0.x, mul),
r4d_qcvt<D, FOLDQ, F16>(l0.y, mul)),
make_uint2(r4d_qcvt<D, FOLDQ, F16>(h0.x, mul),
r4d_qcvt<D, FOLDQ, F16>(h0.y, mul)));
if constexpr (QK8) {
const float m_ = FOLDQ ? mul : 1.0f;
#define R4D_QB(w) __builtin_bit_cast(float, (w) << 16) * m_, \
__builtin_bit_cast(float, (w) & 0xffff0000u) * m_
qf8[t] = (v2i32_r4d){(int)pk_fp8x4(R4D_QB(l0.x), R4D_QB(l0.y)),
(int)pk_fp8x4(R4D_QB(h0.x), R4D_QB(h0.y))};
#undef R4D_QB
} else {
qf[t] = D::mk(make_uint2(r4d_qcvt<D, FOLDQ, F16>(l0.x, mul),
r4d_qcvt<D, FOLDQ, F16>(l0.y, mul)),
make_uint2(r4d_qcvt<D, FOLDQ, F16>(h0.x, mul),
r4d_qcvt<D, FOLDQ, F16>(h0.y, mul)));
}
}
}
@@ -173,6 +226,76 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
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;
uint32_t v4c[U4][2], v4s[U4];
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);
}
v4s[r] = sc[0] | (sc[1] << 16);
}
}
};
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, v4s[r]);
const h2 bias = { (_Float16)1032.0f, (_Float16)1032.0f };
uint16_t* dst = &sV16[(o * 8) * VSTR + 2 * kp];
uint8_t* dst8 = &sV8[(o * 8) * VSTR8 + 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) {
// [dim][key] bytes: the pair's two keys as one 16-bit store a dim
*(uint16_t*)(dst8 + (2 * b) * VSTR8) = (uint16_t)pk_fp8x2_h(__builtin_bit_cast(uint32_t, vl));
*(uint16_t*)(dst8 + (2 * b + 1) * VSTR8) = (uint16_t)pk_fp8x2_h(__builtin_bit_cast(uint32_t, vh));
continue;
}
*(uint32_t*)(dst + (2 * b) * VSTR) = __builtin_bit_cast(uint32_t, vl);
*(uint32_t*)(dst + (2 * b + 1) * VSTR) = __builtin_bit_cast(uint32_t, vh);
}
}
}
};
auto fetchK = [&](int k0, const int* blks) {
#pragma unroll
for (int p = 0; p < KPASS; ++p) {
@@ -184,12 +307,18 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
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) * (2 * HEAD_DIM);
+ (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 {
@@ -212,7 +341,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
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) * (2 * HEAD_DIM) + HEAD_DIM + d0;
+ (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));
@@ -228,6 +357,21 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
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;
if constexpr (QK8 && K6) {
// k6_v4: widen to f16 as below, then round each value once to e4m3
const uint4 r = kreg[p];
#pragma unroll
for (int q = 0; q < 2; ++q) {
uint32_t w4[4];
k6x8_to_f16x4w(q ? r.y : r.x, r.z, q, r.w | (r.w << 16), w4);
*(uint2*)(&sK8[key * KSTR8 + ch * KEL + 8 * q]) =
make_uint2(pk_fp8x4_h(w4[0], w4[1]), pk_fp8x4_h(w4[2], w4[3]));
}
continue;
} else if constexpr (QK8) {
*(uint4*)(&sK8[key * KSTR8 + ch * KEL]) = kreg[p];
continue;
}
uint16_t* kd = &sK[key * KSTR + ch * KEL];
#pragma unroll
for (int q = 0; q < KEL / 8; ++q) {
@@ -238,7 +382,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
w4[2] = D::from_bf16w(r.z); w4[3] = D::from_bf16w(r.w);
} else {
const uint4 r = kreg[p];
fp8x8_to_16x4w<D>(q ? make_uint2(r.z, r.w) : make_uint2(r.x, r.y), w4);
if constexpr (K6) k6x8_to_f16x4w(q ? r.y : r.x, r.z, q, r.w | (r.w << 16), w4);
else fp8x8_to_16x4w<D>(q ? make_uint2(r.z, r.w) : make_uint2(r.x, r.y), w4);
}
*(uint2*)(kd + 8 * q) = make_uint2(w4[0], w4[1]);
*(uint2*)(kd + 8 * q + 4) = make_uint2(w4[2], w4[3]);
@@ -265,6 +410,11 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
// 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);
if constexpr (PV8) {
*(uint2*)(&sV8[(d0 + 2 * vj) * VSTR8 + kg * 8]) = make_uint2(lo0, lo1);
*(uint2*)(&sV8[(d0 + 2 * vj + 1) * VSTR8 + kg * 8]) = make_uint2(hi0, hi1);
continue;
}
uint32_t wl[4], wh[4];
fp8x8_to_16x4w<D>(make_uint2(lo0, lo1), wl);
fp8x8_to_16x4w<D>(make_uint2(hi0, hi1), wh);
@@ -296,6 +446,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
int blk[NB];
if (BTS) load_bt(tstart * NB, blk);
if (GPREV) fetchV(tstart * TILE, blk);
if (V4) fetchV4(tstart * TILE, blk);
for (int ti = tstart; ti < ntiles; ++ti) {
const int k0 = ti * TILE;
@@ -305,18 +456,32 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
}
if (LDSB) lds_barrier(); else __syncthreads();
fetchK(k0, blk);
if (!GPREV) fetchV(k0, blk);
storeV(); // V first: already in registers, so it covers K's load latency
// V first: already in registers, so it covers K's load latency.
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);
#pragma unroll 1
for (int mt = 0; mt < MT; ++mt) {
v8f s = (v8f){0,0,0,0,0,0,0,0};
{
if constexpr (QK8) {
const uint8_t* krow8 = &sK8[(mt * 16 + c) * KSTR8] + 8 * h;
#pragma unroll
for (int g = 0; g < NKS; g += PF) {
v2i32_r4d kb8[PF];
#pragma unroll
for (int j = 0; j < PF; ++j)
kb8[j] = *(const v2i32_r4d*)(krow8 + 16 * (g + j));
if (SGB) sched_barrier();
#pragma unroll
for (int j = 0; j < PF; ++j)
s = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(kb8[j], qf8[g + j], s);
}
} else {
const uint16_t* krow = &sK[(mt * 16 + c) * KSTR] + (CTG ? 8 * h : 0);
// Load PF fragments before issuing their WMMAs, so each WMMA waits on
// s_wait_dscnt PF-1 instead of a full drain.
@@ -376,7 +541,22 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
}
if (!DOT2) l_i += lsum;
{
if constexpr (PV8) {
const v2i32_r4d p8 = (v2i32_r4d){(int)pk_fp8x4(pf[0], pf[1], pf[2], pf[3]),
(int)pk_fp8x4(pf[4], pf[5], pf[6], pf[7])};
const uint8_t* vbase8 = &sV8[c * VSTR8 + mt * 16 + 8 * h];
#pragma unroll
for (int g = 0; g < NKS; g += PF) {
v2i32_r4d vb8[PF];
#pragma unroll
for (int j = 0; j < PF; ++j)
vb8[j] = *(const v2i32_r4d*)(vbase8 + (size_t)(g + j) * 16 * VSTR8);
if (SGB) sched_barrier();
#pragma unroll
for (int j = 0; j < PF; ++j)
acc[g + j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(vb8[j], p8, acc[g + j]);
}
} else {
uint32_t pw[4];
#pragma unroll
for (int e = 0; e < 8; e += 2) pw[e >> 1] = D::pk(pf[e], pf[e + 1]);
+44
View File
@@ -16,6 +16,7 @@
#include "rad_philox.h"
#include <cmath>
#include <cstdlib>
#include <cstring>
namespace {
@@ -972,6 +973,17 @@ __global__ __launch_bounds__(kT) void iota_kernel(int* __restrict__ y, int n, in
if (i < n) y[i] = start + (period > 0 ? i % period : i) * step;
}
// y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j], the lists by value.
constexpr int kAffMax = 16;
struct IntAffine { int src[kAffMax], mul[kAffMax], add[kAffMax]; };
__global__ __launch_bounds__(kAffMax) void int_affine_kernel(const int* __restrict__ x,
int* __restrict__ y, IntAffine p,
int n) {
const int j = threadIdx.x;
if (j < n) y[j] = (p.src[j] < 0 ? 0 : x[p.src[j]]) * p.mul[j] + p.add[j];
}
__global__ __launch_bounds__(kT) void cu_repeat_kernel(const int* __restrict__ len,
int* __restrict__ y, int n, int mult) {
const int j = blockIdx.x * kT + threadIdx.x;
@@ -1619,6 +1631,38 @@ extern "C" int r4d_rad_iota(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
namespace {
int parse_ints(const char* s, int* v, int cap) {
int n = 0;
while (s && *s) {
char* e = nullptr;
const long x = std::strtol(s, &e, 10);
if (e == s) break;
if (n == cap) return -1;
v[n++] = (int)x;
s = e;
}
return n;
}
} // namespace
extern "C" int r4d_rad_int_affine(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
if (!is_i32(x) || !is_i32(y)) return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(x) || !r4d_contig(y)) return R4D_NO(RAD_E_STRIDE);
IntAffine p{};
const int n = parse_ints(r4d_gets(a, "src"), p.src, kAffMax);
if (n <= 0 || parse_ints(r4d_gets(a, "mul"), p.mul, kAffMax) != n ||
parse_ints(r4d_gets(a, "add"), p.add, kAffMax) != n || r4d_numel(y) < n)
return R4D_NO(RAD_E_SHAPE);
for (int j = 0; j < n; ++j)
if (p.src[j] >= r4d_numel(x)) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(int_affine_kernel, dim3(1), dim3(kAffMax), 0, (hipStream_t)s,
(const int*)x->data, (int*)y->data, p, n);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_cu_repeat(const RadArgs* a, RadStream s) {
const RadTensor *len = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!len || !y) return R4D_NO(RAD_E_INVAL);
+85
View File
@@ -0,0 +1,85 @@
// r4d_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): ~1.3 ms of a 14 ms DFlash2 step on the 31B
// (4x R9700, 2026-10-17). 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 r4d_chain_wait / r4d_chain_done; the plain form never reads
// the record, so a launch from outside the engine (r4d_selftest, rad-kbench) is untouched.
//
// Every block must reach r4d_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/r4d_emu) compiles some of these sources as C++: no engine record
* ever reaches a launch there, so a chained form is its plain form. */
__device__ __forceinline__ void r4d_chain_wait() {}
__device__ __forceinline__ void r4d_chain_done() {}
#else
struct R4dChainRec {
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 R4dChainRec* r4d_chain_rec() {
const R4dChainRec* r = (const R4dChainRec*)((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
// R4D_CHAIN_FAST polls are ~64 clocks apart, the rest R4D_CHAIN_SLOW x 64: a long wait ends at most
// that much late and puts 1/R4D_CHAIN_SLOW of the load on the channel.
#ifndef R4D_CHAIN_FAST
#define R4D_CHAIN_FAST 8
#endif
#ifndef R4D_CHAIN_SLOW
#define R4D_CHAIN_SLOW 16
#endif
__device__ __forceinline__ void r4d_chain_wait() {
const R4dChainRec* r = r4d_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 < R4D_CHAIN_FAST) {
__builtin_amdgcn_s_sleep(1);
++n;
} else {
__builtin_amdgcn_s_sleep(R4D_CHAIN_SLOW);
}
}
}
__syncthreads();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
}
// After the block's last write: release, then one add a block.
__device__ __forceinline__ void r4d_chain_done() {
const R4dChainRec* r = r4d_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__ */
+28
View File
@@ -282,3 +282,31 @@ __host__ __device__ __forceinline__ int r4d_act_threads(int M, int K) {
const int lim = K >= 8192 ? (1 << 24) : (K >= 4096 ? 120 : 72);
return M <= lim ? 512 : 256;
}
// The full-card cliff, measured on the R9700 (gfx1201, 64 CUs). A launch whose wavefronts fall
// in the last 32 before a multiple of 2048 runs about five times slower than the same work one
// workgroup wider, whatever the kernel does: 256-thread workgroups take 27.6 us at 253 to 256 of
// them and 5.2 us at 252 or 257, a norm, an LDS-only kernel and a copy alike. The 31B's
// qkv_norm_rope at a tp-4 verify is exactly 256 such workgroups (16 rows x 16 heads), and a
// drafter's 256-row head norm too.
//
// 2048 is every wave slot of the R9700 (64 CUs x 2 SIMDs x 16). Both numbers are that card's and
// apply on every target libr4d builds for; they are not derived from the device, since no other
// card has been measured and HIP's multiProcessorCount counts WGPs, not CUs, on RDNA. On an RDNA4
// part with fewer CUs a launch padded here costs one idle row and gives the same bytes, and a
// cliff at that part's own full-card size, if it has one, is not stepped past.
//
// r4d_cliff_rows() is the row count to launch for a grid of `rows` x `per_row` workgroups of
// `waves` wavefronts each: `rows` where that is clear of the window, else the first count past it.
// The kernel returns at once in a row at or past `rows`, so the result is unchanged.
constexpr uint32_t kR4dCliffWaves = 2048; // the R9700's wave slots: 64 CUs x 2 SIMDs x 16
constexpr uint32_t kR4dCliffWindow = 32; // the slow window, below each multiple of it
__host__ __device__ __forceinline__ uint32_t r4d_cliff_rows(uint32_t rows, uint32_t per_row,
uint32_t waves) {
uint32_t r = rows;
for (int i = 0; i < 64; ++i, ++r) {
const uint64_t w = (uint64_t)r * per_row * waves % kR4dCliffWaves;
if (w != 0 && w <= kR4dCliffWaves - kR4dCliffWindow) break;
}
return r;
}
+32 -3
View File
@@ -4,6 +4,7 @@
#include <hip/hip_runtime.h>
#include "r4d_gdn_args.h"
#include "r4d_dflash_conv_body.h"
#include "r4d_chain.h"
#define DFC_THREADS 128
#define DFC_VEC 8 // bf16 lanes per thread: one dwordx4 in and one out
@@ -19,15 +20,40 @@ __global__ __launch_bounds__(DFC_THREADS) void r4d_dflash_conv_kernel(
blockmask, blockIdx.y, hv);
}
// The chained form (r4d_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 r4dchain_dflash_conv(
const r4d_u16* __restrict__ x, const r4d_u16* __restrict__ delta,
const r4d_u16* __restrict__ base, r4d_u16* __restrict__ out,
int H, int dpitch, int NG, int vpr, int blockmask)
{
r4d_chain_wait();
const int hv = blockIdx.x * DFC_THREADS + threadIdx.x;
r4d_dflash_conv_body<TAPS, GROUP>(x, delta, base, out, H, dpitch, NG, vpr,
blockmask, blockIdx.y, hv);
r4d_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 r4d_dflash_conv_t2_g16_bf16(
const void* x, const void* delta, const void* base, void* out,
int T, int H, int dpitch, int NG, int taps, int group, int block_size, void* stream)
{
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 (r4d_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;
@@ -36,7 +62,9 @@ extern "C" int r4d_dflash_conv_t2_g16_bf16(
const int vpr = H / DFC_VEC;
dim3 grid((vpr + DFC_THREADS - 1) / DFC_THREADS, T), blk(DFC_THREADS);
hipLaunchKernelGGL((r4d_dflash_conv_kernel<2, 16>), grid, blk, 0, (hipStream_t)stream,
hipLaunchKernelGGL((chain && T <= 64 ? r4dchain_dflash_conv<2, 16>
: r4d_dflash_conv_kernel<2, 16>),
grid, blk, 0, (hipStream_t)stream,
(const r4d_u16*)x, (const r4d_u16*)delta, (const r4d_u16*)base,
(r4d_u16*)out, H, dpitch, NG, vpr, block_size - 1);
return (int)hipGetLastError();
@@ -79,7 +107,8 @@ extern "C" int r4d_rad_dflash_conv(const RadArgs* a, RadStream s) {
if (bsz & (bsz - 1)) return R4D_NO(RAD_E_INVAL);
if (dpitch != 2LL * taps * NG) return R4D_NO(RAD_E_STRIDE);
return R4D_RAW(r4d_dflash_conv_t2_g16_bf16(x->data, d->data, bs->data, o->data, (int)T,
(int)H, (int)dpitch, NG, taps, group, bsz, s));
return R4D_RAW(dflash_conv_launch(x->data, d->data, bs->data, o->data, (int)T,
(int)H, (int)dpitch, NG, taps, group, bsz, s,
r4d_geti_or(a, "chain", 0) != 0));
}
+48 -6
View File
@@ -29,6 +29,7 @@
#include "r4d_gdn_args.h"
#include "r4d_dflash_conv_body.h" // r4d_bf2f, r4d_u16
#include "r4d_common.h" // r4d_wave_sum
#include "r4d_chain.h"
#define DSL_THREADS 256
#define DSL_WAVE 32
@@ -47,7 +48,8 @@
// Ids outside [0, V) do occur (row_topk_merge reports an unfilled slot as -1, and step 0's
// predecessor is whatever the anchor plane holds). As in ref_dflash_select, an out-of-range
// predecessor contributes nothing and an out-of-range candidate scores its unary term alone.
__global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below.
__device__ __forceinline__ void r4d_dflash_select_body(
const int* __restrict__ cand, const float* __restrict__ unary,
const r4d_u16* __restrict__ hp, const int* __restrict__ anchor,
const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ,
@@ -134,12 +136,49 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
__syncthreads();
}
}
__global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
const int* __restrict__ cand, const float* __restrict__ unary,
const r4d_u16* __restrict__ hp, const int* __restrict__ anchor,
const r4d_u16* __restrict__ pred, const r4d_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) {
r4d_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 r4dchain_dflash_select(
const int* __restrict__ cand, const float* __restrict__ unary,
const r4d_u16* __restrict__ hp, const int* __restrict__ anchor,
const r4d_u16* __restrict__ pred, const r4d_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) {
r4d_chain_wait();
r4d_dflash_select_body(cand, unary, hp, anchor, pred, succ, out, steps, K, R, V, cand_ld, hp_ld,
out_ld, anchor_stride);
r4d_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 r4d_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;
@@ -149,7 +188,8 @@ extern "C" int r4d_dflash_select_bf16(
/* hp may be null (the bigram form); then hp_ld is unused. */
if (hp && hp_ld < R) return -1;
hipLaunchKernelGGL(r4d_dflash_select_kernel, dim3(M), dim3(DSL_THREADS), 0, (hipStream_t)stream,
hipLaunchKernelGGL((chain ? r4dchain_dflash_select : r4d_dflash_select_kernel), dim3(M),
dim3(DSL_THREADS), 0, (hipStream_t)stream,
(const int*)cand, (const float*)unary, (const r4d_u16*)hp,
(const int*)anchor, (const r4d_u16*)pred, (const r4d_u16*)succ,
(int*)out, steps, K, R, V, cand_ld, hp_ld, out_ld, anchor_stride);
@@ -222,8 +262,10 @@ extern "C" int r4d_rad_dflash_select(const RadArgs* a, RadStream s) {
if (astr < 1 || !r4d_contig(anc)) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(anc) < (M - 1) * astr + 1) return R4D_NO(RAD_E_SHAPE);
return R4D_RAW(r4d_dflash_select_bf16(cand->data, un->data, has_hp ? hp->data : nullptr,
anc->data, pr->data, sc->data,
out->data, (int)M, (int)steps, (int)K, (int)R, (int)V,
(int)cand_ld, (int)hp_ld, (int)out_ld, (int)astr, s));
/* The chained form at decode heights, where the row resolved with `chain`. */
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
return R4D_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));
}
+330
View File
@@ -0,0 +1,330 @@
#include <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_emit.h"
#include "r4d_fwht.h"
#include "r4d_q8.h"
#include "r4d_fp8_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]);
r4d_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 (r4d_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 R4D_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);
}
/* 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();
r4d_fp8::f8v acc[kScoreTiles];
#pragma unroll
for (int tile = 0; tile < kScoreTiles; ++tile) acc[tile] = r4d_fp8::acc_zero();
#pragma unroll
for (int d = 0; d < 128; d += 16) {
const auto a = r4d_fp8::frag<128>(qa, wave * 16, d, lane);
#pragma unroll
for (int tile = 0; tile < kScoreTiles; ++tile)
acc[tile] = r4d_fp8::mma(a, r4d_fp8::frag<128>(kb, tile * 16, d, lane), acc[tile]);
}
#pragma unroll
for (int tile = 0; tile < kScoreTiles; ++tile) {
float value = 0;
#pragma unroll
for (int j = 0; j < 8; ++j)
value += fmaxf(acc[tile][j], 0.0f) * coefficients[wave * 16 + (lane >> 4) * 8 + j];
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 = r4d_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 (r4d_geti_or(a, "n", 0) != 128 || r4d_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 = R4D_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) \
R4D_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));
}
r4d_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 (r4d_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 (r4d_geti_or(a, "n", 0) != 128 || r4d_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 R4D_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 r4d_rad_dsa_pool(const RadArgs* a, RadStream stream) { return pool_body(a, stream); }
extern "C" int r4d_rad_dsa_query(const RadArgs* a, RadStream stream) {
return query_body(a, stream);
}
extern "C" int r4d_rad_dsa_score(const RadArgs* a, RadStream stream) {
return score_body(a, stream);
}
+25
View File
@@ -67,6 +67,31 @@ template<> struct DT16<1> { // f16: 3 more mantissa bits,
};
// Widen 8 fp8 (2 dwords) to 8 16-bit values (4 dwords) in element order.
// Eight K dims of the k6_v4 cache as four f16 dwords, dims (2i, 2i+1) in dword i. `lo` holds
// their low nibbles (dim 2i in bits 8i..8i+3, 2i+1 in 8i+4..8i+7) and `hb` their 16-dim chunk's
// high-bit word (byte j: bits 0-1 dim 2j, 2-3 dim 2j+1, 4-5 dim 8+2j, 6-7 dim 9+2j); `half` says
// which eight of the sixteen these are. One mask and shift put the high bits beside the low
// nibbles, a byte a dim. Codes are 6-bit two's complement: ^ 32 makes them offset binary u,
// 0x6400 | u is the f16 1024 + u, and (x - 1056) * s is the value times the group scale `s2` (the
// f16 in both halves), rounded once.
__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) {
// Byte b of the even dims low, of the odd dims high; perm takes bytes 0-3 from its second
// operand, 4-7 from its first, and 0x0c is a zero byte.
const uint32_t sel = (uint32_t)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);
}
}
template<class D>
__device__ __forceinline__ void fp8x8_to_16x4w(uint2 raw, uint32_t* w4) {
#pragma unroll
+724
View File
@@ -0,0 +1,724 @@
/* Canonical E4M3 weights with exact F32 block scales: native FP8 WMMA and F32 scale folding, no
* checkpoint scale narrowing. The legacy dense form computes one 16x64 output tile a block; the
* dense decode and prefill forms below it produce the same bytes faster, and the grouped form runs
* expert-major over the same per-element sequence. */
#include <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "r4d_fp8_wmma.h"
#include "r4d_launch.h"
#include <climits>
#include <cstdint>
#include <cstring>
namespace {
struct Meta {
long ar, asr, yr, wr, sr, wstep[2], sstep[2];
int T, N, K, experts, topk, sorted_a;
};
__device__ const uint8_t* entry(const void* p, long step, int e) {
return step ? (const uint8_t*)p + step * e : ((const uint8_t* const*)p)[e];
}
/* The legacy dense form: a block per 16 rows by 64 columns, the operands staged through LDS a
* dword at a time, so it serves any row pitch and alignment. */
__global__ void fp8_f32scale(const uint8_t* a, const float* as, const uint8_t* w, const float* ws,
uint16_t* y, Meta m) {
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, n0 = blockIdx.x * 64;
__shared__ uint8_t qa[16 * 136], wb[64 * 136];
__shared__ int source[16];
const int first = (int)blockIdx.y * 16, end = min(first + 16, m.T);
if (tid < 16) {
const int r = first + tid;
source[tid] = r < end ? r : -1;
}
__syncthreads();
auto acc = r4d_fp8::acc_zero();
for (int k0 = 0; k0 < m.K; k0 += 128) {
for (int j = tid; j < 16 * 32; j += 128) {
const int r = j / 32, c = (j % 32) * 4, src = source[r];
uint32_t v = 0;
if (src >= 0) {
const auto* p = a + (long)src * m.ar + k0 + c;
v = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) |
((uint32_t)p[3] << 24);
}
*(uint32_t*)(qa + r * 136 + c) = v;
}
for (int j = tid; j < 64 * 32; j += 128) {
const int r = j / 32, c = (j % 32) * 4;
const auto* p = w + (long)(n0 + r) * m.wr + k0 + c;
*(uint32_t*)(wb + r * 136 + c) = (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
__syncthreads();
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int k = 0; k < 128; k += 16)
raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, 0, k, lane),
r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw);
const float weight_scale = ws[(long)(n0 / 128) * m.sr + k0 / 128];
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int src = source[(lane >> 4) * 8 + j];
const float scale = src >= 0 ? as[(long)src * m.asr + k0 / 128] * weight_scale : 0;
acc[j] += raw[j] * scale;
}
__syncthreads();
}
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = first + (lane >> 4) * 8 + j, c = n0 + wave * 16 + (lane & 15);
if (r < end) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]);
}
}
/* The grouped form expert-major: a block per (column span, expert) takes every row of its
* expert in 16-row tiles, so an expert slice is read from memory once however its rows fall in
* the sorted order (16-row tiles of the sorted order read it once per tile its run spans). Each
* element keeps the sequence above: per 128 of K in order a fresh chain of eight WMMAs, folded as
* raw * (activation scale * weight scale). A block walks ColTiles column tiles of 64, each over K
* in stages of StageK, as one stage sequence with the next stage loaded into registers while the
* current one computes from LDS. Block row `experts` zeroes the dropped rows past
* offsets[experts]. */
typedef unsigned f8_u4 __attribute__((ext_vector_type(4)));
template <int StageK>
struct F8Stage {
static constexpr int KB = StageK / 128;
f8_u4 a[StageK / 128], w[StageK / 32];
float wsc[KB], sa;
};
template <int StageK, int ColTiles>
__global__ __launch_bounds__(128) void fp8_f32scale_experts(const uint8_t* a, const float* as,
const void* w0, const void* s0,
const void* w1, const void* s1,
const int* sorted, const int* offsets,
uint16_t* y, Meta m) {
using St = F8Stage<StageK>;
constexpr int KB = St::KB, P = StageK + 8;
__shared__ __align__(16) uint8_t qa[16 * P], wb[64 * P];
__shared__ float sa[16 * KB];
__shared__ int source[16];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, e = blockIdx.y,
colb = blockIdx.x * 64 * ColTiles;
if (e == m.experts) {
const int r0 = offsets[m.experts];
for (long i = tid; i < (long)(m.T - r0) * 64 * ColTiles; i += 128) {
const int c = colb + (int)(i % (64 * ColTiles));
if (c < m.N) y[(long)(r0 + i / (64 * ColTiles)) * m.yr + c] = 0;
}
return;
}
const int lo = offsets[e], hi = offsets[e + 1];
if (lo >= hi) return;
const int parity = e & 1;
const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e / 2);
const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e / 2);
const int ksn = (m.K + StageK - 1) / StageK, tiles = min(ColTiles, (m.N - colb + 63) / 64),
S = tiles * ksn;
const int rowbase = (lane >> 4) * 8;
for (int r0 = lo; r0 < hi; r0 += 16) {
__syncthreads();
if (tid < 16) {
const int r = r0 + tid, flat = r < hi ? sorted[r] : -1;
source[tid] = r < hi && flat >= 0 ? (m.sorted_a ? r : flat / m.topk) : -1;
}
__syncthreads();
bool rv[8];
#pragma unroll
for (int j = 0; j < 8; ++j) rv[j] = source[rowbase + j] >= 0;
auto load = [&](int s, St& R) {
const int col0 = colb + (s / ksn) * 64, k0 = (s % ksn) * StageK;
#pragma unroll
for (int i = 0; i < StageK / 128; ++i) {
const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16,
src = source[r];
R.a[i] = f8_u4{ 0, 0, 0, 0 };
if (src >= 0 && k0 + c < m.K)
__builtin_memcpy(&R.a[i], a + (long)src * m.ar + k0 + c, 16);
}
#pragma unroll
for (int i = 0; i < StageK / 32; ++i) {
const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
R.w[i] = f8_u4{ 0, 0, 0, 0 };
if (k0 + c < m.K)
__builtin_memcpy(&R.w[i], w + (long)(col0 + r) * m.wr + k0 + c, 16);
}
#pragma unroll
for (int kb = 0; kb < KB; ++kb)
R.wsc[kb] =
k0 + kb * 128 < m.K ? ws[(long)(col0 / 128) * m.sr + (k0 + kb * 128) / 128] : 0;
if (tid < 16 * KB) {
const int src = source[tid / KB], kb = k0 + (tid % KB) * 128;
R.sa = src >= 0 && kb < m.K ? as[(long)src * m.asr + kb / 128] : 0;
}
};
auto store = [&](const St& R) {
#pragma unroll
for (int i = 0; i < StageK / 128; ++i) {
const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
*reinterpret_cast<f8_u4*>(qa + r * P + c) = R.a[i];
}
#pragma unroll
for (int i = 0; i < StageK / 32; ++i) {
const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
*reinterpret_cast<f8_u4*>(wb + r * P + c) = R.w[i];
}
if (tid < 16 * KB) sa[tid] = R.sa;
};
auto acc = r4d_fp8::acc_zero();
St R;
load(0, R);
for (int s = 0; s < S; ++s) {
store(R);
float wsc[KB];
#pragma unroll
for (int kb = 0; kb < KB; ++kb) wsc[kb] = R.wsc[kb];
__syncthreads();
if (s + 1 < S) load(s + 1, R);
const int k0 = (s % ksn) * StageK;
#pragma unroll
for (int kb = 0; kb < KB; ++kb) {
if (k0 + kb * 128 >= m.K) break;
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int k = kb * 128; k < (kb + 1) * 128; k += 16)
raw = r4d_fp8::mma(r4d_fp8::frag<StageK>(qa, 0, k, lane),
r4d_fp8::frag<StageK>(wb, wave * 16, k, lane), raw);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const float scale = rv[j] ? sa[(rowbase + j) * KB + kb] * wsc[kb] : 0;
acc[j] += raw[j] * scale;
}
}
if (s % ksn == ksn - 1) {
const int c = colb + (s / ksn) * 64 + wave * 16 + (lane & 15);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = r0 + rowbase + j;
if (r < hi) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]);
}
acc = r4d_fp8::acc_zero();
}
__syncthreads();
}
}
}
/* The small-M grouped form at GLM's MTP gate_up slice, with fp8_f32scale_experts' per-element
* sequence and so its bytes. A draft pass routes one token to eight experts, and the four column
* tiles a block of the form above leave sixteen blocks, each a chain of 64 stages of 256 K. Here a
* block takes one column tile of the y-th touched expert (the grid has min(experts, rows) + 1
* rows, as at the MXFP4 small-M form), in stages of 512 K, with loads unconditional from clamped
* addresses and masked at the store, barriers that order LDS only, and a 128 of K's eight fragment
* pairs loaded before its WMMA chain. */
typedef unsigned f8_g16 __attribute__((ext_vector_type(4), aligned(1)));
__device__ __forceinline__ f8_u4 f8_ldg16(const uint8_t* p) {
return *(const __attribute__((address_space(1))) f8_g16*)p;
}
__device__ __forceinline__ float f8_ldgf(const float* p) {
return *(const __attribute__((address_space(1))) float*)p;
}
template <int StageK>
struct F8Small {
static constexpr int Threads = 128, KB = StageK / 128, P = StageK + 8;
static constexpr int AChunks = StageK / Threads, WChunks = 64 * StageK / 16 / Threads;
f8_u4 a[AChunks], w[WChunks];
float wsc[KB], sa;
uint32_t ok;
};
template <int StageK>
__global__ __launch_bounds__(128) void fp8_f32scale_small(const uint8_t* a, const float* as,
const void* w0, const void* s0,
const void* w1, const void* s1,
const int* sorted, const int* offsets,
uint16_t* y, Meta m) {
using St = F8Small<StageK>;
constexpr int KB = St::KB, P = St::P, Threads = St::Threads;
static_assert(St::AChunks <= 8 && St::WChunks <= 16 && KB <= 4 && 16 * KB <= Threads &&
64 * P >= 4 * 513,
"stage chunks must fit the load mask and the offsets the weight tile");
__shared__ __align__(16) uint8_t qa[16 * P], wb[64 * P];
__shared__ float sa[16 * KB];
__shared__ int source[16];
__shared__ int pick;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, col0 = blockIdx.x * 64;
if ((int)blockIdx.y == (int)gridDim.y - 1) {
const int r0 = offsets[m.experts];
for (long i = tid; i < (long)(m.T - r0) * 64; i += Threads) {
const int c = col0 + (int)(i % 64);
if (c < m.N) y[(long)(r0 + i / 64) * m.yr + c] = 0;
}
return;
}
{
// The offsets in the weight tile, whose bytes are free until the first stage.
int* offs = reinterpret_cast<int*>(wb);
#pragma unroll
for (int q = 0; q < 5; ++q) {
const int x = tid + q * Threads;
if (x <= m.experts) offs[x] = offsets[x];
}
lds_barrier();
if (wave == 0) {
int want = blockIdx.y, found = -1;
for (int base = 0; base < m.experts; base += 32) {
const int x = base + lane;
const bool live = x < m.experts && offs[x + 1] > offs[x];
const uint32_t mask = __builtin_amdgcn_ballot_w32(live);
const int n = __builtin_popcount(mask);
if (want < n) {
const uint32_t below = mask & ((1u << lane) - 1u);
found = base + __builtin_ctz(__builtin_amdgcn_ballot_w32(
live && __builtin_popcount(below) == want));
break;
}
want -= n;
}
if (lane == 0) pick = found;
}
lds_barrier();
}
const int e = pick;
if (e < 0) return;
const int lo = offsets[e], hi = offsets[e + 1];
const int parity = e & 1;
const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e / 2);
const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e / 2);
const int S = (m.K + StageK - 1) / StageK, rowbase = (lane >> 4) * 8;
for (int r0 = lo; r0 < hi; r0 += 16) {
lds_barrier();
if (tid < 16) {
const int r = r0 + tid, flat = r < hi ? sorted[r] : -1;
source[tid] = flat >= 0 ? (m.sorted_a ? r : flat / m.topk) : -1;
}
lds_barrier();
bool rv[8];
#pragma unroll
for (int j = 0; j < 8; ++j) rv[j] = source[rowbase + j] >= 0;
auto load = [&](int s, St& L) {
const int k0 = s * StageK;
uint32_t ok = 0;
#pragma unroll
for (int i = 0; i < St::AChunks; ++i) {
const int j = tid + i * Threads, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16,
src = source[r];
const bool v = src >= 0 && k0 + c < m.K;
__builtin_memcpy(&L.a[i], a + (v ? (long)src * m.ar + k0 + c : 0), 16);
ok |= (uint32_t)v << i;
}
#pragma unroll
for (int i = 0; i < St::WChunks; ++i) {
const int j = tid + i * Threads, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
const bool v = k0 + c < m.K;
L.w[i] = f8_ldg16(w + (v ? (long)(col0 + r) * m.wr + k0 + c : 0));
ok |= (uint32_t)v << (8 + i);
}
#pragma unroll
for (int kb = 0; kb < KB; ++kb) {
const bool v = k0 + kb * 128 < m.K;
L.wsc[kb] =
f8_ldgf(ws + (v ? (long)(col0 / 128) * m.sr + (k0 + kb * 128) / 128 : 0));
ok |= (uint32_t)v << (24 + kb);
}
{
const int src = source[(tid / KB) & 15], kb = k0 + (tid % KB) * 128;
const bool v = tid < 16 * KB && src >= 0 && kb < m.K;
L.sa = as[v ? (long)src * m.asr + kb / 128 : 0];
ok |= (uint32_t)v << 28;
}
L.ok = ok;
};
auto store = [&](const St& L) {
#pragma unroll
for (int i = 0; i < St::AChunks; ++i) {
const int j = tid + i * Threads, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
*reinterpret_cast<f8_u4*>(qa + r * P + c) =
(L.ok >> i) & 1u ? L.a[i] : f8_u4{ 0, 0, 0, 0 };
}
#pragma unroll
for (int i = 0; i < St::WChunks; ++i) {
const int j = tid + i * Threads, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
*reinterpret_cast<f8_u4*>(wb + r * P + c) =
(L.ok >> (8 + i)) & 1u ? L.w[i] : f8_u4{ 0, 0, 0, 0 };
}
if (tid < 16 * KB) sa[(tid % KB) * 16 + tid / KB] = (L.ok >> 28) & 1u ? L.sa : 0.f;
};
auto acc = r4d_fp8::acc_zero();
St L;
load(0, L);
for (int s = 0; s < S; ++s) {
store(L);
float wsc[KB];
#pragma unroll
for (int kb = 0; kb < KB; ++kb) wsc[kb] = (L.ok >> (24 + kb)) & 1u ? L.wsc[kb] : 0.f;
lds_barrier();
if (s + 1 < S) load(s + 1, L);
const int k0 = s * StageK;
#pragma unroll
for (int kb = 0; kb < KB; ++kb) {
if (k0 + kb * 128 >= m.K) break;
r4d_fp8::i2v fa[8], fb[8];
#pragma unroll
for (int t = 0; t < 8; ++t) {
fa[t] = r4d_fp8::frag<StageK>(qa, 0, kb * 128 + 16 * t, lane);
fb[t] = r4d_fp8::frag<StageK>(wb, wave * 16, kb * 128 + 16 * t, lane);
}
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int t = 0; t < 8; ++t) raw = r4d_fp8::mma(fa[t], fb[t], raw);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const float scale = rv[j] ? sa[kb * 16 + rowbase + j] * wsc[kb] : 0;
acc[j] += raw[j] * scale;
}
}
lds_barrier();
}
const int c = col0 + wave * 16 + (lane & 15);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = r0 + rowbase + j;
if (r < hi) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]);
}
}
}
// Both forms below keep fp8_f32scale's arithmetic for every output: per 128-K block the same
// eight-mma chain from zero over the same fragments (the bytes at k + 8*(lane/16) of the block's
// row segment, which the legacy form copies through LDS unchanged), then acc += raw * (a_scale *
// w_scale) in ascending block order. A WMMA output depends only on its own A row, B column and
// C, so which rows and columns share a tile does not change it.
// Decode: one wave C adjacent 16-column tiles, S waves of a block on S consecutive K blocks at
// once, the fragments loaded straight from global memory; R row tiles share each weight fragment
// and C column tiles each activation fragment. Each wave scales its own partial products (the
// a_scale x w_scale product and the multiply are the legacy fold's own two roundings) into LDS;
// then every wave folds a share of the outputs, adding the round's products in block order to the
// output's running sum, which lives in LDS between rounds. The block's activation scales are
// staged in LDS when they fit (`stage`).
template <int R, int C>
__global__ void fp8_f32scale_decode(const uint8_t* a, const float* as, const uint8_t* w,
const float* ws, uint16_t* y, Meta m, int stage) {
constexpr int SL = R * C * 8;
R4D_DYN_LDS(float, lds);
const int lane = threadIdx.x & 31, s = threadIdx.x >> 5, S = blockDim.x >> 5, h = lane >> 4;
const int c0 = blockIdx.x * 16 * C, first = (int)blockIdx.y * R * 16, KB = m.K / 128;
float* part = lds;
float* sums = part + S * SL * 32;
float* scales = sums + SL * 32;
if (stage)
for (int i = threadIdx.x; i < R * 16 * KB; i += blockDim.x) {
const int r = first + i / KB;
scales[i] = r < m.T ? as[(long)r * m.asr + i % KB] : 0;
}
for (int i = threadIdx.x; i < SL * 32; i += blockDim.x) sums[i] = 0;
const uint8_t* arow[R];
bool alive[R];
#pragma unroll
for (int t = 0; t < R; ++t) {
const int r = first + t * 16 + (lane & 15);
alive[t] = r < m.T;
arow[t] = a + (long)(alive[t] ? r : 0) * m.ar + h * 8;
}
__syncthreads();
for (int k0 = 0; k0 < KB; k0 += S) {
const int kb = k0 + s;
if (kb < KB) {
r4d_fp8::i2v b[C][8];
float weight_scale[C];
#pragma unroll
for (int c = 0; c < C; ++c) {
const uint8_t* wrow =
w + (long)(c0 + c * 16 + (lane & 15)) * m.wr + h * 8 + (long)kb * 128;
#pragma unroll
for (int q = 0; q < 8; ++q) {
const uint2 v = *(const uint2*)(wrow + q * 16);
b[c][q][0] = (int)v.x;
b[c][q][1] = (int)v.y;
}
weight_scale[c] = ws[(long)((c0 + c * 16) / 128) * m.sr + kb];
}
#pragma unroll
for (int t = 0; t < R; ++t) {
r4d_fp8::i2v f[8];
#pragma unroll
for (int q = 0; q < 8; ++q) {
uint2 v = make_uint2(0, 0);
if (alive[t]) v = *(const uint2*)(arow[t] + (long)kb * 128 + q * 16);
f[q][0] = (int)v.x;
f[q][1] = (int)v.y;
}
float act[8];
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int rr = t * 16 + h * 8 + j, r = first + rr;
act[j] =
stage ? scales[rr * KB + kb] : (r < m.T ? as[(long)r * m.asr + kb] : 0);
}
#pragma unroll
for (int c = 0; c < C; ++c) {
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int q = 0; q < 8; ++q) raw = r4d_fp8::mma(f[q], b[c][q], raw);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = first + t * 16 + h * 8 + j;
const float scale = r < m.T ? act[j] * weight_scale[c] : 0;
part[((long)s * SL + (t * C + c) * 8 + j) * 32 + lane] = raw[j] * scale;
}
}
}
}
__syncthreads();
for (int slot = s; slot < SL; slot += S) {
float acc = sums[slot * 32 + lane];
for (int q = 0; q < S && k0 + q < KB; ++q)
acc += part[((long)q * SL + slot) * 32 + lane];
sums[slot * 32 + lane] = acc;
}
__syncthreads();
}
for (int slot = s; slot < SL; slot += S) {
const int t = slot / (C * 8), c = slot / 8 % C, j = slot % 8,
r = first + t * 16 + h * 8 + j;
if (r < m.T)
y[(long)r * m.yr + c0 + c * 16 + (lane & 15)] = f32_to_bf16(sums[slot * 32 + lane]);
}
}
// Prefill: the legacy form's 64-column block and LDS layout over R row tiles, so a staged weight
// block serves R*16 rows instead of 16, staged with 16-byte loads and the next K block loaded
// into registers while the current one is multiplied.
template <int R>
__global__ void __launch_bounds__(128)
fp8_f32scale_rows(const uint8_t* a, const float* as, const uint8_t* w, const float* ws,
uint16_t* y, Meta m) {
constexpr int P = 136, AV = R * 16 * 8 / 128, WV = 64 * 8 / 128;
__shared__ uint8_t qa[R * 16 * P], wb[64 * P];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, h = lane >> 4,
n0 = blockIdx.x * 64;
const int first = (int)blockIdx.y * R * 16, KB = m.K / 128;
uint4 av[AV], wv[WV];
auto load = [&](int kb) {
#pragma unroll
for (int i = 0; i < AV; ++i) {
const int j = tid + i * 128, r = j / 8, c = (j % 8) * 16;
av[i] = first + r < m.T
? *(const uint4*)(a + (long)(first + r) * m.ar + (long)kb * 128 + c)
: make_uint4(0, 0, 0, 0);
}
#pragma unroll
for (int i = 0; i < WV; ++i) {
const int j = tid + i * 128, r = j / 8, c = (j % 8) * 16;
wv[i] = *(const uint4*)(w + (long)(n0 + r) * m.wr + (long)kb * 128 + c);
}
};
r4d_fp8::f8v acc[R];
#pragma unroll
for (int t = 0; t < R; ++t) acc[t] = r4d_fp8::acc_zero();
load(0);
for (int kb = 0; kb < KB; ++kb) {
// The 136-byte pitch keeps 8-byte alignment only, so each 16 bytes go in as two halves.
auto put = [](uint8_t* p, const uint4& v) {
((uint2*)p)[0] = make_uint2(v.x, v.y);
((uint2*)p)[1] = make_uint2(v.z, v.w);
};
#pragma unroll
for (int i = 0; i < AV; ++i) {
const int j = tid + i * 128;
put(qa + (j / 8) * P + (j % 8) * 16, av[i]);
}
#pragma unroll
for (int i = 0; i < WV; ++i) {
const int j = tid + i * 128;
put(wb + (j / 8) * P + (j % 8) * 16, wv[i]);
}
__syncthreads();
if (kb + 1 < KB) load(kb + 1);
const float weight_scale = ws[(long)(n0 / 128) * m.sr + kb];
#pragma unroll
for (int t = 0; t < R; ++t) {
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int k = 0; k < 128; k += 16)
raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, t * 16, k, lane),
r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = first + t * 16 + h * 8 + j;
const float scale = r < m.T ? as[(long)r * m.asr + kb] * weight_scale : 0;
acc[t][j] += raw[j] * scale;
}
}
__syncthreads();
}
#pragma unroll
for (int t = 0; t < R; ++t)
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = first + t * 16 + h * 8 + j, c = n0 + wave * 16 + (lane & 15);
if (r < m.T) y[(long)r * m.yr + c] = f32_to_bf16(acc[t][j]);
}
}
// The dense form: a decode form (`decode`, C column tiles a wave, S waves a block) or the row
// tiles (R of 16 rows a block), by the rule at the end of dense_form. The forms are
// byte-identical; the choice is speed only.
struct Form {
bool decode = false;
int r = 1, s = 1, c = 1;
};
constexpr int kLdsCap = 64 * 1024;
long decode_lds(int R, int S, int C, long KB, bool stage) {
return ((long)S * R * C * 8 * 32 + (long)R * C * 8 * 32 + (stage ? (long)R * 16 * KB : 0)) * 4;
}
Form dense_form(long N, long K, long T) {
// Measured on gfx1201 (r4d_selftest --perfq, cold) at GLM's six shapes: decode1x8 up to 16
// rows; from 17 to 64 two column tiles a wave (decode1x8x2) lead by 5 to 15 %, except at N 512
// (too few column tiles, 1x8 stays) and N 4096 over K 1536, where the 16-row tile wins; from 65
// to 128 rows decode1x8 holds at K 4096 and the row tiles win at K 2048 and below. Among the
// row tiles (and past 128 rows) the 16-row tile beats the 64-row tile by a quarter; the 32-row
// tile wins at N 4096.
const long kb = K / 128;
Form f;
const bool rows =
T > 128 || (T > 64 && K <= 2048) || (T > 16 && T <= 64 && K <= 1536 && N >= 4096);
if (!rows) {
f.decode = true;
f.c = T > 16 && T <= 64 && N > 512 ? 2 : 1;
f.s = 8;
while (f.s > 1 && f.s > kb) f.s /= 2;
return f;
}
f.r = T > 64 && N >= 4096 ? 2 : 1;
return f;
}
template <int R>
int emit_rows(RadStream stream, const uint8_t* xa, const float* xsa, const uint8_t* wa,
const float* wsa, uint16_t* ya, const Meta& m) {
return R4D_EMIT(stream, fp8_f32scale_rows<R>,
dim3(m.N / 64, (unsigned)((m.T + R * 16 - 1) / (R * 16))), dim3(128), 0, xa,
xsa, wa, wsa, ya, m);
}
int dense_fast(RadStream stream, const RadTensor& x, const RadTensor& xs, const RadTensor& w,
const RadTensor& ws, const RadTensor& y, const Meta& m, bool* done) {
*done = false;
const Form f = dense_form(m.N, m.K, m.T);
if (m.wr % 16 || m.ar % 16 ||
(reinterpret_cast<uintptr_t>(x.data) | reinterpret_cast<uintptr_t>(w.data)) % 16)
return RAD_OK;
const uint8_t *xa = (const uint8_t*)x.data, *wa = (const uint8_t*)w.data;
const float *xsa = (const float*)xs.data, *wsa = (const float*)ws.data;
uint16_t* ya = (uint16_t*)y.data;
if (f.decode) {
const long kb = m.K / 128;
const int stage = decode_lds(1, f.s, f.c, kb, true) <= kLdsCap;
const long lds = decode_lds(1, f.s, f.c, kb, stage);
if (lds > kLdsCap || m.N % (16 * f.c)) return RAD_OK;
*done = true;
const dim3 grid(m.N / (16 * f.c), (unsigned)((m.T + 15) / 16)), block(32 * f.s);
if (f.c == 2)
return R4D_EMIT(stream, (fp8_f32scale_decode<1, 2>), grid, block, (uint32_t)lds, xa,
xsa, wa, wsa, ya, m, stage);
return R4D_EMIT(stream, (fp8_f32scale_decode<1, 1>), grid, block, (uint32_t)lds, xa, xsa,
wa, wsa, ya, m, stage);
}
*done = true;
if (f.r == 2) return emit_rows<2>(stream, xa, xsa, wa, wsa, ya, m);
return emit_rows<1>(stream, xa, xsa, wa, wsa, ya, m);
}
int body(const RadArgs* a, RadStream stream, bool grouped) {
if (!a || !a->t || a->n_t < (grouped ? 9 : 5)) return RAD_E_INVAL;
const auto &x = a->t[0], &xs = a->t[1], &w = a->t[2], &ws = a->t[3], &y = a->t[grouped ? 8 : 4];
const int64_t N = r4d_geti_or(a, "N", 0), K = r4d_geti_or(a, "K", 0);
if (N < 128 || N % 128 || K < 128 || K % 128 || N > INT_MAX || K > INT_MAX ||
r4d_geti_or(a, "group", 0) != 128 || r4d_geti_or(a, "pb1", 0) > 0)
return RAD_E_SHAPE;
if (x.dtype != RAD_F8E4M3 || xs.dtype != RAD_F32 || w.dtype != RAD_F8E4M3 ||
ws.dtype != RAD_F32 || y.dtype != RAD_BF16)
return RAD_E_DTYPE;
if (!x.data || !xs.data || !w.data || !ws.data || !y.data || x.rank != 2 || xs.rank != 2 ||
y.rank != 2 || x.shape[1] != K || xs.shape[0] != x.shape[0] || xs.shape[1] != K / 128 ||
y.shape[1] != N || x.stride[1] != 1 || xs.stride[1] != 1 || y.stride[1] != 1 ||
y.shape[0] < 1 || y.shape[0] > INT_MAX)
return RAD_E_SHAPE;
const uint32_t rank = grouped ? 3 : 2;
if (w.rank != rank || ws.rank != rank || w.shape[rank - 2] != N || w.shape[rank - 1] != K ||
ws.shape[rank - 2] != N / 128 || ws.shape[rank - 1] != K / 128 || w.stride[rank - 1] != 1 ||
ws.stride[rank - 1] != 1)
return RAD_E_SHAPE;
Meta m{};
m.ar = x.stride[0];
m.asr = xs.stride[0];
m.yr = y.stride[0];
m.wr = w.stride[rank - 2];
m.sr = ws.stride[rank - 2];
m.T = (int)y.shape[0];
m.N = N;
m.K = K;
if (!grouped) {
if (x.shape[0] != m.T) return RAD_E_SHAPE;
bool done = false;
const int rc = dense_fast(stream, x, xs, w, ws, y, m, &done);
if (done || rc < 0) return rc;
return R4D_EMIT(stream, fp8_f32scale, dim3(N / 64, (m.T + 15) / 16), dim3(128), 0,
(const uint8_t*)x.data, (const float*)xs.data, (const uint8_t*)w.data,
(const float*)ws.data, (uint16_t*)y.data, m);
}
m.experts = r4d_geti_or(a, "n_expert", 0);
m.topk = r4d_geti_or(a, "top_k", 0);
const char* order = r4d_gets(a, "a_order");
m.sorted_a = order && !std::strcmp(order, "sorted");
const auto &wo = a->t[6], &so = a->t[7], &st = a->t[4], &off = a->t[5];
if (m.experts < 2 || m.topk < 1 || r4d_geti_or(a, "N_odd", N) != N ||
r4d_geti_or(a, "K_odd", K) != K || wo.dtype != RAD_F8E4M3 || so.dtype != RAD_F32 ||
wo.rank != 3 || so.rank != 3 || wo.shape[1] != N || wo.shape[2] != K ||
so.shape[1] != N / 128 || so.shape[2] != K / 128 || wo.stride[1] != m.wr ||
so.stride[1] != m.sr || wo.stride[2] != 1 || so.stride[2] != 1 || st.dtype != RAD_I32 ||
off.dtype != RAD_I32 || st.rank != 1 || off.rank != 1 || st.stride[0] != 1 ||
off.stride[0] != 1 || st.shape[0] < m.T || off.shape[0] < m.experts + 1 || !wo.data ||
!so.data || !st.data || !off.data)
return RAD_E_SHAPE;
m.wstep[0] = w.stride[0];
m.wstep[1] = wo.stride[0];
m.sstep[0] = ws.stride[0] * 4;
m.sstep[1] = so.stride[0] * 4;
if (w.shape[0] < (m.experts + 1) / 2 || wo.shape[0] < m.experts / 2) return RAD_E_SHAPE;
/* The small-M form at the MTP layer's gate_up slice up to 384 routed rows: a draft pass routes
* one token, a verify pass a few. Measured there (perfmxf8, cold), expert-major against
* small-M at 1, 2, 4, 8 and 16 tokens: 73.6/36.7, 83.6/65.8, 118.4/114.9, 214.0/203.9 and
* 375.6/343.9 us. Down's K of 256 gains nothing from it (within a few percent, a quarter slower
* at three tokens). */
if (m.experts == 288 && m.topk == 8 && N == 512 && K == 4096 && m.T <= 384)
return R4D_EMIT(stream, fp8_f32scale_small<512>,
dim3(N / 64, (m.T < m.experts ? m.T : m.experts) + 1), dim3(128), 0,
(const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, wo.data,
so.data, (const int*)st.data, (const int*)off.data, (uint16_t*)y.data, m);
/* The expert-major form at every routed-row count. Measured at GLM's TP8 slices: a long K
* (gate_up's 4096) wants the 256 stage, 25 to 40 % ahead of 128, and under 128 routed rows
* four tiles a block on top; at down's K of 256 every variant reads within a few percent of
* the bandwidth, so it keeps 128 over four tiles. */
#define F8_EXPERTS(SK, C) \
R4D_EMIT(stream, (fp8_f32scale_experts<SK, C>), \
dim3((N + 64 * C - 1) / (64 * C), m.experts + 1), dim3(128), 0, \
(const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, wo.data, so.data, \
(const int*)st.data, (const int*)off.data, (uint16_t*)y.data, m)
if (K > 256) return m.T < 128 ? F8_EXPERTS(256, 4) : F8_EXPERTS(256, 1);
return F8_EXPERTS(128, 4);
#undef F8_EXPERTS
}
int dense(const RadArgs* a, RadStream stream) { return body(a, stream, false); }
int grouped(const RadArgs* a, RadStream stream) { return body(a, stream, true); }
}
extern "C" int r4d_rad_fp8_f32scale(const RadArgs* a, RadStream stream) { return dense(a, stream); }
extern "C" int r4d_rad_moe_fp8_f32scale(const RadArgs* a, RadStream stream) {
return grouped(a, stream);
}
extern "C" int r4d_layout_fp8_f32scale(const RadParam*, int, int operand, const RadEncoding* e,
const int* sel, const RadTensor*, int n, RadLayout*) {
if (operand != 2 && operand != 3 && operand != 6 && operand != 7) return RAD_E_UNSUPPORTED;
if (!e || !sel || n != 1 || !rad_enc_is(e, "affine") || e->n_planes != 2 ||
e->plane[0].dtype != RAD_F8E4M3 || e->plane[1].dtype != RAD_F32 ||
e->plane[1].block[0] != 128 || e->plane[1].block[1] != 128 ||
sel[0] != (operand == 3 || operand == 7 ? 1 : 0))
return RAD_E_DTYPE;
return RAD_E_UNSUPPORTED; // Both canonical planes are read without a relayout.
}
+17 -3
View File
@@ -228,8 +228,18 @@ extern "C" int r4d_rad_unrelayout_fp8_block(const RadParam* p, int n_p, int oper
* 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. */
* 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 = r4d_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;
@@ -237,7 +247,10 @@ int i8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
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 (!r4d_enc::affine(enc, RAD_I8, RAD_BF16, 1, R4D_FP8_BLOCK)) return RAD_E_DTYPE;
const bool rot = i8_rotated(p, n_p);
if (!r4d_enc::affine(enc, RAD_I8, RAD_BF16, 1, R4D_FP8_BLOCK, RAD_DT_INVALID,
rot ? "fwht128" : ""))
return RAD_E_DTYPE;
if (operand == FL_BSCALE) {
if (!r4d_enc::selects(enc, sel, n, "scale") || !r4d_enc::dims(pl[0], g.N, g.sk))
return RAD_E_SHAPE;
@@ -248,7 +261,8 @@ int i8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
if (!r4d_enc::selects(enc, sel, n, "codes") || !r4d_enc::dims(pl[0], g.N, g.K))
return RAD_E_SHAPE;
if (g.K % R4D_FP8_SUPER_K || g.N % r4d_fp8::kFragRows) return RAD_E_SHAPE;
ffill(out, "r4d.i8.w.frag64", RAD_I8, g.N, g.K, r4d_fp8::frag_bytes(g.N, g.K));
ffill(out, rot ? "r4d.i8h.w.frag64" : "r4d.i8.w.frag64", RAD_I8, g.N, g.K,
r4d_fp8::frag_bytes(g.N, g.K));
return RAD_OK;
}
} /* namespace */
+152 -1
View File
@@ -1,7 +1,7 @@
/* r4d_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. Eleven of libr4d's fusions have no libref kernel, so this is their only
* it replaces executable. Most of libr4d's fusions have no libref kernel, so this is their only
* oracle: a caller runs the fused row against its chain built from this plugin's own unfused rows,
* and expects identical bytes, not a tolerance.
*
@@ -149,6 +149,16 @@ struct Step {
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{};
@@ -306,6 +316,82 @@ extern "C" int r4d_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t pre
}
}
/* ==========================================================================================
* swiglu_clamped_quant_fp8 -- GLM's clipped SwiGLU and the fp8 quantiser in one pass.
* (kernel: libr4d/r4d_glm.hip, swiglu_clamped_quant_kernel)
*
* Operands: [0] gate_up [1] q [2] scale [3] out_bf16?
*
* Each element is `swiglu_clamped_bf16`'s expression, rounded to bf16 once, and the codes are
* quant_act_fp8's over that rounded value, so the chain is the two rows with the product between.
*/
extern "C" int r4d_fuse_swiglu_clamped_quant_fp8(const RadParam* p, int n_p, uint64_t present,
int step, RadFuseStep* out) {
if (!out) return RAD_E_INVAL;
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED;
const int16_t mid = RAD_FUSE_HAS(present, 3) ? (int16_t)3 : RAD_FUSE_TMP(0);
switch (step) {
case 0: {
Step s(out, "swiglu_clamped");
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "limit").mirror(p, n_p, "dtype");
return s.wire({ 0, mid }); /* gate_up, y */
}
case 1: {
Step s(out, "quant_act_fp8");
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "group").mirror(p, n_p, "dtype");
return s.wire({ mid, 1, 2 }); /* x, q, scale */
}
default:
return RAD_E_NOTFOUND;
}
}
/* ==========================================================================================
* router_sigmoid_topk_scatter -- GLM's selection, the sort over its ids and the shared gate's fill.
* (kernel: libr4d/r4d_glm.hip, router_sigmoid_scatter_kernel)
*
* 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 r4d_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: libr4d/r4d_fused_quant_fp8.hip, gate_quant_fp8_kernel)
@@ -500,6 +586,71 @@ extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, u
}
}
/* ==========================================================================================
* 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: libr4d/r4d_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 r4d_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: libr4d/r4d_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 r4d_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: libr4d/r4d_attn_decode_h256_gqa6.hip, the
+165 -39
View File
@@ -101,7 +101,13 @@ __device__ __forceinline__ void quant_group(const float v[4], float* __restrict_
// consecutive columns, so the group's amax is a wave reduction and the store a single dword. `nr`
// is the row the norm is taken of, already in memory (see the bit-identity note above). Shared so
// the fused all-reduce cannot drift from the standalone norm.
template <bool WF32, uint32_t THR>
//
// HI8 is had_quant_act_i8g's form (the `_had_quant_i8g` ops): the width-128 Hadamard between the
// bf16-rounded norm output and the absmax, then int8 codes, as gated_quant_fp8_kernel's ROT and I8
// together. r4d_quant_act_fp8's kernel has the same mapping, rotation and rounding, so the codes
// are the norm + had_quant_act_i8g pair's bytes. `y` still receives the unrotated norm output.
// The launchers require n % 128 == 0, so no rotated group contains padding.
template <bool WF32, uint32_t THR, bool HI8 = false>
__device__ __forceinline__ void norm_quant_row(
const uint16_t* __restrict__ nr, const void* __restrict__ w, uint16_t* __restrict__ yr,
uint8_t* __restrict__ qr, float* __restrict__ s, size_t s_row, uint32_t n, uint32_t nkb,
@@ -128,13 +134,14 @@ __device__ __forceinline__ void norm_quant_row(
v[j] = bf2f(h);
}
}
quant_group(v, s, qr, s_row + kb, c0, n, lane);
if constexpr (HI8) r4d_fwht_wave<(int)kGroup>(v, (int)lane);
quant_group<HI8>(v, s, qr, s_row + kb, c0, n, lane);
}
}
// ---------------------------------------------------------------------------- rmsnorm -> quant
// One block per row. Pass one is the block-wide sum of squares; pass two is norm_quant_row.
template <bool WF32, bool RES, uint32_t THR>
template <bool WF32, bool RES, uint32_t THR, bool HI8 = false>
__global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
uint16_t* __restrict__ y, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n,
@@ -178,8 +185,8 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
}
const float rs = rsqrtf(block_sum<THR / kWave>(ss, lds) / (float)n + eps);
norm_quant_row<WF32, THR>(nr, w, y ? y + (size_t)row * y_ld : nullptr, q + (size_t)row * q_ld,
s, (size_t)row * s_ld, n, nkb, rs, wadd);
norm_quant_row<WF32, THR, HI8>(nr, w, y ? y + (size_t)row * y_ld : nullptr,
q + (size_t)row * q_ld, s, (size_t)row * s_ld, n, nkb, rs, wadd);
}
// ---------------------------------------------------------------------------- gate -> quant
@@ -363,9 +370,16 @@ __device__ __forceinline__ unsigned int arq_load_acq(const unsigned int* p) {
return __hip_atomic_load(p, __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_SYSTEM);
}
template <bool WF32, bool RES, uint32_t THR, int WIRE>
// POST: a sandwich-norm junction (Gemma 3): the reduced sum is post-normed against `wp` before the
// residual add, `v = bf16(sum * s1 * (wp + wadd))` with s1 the sum's own rms, as rmsnorm_quant_i8's
// POST computes it. `x` still receives the reduced sum. Exact wire and a residual only.
//
// HI8: ar_rmsnorm_had_quant_i8g, pass two in norm_quant_row's rotated int8 form. The reduction and
// the norm are untouched, so `x`, the residual and `y` are ar_rmsnorm_quant_fp8's bytes.
template <bool WF32, bool RES, uint32_t THR, int WIRE, bool POST = false, bool HI8 = false>
__global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp,
uint16_t* __restrict__ y, uint8_t* __restrict__ q, float* __restrict__ s,
int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags,
unsigned int* seq_ctrs, char* loc_pack, long loc_scale_off, int M, uint32_t n, uint32_t nkb,
@@ -546,6 +560,27 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
(void)pr;
float ss = 0.0f;
if constexpr (POST && WIRE == 0 && RES) {
/* Pass one reduces and takes the sum's sum of squares; pass two post-norms it, adds it
* into the stream and takes the stream's. Each thread reads back only its own columns. */
float s1s = 0.0f;
for (uint32_t i = tid; i < n; i += THR) {
const uint16_t a = f2bf(bf2f(xr[i]) + bf2f(pr[i]));
xr[i] = a;
const float av = bf2f(a);
s1s += av * av;
}
const float s1 = rsqrtf(block_sum<THR / kWave>(s1s, lds) / (float)n + eps);
__syncthreads(); // lds is reused by the second sum
for (uint32_t i = tid; i < n; i += THR) {
const float g = WF32 ? ((const float*)wp)[i] : bf2f(((const uint16_t*)wp)[i]);
const uint16_t pv = f2bf(bf2f(xr[i]) * s1 * (g + wadd));
const uint16_t h = f2bf(bf2f(rr[i]) + bf2f(pv));
rr[i] = h;
const float v = bf2f(h);
ss += v * v;
}
} else
for (uint32_t i = tid; i < n; i += THR) {
/* The exact wire reduces here, in the norm's first pass; the compressed one already
* reduced into `x`. */
@@ -559,8 +594,9 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
}
/* block_sum's barrier is also what publishes pass one's stores to pass two's reads. */
const float rs = rsqrtf(block_sum<THR / kWave>(ss, lds) / (float)n + eps);
norm_quant_row<WF32, THR>(nr, w, y ? y + (size_t)row * y_ld : nullptr,
q + (size_t)row * q_ld, s, (size_t)row * s_ld, n, nkb, rs, wadd);
norm_quant_row<WF32, THR, HI8>(nr, w, y ? y + (size_t)row * y_ld : nullptr,
q + (size_t)row * q_ld, s, (size_t)row * s_ld, n, nkb, rs,
wadd);
/* lds is reused by this block's next row; without the barrier a thread still reading it
* would race the next row's write. */
__syncthreads();
@@ -581,14 +617,18 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
// res [M][n] bf16, `r_ld` elements a row (0 = n), optional, read and written
// w [n] f32 or bf16
// y [M][n] bf16, `y_ld` elements a row (0 = n), optional
// q [M][n] E4M3, `q_ld` bytes a row (0 = n), rounded up to 4
// q [M][n] E4M3 (rotated int8 when `hi8`), `q_ld` bytes a row (0 = n), rounded
// up to 4
// s [M][ceil(n/128)] f32, `s_ld` elements a row (0 = ceil(n/128))
extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, long s, int M, int n,
float eps, float wadd, int w_f32, int x_ld, int r_ld,
int y_ld, int q_ld, int s_ld, long stream) {
//
// `hi8` additionally requires n % 128 == 0, as gated_quant_fp8_launch's `rot`.
static int rmsnorm_quant_launch(long x, long res, long w, long y, long q, long s, int M, int n,
float eps, float wadd, int w_f32, int x_ld, int r_ld, int y_ld,
int q_ld, int s_ld, long stream, bool hi8) {
if (!x || !w || !q || !s) return -1;
if (M <= 0 || n <= 0) return -2;
if (n % 4) return -3; // a lane owns four columns; see the kernel
if (hi8 && (n % (int)kGroup)) return -6;
if (!x_ld) x_ld = n;
if (!r_ld) r_ld = n;
if (!y_ld) y_ld = n;
@@ -602,12 +642,14 @@ extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, l
// rmsnorm_bf16 must pick the same width from the same function: the width decides which
// columns a thread sums, so a different width changes the last bits and breaks bit identity.
const int thr = r4d_act_threads(M, n);
#define R4D_RQ_T(wf, rs, T) \
hipLaunchKernelGGL((rmsnorm_quant_fp8_kernel<wf, rs, T>), dim3((uint32_t)M), dim3(T), 0, \
#define R4D_RQ_H(wf, rs, T, H) \
hipLaunchKernelGGL((rmsnorm_quant_fp8_kernel<wf, rs, T, H>), dim3((uint32_t)M), dim3(T), 0, \
(hipStream_t)stream, (const uint16_t*)x, (uint16_t*)res, (const void*)w, \
(uint16_t*)y, (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)nkb, eps, \
wadd, (uint32_t)x_ld, (uint32_t)r_ld, (uint32_t)y_ld, (uint32_t)q_ld, \
(uint32_t)s_ld)
#define R4D_RQ_T(wf, rs, T) \
do { if (hi8) R4D_RQ_H(wf, rs, T, true); else R4D_RQ_H(wf, rs, T, false); } while (0)
#define R4D_RQ(wf, rs) \
do { if (thr == 1024) R4D_RQ_T(wf, rs, 1024); \
else if (thr == 512) R4D_RQ_T(wf, rs, 512); \
@@ -616,9 +658,26 @@ extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, l
else { if (res) R4D_RQ(false, true); else R4D_RQ(false, false); }
#undef R4D_RQ
#undef R4D_RQ_T
#undef R4D_RQ_H
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, long s, int M, int n,
float eps, float wadd, int w_f32, int x_ld, int r_ld,
int y_ld, int q_ld, int s_ld, long stream) {
return rmsnorm_quant_launch(x, res, w, y, q, s, M, n, eps, wadd, w_f32, x_ld, r_ld, y_ld,
q_ld, s_ld, stream, false);
}
// The same norm with had_quant_act_i8g's quantiser on its pass: the width-128 Hadamard, then int8
// codes at amax / 127 per (row, 128). For a rotated int8 linear (dtype i8a8h); `q` is int8.
extern "C" int r4d_rmsnorm_had_quant_i8g(long x, long res, long w, long y, long q, long s, int M,
int n, float eps, float wadd, int w_f32, int x_ld,
int r_ld, int y_ld, int q_ld, int s_ld, long stream) {
return rmsnorm_quant_launch(x, res, w, y, q, s, M, n, eps, wadd, w_f32, x_ld, r_ld, y_ld,
q_ld, s_ld, stream, true);
}
// `mode` is 0 for silu (down_proj's input) and 1 for sigmoid (a gated attention o_proj's), as in
// r4d_gated_had_quant_i8.
//
@@ -629,6 +688,8 @@ extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, l
//
// `rot` additionally requires n % 128 == 0: a ragged last group is fine unrotated (zero-padded,
// masked by the GEMM) but a butterfly mixing real values with padding has no matching weight block.
// `rot` with `i8` is had_quant_act_i8g's form (gated_had_quant_i8g), for a rotated int8 down
// projection; `rot` alone pairs with a rotated four-bit expert, which reads E4M3.
static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n, int mode,
int gu_ld, int y_ld, int q_ld, int s_ld, RadStream stream,
bool rot, bool i8 = false) {
@@ -638,8 +699,6 @@ static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n,
if (n % 4) return -3;
if (mode != 0 && mode != 1) return -5;
if (rot && (n % (int)kGroup)) return -6;
// The rotated codes pair with a rotated four-bit expert, which reads E4M3 only.
if (rot && i8) return -7;
if (!gu_ld) gu_ld = 2 * n;
if (!y_ld) y_ld = n;
if (!q_ld) q_ld = n;
@@ -654,7 +713,8 @@ static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n,
(float*)s, (uint32_t)n, (uint32_t)nkb, (uint32_t)gu_ld, (uint32_t)y_ld, \
(uint32_t)q_ld, (uint32_t)s_ld)
#define R4D_GQ(a) \
do { if (rot) R4D_GQ_R(a, true, false); \
do { if (rot && i8) R4D_GQ_R(a, true, true); \
else if (rot) R4D_GQ_R(a, true, false); \
else if (i8) R4D_GQ_R(a, false, true); \
else R4D_GQ_R(a, false, false); } while (0)
if (mode == 0) R4D_GQ(0);
@@ -677,6 +737,13 @@ extern "C" int r4d_gated_had_quant_fp8(long gu, long y, long q, long s, int M, i
(RadStream)(uintptr_t)stream, true);
}
// The same product with had_quant_act_i8g's quantiser: `q` is int8.
extern "C" int r4d_gated_had_quant_i8g(long gu, long y, long q, long s, int M, int n, int mode,
int gu_ld, int y_ld, int q_ld, int s_ld, long stream) {
return gated_quant_fp8_launch(gu, y, q, s, M, n, mode, gu_ld, y_ld, q_ld, s_ld,
(RadStream)(uintptr_t)stream, true, true);
}
// act . x with the gate and x in separate buffers; see the kernel for why a row is a (token, head)
// pair and why the activation is rounded to bf16 before the product. `mode` as in
// r4d_gated_quant_fp8.
@@ -735,14 +802,19 @@ extern "C" int r4d_gate_quant_fp8(long g, long x, long y, long q, long s, int M,
// `res` behaves as in r4d_rmsnorm_quant_fp8. Returns 0, or a negative code for an unserved shape.
extern "C" int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void) { return ARQ_CE; }
extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flags,
long my_flags, long seq_ctrs, long slot_stride16,
long x, long res, long w, long y, long q, long s,
int M, int n, float eps, float wadd, int w_f32,
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq, int wire,
long loc_pack, long loc_scale_off) {
// `hi8` is the rotated int8 form (ar_rmsnorm_had_quant_i8g): `q` is int8, n % 128 == 0, and there
// is no post-norm.
static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer_flags,
long my_flags, long seq_ctrs, long slot_stride16,
long x, long res, long w, long y, long q, long s,
int M, int n, float eps, float wadd, int w_f32,
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq, int wire,
long loc_pack, long loc_scale_off, long wp, bool hi8) {
if (!x || !w || !q || !s) return -1;
if (wp && (!res || wire != 0)) return -10; // a post-norm needs the stream and the exact wire
if (hi8 && wp) return -11;
if (hi8 && (n % (int)kGroup)) return -12;
if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1;
if (M <= 0 || n <= 0) return -2;
// n % 8: n bf16 is a whole number of 16B words (see the push), which also gives every lane its
@@ -765,18 +837,25 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long
// The width must be r4d_act_threads', as for the standalone norm (it fixes the summation order).
const int thr = nthreads ? nthreads : r4d_act_threads(M, n);
if (thr != 256 && thr != 512 && thr != 1024) return -6;
#define R4D_ARQ_T(wf, rs, T, W) \
hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel<wf, rs, T, W>), dim3((uint32_t)nb), dim3(T), \
0, \
#define R4D_ARQ_H(wf, rs, T, W, PO, H) \
hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel<wf, rs, T, W, PO, H>), dim3((uint32_t)nb), \
dim3(T), 0, \
(hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, (const void*)w, \
(const void*)wp, \
(uint16_t*)y, (uint8_t*)q, (float*)s, (int4*)peer_scratch, \
(const int4*)my_scratch, (unsigned int*)peer_flags, \
(unsigned int*)my_flags, (unsigned int*)seq_ctrs, (char*)loc_pack, \
(long)loc_scale_off, M, (uint32_t)n, \
(uint32_t)nkb, eps, wadd, (uint32_t)r_ld, (uint32_t)y_ld, (uint32_t)q_ld, \
(uint32_t)s_ld, (int)slot_stride16, drain, acq, (unsigned)nbw)
#define R4D_ARQ_P(wf, rs, T, W, PO) R4D_ARQ_H(wf, rs, T, W, PO, false)
#define R4D_ARQ_T(wf, rs, T, W) \
do { if (hi8) R4D_ARQ_H(wf, rs, T, W, false, true); \
else R4D_ARQ_P(wf, rs, T, W, false); } while (0)
#define R4D_ARQ_W(wf, rs, T) \
do { if (wire == 6) R4D_ARQ_T(wf, rs, T, 6); else R4D_ARQ_T(wf, rs, T, 0); } while (0)
do { if (wire == 6) R4D_ARQ_T(wf, rs, T, 6); \
else if (rs && wp) R4D_ARQ_P(wf, rs, T, 0, true); \
else R4D_ARQ_T(wf, rs, T, 0); } while (0)
#define R4D_ARQ(wf, rs) \
do { if (thr == 1024) R4D_ARQ_W(wf, rs, 1024); \
else if (thr == 512) R4D_ARQ_W(wf, rs, 512); \
@@ -786,9 +865,38 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long
#undef R4D_ARQ
#undef R4D_ARQ_W
#undef R4D_ARQ_T
#undef R4D_ARQ_P
#undef R4D_ARQ_H
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flags,
long my_flags, long seq_ctrs, long slot_stride16,
long x, long res, long w, long y, long q, long s,
int M, int n, float eps, float wadd, int w_f32,
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq, int wire,
long loc_pack, long loc_scale_off, long wp) {
return ar_rmsnorm_quant_launch(peer_scratch, my_scratch, peer_flags, my_flags, seq_ctrs,
slot_stride16, x, res, w, y, q, s, M, n, eps, wadd, w_f32,
r_ld, y_ld, q_ld, s_ld, stream, nblocks, nthreads, drain, acq,
wire, loc_pack, loc_scale_off, wp, false);
}
// The same with had_quant_act_i8g's quantiser on the norm's pass (no post-norm).
extern "C" int r4d_ar_rmsnorm_had_quant_i8g(long peer_scratch, long my_scratch, long peer_flags,
long my_flags, long seq_ctrs, long slot_stride16,
long x, long res, long w, long y, long q, long s,
int M, int n, float eps, float wadd, int w_f32,
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq,
int wire, long loc_pack, long loc_scale_off) {
return ar_rmsnorm_quant_launch(peer_scratch, my_scratch, peer_flags, my_flags, seq_ctrs,
slot_stride16, x, res, w, y, q, s, M, n, eps, wadd, w_f32,
r_ld, y_ld, q_ld, s_ld, stream, nblocks, nthreads, drain, acq,
wire, loc_pack, loc_scale_off, 0, true);
}
// ============================================================== the plugin ABI entry points
//
// The shared operand reader is r4d_fp8_args.h; see libr4d/r4d_args.h.
@@ -797,7 +905,9 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long
* The standalone quantiser's shape rules, applied to the operand that produces the row. The bf16
* output is optional so a layer without a bf16 consumer skips the store. */
extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
/* `hi8`: rmsnorm_had_quant_i8g, whose codes are int8 and whose row is whole 128s (the rotation's
* width). Separate ops for the reason given at r4d_rad_gated_had_quant_fp8. */
static int rad_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) {
const RadTensor* x = r4d_opt(a, RQ_X);
const RadTensor* rs = r4d_opt(a, RQ_RES);
const RadTensor* w = r4d_opt(a, RQ_W);
@@ -805,7 +915,7 @@ extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
const RadTensor* sc = r4d_opt(a, RQ_S);
const RadTensor* y = r4d_opt(a, RQ_Y);
if (!x || !w || !q || !sc) return R4D_NO(RAD_E_INVAL);
if (q->dtype != RAD_F8E4M3) return R4D_NO(RAD_E_DTYPE);
if (q->dtype != (hi8 ? RAD_I8 : RAD_F8E4M3)) return R4D_NO(RAD_E_DTYPE);
/* Rank 2 on the input too, unlike the standalone quantiser: a norm has one gain per channel,
* and folding trailing dims would spread a gain across heads. */
if (x->rank != 2 || q->rank != 2 || sc->rank != 2) return R4D_NO(RAD_E_SHAPE);
@@ -819,21 +929,30 @@ extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
if (q->shape[0] != M || q->shape[1] != K) return R4D_NO(RAD_E_SHAPE);
if (sc->shape[0] != M || sc->shape[1] != nkb) return R4D_NO(RAD_E_SHAPE);
if (y && (y->shape[0] != M || y->shape[1] != K)) return R4D_NO(RAD_E_SHAPE);
if (hi8 && K % grp) return R4D_NO(RAD_E_SHAPE);
/* The residual has the input's extent and is read and written. It may alias `out_bf16` (see
* the note at the top of the file). */
if (rs && (rs->rank != 2 || rs->shape[0] != M || rs->shape[1] != K)) return R4D_NO(RAD_E_SHAPE);
const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc);
const long long yp = y ? r4d_row_pitch(y) : 0, rp = rs ? r4d_row_pitch(rs) : 0;
if (xp < 0 || qp < 0 || sp < 0 || yp < 0 || rp < 0) return R4D_NO(RAD_E_STRIDE);
const int e = r4d_rmsnorm_quant_fp8(r4d_addr(x), rs ? r4d_addr(rs) : 0, r4d_addr(w),
y ? r4d_addr(y) : 0, r4d_addr(q), r4d_addr(sc),
(int)M, (int)K,
(float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0),
w->dtype == RAD_F32, (int)xp, (int)rp, (int)yp, (int)qp,
(int)sp, (long)(uintptr_t)s);
const int e = rmsnorm_quant_launch(r4d_addr(x), rs ? r4d_addr(rs) : 0, r4d_addr(w),
y ? r4d_addr(y) : 0, r4d_addr(q), r4d_addr(sc),
(int)M, (int)K,
(float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0),
w->dtype == RAD_F32, (int)xp, (int)rp, (int)yp, (int)qp,
(int)sp, (long)(uintptr_t)s, hi8);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
return rad_rmsnorm_quant(a, s, false);
}
extern "C" int r4d_rad_rmsnorm_had_quant_i8g(const RadArgs* a, RadStream s) {
return rad_rmsnorm_quant(a, s, true);
}
/* The gate's activation: `act` by name overrides `mode` (libr4d's integer: 0 silu, 1 sigmoid) when
* both are given, as for r4d_gated_had_quant_i8. Returns -1 for an unknown name. */
static int act_mode(const RadArgs* a, int dflt) {
@@ -844,15 +963,17 @@ static int act_mode(const RadArgs* a, int dflt) {
return -1;
}
static int rad_gated_quant_fp8(const RadArgs* a, RadStream stream, bool rot) {
/* `hi8` (with `rot`): gated_had_quant_i8g, int8 codes only. */
static int rad_gated_quant_fp8(const RadArgs* a, RadStream stream, bool rot, bool hi8 = false) {
const RadTensor* gu = r4d_opt(a, GQ_GU);
const RadTensor* q = r4d_opt(a, GQ_Q);
const RadTensor* sc = r4d_opt(a, GQ_S);
const RadTensor* y = r4d_opt(a, GQ_Y);
if (!gu || !q || !sc) return R4D_NO(RAD_E_INVAL);
/* The codes' dtype picks the quantiser: E4M3, or int8 for an int8 down projection. */
/* The codes' dtype picks the quantiser: E4M3, or int8 for an int8 down projection. The two
* rotated ops each take one: E4M3 for a four-bit expert, int8 for a rotated int8 weight. */
if (q->dtype != RAD_F8E4M3 && q->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE);
if (rot && q->dtype == RAD_I8) return R4D_NO(RAD_E_DTYPE);
if (rot && q->dtype != (hi8 ? RAD_I8 : RAD_F8E4M3)) return R4D_NO(RAD_E_DTYPE);
if (gu->rank != 2 || q->rank != 2 || sc->rank != 2) return R4D_NO(RAD_E_SHAPE);
if (y && y->rank != 2) return R4D_NO(RAD_E_SHAPE);
const long long M = gu->shape[0], K = q->shape[1];
@@ -885,6 +1006,11 @@ extern "C" int r4d_rad_gated_had_quant_fp8(const RadArgs* a, RadStream stream) {
return rad_gated_quant_fp8(a, stream, true);
}
/* Its int8 twin, had_quant_act_i8g's codes: pairs only with a weight stored at dtype i8a8h. */
extern "C" int r4d_rad_gated_had_quant_i8g(const RadArgs* a, RadStream stream) {
return rad_gated_quant_fp8(a, stream, true, true);
}
/* Elements between consecutive `width`-wide rows, as r4d_gdn.cpp's gn_row_pitch: a
* [.., heads, width] operand steps by the stride of the second-to-last axis; a flattened one is
* contiguous and steps by `width`. This reads a column view of an interleaved projection (a gated
@@ -850,7 +850,10 @@ static unsigned int* ru_conv_ctr(RadStream s, const void* out) {
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
void* p = nullptr;
if (hipMalloc(&p, (size_t)kMaxConvCtr * sizeof(unsigned int)) != hipSuccess) return nullptr;
if (hipMemset(p, 0, (size_t)kMaxConvCtr * sizeof(unsigned int)) != hipSuccess) {
// 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 r4d_moe.hip's router counters do).
if (hipMemset(p, 0, (size_t)kMaxConvCtr * sizeof(unsigned int)) != hipSuccess ||
hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return nullptr;
}
+25 -3
View File
@@ -9,14 +9,18 @@
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "r4d_chain.h"
#include <cstdint>
namespace {
template <uint32_t THR>
__global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel(
// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); every block runs
// to the end. The plain kernel and the chained one (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) r4d_chain_wait();
extern __shared__ uint16_t ybuf[];
__shared__ float lm[THR / 32];
const uint32_t row = blockIdx.x;
@@ -49,6 +53,20 @@ __global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel(
const int t = __float2int_rn(bf16_to_f32(ybuf[src]) * inv);
qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
}
if (CHAIN) r4d_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 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
@@ -79,13 +97,17 @@ extern "C" int r4d_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream stream) {
const size_t lds = (size_t)n * sizeof(uint16_t);
if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE);
const int thr = r4d_act_threads((int)M, (int)n);
#define R4D_GMQ_T(T) emit_rc = R4D_EMIT(stream, (gelu_mul_quant_i8_kernel<T>), dim3((uint32_t)M), dim3(T), lds, \
const bool chain = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; /* RadKernelChainFn, decode */
#define R4D_GMQ_C(T, C) R4D_EMIT(stream, (C ? r4dchain_gelu_mul_quant_i8<T> : gelu_mul_quant_i8_kernel<T>), \
dim3((uint32_t)M), dim3(T), lds, \
(const uint16_t*)r4d_p(gu), (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), \
(uint32_t)n, (uint32_t)gp, (uint32_t)yp)
#define R4D_GMQ_T(T) emit_rc = chain ? R4D_GMQ_C(T, true) : R4D_GMQ_C(T, false)
if (thr == 1024) R4D_GMQ_T(1024);
else if (thr == 512) R4D_GMQ_T(512);
else if (thr == 256) R4D_GMQ_T(256);
else return R4D_NO(RAD_E_INVAL);
#undef R4D_GMQ_T
#undef R4D_GMQ_C
return emit_rc;
}
+32 -6
View File
@@ -19,6 +19,7 @@
#include "r4d.h"
#include "r4d_gemm_args.h"
#include "r4d_gdn_wmma.h"
#include "r4d_chain.h"
#include <hip/hip_bf16.h>
#include <cstdint>
#include <stdexcept>
@@ -48,10 +49,13 @@ __device__ __forceinline__ v8bf fragU(r4d_gu2 p, int u) {
// More amortises each weight fragment, fewer puts more blocks on the machine, so MT is tunable.
// KU is the k-step unroll; see the loop.
constexpr int KU = 8;
template <int MT>
__global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel(
// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); no block returns
// early. r4d_gemm_bf16_nt_m64_kernel and r4dchain_gemm_bf16_nt_m64 below wrap it.
template <int MT, bool CHAIN>
__device__ __forceinline__ void r4d_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) r4d_chain_wait();
extern __shared__ 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;
@@ -124,12 +128,33 @@ __global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel(
if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)v;
}
}
if (CHAIN) r4d_chain_done();
}
template <int MT>
__global__ __launch_bounds__(1024) void r4d_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) {
r4d_gemm_bf16_nt_m64_body<MT, false>(A, W, C, M, K, N, WV, SK);
}
template <int MT>
__global__ __launch_bounds__(1024) void 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) {
r4d_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 r4d_gemm_bf16_nt_m64(long a, long w, long c, int M, int K, int N, int WV, int SK, int MB,
long stream) {
gemm_bf16_m64_launch(a, w, c, M, K, N, WV, SK, MB, stream, false);
}
/* `chain`: the chained form (r4d_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 > R4D_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");
@@ -140,8 +165,9 @@ void r4d_gemm_bf16_nt_m64(long a, long w, long c, int M, int K, int N, int WV, i
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(r4d_gemm_bf16_nt_m64_kernel<MT>, grid, block, smem, st, \
Ap, Wp, Cp, M, K, N, WV, SK)
#define LAUNCH(MT) hipLaunchKernelGGL((chain ? r4dchain_gemm_bf16_nt_m64<MT> \
: r4d_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;
@@ -166,9 +192,9 @@ extern "C" int r4d_rad_gemm_bf16_m64(const RadArgs* a, RadStream s) {
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;
R4D_TRY("gemm_bf16_nt_m64",
r4d_gemm_bf16_nt_m64(r4d_addr(g.a), r4d_addr(g.b), r4d_addr(g.y),
gemm_bf16_m64_launch(r4d_addr(g.a), r4d_addr(g.b), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb,
(long)(uintptr_t)s));
(long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0));
return RAD_OK;
}
+31 -7
View File
@@ -30,6 +30,7 @@
#include "r4d_args.h"
#include "r4d_fp8_lm.h"
#include "r4d_fp8_wmma.h"
#include "r4d_chain.h"
#include <algorithm>
@@ -479,8 +480,9 @@ constexpr uint32_t lm_waves(uint32_t mt, uint32_t fkb) {
return fkb == 2u ? 6u : mt >= 4u ? 6u : mt == 3u ? 7u : mt == 2u ? 9u : 12u;
}
template <uint32_t MT, uint32_t FKB, bool I8 = false>
__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm_wmma_kernel(
// The body; lm_wmma_kernel and its chained form (RadKernelChainFn) wrap it.
template <uint32_t MT, uint32_t FKB, bool I8>
__device__ __forceinline__ void lm_wmma_body(
const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, uint32_t a_ld,
float* __restrict__ C, uint32_t c_ld,
uint32_t rows, uint32_t cols, uint32_t w_ld, uint32_t m_real) {
@@ -597,6 +599,23 @@ __global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm
}
}
}
#define R4D_LMW_PARAMS const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, \
uint32_t a_ld, float* __restrict__ C, uint32_t c_ld, uint32_t rows, uint32_t cols, \
uint32_t w_ld, uint32_t m_real
template <uint32_t MT, uint32_t FKB, bool I8 = false>
__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm_wmma_kernel(
R4D_LMW_PARAMS) {
lm_wmma_body<MT, FKB, I8>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
}
template <uint32_t MT, uint32_t FKB, bool I8 = false>
__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void r4dchain_lm_wmma(
R4D_LMW_PARAMS) {
r4d_chain_wait();
lm_wmma_body<MT, FKB, I8>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
r4d_chain_done();
}
#undef R4D_LMW_PARAMS
} // namespace
extern "C" int r4d_gemm_fp8a16_nt_m1_block(void) { return (int)kBlock; }
@@ -677,7 +696,7 @@ extern "C" int r4d_gemm_fp8a16_nt_mt(long a, long wq, long ws, long c,
// core/build/rad_builder.cpp refuses such a split at declare time.
template <bool I8>
static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld, int c_ld,
int w_ld, long stream);
int w_ld, long stream, bool chain = false);
extern "C" int r4d_logits_gemm_fp8(long a, long wq, long c, int M, int K, int N,
int a_ld, int c_ld, int w_ld, long stream) {
@@ -691,9 +710,11 @@ extern "C" int r4d_logits_gemm_i8(long a, long wq, long c, int M, int K, int N,
return logits_gemm_8<true>(a, wq, c, M, K, N, a_ld, c_ld, w_ld, stream);
}
/* `chain`: the WMMA pass's chained form (the plugin entry, where the row resolved with `chain`);
* the matvec below three rows stays plain. */
template <bool I8>
static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld, int c_ld,
int w_ld, long stream) {
int w_ld, long stream, bool chain) {
if (!a || !wq || !c) return -1;
if (M <= 0 || K <= 0 || N <= 0) return -2;
if (K % (int)kBlock) return -4;
@@ -722,7 +743,8 @@ static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld,
const uint16_t* ac = (const uint16_t*)a + (size_t)m0 * a_ld;
float* cc = (float*)c + (size_t)m0 * c_ld;
#define R4D_LMW2(MTV, FKV) \
hipLaunchKernelGGL((lm_wmma_kernel<MTV, FKV, I8>), dim3(blocks), dim3(kDenseThreads), 0, \
hipLaunchKernelGGL((chain ? r4dchain_lm_wmma<MTV, FKV, I8> : lm_wmma_kernel<MTV, FKV, I8>), \
dim3(blocks), dim3(kDenseThreads), 0, \
(hipStream_t)stream, (const uint8_t*)wq, ac, (uint32_t)a_ld, cc, \
(uint32_t)c_ld, rows, cols, (uint32_t)w_ld, (uint32_t)Mc)
#define R4D_LMW(MTV) do { if (fkb == 2u) R4D_LMW2(MTV, 2); else R4D_LMW2(MTV, 1); } while (0)
@@ -836,9 +858,11 @@ static int rad_logits_gemm_8(const RadArgs* a, RadStream s, bool i8) {
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16)) return R4D_NO(RAD_E_ALIGN);
return (i8 ? r4d_logits_gemm_i8 : r4d_logits_gemm_fp8)(
/* The chained form at decode heights, where the row resolved with `chain`. */
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
return (i8 ? logits_gemm_8<true> : logits_gemm_8<false>)(
r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n_embd, (int)n_vocab,
(int)x_ld, (int)y_ld, (int)stride, (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
(int)x_ld, (int)y_ld, (int)stride, (long)(uintptr_t)s, ch) == 0 ? RAD_OK : RAD_E_DEVICE;
}
extern "C" int r4d_rad_logits_gemm_fp8(const RadArgs* a, RadStream s) {
+92 -18
View File
@@ -28,6 +28,7 @@
#include "r4d.h"
#include "r4d_fp8_args.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_fp8_wmma.h"
#include <algorithm>
@@ -176,10 +177,12 @@ constexpr uint32_t f8_waves(bool full, uint32_t nt, uint32_t mw, uint32_t fk, bo
//
// The narrow tile: MW waves a block, a wave one 16-row weight tile (A, fragments straight from the
// plane into registers) against NT 16-token tiles (B, staged through LDS).
/* The body. gemm_fp8a8_kernel and its chained form r4dchain_gemm_fp8a8 (r4d_chain.h) wrap it
* after it: its blocks return early (an empty K slice, the finisher's losers), and every block of
* a chained launch must still count itself in. */
template <bool Full, uint32_t NT, uint32_t MW, uint32_t FK,
bool GATED = false, bool I8 = false, bool BIAS = false>
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8))
void gemm_fp8a8_kernel(
__device__ __forceinline__ void gemm_fp8a8_body(
const uint8_t* __restrict__ Ap, const void* __restrict__ Sa,
const uint8_t* __restrict__ Bp, const void* __restrict__ Sb,
void* __restrict__ Y, void* __restrict__ C, unsigned int* __restrict__ Ctr,
@@ -591,6 +594,42 @@ void gemm_fp8a8_kernel(
}
}
#define R4D_F8K_ARGS Ap, Sa, Bp, Sb, Y, C, Ctr, rows, cols, nb, a_ld, b_ld, sa_ld, sb_ld, ck, Q, \
Sc, Yb, q_ld, s_ld, y_ld, Bias, c_ld
template <bool Full, uint32_t NT, uint32_t MW, uint32_t FK,
bool GATED = false, bool I8 = false, bool BIAS = false>
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8))
void gemm_fp8a8_kernel(
const uint8_t* __restrict__ Ap, const void* __restrict__ Sa,
const uint8_t* __restrict__ Bp, const void* __restrict__ Sb,
void* __restrict__ Y, void* __restrict__ C, unsigned int* __restrict__ Ctr,
uint32_t rows, uint32_t cols, uint32_t nb,
uint32_t a_ld, uint32_t b_ld, uint32_t sa_ld, uint32_t sb_ld, uint32_t ck,
uint8_t* __restrict__ Q = nullptr, float* __restrict__ Sc = nullptr,
uint16_t* __restrict__ Yb = nullptr,
uint32_t q_ld = 0, uint32_t s_ld = 0, uint32_t y_ld = 0,
const uint16_t* __restrict__ Bias = nullptr, uint32_t c_ld = 0) {
gemm_fp8a8_body<Full, NT, MW, FK, GATED, I8, BIAS>(R4D_F8K_ARGS);
}
template <bool Full, uint32_t NT, uint32_t MW, uint32_t FK,
bool GATED = false, bool I8 = false, bool BIAS = false>
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8))
void r4dchain_gemm_fp8a8(
const uint8_t* __restrict__ Ap, const void* __restrict__ Sa,
const uint8_t* __restrict__ Bp, const void* __restrict__ Sb,
void* __restrict__ Y, void* __restrict__ C, unsigned int* __restrict__ Ctr,
uint32_t rows, uint32_t cols, uint32_t nb,
uint32_t a_ld, uint32_t b_ld, uint32_t sa_ld, uint32_t sb_ld, uint32_t ck,
uint8_t* __restrict__ Q = nullptr, float* __restrict__ Sc = nullptr,
uint16_t* __restrict__ Yb = nullptr,
uint32_t q_ld = 0, uint32_t s_ld = 0, uint32_t y_ld = 0,
const uint16_t* __restrict__ Bias = nullptr, uint32_t c_ld = 0) {
r4d_chain_wait();
gemm_fp8a8_body<Full, NT, MW, FK, GATED, I8, BIAS>(R4D_F8K_ARGS);
r4d_chain_done();
}
#undef R4D_F8K_ARGS
// Sum the split-K partials into bf16 C, in fixed z order with no atomics. Latency bound, so eight
// loads are issued before their adds; the order of the adds is unchanged.
__global__ void splitk_reduce_kernel(const float* __restrict__ ws, uint16_t* __restrict__ y,
@@ -824,7 +863,10 @@ unsigned int* split_ctr(RadStream s, const void* out) {
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
void* p = nullptr;
if (hipMalloc(&p, (size_t)kMaxCtr * sizeof(unsigned int)) != hipSuccess) return nullptr;
if (hipMemset(p, 0, (size_t)kMaxCtr * sizeof(unsigned int)) != hipSuccess) {
/* 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 r4d_moe.hip's router counters do). */
if (hipMemset(p, 0, (size_t)kMaxCtr * sizeof(unsigned int)) != hipSuccess ||
hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return nullptr;
}
@@ -928,7 +970,7 @@ extern "C" int r4d_gemm_fp8a8_block(void) { return (int)kBlock; }
static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
long scratch, long scratch_bytes, RadStream stream,
bool i8 = false);
bool i8 = false, int split_n = 0, bool chain = false);
extern "C" int r4d_gemm_fp8a8_nt_m16(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
@@ -958,12 +1000,21 @@ extern "C" void r4d_gemm_fp8a8_pin_nt(int nt) {
// Bytes of f32 scratch one r4d_gemm_fp8a8_nt_m16 call needs, or 0 when it will not split. The
// caller may pass more, or none (the launch then runs unsplit: correct but slow, and unreported).
// The bound is max_m() so the query and the band cannot drift apart.
extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) {
//
// `split_n` (0: N) is the width the split is chosen for. The split depends on N alone, and it
// fixes the order K partials are summed in, so a row slice of a wider linear (N rows of a
// split_n-row weight) passes the whole width to sum each output as the whole linear does: the
// slice's outputs are then the linear's to the bit.
static long m16_scratch(int M, int K, int N, int split_n) {
if (M <= 0 || K <= 0 || N <= 0 || M > r4d_gemm_fp8a8_nt_m16_max_m()) return 0;
uint32_t ck = 0;
const uint32_t k2 = narrow_ksplit((uint32_t)N, (uint32_t)K, (uint32_t)M, &ck);
const uint32_t k2 = narrow_ksplit((uint32_t)(split_n > 0 ? split_n : N), (uint32_t)K,
(uint32_t)M, &ck);
return k2 > 1 ? (long)k2 * M * N * (long)sizeof(float) : 0;
}
extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) {
return m16_scratch(M, K, N, 0);
}
// C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, M <= 64.
//
@@ -973,10 +1024,12 @@ extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) {
// ws [ceil(N/128)][ceil(K/128)] bf16, `sw_ld` elements a row (0 = ceil(K/128))
// c [M][N] bf16
//
// Returns 0, or a negative code for a shape it does not serve. `scratch` may be 0.
// Returns 0, or a negative code for a shape it does not serve. `scratch` may be 0. `split_n` is
// r4d_gemm_fp8a8_nt_m16_scratch's.
static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
long scratch, long scratch_bytes, RadStream stream, bool i8) {
long scratch, long scratch_bytes, RadStream stream, bool i8,
int split_n, bool chain) {
int emit_rc = RAD_OK;
if (!a || !ascale || !wq || !ws || !c) return -1;
if (M <= 0 || K <= 0 || N <= 0) return -2;
@@ -997,7 +1050,8 @@ static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c,
const uint32_t gx = ((uint32_t)N + fm - 1) / fm;
uint32_t ck = 0;
uint32_t ksplit = narrow_ksplit((uint32_t)N, (uint32_t)K, (uint32_t)M, &ck);
uint32_t ksplit = narrow_ksplit((uint32_t)(split_n > 0 ? split_n : N), (uint32_t)K,
(uint32_t)M, &ck);
const long need = ksplit > 1 ? (long)ksplit * M * N * (long)sizeof(float) : 0;
if (need && (!scratch || scratch_bytes < need)) { ksplit = 1; ck = 0; }
@@ -1019,7 +1073,9 @@ static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c,
(ksplit > 1 && gx <= kMaxCtr) ? split_ctr(stream, (const void*)c) : nullptr;
#define R4D_F8D(f, mw_, nt_, fk_, i8_) \
emit_rc = R4D_EMIT(stream, (gemm_fp8a8_kernel<f, nt_, mw_, fk_, false, i8_>), \
emit_rc = R4D_EMIT(stream, \
(chain ? r4dchain_gemm_fp8a8<f, nt_, mw_, fk_, false, i8_> \
: gemm_fp8a8_kernel<f, nt_, mw_, fk_, false, i8_>), \
grid, dim3(mw_ * kWave), \
0, (const uint8_t*)wq, (const void*)ws, \
(const uint8_t*)a, (const void*)ascale, dst, (void*)c, ctr, \
@@ -1142,11 +1198,23 @@ extern "C" int r4d_gemm_fp8a8_bias_nt_m16(long a, long ascale, long wq, long ws,
// The weight is the gate_up plane [2*nout][K], gate first, as the unfused GEMM reads it.
extern "C" int r4d_gemm_fp8a8_gated_nt_m16_max_m(void) { return 64; }
static int gemm_fp8a8_gated_launch(long a, long ascale, long wq, long ws, long q, long s,
long y, int act, int M, int K, int nout, int a_ld, int sa_ld,
int w_ld, int sw_ld, int q_ld, int s_ld, int y_ld, long stream,
bool chain);
extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws,
long q, long s, long y, int act,
int M, int K, int nout,
int a_ld, int sa_ld, int w_ld, int sw_ld,
int q_ld, int s_ld, int y_ld, long stream) {
return gemm_fp8a8_gated_launch(a, ascale, wq, ws, q, s, y, act, M, K, nout, a_ld, sa_ld,
w_ld, sw_ld, q_ld, s_ld, y_ld, stream, false);
}
/* `chain`: the chained form (r4d_rad_gemm_fp8a8_gated_m16 passes the row's parameter). */
static int gemm_fp8a8_gated_launch(long a, long ascale, long wq, long ws, long q, long s,
long y, int act, int M, int K, int nout, int a_ld, int sa_ld,
int w_ld, int sw_ld, int q_ld, int s_ld, int y_ld, long stream,
bool chain) {
if (!a || !ascale || !wq || !ws || !q || !s) return -1;
if (M <= 0 || K <= 0 || nout <= 0) return -2;
if (M > r4d_gemm_fp8a8_gated_nt_m16_max_m()) return -3;
@@ -1179,14 +1247,18 @@ extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws
const dim3 grid((uint32_t)(nout / 128), 1, 1);
#define R4D_F8G_NT(f, nt_) \
hipLaunchKernelGGL((gemm_fp8a8_kernel<f, nt_, kGmw, kFKNarrow, true>), grid, \
hipLaunchKernelGGL((chain ? r4dchain_gemm_fp8a8<f, nt_, kGmw, kFKNarrow, true> \
: gemm_fp8a8_kernel<f, nt_, kGmw, kFKNarrow, true>), grid, \
dim3(kGmw * kWave), \
0, (hipStream_t)stream, (const uint8_t*)wq, (const void*)ws, \
(const uint8_t*)a, (const void*)ascale, nullptr, nullptr, nullptr, \
(uint32_t)N, (uint32_t)K, \
(uint32_t)M, (uint32_t)w_ld, (uint32_t)a_ld, (uint32_t)sw_ld, \
(uint32_t)sa_ld, 0u, (uint8_t*)q, (float*)s, (uint16_t*)y, \
(uint32_t)q_ld, (uint32_t)s_ld, (uint32_t)y_ld)
(uint32_t)q_ld, (uint32_t)s_ld, (uint32_t)y_ld, \
/* the bias's two, spelled out: a kernel chosen through a pointer takes \
* no default arguments */ \
(const uint16_t*)nullptr, 0u)
#define R4D_F8G(f) \
do { if (nt == 4u) R4D_F8G_NT(f, 4u); \
else if (nt == 3u) R4D_F8G_NT(f, 3u); \
@@ -1257,10 +1329,10 @@ static int gemm_8a8_tiled(long a, long ascale, long wq, long ws, long c, int M,
// The shared operand reader is r4d_fp8_args.h; see libr4d/r4d_args.h.
extern "C" int64_t r4d_rad_gemm_fp8a8_m16_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0),
K = r4d_geti_or(a, "K", 0);
K = r4d_geti_or(a, "K", 0), sn = r4d_geti_or(a, "split_n", 0);
if (M < 1 || N < 1 || K < 1) return 0;
if (M > r4d_gemm_fp8a8_nt_m16_max_m()) return 0;
return (int64_t)r4d_gemm_fp8a8_nt_m16_scratch((int)M, (int)K, (int)N);
return (int64_t)m16_scratch((int)M, (int)K, (int)N, (int)sn);
}
extern "C" int r4d_rad_gemm_fp8a8_m16(const RadArgs* a, RadStream stream) {
@@ -1273,7 +1345,8 @@ extern "C" int r4d_rad_gemm_fp8a8_m16(const RadArgs* a, RadStream stream) {
const int e = gemm_fp8a8_nt_m16_emit(
r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld,
(long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream);
(long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream, false,
(int)r4d_geti_or(a, "split_n", 0), r4d_geti_or(a, "chain", 0) != 0);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
@@ -1364,11 +1437,11 @@ extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) {
const char* act = r4d_gets(a, "act");
if (!act || std::strcmp(act, "silu")) return R4D_NO(RAD_E_UNSUPPORTED);
const int e = r4d_gemm_fp8a8_gated_nt_m16(
const int e = gemm_fp8a8_gated_launch(
r4d_addr(x), r4d_addr(xs), r4d_addr(w), r4d_addr(wsc),
r4d_addr(q), r4d_addr(sc), y ? r4d_addr(y) : 0, 0,
(int)M, (int)K, (int)nout, (int)ap, (int)asp, (int)wp, (int)wsp,
(int)qp, (int)sp, (int)yp, (long)(uintptr_t)s);
(int)qp, (int)sp, (int)yp, (long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
@@ -1387,7 +1460,8 @@ extern "C" int r4d_rad_gemm_i8a8_m16(const RadArgs* a, RadStream stream) {
const int e = gemm_fp8a8_nt_m16_emit(
r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld,
(long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream, true);
(long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream, true,
(int)r4d_geti_or(a, "split_n", 0), r4d_geti_or(a, "chain", 0) != 0);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
+6 -1
View File
@@ -472,7 +472,12 @@ unsigned* mxd_out_ctr(const void* out) {
const size_t n = R4D_MXD_MAX_N / (R4D_MXD_DWN * 16);
unsigned* p = nullptr;
if (hipMalloc((void**)&p, n * sizeof(unsigned)) != hipSuccess) return nullptr;
if (hipMemset(p, 0, n * sizeof(unsigned)) != hipSuccess) { (void)hipFree(p); 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 r4d_moe.hip's router counters do).
if (hipMemset(p, 0, n * sizeof(unsigned)) != hipSuccess || hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return nullptr;
}
blocks.emplace(key, p);
return p;
}
+72 -13
View File
@@ -42,6 +42,7 @@
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_gdn_wmma.h"
#include "r4d_chain.h"
#include <hip/hip_bf16.h>
#include <hip/hip_fp16.h>
#include <cstdint>
@@ -95,12 +96,15 @@ __device__ __forceinline__ v8i mmai(v2i a, v2i b, v8i c) {
// limit, so the host checks WV*SK against the same expression.
#define R4D_W4A8_BOUNDS(NPW) ((NPW) >= 8 ? 256 : ((NPW) >= 4 ? 512 : 1024))
template <int MT, int NPW, bool NT, bool ASYM>
__global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_kernel(
// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); every block runs
// to the end. The two kernels below are the plain form and the chained one (r4dchain*).
template <int MT, int NPW, bool NT, bool ASYM, bool CHAIN>
__device__ __forceinline__ void r4d_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) r4d_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;
@@ -252,11 +256,25 @@ __global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_ker
if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)(v * Ascale[m] * 0.0625f);
}
}
if (CHAIN) r4d_chain_done();
}
#define R4D_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__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_kernel(R4D_W4A8_PARAMS) {
r4d_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__(R4D_W4A8_BOUNDS(NPW)) void r4dchain_gemm_w4a8_nt_m64(R4D_W4A8_PARAMS) {
r4d_gemm_w4a8_nt_m64_body<MT, NPW, NT, ASYM, true>(A, Ascale, Wq, Ws, Asum, C, M, K, N, WV, SK);
}
#undef R4D_W4A8_PARAMS
static void r4d_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 asym, long stream, bool chain = false) {
if (M < 1 || M > R4D_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");
@@ -279,8 +297,11 @@ static void r4d_gemm_w4a8_impl(long a, long ascale, long wq, long ws, long asum,
auto Up = (const float*)asum;
auto Cp = (__hip_bfloat16*)c;
hipStream_t st = (hipStream_t)stream;
#define LAUNCH(MT, NP, TT, AS) hipLaunchKernelGGL((r4d_gemm_w4a8_nt_m64_kernel<MT, NP, TT, AS>), \
grid, block, smem, st, Ap, Sp, Wp, Zp, Up, Cp, M, K, N, WV, SK)
#define LAUNCH(MT, NP, TT, AS) do { if (chain) \
hipLaunchKernelGGL((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((r4d_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; \
@@ -326,6 +347,41 @@ int r4d_gemm_w4a8_nt_m64_group(void) { return R4D_GEMM_W4A8_GROUP; }
// The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_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;
R4dGemmCfg cv;
r4d_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 r4d_rad_gemm_w4a8_m64(const RadArgs* a, RadStream s) {
@@ -339,21 +395,24 @@ extern "C" int r4d_rad_gemm_w4a8_m64(const RadArgs* a, RadStream s) {
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 = r4d_geti_or(a, "chain", 0) != 0 && g.M <= 64;
if (is_asym(a)) {
if (!g.asum) return R4D_NO(RAD_E_INVAL); /* the entry point throws "asum is required" */
R4D_TRY("gemm_w4a8_asym_nt_m64",
r4d_gemm_w4a8_asym_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
r4d_addr(g.bscale), r4d_addr(g.asum), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw,
c.nt, (long)(uintptr_t)s));
r4d_gemm_w4a8_impl(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
r4d_addr(g.bscale), r4d_addr(g.asum), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw,
c.nt, true, (long)(uintptr_t)s, chain));
return RAD_OK;
}
R4D_TRY("gemm_w4a8_nt_m64",
r4d_gemm_w4a8_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
r4d_addr(g.bscale), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt,
(long)(uintptr_t)s));
r4d_gemm_w4a8_impl(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
r4d_addr(g.bscale), 0, r4d_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;
}
+37 -6
View File
@@ -28,6 +28,7 @@
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_gdn_wmma.h"
#include "r4d_chain.h"
#include <hip/hip_bf16.h>
#include <hip/hip_fp16.h>
#include <cstdint>
@@ -68,8 +69,10 @@ __device__ __forceinline__ v8i mmai8(v2i a, v2i b, v8i c) {
// VGPRs. The bound is a hard launch limit, so the host checks WV*SK against the same expression.
#define R4D_W8A8_BOUNDS(MT, NPW) ((MT) * (NPW) >= 8 ? 256 : ((MT) * (NPW) >= 4 ? 512 : 1024))
// The body; the plain kernel and its chained form (r4d_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>
__global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64_kernel(
__device__ __forceinline__ void r4d_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) {
@@ -219,9 +222,34 @@ __global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64
}
}
}
template <int MT, int NPW, bool NT>
__global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_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) {
r4d_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__(R4D_W8A8_BOUNDS(MT, NPW)) void 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) {
r4d_chain_wait();
r4d_gemm_w8a8_nt_m64_body<MT, NPW, NT>(A, Ascale, Wq, Ws, C, M, K, N, WV, SK);
r4d_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 r4d_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 > R4D_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");
@@ -244,7 +272,8 @@ void r4d_gemm_w8a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M,
auto Zp = (const unsigned short*)ws;
auto Cp = (__hip_bfloat16*)c;
hipStream_t st = (hipStream_t)stream;
#define LAUNCH8(MT, NP, TT) hipLaunchKernelGGL((r4d_gemm_w8a8_nt_m64_kernel<MT, NP, TT>), \
#define LAUNCH8(MT, NP, TT) hipLaunchKernelGGL((chain ? r4dchain_gemm_w8a8_nt_m64<MT, NP, TT> \
: r4d_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.
@@ -293,11 +322,13 @@ extern "C" int r4d_rad_gemm_w8a8_m64(const RadArgs* a, RadStream s) {
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 = r4d_geti_or(a, "chain", 0) != 0 && g.M <= 64;
R4D_TRY("gemm_w8a8_nt_m64",
r4d_gemm_w8a8_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
r4d_addr(g.bscale), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt,
(long)(uintptr_t)s));
gemm_w8a8_m64_impl(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
r4d_addr(g.bscale), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt,
(long)(uintptr_t)s, chain));
return RAD_OK;
}
+531 -13
View File
@@ -17,6 +17,7 @@
#include "r4d_q8.h"
#include "rad_philox.h"
#include <algorithm>
#include <cmath>
#include <initializer_list>
#include <cstdlib>
@@ -116,6 +117,62 @@ __global__ __launch_bounds__(kT) void gate_add_kernel(
}
}
// ---------------------------------------------------------------------------- table_add
// y[r, l n + c] = x[r, c] + t[l, c], f32 sum rounded once: one workgroup a (row, table row).
__global__ __launch_bounds__(kT) void table_add_kernel(
const uint16_t* __restrict__ x, const uint16_t* __restrict__ t, uint16_t* __restrict__ y,
int n, int L, int x_ld, int y_ld) {
const int r = blockIdx.x / L, l = blockIdx.x % L;
for (int i = threadIdx.x * 8; i < n; i += kT * 8) {
float a[8], b[8];
ld8(x + (size_t)r * x_ld + i, a);
ld8(t + (size_t)l * n + i, b);
#pragma unroll
for (int j = 0; j < 8; ++j) a[j] += b[j];
st8(y + (size_t)r * y_ld + (size_t)l * n + i, a);
}
}
// ---------------------------------------------------------------------------- mix_rows
// y[r, c] = sum_i w[i] x[r k + i, c], f32 in ascending i, rounded once: one workgroup a row.
__global__ __launch_bounds__(kT) void mix_rows_kernel(
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, uint16_t* __restrict__ y,
int n, int k, int x_ld, int y_ld) {
const int r = blockIdx.x;
for (int i = threadIdx.x * 8; i < n; i += kT * 8) {
float acc[8] = {0, 0, 0, 0, 0, 0, 0, 0}, v[8];
for (int q = 0; q < k; ++q) {
const float wq = bf2f(w[q]);
ld8(x + (size_t)(r * k + q) * x_ld + i, v);
#pragma unroll
for (int j = 0; j < 8; ++j) acc[j] += wq * v[j];
}
st8(y + (size_t)r * y_ld + i, acc);
}
}
// ---------------------------------------------------------------------------- chan_stats
// The statistics are rounded on the host side of each thread (cheap: n reads), every step as
// libref rounds it.
__global__ __launch_bounds__(kT) void chan_stats_kernel(
const uint16_t* __restrict__ x, const uint16_t* __restrict__ mean,
const uint16_t* __restrict__ sv, uint16_t* __restrict__ y, int n, int x_ld, int y_ld,
int var, float eps, int norm) {
const int r = blockIdx.x;
for (int i = threadIdx.x * 8; i < n; i += kT * 8) {
float a[8], mu[8], sd[8];
ld8(x + (size_t)r * x_ld + i, a);
ld8(mean + i, mu);
ld8(sv + i, sd);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const float s = var ? bfr(sqrtf(sd[j] + eps)) : sd[j];
a[j] = norm ? bfr(bfr(a[j] - mu[j]) / s) : bfr(bfr(a[j] * s) + mu[j]);
}
st8(y + (size_t)r * y_ld + i, a);
}
}
// ---------------------------------------------------------------------------- ln_mod_quant_fp8
// gate_add, ln_mod and quant_act_fp8 in one pass over the row: the DiT block's norm in front of
// every quantised linear, with the previous branch's gated residual folded in. Three passes over a
@@ -207,7 +264,8 @@ __global__ __launch_bounds__(kT) void timestep_kernel(
int round, float clamp_min, int y_ld) {
const int m = blockIdx.x;
const float tv = fmaxf(t[m], clamp_min); /* ref pins are floors; 0 -> identity */
const float tt = round ? scale * bfr(bfr(tv * scale) / scale) : scale * tv;
const float tt = round == 3 ? bfr(scale * bfr(tv)) : round == 2 ? scale * bfr(tv)
: round ? scale * bfr(bfr(tv * scale) / scale) : scale * tv;
for (int i = threadIdx.x; i < h; i += kT) {
const float f = expf(coef * (float)i / (float)h);
const float arg = tt * f;
@@ -344,6 +402,118 @@ __global__ __launch_bounds__(kT) void flow_euler_kernel(
st[so] = f32_to_bf16(xn);
}
// ---------------------------------------------------------------------------- kd_input, kd_step
// The k-diffusion sampler over a discrete-time denoiser (libref's ref_kd_input / ref_kd_step): the
// lanes hold x = x0 + sigma eps in f32, a thread one element of one entry, every entry's constants
// computed by each of its threads (a handful of f32 operations beside the element's own).
constexpr int kKdEuler = 0, kKdAncestral = 1, kKdDpm2m = 2;
struct KdConst {
float s, sn, w, cskip, cout, sup, sdown, ratio, em, c1, c2;
bool second;
};
__device__ __forceinline__ KdConst kd_const(float s, float sn, float sp, float w, int sampler,
bool first) {
KdConst k{};
k.s = s;
k.sn = sn;
k.w = w;
const float s2p = s * s + 1.0f;
k.cskip = 1.0f / s2p;
k.cout = s / sqrtf(s2p);
if (sampler == kKdAncestral) {
const float s2 = s * s, sn2 = sn * sn;
const float up2 = sn2 * (s2 - sn2) / s2;
float sup = sqrtf(up2);
if (!(sup < sn)) sup = sn;
const float dn2 = sn2 - sup * sup;
k.sup = sup;
k.sdown = sqrtf(dn2 > 0.0f ? dn2 : 0.0f);
} else if (sampler == kKdDpm2m && sn > 0.0f) {
const float t = -logf(s), tn = -logf(sn);
const float h = tn - t;
k.ratio = sn / s;
k.em = expm1f(-h);
if (!first) {
const float r = (t - (-logf(sp))) / h;
k.c2 = 1.0f / (2.0f * r);
k.c1 = 1.0f + k.c2;
k.second = true;
}
}
return k;
}
__device__ __forceinline__ float kd_den(const KdConst& k, bool v_pred, float x, float o) {
return v_pred ? x * k.cskip - o * k.cout : x - k.s * o;
}
__global__ __launch_bounds__(kT) void kd_input_kernel(
const float* __restrict__ sg, const int* __restrict__ pair, const int* __restrict__ lane,
const int* __restrict__ flags, const uint32_t* __restrict__ seed, const int* __restrict__ cu,
float* __restrict__ st, uint16_t* __restrict__ y, int n, int stride, int st_ld, int y_ld) {
const int e = blockIdx.y;
const int pr = pair[e];
if (pr == -2) return;
const int b0 = cu[e];
const int64_t len = cu[e + 1] - b0;
const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x;
if (i >= len * n) return;
const int64_t k = i / n, c = i % n;
const float s = sg[e];
float* xp = st + ((size_t)lane[e] * stride + k) * st_ld + c;
if (flags[e] & 1) *xp = rad_philox_normal(seed_of(seed, e), (uint64_t)i) * sqrtf(1.0f + s * s);
const uint16_t v = f32_to_bf16(*xp * (1.0f / sqrtf(s * s + 1.0f)));
y[(size_t)(b0 + k) * y_ld + c] = v;
if (pr >= 0) y[(size_t)(cu[pr] + k) * y_ld + c] = v;
}
__global__ __launch_bounds__(kT) void kd_step_kernel(
const uint16_t* __restrict__ out, const float* __restrict__ sg, const float* __restrict__ sgn,
const float* __restrict__ sgp, const float* __restrict__ cfg, const int* __restrict__ pair,
const int* __restrict__ lane, const int* __restrict__ flags, const uint32_t* __restrict__ seed,
const int* __restrict__ sampler, const int* __restrict__ step, const int* __restrict__ cu,
float* __restrict__ st, float* __restrict__ hist, float* __restrict__ pv, int n, int stride,
int o_ld, int st_ld, int h_ld, int pv_ld, int v_pred) {
const int e = blockIdx.y;
const int pr = pair[e];
if (pr == -2) return;
const int b0 = cu[e];
const int64_t len = cu[e + 1] - b0;
const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x;
if (i >= len * n) return;
const int64_t k = i / n, c = i % n;
const int f = flags[e], sm = sampler[e];
const KdConst K = kd_const(sg[e], sgn[e], sgp[e], cfg[e], sm, (f & 1) != 0);
const size_t row = (size_t)lane[e] * stride + k;
const float x = st[row * st_ld + c];
float D = kd_den(K, v_pred != 0, x, bf2f(out[(size_t)(b0 + k) * o_ld + c]));
if (pr >= 0) {
const float Du = kd_den(K, v_pred != 0, x, bf2f(out[(size_t)(cu[pr] + k) * o_ld + c]));
D = Du + K.w * (D - Du);
}
if ((f & 4) && pv) pv[row * pv_ld + c] = D;
float xn;
if (sm == kKdEuler) {
xn = x + (K.sn - K.s) * ((x - D) / K.s);
} else if (sm == kKdAncestral) {
xn = x + ((x - D) / K.s) * (K.sdown - K.s);
if (K.sn > 0.0f)
xn += rad_philox_normal_s(seed_of(seed, e), (uint64_t)(uint32_t)(1 + step[e]),
(uint64_t)i) * K.sup;
} else if (sm != kKdDpm2m) {
return;
} else if (K.sn == 0.0f) {
xn = D;
} else {
const float Dd = K.second ? K.c1 * D - K.c2 * hist[row * h_ld + c] : D;
xn = K.ratio * x - K.em * Dd;
}
st[row * st_ld + c] = xn;
hist[row * h_ld + c] = D;
}
// ---------------------------------------------------------------------------- per-channel ops
// The two lists ride in the kernel arguments, whose segment the backend caps at 768 bytes; two
// lists of 64 channels (a latent's) take 512.
@@ -360,6 +530,25 @@ __device__ __forceinline__ float ca_rd(const float*, float v) { return v; }
__device__ __forceinline__ void ca_st(uint16_t* p, int64_t i, float v) { p[i] = f32_to_bf16(v); }
__device__ __forceinline__ void ca_st(float* p, int64_t i, float v) { p[i] = v; }
// The element-wise form, any of x, the statistics (TW) and y in bf16 or f32: a latent kept in
// f32, or rows whose pitch the 8-wide kernel cannot take (an encoder's mean channels beside its
// log-variance). Each step rounds to y's dtype as the reference stores it; the explicit _rn
// intrinsics keep the compiler from contracting x s + mean into one fused multiply-add.
template <typename TX, typename TW, typename TY>
__global__ __launch_bounds__(kT) void chan_stats_any_kernel(
const TX* __restrict__ x, const TW* __restrict__ mean, const TW* __restrict__ sv,
TY* __restrict__ y, int n, int x_ld, int y_ld, int var, float eps, int norm) {
const int r = blockIdx.x;
for (int i = threadIdx.x; i < n; i += kT) {
const float mu = ca_rd(y, ca_ld(mean, (size_t)i)), v = ca_ld(sv, (size_t)i);
const float sd = ca_rd(y, var ? __fsqrt_rn(__fadd_rn(v, eps)) : v);
const float a = ca_ld(x, (size_t)r * x_ld + i);
ca_st(y, (int64_t)r * y_ld + i,
norm ? ca_rd(y, __fdiv_rn(ca_rd(y, __fsub_rn(a, mu)), sd))
: ca_rd(y, __fadd_rn(ca_rd(y, __fmul_rn(a, sd)), mu)));
}
}
template <typename T>
__global__ __launch_bounds__(kT) void chan_affine_kernel(
const T* __restrict__ x, T* __restrict__ y, int64_t total, int n, int x_ld, int inv, int rnd,
@@ -449,6 +638,20 @@ __global__ __launch_bounds__(kT) void to_rgba8_kernel(const uint16_t* __restrict
y[i] = (uint8_t)rintf(u * 255.0f);
}
// ---------------------------------------------------------------------------- gelu_quick
// CLIP's quick_gelu, libref's three roundings: a workgroup a row, a thread an element.
template <typename T>
__global__ __launch_bounds__(kT) void gelu_quick_kernel(const T* __restrict__ x, T* __restrict__ y,
int n, int x_ld, int y_ld) {
const int r = blockIdx.x;
for (int c = threadIdx.x; c < n; c += kT) {
const float v = ca_ld(x, (size_t)r * x_ld + c);
const float a = ca_rd(y, 1.702f * v);
const float s = ca_rd(y, 1.0f / (1.0f + expf(-a)));
ca_st(y, (int64_t)r * y_ld + c, v * s);
}
}
__global__ __launch_bounds__(kT) void gelu_tanh_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int n, int x_ld, int y_ld) {
const int r = blockIdx.x;
@@ -488,7 +691,7 @@ 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 x_ld, int y_ld, int Mpx, int K) {
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;
@@ -533,7 +736,7 @@ __global__ __launch_bounds__(256) void conv_igemm_kernel(
auto loadA = [&](int i) -> r4d_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 - pt;
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;
@@ -621,7 +824,7 @@ __global__ __launch_bounds__(256) void conv_igemm_kernel(
__global__ __launch_bounds__(kT) 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 x_ld, int y_ld, int64_t total) {
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 * kT + threadIdx.x;
if (t >= total) return;
const int co = (int)(t % cout);
@@ -633,7 +836,7 @@ __global__ __launch_bounds__(kT) void conv_direct_kernel(
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 - pt;
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;
@@ -643,6 +846,91 @@ __global__ __launch_bounds__(kT) void conv_direct_kernel(
y[(size_t)oy * y_ld + (size_t)ox * cout + co] = f32_to_bf16(acc + bf2f(bias[co]));
}
// ---------------------------------------------------------------------------- im2col_nhwc
// conv2d_nhwc's receptive fields as rows: y[oy Wo + ox][(ci k + i) k + j] = the input at tap
// (i, j) of output pixel (oy, ox), channel ci. A block is a run of IC_TW output pixels of one
// output row and IC_CC input channels: it stages the k input rows those pixels read (through the
// upsample and the zero padding) in LDS channel-major, [cl][i][xw], 16 bytes of NHWC channels a
// load, then writes each pixel's cc k k columns -- one contiguous run of its y row -- VW elements a
// thread, so both the reads and the writes are coalesced. KS is k at compile time (3 and 1), 0 for
// any other. Values are copied bit for bit.
constexpr int IC_TW = 32;
constexpr int IC_CC = 64;
template <int KS, int VW>
__global__ __launch_bounds__(kT) void im2col_nhwc_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo,
int k_rt, int stride, int up, int pt, int pl, int64_t x_ld, int64_t y_ld, int vec) {
extern __shared__ uint16_t ic_lds[];
const int k = KS ? KS : k_rt, kk = k * k;
const int ox0 = blockIdx.x * IC_TW, oy = blockIdx.y, c0 = blockIdx.z * IC_CC;
const int cc = min(IC_CC, cin - c0), nq = min(IC_TW, Wo - ox0);
const int W = (IC_TW - 1) * stride + k;
const int iy0 = oy * stride - pt, ix0 = ox0 * stride - pl;
const int sites = k * W;
const int tid = threadIdx.x;
if (vec) {
const int groups = cc >> 3;
for (int u = tid; u < sites * groups; u += kT) {
const int g = u % groups, site = u / groups;
const int i = site / W, xw = site - i * W;
const int iy = iy0 + i, ix = ix0 + xw;
uint4 v = make_uint4(0, 0, 0, 0);
if (iy >= 0 && iy < Hv && ix >= 0 && ix < Wv)
v = *(const uint4*)(x + (size_t)(iy / up) * x_ld + (size_t)(ix / up) * cin + c0 +
g * 8);
const uint32_t w4[4] = { v.x, v.y, v.z, v.w };
#pragma unroll
for (int e = 0; e < 8; ++e)
ic_lds[((g * 8 + e) * k + i) * W + xw] =
(uint16_t)(e & 1 ? w4[e >> 1] >> 16 : w4[e >> 1] & 0xffffu);
}
} else {
for (int u = tid; u < sites * cc; u += kT) {
const int cl = u % cc, site = u / cc;
const int i = site / W, xw = site - i * W;
const int iy = iy0 + i, ix = ix0 + xw;
uint16_t v = 0;
if (iy >= 0 && iy < Hv && ix >= 0 && ix < Wv)
v = x[(size_t)(iy / up) * x_ld + (size_t)(ix / up) * cin + c0 + cl];
ic_lds[(cl * k + i) * W + xw] = v;
}
}
__syncthreads();
/* The block's pixels' runs as one list of VW-element pieces, so every thread stores whatever
* the run length; a thread's (pixel, piece) advances by the block each pass, without a
* division. */
const int span = cc * kk, pieces = span / VW;
uint16_t* yb = y + (size_t)((int64_t)oy * Wo + ox0) * y_ld + (size_t)c0 * kk;
int q = tid / pieces, pc = tid - q * pieces;
for (; q < nq;) {
const int t = pc * VW;
uint16_t* yr = yb + (size_t)q * y_ld;
const int xq = q * stride;
uint16_t v[VW];
#pragma unroll
for (int e = 0; e < VW; ++e) {
const int te = t + e;
const int cl = te / kk, r = te - cl * kk, i = r / k, j = r - i * k;
v[e] = ic_lds[(cl * k + i) * W + xq + j];
}
if constexpr (VW == 8)
*(uint4*)(yr + t) = make_uint4((uint32_t)v[0] | ((uint32_t)v[1] << 16),
(uint32_t)v[2] | ((uint32_t)v[3] << 16),
(uint32_t)v[4] | ((uint32_t)v[5] << 16),
(uint32_t)v[6] | ((uint32_t)v[7] << 16));
else if constexpr (VW == 4)
*(uint2*)(yr + t) = make_uint2((uint32_t)v[0] | ((uint32_t)v[1] << 16),
(uint32_t)v[2] | ((uint32_t)v[3] << 16));
else if constexpr (VW == 2)
*(uint32_t*)(yr + t) = (uint32_t)v[0] | ((uint32_t)v[1] << 16);
else
yr[t] = v[0];
pc += kT;
while (pc >= pieces) { pc -= pieces; ++q; }
}
}
inline int st_of(hipError_t e) { return e == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); }
inline unsigned blocks_for(int64_t n) { return (unsigned)((n + kT - 1) / kT); }
@@ -658,9 +946,10 @@ inline bool rows8(const RadTensor* t, long long n, long long* rows, long long* l
}
// A dense [H, W * c] image operand.
inline bool image_of(const RadTensor* t, long long c, long long* H, long long* W) {
inline bool 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 ||
t->stride[0] != t->shape[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;
@@ -773,6 +1062,87 @@ extern "C" int r4d_rad_gate_add(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_table_add(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *t = r4d_opt(a, 1), *y = r4d_opt(a, 2);
if (!x || !t || !y) return R4D_NO(RAD_E_INVAL);
if (!is_bf16(x) || !is_bf16(t) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0), L = r4d_geti_or(a, "L", 0);
long long rx = 0, xl = 0, ry = 0, yl = 0;
if (L <= 0 || !rows8(x, n, &rx, &xl) || !rows8(y, n * L, &ry, &yl) || !r4d_contig(t) ||
((uintptr_t)t->data & 15))
return R4D_NO(RAD_E_STRIDE);
if (ry <= 0 || rx < ry || r4d_numel(t) < L * n) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(table_add_kernel, dim3((unsigned)(ry * L)), dim3(kT), 0, (hipStream_t)s,
(const uint16_t*)x->data, (const uint16_t*)t->data, (uint16_t*)y->data,
(int)n, (int)L, (int)xl, (int)yl);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_mix_rows(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *w = r4d_opt(a, 1), *y = r4d_opt(a, 2);
if (!x || !w || !y) return R4D_NO(RAD_E_INVAL);
if (!is_bf16(x) || !is_bf16(w) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0), k = r4d_geti_or(a, "k", 0);
long long rx = 0, xl = 0, ry = 0, yl = 0;
if (k <= 0 || !rows8(x, n, &rx, &xl) || !rows8(y, n, &ry, &yl) || !r4d_contig(w))
return R4D_NO(RAD_E_STRIDE);
if (ry <= 0 || rx < ry * k || r4d_numel(w) < k) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(mix_rows_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s,
(const uint16_t*)x->data, (const uint16_t*)w->data, (uint16_t*)y->data,
(int)n, (int)k, (int)xl, (int)yl);
return st_of(hipGetLastError());
}
template <typename TX, typename TW, typename TY>
static int chan_stats_any(const RadTensor* x, const RadTensor* mn, const RadTensor* sv,
const RadTensor* y, long long rows, long long n, long long xl,
long long yl, int var, float eps, int norm, RadStream s) {
hipLaunchKernelGGL((chan_stats_any_kernel<TX, TW, TY>), dim3((unsigned)rows), dim3(kT), 0,
(hipStream_t)s, (const TX*)x->data, (const TW*)mn->data,
(const TW*)sv->data, (TY*)y->data, (int)n, (int)xl, (int)yl, var, eps,
norm);
return st_of(hipGetLastError());
}
/* Both rows: bf16 (chan_stats_bf16, eight channels a thread when every row and statistic is
* 16-byte aligned, element-wise otherwise) and f32 (chan_stats_f32: x and y f32 over bf16 or f32
* statistics, a latent kept in f32 before a bf16 network reads it). */
extern "C" int r4d_rad_chan_stats(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *mn = r4d_opt(a, 1), *sv = r4d_opt(a, 2), *y = r4d_opt(a, 3);
if (!x || !mn || !sv || !y) return R4D_NO(RAD_E_INVAL);
const long long n = r4d_geti_or(a, "n", 0);
const char* mode = r4d_gets(a, "mode");
const int norm = mode && !std::strcmp(mode, "norm");
if (!mode || (!norm && std::strcmp(mode, "denorm"))) return R4D_NO(RAD_E_INVAL);
auto bf_f32 = [](const RadTensor* t) { return is_bf16(t) || t->dtype == RAD_F32; };
if (!bf_f32(x) || !bf_f32(y) || !bf_f32(mn) || mn->dtype != sv->dtype || x->dtype != y->dtype)
return R4D_NO(RAD_E_DTYPE);
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
const int var = (int)r4d_geti_or(a, "var", 0);
const float eps = (float)r4d_getf(a, "eps", 0.0);
long long rx = 0, xl = 0, ry = 0, yl = 0;
if (is_bf16(x) && is_bf16(mn) && rows8(x, n, &rx, &xl) && rows8(y, n, &ry, &yl) &&
r4d_contig(mn) && r4d_contig(sv) && !((uintptr_t)mn->data & 15) &&
!((uintptr_t)sv->data & 15)) {
if (ry <= 0 || rx < ry || r4d_numel(mn) < n || r4d_numel(sv) < n)
return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(chan_stats_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s,
(const uint16_t*)x->data, (const uint16_t*)mn->data,
(const uint16_t*)sv->data, (uint16_t*)y->data, (int)n, (int)xl, (int)yl,
var, eps, norm);
return st_of(hipGetLastError());
}
xl = r4d_rows_pitch(x, n, &rx);
yl = r4d_rows_pitch(y, n, &ry);
if (xl < 0 || yl < 0 || !r4d_contig(mn) || !r4d_contig(sv)) return R4D_NO(RAD_E_STRIDE);
if (ry <= 0 || rx < ry || r4d_numel(mn) < n || r4d_numel(sv) < n) return R4D_NO(RAD_E_SHAPE);
const bool f = x->dtype == RAD_F32, wf = mn->dtype == RAD_F32;
#define R4D_CS(TX, TW) chan_stats_any<TX, TW, TX>(x, mn, sv, y, ry, n, xl, yl, var, eps, norm, s)
if (f) return wf ? R4D_CS(float, float) : R4D_CS(float, uint16_t);
return wf ? R4D_CS(uint16_t, float) : R4D_CS(uint16_t, uint16_t);
#undef R4D_CS
}
/* Both rows: a bf16 embedding (timestep_embed_bf16) or an f32 one (timestep_embed_f32, a timestep
* MLP kept in f32). With `curve` = G > 0 and a `table` [G, n] f32 operand the sinusoid is replaced
* by a lerp over that precomputed adaln curve. */
@@ -955,6 +1325,72 @@ extern "C" int r4d_rad_flow_euler(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_kd_input(const RadArgs* a, RadStream s) {
const RadTensor *sg = r4d_opt(a, 0), *pair = r4d_opt(a, 1), *lane = r4d_opt(a, 2);
const RadTensor *fl = r4d_opt(a, 3), *seed = r4d_opt(a, 4), *cu = r4d_opt(a, 5);
const RadTensor *st = r4d_opt(a, 6), *y = r4d_opt(a, 7);
if (!sg || !pair || !lane || !fl || !seed || !cu || !st || !y) return R4D_NO(RAD_E_INVAL);
if (st->dtype != RAD_F32 || !is_bf16(y) || sg->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0);
long long rs = 0, ry = 0;
const long long sl = r4d_rows_pitch(st, n, &rs), yl = r4d_rows_pitch(y, n, &ry);
if (sl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE);
const long long n_seq = r4d_numel(cu) - 1;
if (n <= 0 || stride <= 0 || n_seq <= 0 || rs < stride) return R4D_NO(RAD_E_SHAPE);
/* One scalar of each kind an entry, two seed words. A lane's rows, a pair's entry and a
* repaint flag (device data) are not checked. */
for (const RadTensor* e : { sg, pair, lane, fl })
if (r4d_numel(e) < n_seq) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(seed) < 2 * n_seq) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(kd_input_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), 0,
(hipStream_t)s, (const float*)sg->data, (const int*)pair->data,
(const int*)lane->data, (const int*)fl->data, (const uint32_t*)seed->data,
(const int*)cu->data, (float*)st->data, (uint16_t*)y->data, (int)n,
(int)stride, (int)sl, (int)yl);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_kd_step(const RadArgs* a, RadStream s) {
const RadTensor *o = r4d_opt(a, 0), *sg = r4d_opt(a, 1), *sgn = r4d_opt(a, 2);
const RadTensor *sgp = r4d_opt(a, 3), *cfg = r4d_opt(a, 4), *pair = r4d_opt(a, 5);
const RadTensor *lane = r4d_opt(a, 6), *fl = r4d_opt(a, 7), *seed = r4d_opt(a, 8);
const RadTensor *smp = r4d_opt(a, 9), *stp = r4d_opt(a, 10), *cu = r4d_opt(a, 11);
const RadTensor *st = r4d_opt(a, 12), *hs = r4d_opt(a, 13), *pv = r4d_opt(a, 14);
if (!o || !sg || !sgn || !sgp || !cfg || !pair || !lane || !fl || !seed || !smp || !stp || !cu ||
!st || !hs)
return R4D_NO(RAD_E_INVAL);
if (!is_bf16(o) || st->dtype != RAD_F32 || hs->dtype != RAD_F32 ||
(pv && pv->dtype != RAD_F32))
return R4D_NO(RAD_E_DTYPE);
const char* pred = r4d_gets(a, "pred");
const int v_pred = pred && !std::strcmp(pred, "v");
if (!v_pred && (!pred || std::strcmp(pred, "eps"))) return R4D_NO(RAD_E_INVAL);
const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0);
long long ro = 0, rs = 0, rh = 0, rp = 0;
const long long ol = r4d_rows_pitch(o, n, &ro), sl = r4d_rows_pitch(st, n, &rs);
const long long hl = r4d_rows_pitch(hs, n, &rh), pl = pv ? r4d_rows_pitch(pv, n, &rp) : 0;
if (ol < 0 || sl < 0 || hl < 0 || pl < 0) return R4D_NO(RAD_E_STRIDE);
const long long n_seq = r4d_numel(cu) - 1;
if (n <= 0 || stride <= 0 || n_seq <= 0 || rs < stride || rh < rs || (pv && rp < rs))
return R4D_NO(RAD_E_SHAPE);
/* One scalar of each kind an entry, two seed words. A lane's rows, a pair's entry, the
* sampler ids and the flags (device data) are not checked here: the kernel leaves the lane of
* an entry whose sampler it does not know, and writes no preview without the operand, where
* libref refuses both. */
for (const RadTensor* e : { sg, sgn, sgp, cfg, pair, lane, fl, smp, stp })
if (r4d_numel(e) < n_seq) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(seed) < 2 * n_seq) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(kd_step_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), 0,
(hipStream_t)s, (const uint16_t*)o->data, (const float*)sg->data,
(const float*)sgn->data, (const float*)sgp->data, (const float*)cfg->data,
(const int*)pair->data, (const int*)lane->data, (const int*)fl->data,
(const uint32_t*)seed->data, (const int*)smp->data, (const int*)stp->data,
(const int*)cu->data, (float*)st->data, (float*)hs->data,
pv ? (float*)pv->data : nullptr, (int)n, (int)stride, (int)ol, (int)sl,
(int)hl, (int)pl, v_pred);
return st_of(hipGetLastError());
}
/* Both rows: x and y bf16 (chan_affine_bf16) or both f32 (chan_affine_f32). `round` 0 keeps the
* lists and the arithmetic in f32. */
extern "C" int r4d_rad_chan_affine(const RadArgs* a, RadStream s) {
@@ -997,13 +1433,19 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
const long long up = r4d_geti_or(a, "up", 1);
const char* pad = r4d_gets(a, "pad");
const bool down = pad && !std::strcmp(pad, "down");
if (pad && !down && std::strcmp(pad, "same")) return R4D_NO(RAD_E_INVAL);
const bool causal = pad && !std::strcmp(pad, "causal");
if (pad && !down && !causal && std::strcmp(pad, "same")) return R4D_NO(RAD_E_INVAL);
if (cin <= 0 || cout <= 0 || k <= 0 || stride <= 0 || up <= 0) return R4D_NO(RAD_E_SHAPE);
long long Hin = 0, Win = 0, Ho = 0, Wo = 0;
if (!image_of(x, cin, &Hin, &Win) || !image_of(y, cout, &Ho, &Wo)) return R4D_NO(RAD_E_SHAPE);
/* y may be a column slice of wider rows (a channel written into its own columns): both kernels
* store at its row pitch. */
if (!image_of(x, cin, &Hin, &Win) || !image_of(y, cout, &Ho, &Wo, true))
return R4D_NO(RAD_E_SHAPE);
const long long Hv = Hin * up, Wv = Win * up;
const long long pt = down ? 0 : k / 2, pb = down ? 1 : k / 2;
if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo)
/* 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 R4D_NO(RAD_E_SHAPE);
const long long K = k * k * cin;
if (r4d_numel(w) < cout * K || r4d_numel(b) < cout) return R4D_NO(RAD_E_SHAPE);
@@ -1017,7 +1459,7 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
(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)x->stride[0], (int)y->stride[0], (int64_t)total);
(int)pl, (int)x->stride[0], (int)y->stride[0], (int64_t)total);
return st_of(hipGetLastError());
}
// 128 pixels a block, and the widest channel tile (192, 128, then 64) that leaves under a third
@@ -1035,7 +1477,7 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
(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)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 R4D_CONV_K(TP, TC) \
@@ -1051,6 +1493,61 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_im2col_nhwc(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
if (!is_bf16(x) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE);
const long long cin = r4d_geti_or(a, "cin", 0), k = r4d_geti_or(a, "k", 0);
const long long stride = r4d_geti_or(a, "stride", 1), up = r4d_geti_or(a, "up", 1);
const char* pad = r4d_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 R4D_NO(RAD_E_INVAL);
if (cin <= 0 || k <= 0 || k > 7 || stride <= 0 || stride > 2 || up <= 0 || up > 2)
return R4D_NO(RAD_E_SHAPE);
long long Hin = 0, Win = 0;
if (!image_of(x, cin, &Hin, &Win, true)) return R4D_NO(RAD_E_SHAPE);
const long long Hv = Hin * up, Wv = Win * up;
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;
const long long Ho = (Hv + pt + pb - k) / stride + 1, Wo = (Wv + pl + pr - k) / stride + 1;
const long long KK = cin * k * k;
long long rows = 0;
const long long y_ld = r4d_rows_pitch(y, KK, &rows);
if (y_ld < 0 || y->stride[y->rank - 1] != 1) return R4D_NO(RAD_E_STRIDE);
if (Ho <= 0 || Wo <= 0 || rows != Ho * Wo || Ho > 65535 || Ho * Wo * y_ld >= (1ll << 40))
return R4D_NO(RAD_E_SHAPE);
/* 16-byte channel loads where every chunk's channels start on one; the widest store every
* chunk's run, the row pitch and the base allow. */
const long long tail = cin % IC_CC ? cin % IC_CC : IC_CC;
const int vec = cin % 8 == 0 && x->stride[0] % 8 == 0 && !((uintptr_t)x->data & 15);
auto fits = [&](long long vw) {
return (std::min((long long)IC_CC, cin) * k * k) % vw == 0 && (tail * k * k) % vw == 0 &&
y_ld % vw == 0 && !((uintptr_t)y->data & (2 * vw - 1));
};
const int VW = fits(8) ? 8 : fits(4) ? 4 : fits(2) ? 2 : 1;
const long long W = (IC_TW - 1) * stride + k;
const size_t lds = (size_t)(std::min((long long)IC_CC, cin) * k * W) * sizeof(uint16_t);
const dim3 grid((unsigned)((Wo + IC_TW - 1) / IC_TW), (unsigned)Ho,
(unsigned)((cin + IC_CC - 1) / IC_CC));
#define R4D_IC(KS, V) \
hipLaunchKernelGGL((im2col_nhwc_kernel<KS, V>), grid, dim3(kT), lds, (hipStream_t)s, \
(const uint16_t*)x->data, (uint16_t*)y->data, (int)Hv, (int)Wv, (int)cin, \
(int)Wo, (int)k, (int)stride, (int)up, (int)pt, (int)pl, \
(int64_t)x->stride[0], (int64_t)y_ld, vec)
#define R4D_IC_K(V) \
if (k == 3) R4D_IC(3, V); \
else if (k == 1) R4D_IC(1, V); \
else R4D_IC(0, V)
if (VW == 8) { R4D_IC_K(8); }
else if (VW == 4) { R4D_IC_K(4); }
else if (VW == 2) { R4D_IC_K(2); }
else { R4D_IC_K(1); }
#undef R4D_IC_K
#undef R4D_IC
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_l2norm_chan(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *g = r4d_opt(a, 1), *y = r4d_opt(a, 2);
if (!x || !g || !y) return R4D_NO(RAD_E_INVAL);
@@ -1122,6 +1619,27 @@ extern "C" int r4d_rad_to_rgba8(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_gelu_quick(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
const bool f32 = x->dtype == RAD_F32;
if ((!is_bf16(x) && !f32) || y->dtype != x->dtype) return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0);
long long rx = 0, ry = 0;
const long long xl = r4d_rows_pitch(x, n, &rx), yl = r4d_rows_pitch(y, n, &ry);
if (n <= 0 || xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE);
if (ry <= 0 || rx < ry) return R4D_NO(RAD_E_SHAPE);
if (f32)
hipLaunchKernelGGL(gelu_quick_kernel<float>, dim3((unsigned)ry), dim3(kT), 0,
(hipStream_t)s, (const float*)x->data, (float*)y->data, (int)n, (int)xl,
(int)yl);
else
hipLaunchKernelGGL(gelu_quick_kernel<uint16_t>, dim3((unsigned)ry), dim3(kT), 0,
(hipStream_t)s, (const uint16_t*)x->data, (uint16_t*)y->data, (int)n,
(int)xl, (int)yl);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_gelu_tanh(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
+421
View File
@@ -0,0 +1,421 @@
#include <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_emit.h"
#include "r4d_moe_sort.h"
#include <climits>
#include <cmath>
namespace {
// One wave computes R rows by C columns, so each loaded weight serves R rows and each input
// C columns. Every output has the same arithmetic: lane l accumulates k = l, l+32, ... in
// ascending order with fmaf, then the xor butterfly over 16, 8, 4, 2, 1. A lane loads U steps of
// k before their FMAs: at a decode pass's few rows a wave streams its weight row with no other
// work to hide the load behind, and one step in flight left the router at 150 GB/s. Tail rows and
// columns read a clamped valid address and are never stored.
template <int R, int C, int U>
__global__ void __launch_bounds__(128)
gemm_nt_f32_tile_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp, long yp,
int m, int n, int k) {
const int lane = threadIdx.x & 31, c0 = (blockIdx.x * 4 + (threadIdx.x >> 5)) * C,
r0 = blockIdx.y * R;
if (c0 >= n) return;
const uint16_t* xr[R];
const float* wc[C];
#pragma unroll
for (int q = 0; q < R; ++q) xr[q] = x + (long)(r0 + q < m ? r0 + q : m - 1) * xp;
#pragma unroll
for (int c = 0; c < C; ++c) wc[c] = w + (long)(c0 + c < n ? c0 + c : n - 1) * wp;
float sum[R][C];
#pragma unroll
for (int q = 0; q < R; ++q)
#pragma unroll
for (int c = 0; c < C; ++c) sum[q][c] = 0;
int j = lane;
for (; j + 32 * (U - 1) < k; j += 32 * U) {
float weight[U][C];
uint16_t in[U][R];
#pragma unroll
for (int u = 0; u < U; ++u)
#pragma unroll
for (int c = 0; c < C; ++c) weight[u][c] = wc[c][j + 32 * u];
#pragma unroll
for (int u = 0; u < U; ++u)
#pragma unroll
for (int q = 0; q < R; ++q) in[u][q] = xr[q][j + 32 * u];
#pragma unroll
for (int u = 0; u < U; ++u)
#pragma unroll
for (int q = 0; q < R; ++q) {
const float v = bf16_to_f32(in[u][q]);
#pragma unroll
for (int c = 0; c < C; ++c) sum[q][c] = fmaf(v, weight[u][c], sum[q][c]);
}
}
for (; j < k; j += 32) {
#pragma unroll
for (int q = 0; q < R; ++q) {
const float v = bf16_to_f32(xr[q][j]);
#pragma unroll
for (int c = 0; c < C; ++c) sum[q][c] = fmaf(v, wc[c][j], sum[q][c]);
}
}
#pragma unroll
for (int q = 0; q < R; ++q)
#pragma unroll
for (int c = 0; c < C; ++c) {
#pragma unroll
for (int mask = 16; mask; mask >>= 1) sum[q][c] += __shfl_xor(sum[q][c], mask, 32);
}
if (lane) return;
#pragma unroll
for (int q = 0; q < R; ++q)
if (r0 + q < m)
#pragma unroll
for (int c = 0; c < C; ++c)
if (c0 + c < n) y[(long)(r0 + q) * yp + c0 + c] = sum[q][c];
}
template <int R, int C, int U = 1>
int gemm_f32_tile(RadStream stream, const RadTensor& x, const RadTensor& w, const RadTensor& y,
long n, long k) {
const long m = x.shape[0];
return R4D_EMIT(stream, (gemm_nt_f32_tile_kernel<R, C, U>),
dim3((unsigned)((n + 4 * C - 1) / (4 * C)), (unsigned)((m + R - 1) / R)),
dim3(128), 0, (const uint16_t*)x.data, (const float*)w.data, (float*)y.data,
x.stride[0], w.stride[0], y.stride[0], (int)m, (int)n, (int)k);
}
int gemm_f32_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 3) return RAD_E_INVAL;
const auto &x = a->t[0], &w = a->t[1], &y = a->t[2];
const long n = r4d_geti_or(a, "N", 0), k = r4d_geti_or(a, "K", 0);
if (x.dtype != RAD_BF16 || w.dtype != RAD_F32 || y.dtype != RAD_F32) return RAD_E_DTYPE;
if (!x.data || !w.data || !y.data) return RAD_E_INVAL;
if (n < 1 || n > 512 || k < 1 || k > 16384 || x.rank != 2 || w.rank != 2 || y.rank != 2 ||
x.shape[0] < 1 || x.shape[0] > 65535 || x.shape[1] != k || w.shape[0] != n ||
w.shape[1] != k || y.shape[0] != x.shape[0] || y.shape[1] != n || x.stride[1] != 1 ||
w.stride[1] != 1 || y.stride[1] != 1 || x.stride[0] < k || w.stride[0] < k ||
y.stride[0] < n)
return RAD_E_SHAPE;
/* The tile form, rows x columns per wave and steps of k in flight, by M; all forms are
* byte-identical, so the choice is speed only. Measured on gfx1201 (r4d_selftest --perff32,
* cold) at N 4/32/36/288, K 4096: 16x4 gains 3-5 % at N 288/32 above 64 rows but loses 16 % at
* N 36; 8x4 holds at every width. Below 64 rows the steps in flight decide: at N 288 one step
* a lane took 28.1 / 36.0 / 36.3 / 41.9 / 45.4 / 47.9 us at 1 / 4 / 8 / 16 / 24 / 48 rows,
* 2x2 with 16 steps 14.4 / 14.5 / 15.0 / 19.1 us to 16 rows and 8x1 with 8 steps 21.6 / 35.5
* us at 24 / 48; at N 32 2x2 with 16 steps 9.8 to 10.2 us at every count below 64, where one
* step took 27.3 to 36.4.
* A projection of a few columns has too few waves for wide tiles at any M. */
const long rows = x.shape[0];
if (n <= 8) return gemm_f32_tile<4, 1>(stream, x, w, y, n, k);
if (rows <= 16 || (rows < 64 && n < 128)) return gemm_f32_tile<2, 2, 16>(stream, x, w, y, n, k);
if (rows < 64) return gemm_f32_tile<8, 1, 8>(stream, x, w, y, n, k);
return gemm_f32_tile<8, 4>(stream, x, w, y, n, k);
}
// router_sigmoid_topk in one wave per row: p = sigmoid(logit), the top_k largest ranks p + bias
// in descending order, equal ranks to the lower expert, as a serial scan with a strict `>` takes
// them. Lane l holds experts l, l+32, ... as 64-bit keys: the rank's order-preserving bits (-0
// folded to +0) over ~e, so equal ranks order to the lower expert. Round j takes the largest key
// below round j-1's winner and parks it on lane j (top_k <= 32). `total` sums the selected p in
// round order, mult = norm ? factor / (total + 1e-20) : factor, and a weight is p * mult. A NaN
// rank is never selected.
// OWN is a template bound because the keys are registers; a lane-derived trip count would index
// them divergently, which gfx12 lowers to a v_movrels loop.
__device__ __forceinline__ unsigned long long router_rank_key(float rank, int e) {
uint32_t u = __float_as_uint(rank);
if (u == 0x80000000u) u = 0;
const uint32_t k = (u & 0x80000000u) ? ~u : (u | 0x80000000u);
return rank == rank ? ((unsigned long long)k << 32) | (uint32_t)~e : 0ull;
}
__device__ __forceinline__ unsigned long long router_wave_max(unsigned long long b) {
unsigned long long o;
o = r4d_xor_lane_u64<16>(b);
b = b > o ? b : o;
o = r4d_xor_lane_u64<8>(b);
b = b > o ? b : o;
o = r4d_xor_lane_u64<4>(b);
b = b > o ? b : o;
o = r4d_xor_lane_u64<2>(b);
b = b > o ? b : o;
o = r4d_xor_lane_u64<1>(b);
b = b > o ? b : o;
return b;
}
// One row in one wave, from any grid: the standalone select and the fused one below run this. A
// lane below `k` returns its slot's expert as written to `ids`.
template <int OWN>
__device__ __forceinline__ int router_sigmoid_row(const float* logits, const float* bias, int* ids,
float* weights, long lp, long bp, long ip,
long wp, int r, int ne, int k, int norm,
float factor, int lane) {
float p[OWN];
unsigned long long key[OWN];
#pragma unroll
for (int i = 0; i < OWN; ++i) {
const int e = lane + 32 * i, s = e < ne ? e : 0;
p[i] = 1.0f / (1.0f + expf(-logits[(long)r * lp + s]));
key[i] = e < ne ? router_rank_key(p[i] + bias[(long)s * bp], e) : 0ull;
}
unsigned long long below = ~0ull, mine = 0;
for (int j = 0; j < k; ++j) {
unsigned long long best = 0;
#pragma unroll
for (int i = 0; i < OWN; ++i) {
const unsigned long long c = key[i] < below ? key[i] : 0ull;
best = c > best ? c : best;
}
best = router_wave_max(best);
if (lane == j) mine = best;
below = best;
}
const int e = mine ? (int)~(uint32_t)mine : 0;
float chosen = 0;
#pragma unroll
for (int i = 0; i < OWN; ++i) {
const float v = __shfl(p[i], e & 31, 32);
if ((e >> 5) == i) chosen = v;
}
float total = 0;
for (int j = 0; j < k; ++j)
total += __int_as_float(__builtin_amdgcn_readlane(__float_as_int(chosen), j));
const float mult = norm ? factor / (total + 1e-20f) : factor;
if (lane < k) {
ids[(long)r * ip + lane] = e;
weights[(long)r * wp + lane] = chosen * mult;
}
return e;
}
template <int OWN>
__global__ void __launch_bounds__(128)
router_sigmoid_wave_kernel(const float* logits, const float* bias, int* ids, float* weights,
long lp, long bp, long ip, long wp, int m, int ne, int k, int norm,
float factor) {
const int lane = threadIdx.x & 31, r = blockIdx.x * 4 + (threadIdx.x >> 5);
if (r >= m) return;
(void)router_sigmoid_row<OWN>(logits, bias, ids, weights, lp, bp, ip, wp, r, ne, k, norm,
factor, lane);
}
// router_sigmoid_topk, then moe_scatter over its ids, then the `fill` of an ungated shared arm's
// gate with 1, in one workgroup. Rows wrap over the NW waves; each leaves its slots in the sort's
// LDS list instead of re-reading `ids`. A slot carries the expert its row wrote, including the
// expert 0 of a row with fewer finite ranks than top_k, so every output equals the three launches'.
// INV also writes the inverse, as moe_scatter_inv does.
template <int OWN, uint32_t NW, bool INV>
__global__ void __launch_bounds__(NW * 32)
router_sigmoid_scatter_kernel(const float* logits, const float* bias, int* ids, float* weights,
int32_t* sorted, int32_t* off, int32_t* cnt, uint16_t* gate,
int32_t* inv, long lp, long bp, long ip, long wp, long gp, int m,
int ne, int n_local, int k, int norm, float factor, int base,
r4d_moesort::Protect prot) {
__shared__ r4d_moesort::ScatterLds<NW> sl;
const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
for (int e = threadIdx.x; e < n_local; e += (int)(NW * 32)) sl.cnt[e] = 0;
for (int r = wave; r < m; r += (int)NW) {
const int e = router_sigmoid_row<OWN>(logits, bias, ids, weights, lp, bp, ip, wp, r, ne, k,
norm, factor, lane) -
base;
if (lane < k)
sl.e[r * k + lane] =
e >= 0 && e < n_local ? r4d_moesort::sort_place(e, (uint32_t)n_local, prot) : -1;
if (gate && !lane) gate[(long)r * gp] = f32_to_bf16(1.0f);
}
lds_barrier();
r4d_moesort::scatter_small_place<NW, INV>(sorted, off, cnt, (uint32_t)(m * k),
(uint32_t)n_local, sl, inv);
}
int router_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 4) return RAD_E_INVAL;
const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &w = a->t[3];
const long ne = r4d_geti_or(a, "n_expert", 0), k = r4d_geti_or(a, "top_k", 0);
const float factor = (float)r4d_getf(a, "route_scale", 0);
if (lg.dtype != RAD_F32 || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 || w.dtype != RAD_F32)
return RAD_E_DTYPE;
if (ne < 1 || ne > 512 || k < 1 || k > 32 || k > ne || !std::isfinite(factor) || factor <= 0 ||
!lg.data || !bias.data || !ids.data || !w.data || lg.rank != 2 || lg.shape[0] < 1 ||
lg.shape[0] > 65535 || lg.shape[1] != ne || bias.rank != 1 || bias.shape[0] != ne ||
ids.rank != 2 || w.rank != 2 || ids.shape[0] != lg.shape[0] || w.shape[0] != lg.shape[0] ||
ids.shape[1] != k || w.shape[1] != k || lg.stride[1] != 1 || ids.stride[1] != 1 ||
w.stride[1] != 1 || lg.stride[0] < ne || ids.stride[0] < k || w.stride[0] < k ||
bias.stride[0] < 1)
return RAD_E_SHAPE;
const int norm = (int)(r4d_geti_or(a, "norm", 0) != 0);
const dim3 grid((unsigned)((lg.shape[0] + 3) / 4));
if (ne <= 9 * 32)
return R4D_EMIT(stream, router_sigmoid_wave_kernel<9>, grid, dim3(128), 0,
(const float*)lg.data, (const float*)bias.data, (int*)ids.data,
(float*)w.data, lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0],
(int)lg.shape[0], (int)ne, (int)k, norm, factor);
return R4D_EMIT(stream, router_sigmoid_wave_kernel<16>, grid, dim3(128), 0,
(const float*)lg.data, (const float*)bias.data, (int*)ids.data, (float*)w.data,
lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0], (int)lg.shape[0],
(int)ne, (int)k, norm, factor);
}
/* Operands: router_sigmoid_topk's four, moe_scatter's three outputs, then the optional gate and the
* optional inverse. The sort is the single-workgroup form, so M * top_k must fit it; a larger pass
* is refused rather than served at another cost. */
int router_scatter_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 7) return RAD_E_INVAL;
const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &w = a->t[3];
const RadTensor *sorted = &a->t[4], *off = &a->t[5], *cnt = &a->t[6];
const RadTensor* gate = a->n_t > 7 ? r4d_opt(a, 7) : nullptr;
const RadTensor* inv = a->n_t > 8 ? r4d_opt(a, 8) : nullptr;
const long ne = r4d_geti_or(a, "n_expert", 0), k = r4d_geti_or(a, "top_k", 0);
const long nl = r4d_geti_or(a, "n_local", ne), base = r4d_geti_or(a, "expert_base", 0);
const float factor = (float)r4d_getf(a, "route_scale", 0);
if (lg.dtype != RAD_F32 || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 ||
w.dtype != RAD_F32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 ||
cnt->dtype != RAD_I32 || (gate && gate->dtype != RAD_BF16) ||
(inv && inv->dtype != RAD_I32))
return RAD_E_DTYPE;
if (ne < 1 || ne > 512 || k < 1 || k > 32 || k > ne || !std::isfinite(factor) || factor <= 0 ||
!lg.data || !bias.data || !ids.data || !w.data || !sorted->data || !off->data ||
!cnt->data || lg.rank != 2 || lg.shape[0] < 1 || lg.shape[1] != ne || bias.rank != 1 ||
bias.shape[0] != ne || ids.rank != 2 || w.rank != 2 || ids.shape[0] != lg.shape[0] ||
w.shape[0] != lg.shape[0] || ids.shape[1] != k || w.shape[1] != k || lg.stride[1] != 1 ||
ids.stride[1] != 1 || w.stride[1] != 1 || lg.stride[0] < ne || ids.stride[0] < k ||
w.stride[0] < k || bias.stride[0] < 1)
return RAD_E_SHAPE;
const long m = lg.shape[0], T = m * k;
if (T > (long)r4d_moesort::kScatterSmall || nl < 1 || nl > ne || base < 0 || base + nl > ne ||
!r4d_contig(sorted) || !r4d_contig(off) || !r4d_contig(cnt) || r4d_numel(sorted) < T ||
r4d_numel(off) < nl + 1 || r4d_numel(cnt) < nl ||
(inv && (!r4d_contig(inv) || r4d_numel(inv) < T)))
return RAD_E_SHAPE;
long long grows = 0;
const long long gp = gate ? r4d_rows_pitch(gate, 1, &grows) : 0;
if (gate && (gp < 1 || grows < m)) return RAD_E_SHAPE;
r4d_moesort::Protect prot;
const int prc = r4d_moesort::protect_of(a, nl, &prot);
if (prc != RAD_OK) return prc;
const int norm = (int)(r4d_geti_or(a, "norm", 0) != 0);
// A wave a row up to 32 rows, as router_topk_scatter: the rows a wave serves run back to back.
const int nw = m <= 8 ? 8 : m <= 16 ? 16 : 32;
#define R4D_RSS_I(OWN, NW, INV) \
return R4D_EMIT(stream, (router_sigmoid_scatter_kernel<OWN, NW, INV>), dim3(1), \
dim3((NW) * 32), 0, (const float*)lg.data, (const float*)bias.data, \
(int*)ids.data, (float*)w.data, (int32_t*)sorted->data, (int32_t*)off->data, \
(int32_t*)cnt->data, gate ? (uint16_t*)gate->data : (uint16_t*)nullptr, \
inv ? (int32_t*)inv->data : (int32_t*)nullptr, lg.stride[0], bias.stride[0], \
ids.stride[0], w.stride[0], (long)gp, (int)m, (int)ne, (int)nl, (int)k, norm, \
factor, (int)base, prot)
#define R4D_RSS(OWN, NW) \
do { \
if (inv) R4D_RSS_I(OWN, NW, true); \
R4D_RSS_I(OWN, NW, false); \
} while (0)
if (ne <= 9 * 32) {
if (nw == 8) R4D_RSS(9, 8u);
if (nw == 16) R4D_RSS(9, 16u);
R4D_RSS(9, 32u);
}
if (nw == 8) R4D_RSS(16, 8u);
if (nw == 16) R4D_RSS(16, 16u);
R4D_RSS(16, 32u);
#undef R4D_RSS
#undef R4D_RSS_I
}
__global__ void swiglu_clamped_kernel(const uint16_t* gu, uint16_t* y, long gp, long yp, int n,
float limit) {
const long r = blockIdx.x;
const int i = blockIdx.y * 256 + threadIdx.x;
if (i >= n) return;
const float g = fminf(bf16_to_f32(gu[r * gp + i]), limit);
const float u = fminf(fmaxf(bf16_to_f32(gu[r * gp + n + i]), -limit), limit);
y[r * yp + i] = f32_to_bf16((g / (1.0f + expf(-g))) * u);
}
int clamped_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 2) return RAD_E_INVAL;
const auto &gu = a->t[0], &y = a->t[1];
const long n = r4d_geti_or(a, "n", 0);
const float limit = (float)r4d_getf(a, "limit", 0);
if (gu.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE;
if (n < 1 || n > INT_MAX / 2 || !std::isfinite(limit) || limit <= 0 || !gu.data || !y.data ||
gu.rank != 2 || y.rank != 2 || y.shape[0] < 1 || y.shape[0] > 65535 ||
gu.shape[0] != y.shape[0] || gu.shape[1] != 2 * n || y.shape[1] != n || gu.stride[1] != 1 ||
y.stride[1] != 1 || gu.stride[0] < 2 * n || y.stride[0] < n)
return RAD_E_SHAPE;
return R4D_EMIT(stream, swiglu_clamped_kernel, dim3(y.shape[0], (n + 255) / 256), dim3(256), 0,
(const uint16_t*)gu.data, (uint16_t*)y.data, gu.stride[0], y.stride[0], (int)n,
limit);
}
// swiglu_clamped, then quant_act_fp8 over its product, in one pass: a wave per (row, 128 columns),
// four columns a lane, as the quantiser maps them. Each element is swiglu_clamped_kernel's
// expression and each group quant_act_fp8_kernel's. The product is rounded to bf16 and read back
// before the absmax because the separate quantiser reads the stored bf16 bytes.
__global__ void __launch_bounds__(256)
swiglu_clamped_quant_kernel(const uint16_t* gu, uint16_t* y, uint8_t* q, float* s, long gp,
long yp, long qp, long sp, int n, int nkb, float limit) {
const long r = blockIdx.x;
const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
for (int kb = wave; kb < nkb; kb += (int)(blockDim.x >> 5)) {
const int c0 = kb * 128 + lane * 4;
float v[4], m = 0.0f;
#pragma unroll
for (int j = 0; j < 4; ++j) {
const int c = c0 + j;
v[j] = 0.0f;
if (c < n) {
const float g = fminf(bf16_to_f32(gu[r * gp + c]), limit);
const float u = fminf(fmaxf(bf16_to_f32(gu[r * gp + n + c]), -limit), limit);
const uint16_t h = f32_to_bf16((g / (1.0f + expf(-g))) * u);
if (y) y[r * yp + c] = h;
v[j] = bf16_to_f32(h);
}
}
#pragma unroll
for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j]));
m = r4d_wave_max(m);
const float sc = m > 0.0f ? m * (1.0f / 448.0f) : 1.0f;
if (!lane) s[r * sp + kb] = sc;
const float inv = 1.0f / sc;
int pk = 0;
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[0] * inv, -448.0f), 448.0f),
fminf(fmaxf(v[1] * inv, -448.0f), 448.0f), pk, false);
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[2] * inv, -448.0f), 448.0f),
fminf(fmaxf(v[3] * inv, -448.0f), 448.0f), pk, true);
if (c0 < n) *(uint32_t*)(q + r * qp + c0) = (uint32_t)pk;
}
}
/* Operands: gate_up [M, 2n], q [M, n] E4M3, scale [M, ceil(n/128)] f32, out_bf16 [M, n] optional.
* n a multiple of 4 and group 128, as quant_act_fp8 requires. */
int clamped_quant_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 3) return RAD_E_INVAL;
const auto &gu = a->t[0], &q = a->t[1], &sc = a->t[2];
const RadTensor* y = a->n_t > 3 ? r4d_opt(a, 3) : nullptr;
const long n = r4d_geti_or(a, "n", 0), nkb = (n + 127) / 128;
const float limit = (float)r4d_getf(a, "limit", 0);
if (gu.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || sc.dtype != RAD_F32 ||
(y && y->dtype != RAD_BF16))
return RAD_E_DTYPE;
if (r4d_geti_or(a, "group", 128) != 128 || n < 4 || n % 4 || n > INT_MAX / 2 ||
!std::isfinite(limit) || limit <= 0 || !gu.data || !q.data || !sc.data || gu.rank != 2 ||
q.rank != 2 || sc.rank != 2 || gu.shape[0] < 1 || gu.shape[0] > 65535 ||
gu.shape[1] != 2 * n || q.shape[0] != gu.shape[0] || q.shape[1] != n ||
sc.shape[0] != gu.shape[0] || sc.shape[1] != nkb || gu.stride[1] != 1 || q.stride[1] != 1 ||
sc.stride[1] != 1 || gu.stride[0] < 2 * n || q.stride[0] < n || sc.stride[0] < nkb ||
(y && (y->rank != 2 || y->shape[0] != gu.shape[0] || y->shape[1] != n ||
y->stride[1] != 1 || y->stride[0] < n)))
return RAD_E_SHAPE;
// A wave a group, at most eight: a row of GLM's TP8 expert width is two groups.
const unsigned thr = (unsigned)(nkb < 8 ? nkb : 8) * 32u;
return R4D_EMIT(stream, swiglu_clamped_quant_kernel, dim3((unsigned)gu.shape[0]), dim3(thr), 0,
(const uint16_t*)gu.data, y ? (uint16_t*)y->data : (uint16_t*)nullptr,
(uint8_t*)q.data, (float*)sc.data, gu.stride[0], y ? (long)y->stride[0] : 0L,
q.stride[0], sc.stride[0], (int)n, (int)nkb, limit);
}
}
extern "C" int r4d_rad_swiglu_clamped(const RadArgs* a, RadStream stream) {
return clamped_body(a, stream);
}
extern "C" int r4d_rad_swiglu_clamped_quant_fp8(const RadArgs* a, RadStream stream) {
return clamped_quant_body(a, stream);
}
extern "C" int r4d_rad_gemm_nt_f32(const RadArgs* a, RadStream stream) {
return gemm_f32_body(a, stream);
}
extern "C" int r4d_rad_router_sigmoid_topk(const RadArgs* a, RadStream stream) {
return router_body(a, stream);
}
extern "C" int r4d_rad_router_sigmoid_topk_scatter(const RadArgs* a, RadStream stream) {
return router_scatter_body(a, stream);
}
+63 -2
View File
@@ -1,4 +1,5 @@
// r4d_hc_bf16.hip -- the gated residual (hyper-connections): hc_enter, hc_read and hc_write.
// r4d_hc_bf16.hip -- the gated residual (hyper-connections): hc_enter, hc_read,
// hc_write and hc_project.
//
// Qwen4-Exp carries a residual stream `hc` times the model width, with no pre-norm and no residual
// add: every block reads a data-dependent mix of the hc sub-streams and writes its output back into
@@ -294,6 +295,39 @@ void hc_write_kernel(const unsigned short* __restrict__ y, const unsigned short*
}
}
/* ============================================================== hc_project
*
* The control vector (core/cvec.h): h[s] -= scale * (h[s] . v) * v for each of the hc streams of a
* row whose `on` flag is 1 -- llama.cpp's `--cvec-mode project`, issued after a layer's write into
* the stream. ONE direction for every stream: the dot is per stream, against the same v. One
* workgroup per (row, stream), and a zero flag is not read and not written, so an unprojected
* request's stream is the stock model's. */
__global__ __launch_bounds__(kThreads)
void hc_project_kernel(unsigned short* __restrict__ h, const float* __restrict__ v,
const int32_t* __restrict__ on, long rows, long n, long hrow, float scale) {
const long r = blockIdx.y;
if (r >= rows || on[r] == 0) return; /* a row's switch: the whole workgroup takes it */
unsigned short* hp = h + r * hrow + (long)blockIdx.x * n;
float acc = 0.0f;
for (long i = threadIdx.x; i < n; i += kThreads) acc += bf2f(hp[i]) * v[i];
/* A wave sums itself and the waves meet in LDS, at kWave 32: the shuttle is the wave's own
* width here, not the 64 a 64-wide __shfl_down would assume but gfx12 does not run. */
__shared__ float s_g[kWaves];
const float w = r4d_wave_sum(acc);
if ((threadIdx.x % kWave) == 0) s_g[threadIdx.x / kWave] = w;
__syncthreads();
if (threadIdx.x == 0) {
float g = 0.0f;
for (int k = 0; k < kWaves; ++k) g += s_g[k];
s_g[0] = g * scale;
}
__syncthreads();
const float g = s_g[0];
for (long i = threadIdx.x; i < n; i += kThreads) hp[i] = f2bf(bf2f(hp[i]) - g * v[i]);
}
/* A wave's dot product of the LDS vector with a contiguous bf16 row, using 512-byte loads but
* summing in the scalar form's order.
*
@@ -2153,7 +2187,10 @@ unsigned int* hc_mix_ctr(RadStream s) {
if (fi < 0) return nullptr;
void* p = nullptr;
if (hipMalloc(&p, (size_t)kMaxMixCtr * sizeof(unsigned int)) != hipSuccess) return nullptr;
if (hipMemset(p, 0, (size_t)kMaxMixCtr * sizeof(unsigned int)) != hipSuccess) {
/* 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 r4d_moe.hip's router counters do). */
if (hipMemset(p, 0, (size_t)kMaxMixCtr * sizeof(unsigned int)) != hipSuccess ||
hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return nullptr;
}
@@ -3238,6 +3275,30 @@ extern "C" int r4d_rad_hc_write(const RadArgs* a, RadStream stream) {
(long)rows, (long)n, (int)hc, (long)yrow, (long)irow, (long)hrow);
}
enum { HCP_H = 0, HCP_V, HCP_ON };
/* The control vector's projection. `v` is one layer's unit direction, [n], used for EVERY stream
* (the dot is per stream against the same direction): a [hc, n] table is refused here rather than
* read as one direction a stream, which is what a per-stream offset would silently do. */
extern "C" int r4d_rad_hc_project(const RadArgs* a, RadStream stream) {
const RadTensor* h = r4d_opt(a, HCP_H);
const RadTensor* v = r4d_opt(a, HCP_V);
const RadTensor* on = r4d_opt(a, HCP_ON);
if (!h || !v || !on) return R4D_NO(RAD_E_INVAL);
R4D_DT(h, RAD_BF16); R4D_DT(v, RAD_F32); R4D_DT(on, RAD_I32);
long long rows = 0, n = 0, hc = 0, hrow = 0;
const int rc = hc_common(a, h, &rows, &n, &hc, &hrow);
if (rc != RAD_OK) return rc;
long long vrows = 0, onrows = 0;
if (r4d_rows_pitch(v, n, &vrows) < 0 || vrows != 1) return R4D_NO(RAD_E_STRIDE);
if (r4d_rows_pitch(on, 1, &onrows) < 0 || onrows < rows) return R4D_NO(RAD_E_STRIDE);
return R4D_EMIT(stream, hc_project_kernel, dim3((unsigned)hc, (unsigned)rows), dim3(kThreads),
0, (unsigned short*)h->data, (const float*)v->data,
(const int32_t*)on->data, (long)rows, (long)n, (long)hrow,
(float)r4d_getf(a, "scale", 1.0));
}
enum { MTE_H = 0, MTE_E, MTE_WH, MTE_WE, MTE_FCH, MTE_FCE, MTE_X };
extern "C" int r4d_rad_mtp_enter(const RadArgs* a, RadStream stream) {
+342
View File
@@ -0,0 +1,342 @@
/* Exact recurrent baseline for GLM KDA, including speculative candidate snapshots.
* One wave owns four value rows and keeps each row's 128-wide state in four registers per lane.
* Prefill uses the same recurrence and commits only its final state. */
#include <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_emit.h"
#include <climits>
#include <cstdlib>
#include <cstring>
namespace {
struct KdaMeta {
int row[5], head[5];
long os0, os1, ss0, ss1, ss2;
long is0, is1, cs0, as0, hs0;
int tokens, slots, width, verify, anchor;
float lower, eps, scale;
};
struct KdaJob : KdaMeta {
const uint16_t* input[5];
const float *alog, *bias;
float* state;
uint16_t* out;
const int *idx, *cu, *accepted, *init;
};
__device__ long factor_offset(long base, int logical, long pitch) {
return base + (logical / 128) * pitch + (logical % 128);
}
/* Separate dispatch: all old factor reads finish before the next window overwrites them. */
__global__ void kda_replay_kernel(float* state, const int* idx, const int* cu, const int* accepted,
const int* init, KdaMeta m) {
const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y,
seq = blockIdx.z;
/* A sequence without tokens this step leaves its slots as they are. */
if (cu[(long)seq * m.cs0] == cu[(long)(seq + 1) * m.cs0]) return;
const int anchor = idx[(long)seq * m.is0],
scratch = idx[(long)seq * m.is0 + (m.width / 2) * m.is1];
if (anchor < 0 || anchor >= m.slots || scratch < 0 || scratch >= m.slots || anchor == scratch)
return;
const long fb = (long)scratch * m.ss0 + (long)head * m.ss1;
const long sb = (long)anchor * m.ss0 + (long)head * m.ss1 + (long)e * m.ss2;
if (init && !init[(long)seq * m.hs0]) {
#pragma unroll
for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = 0;
return;
}
const float count = state[fb];
const int na = accepted ? accepted[(long)seq * m.as0] : 1;
if (!(count >= 0 && count <= 32) || count != floorf(count) || na < 1 || na > 32 ||
(count > 0 && na > count))
return;
float s[4];
#pragma unroll
for (int d = 0; d < 4; ++d) s[d] = state[sb + lane + d * 32];
for (int t = 0; t < (count > 0 ? na : 0); ++t) {
const int f = 1 + t * 385;
float k[4], prediction = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
const int c = lane + d * 32;
k[d] = state[factor_offset(fb, f + c, m.ss2)];
s[d] *= state[factor_offset(fb, f + 256 + c, m.ss2)];
prediction += s[d] * k[d];
}
const float delta =
state[factor_offset(fb, f + 384, m.ss2)] *
(state[factor_offset(fb, f + 128 + e, m.ss2)] - r4d_wave_sum(prediction));
#pragma unroll
for (int d = 0; d < 4; ++d) s[d] += delta * k[d];
}
#pragma unroll
for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = s[d];
}
/* R value rows a wave: the loads, norms and decay exponentials, which do not depend on the state,
* are formed once for R rows, and the rows' reductions interleave. The next token's operands are
* loaded while this one is reduced. */
template <int R>
__global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint16_t* v,
const uint16_t* g, const uint16_t* beta, const float* alog,
const float* bias, float* state_ptr, uint16_t* out, const int* idx,
const int* cu, const int* accepted_ptr, const int* init,
KdaMeta meta) {
static_assert(32 % R == 0, "the 128 value rows split evenly over the waves");
KdaJob j{};
static_cast<KdaMeta&>(j) = meta;
j.input[0] = q;
j.input[1] = k;
j.input[2] = v;
j.input[3] = g;
j.input[4] = beta;
j.alog = alog;
j.bias = bias;
j.state = state_ptr;
j.out = out;
j.idx = idx;
j.cu = cu;
j.accepted = accepted_ptr;
j.init = init;
const int lane = threadIdx.x & 31, e0 = (blockIdx.x * 4 + (threadIdx.x >> 5)) * R;
const int head = blockIdx.y, seq = blockIdx.z;
const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0];
const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1;
if (begin < 0 || end <= begin || end > j.tokens || accepted < 1 ||
accepted > (j.anchor ? 32 : j.width) ||
(j.verify && end - begin > (j.anchor ? 32 : j.width)))
return;
const int read = j.idx[(long)seq * j.is0 + (j.verify && !j.anchor ? accepted - 1 : 0) * j.is1];
if (read >= j.slots) return;
uint16_t* const out_row = j.out + (long)head * j.os1 + e0;
if (read < 0) {
if (lane < R)
for (int t = begin; t < end; ++t) out_row[(long)t * j.os0 + lane] = 0;
return;
}
const bool initialized = !j.init || j.init[(long)seq * j.hs0] != 0;
const int scratch = j.anchor ? j.idx[(long)seq * j.is0 + (j.width / 2) * j.is1] : 0;
if (j.anchor && (scratch < 0 || scratch >= j.slots || scratch == read)) return;
const long fb = (long)scratch * j.ss0 + (long)head * j.ss1;
const long initial = (long)read * j.ss0 + (long)head * j.ss1 + (long)e0 * j.ss2;
float state[R][4];
#pragma unroll
for (int r = 0; r < R; ++r)
#pragma unroll
for (int d = 0; d < 4; ++d)
state[r][d] = initialized ? j.state[initial + r * j.ss2 + lane + 32 * d] : 0;
const float gain = expf(j.alog[head]);
float shift[4];
#pragma unroll
for (int d = 0; d < 4; ++d) shift[d] = j.bias[head * 128 + lane + 32 * d];
const uint16_t* const qb = j.input[0] + (long)head * j.head[0] + lane;
const uint16_t* const kb = j.input[1] + (long)head * j.head[1] + lane;
const uint16_t* const vb = j.input[2] + (long)head * j.head[2] + e0;
const uint16_t* const gb = j.input[3] + (long)head * j.head[3] + lane;
const uint16_t* const bb = j.input[4] + (long)head * j.head[4];
struct Token {
uint32_t q[4], k[4], g[4], beta, value[R];
};
auto fetch = [&](int t, Token& o) {
#pragma unroll
for (int d = 0; d < 4; ++d) {
o.q[d] = ldg_u16(qb + (long)t * j.row[0] + 32 * d);
o.k[d] = ldg_u16(kb + (long)t * j.row[1] + 32 * d);
o.g[d] = ldg_u16(gb + (long)t * j.row[3] + 32 * d);
}
o.beta = ldg_u16(bb + (long)t * j.row[4]);
#pragma unroll
for (int r = 0; r < R; ++r) o.value[r] = ldg_u16(vb + (long)t * j.row[2] + r);
};
Token cur;
if (begin < end) fetch(begin, cur);
for (int t = begin; t < end; ++t) {
Token next;
/* The last token loads itself again rather than a row past `end`. */
fetch(t + 1 < end ? t + 1 : t, next);
float qv[4], kv[4], decay[4], sq = 0, sk = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
qv[d] = bf16w_lo(cur.q[d]);
kv[d] = bf16w_lo(cur.k[d]);
sq += qv[d] * qv[d];
sk += kv[d] * kv[d];
const float raw = bf16w_lo(cur.g[d]);
decay[d] = expf(j.lower / (1.0f + expf(-gain * (raw + shift[d]))));
}
const float qi = j.scale * rsqrtf(r4d_wave_sum(sq) + j.eps),
ki = rsqrtf(r4d_wave_sum(sk) + j.eps);
const float b = 1.0f / (1.0f + expf(-bf16w_lo(cur.beta)));
float predicted[R];
#pragma unroll
for (int r = 0; r < R; ++r) predicted[r] = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
qv[d] *= qi;
kv[d] *= ki;
#pragma unroll
for (int r = 0; r < R; ++r) {
state[r][d] *= decay[d];
predicted[r] += state[r][d] * kv[d];
}
}
float value[R];
#pragma unroll
for (int r = 0; r < R; ++r) {
predicted[r] = r4d_wave_sum(predicted[r]);
value[r] = bf16w_lo(cur.value[r]);
}
if (j.anchor && j.verify) {
const int f = 1 + (t - begin) * 385;
if (e0 == 0) {
#pragma unroll
for (int d = 0; d < 4; ++d) {
const int c = lane + 32 * d;
j.state[factor_offset(fb, f + c, j.ss2)] = kv[d];
j.state[factor_offset(fb, f + 256 + c, j.ss2)] = decay[d];
}
if (!lane) j.state[factor_offset(fb, f + 384, j.ss2)] = b;
}
if (!lane) {
#pragma unroll
for (int r = 0; r < R; ++r)
j.state[factor_offset(fb, f + 128 + e0 + r, j.ss2)] = value[r];
}
}
float result[R];
#pragma unroll
for (int r = 0; r < R; ++r) {
const float delta = b * (value[r] - predicted[r]);
result[r] = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
state[r][d] += delta * kv[d];
result[r] += state[r][d] * qv[d];
}
}
float mine = 0;
#pragma unroll
for (int r = 0; r < R; ++r) {
result[r] = r4d_wave_sum(result[r]);
if (lane == r) mine = result[r];
}
if (lane < R) out_row[(long)t * j.os0 + lane] = f32_to_bf16(mine);
if ((!j.anchor && j.verify) || (!j.verify && t + 1 == end)) {
const int write = j.idx[(long)seq * j.is0 + (j.verify ? t - begin : 0) * j.is1];
if (write >= 0 && write < j.slots) {
const long target = (long)write * j.ss0 + (long)head * j.ss1 + (long)e0 * j.ss2;
#pragma unroll
for (int r = 0; r < R; ++r)
#pragma unroll
for (int d = 0; d < 4; ++d)
j.state[target + r * j.ss2 + lane + 32 * d] = state[r][d];
}
}
cur = next;
}
if (j.anchor && e0 == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f;
}
template <class Pitch>
bool headed(const RadTensor& t, long tokens, long heads, long dim, Pitch* row, Pitch* head) {
if (!t.data || t.dtype != RAD_BF16 || t.shape[0] != tokens || t.stride[0] > INT_MAX ||
(t.rank == 3 && t.stride[1] > INT_MAX))
return false;
if (t.rank == 3 && t.shape[1] == heads && t.shape[2] == dim && t.stride[2] == 1 &&
t.stride[1] >= dim && t.stride[0] >= heads * t.stride[1]) {
*row = t.stride[0];
*head = t.stride[1];
return true;
}
if (t.rank == 2 && t.shape[1] == heads * dim && t.stride[1] == 1 &&
t.stride[0] >= heads * dim) {
*row = t.stride[0];
*head = dim;
return true;
}
return false;
}
bool vector(const RadTensor& t, uint32_t dt, long n) {
return t.data && t.dtype == dt && t.rank == 1 && t.shape[0] >= n && t.stride[0] == 1;
}
int body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 13) return RAD_E_INVAL;
const long H = r4d_geti_or(a, "heads", 0);
if (H < 1 || H > 65535 || r4d_geti_or(a, "head_k", 0) != 128 ||
r4d_geti_or(a, "head_v", 0) != 128)
return RAD_E_SHAPE;
KdaJob j{};
const auto &state = a->t[7], &idx = a->t[8], &cu = a->t[9];
const long tokens = a->t[0].shape[0];
if (tokens < 1 || tokens > INT_MAX || state.rank != 4 || state.dtype != RAD_F32 ||
!state.data || state.shape[0] < 1 || state.shape[0] > INT_MAX || state.shape[1] != H ||
state.shape[2] != 128 || state.shape[3] != 128 || state.stride[3] != 1 ||
state.stride[2] < 128 || state.stride[1] < 128 * state.stride[2] ||
state.stride[0] < H * state.stride[1] || cu.rank != 1 || cu.dtype != RAD_I32 || !cu.data ||
cu.shape[0] < 2 || cu.shape[0] > 65536 || cu.stride[0] < 1 || idx.rank != 2 ||
idx.dtype != RAD_I32 || !idx.data || idx.shape[0] < cu.shape[0] - 1 || idx.shape[1] < 1 ||
idx.shape[1] > INT_MAX || idx.stride[1] < 1 || idx.stride[0] < idx.shape[1] * idx.stride[1])
return RAD_E_SHAPE;
for (int i = 0; i < 5; ++i) {
if (!headed(a->t[i], tokens, H, i == 4 ? 1 : 128, &j.row[i], &j.head[i]))
return RAD_E_SHAPE;
j.input[i] = (const uint16_t*)a->t[i].data;
}
if (!headed(a->t[12], tokens, H, 128, &j.os0, &j.os1) || !vector(a->t[5], RAD_F32, H) ||
!vector(a->t[6], RAD_F32, H * 128))
return RAD_E_SHAPE;
const RadTensor *accepted = rad_arg_in(a, 10), *init = rad_arg_in(a, 11);
if ((accepted && !vector(*accepted, RAD_I32, cu.shape[0] - 1)) ||
(init && !vector(*init, RAD_I32, cu.shape[0] - 1)))
return RAD_E_SHAPE;
const char* mode = r4d_gets(a, "mode");
if (!mode || (std::strcmp(mode, "verify") && std::strcmp(mode, "prefill"))) return RAD_E_INVAL;
j.verify = !std::strcmp(mode, "verify");
const char* form = r4d_gets(a, "state_form");
j.anchor = form && !std::strcmp(form, "anchor");
if (form && !j.anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL;
if (j.anchor && idx.shape[1] < 2) return RAD_E_SHAPE;
j.lower = (float)r4d_getf(a, "lower_bound", 0);
j.eps = (float)r4d_getf(a, "l2_eps", 0);
j.scale = (float)r4d_getf(a, "scale", 1);
if (!std::isfinite(j.lower) || j.lower >= 0 || !std::isfinite(j.eps) || j.eps <= 0 ||
!std::isfinite(j.scale))
return RAD_E_SHAPE;
j.tokens = (int)tokens;
j.slots = (int)state.shape[0];
j.width = (int)idx.shape[1];
j.alog = (const float*)a->t[5].data;
j.bias = (const float*)a->t[6].data;
j.state = (float*)state.data;
j.out = (uint16_t*)a->t[12].data;
j.ss0 = state.stride[0];
j.ss1 = state.stride[1];
j.ss2 = state.stride[2];
j.idx = (const int*)idx.data;
j.is0 = idx.stride[0];
j.is1 = idx.stride[1];
j.cu = (const int*)cu.data;
j.cs0 = cu.stride[0];
if (accepted) {
j.accepted = (const int*)accepted->data;
j.as0 = accepted->stride[0];
}
if (init) {
j.init = (const int*)init->data;
j.hs0 = init->stride[0];
}
const unsigned seqs = (unsigned)(cu.shape[0] - 1);
if (j.anchor && j.verify) {
const int rc =
R4D_EMIT(stream, kda_replay_kernel, dim3(32, (unsigned)H, seqs), dim3(128), 0, j.state,
j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j));
if (rc != RAD_OK) return rc;
}
constexpr int kRows = 4;
return R4D_EMIT(stream, (kda_rows_kernel<kRows>), dim3(32 / kRows, (unsigned)H, seqs),
dim3(128), 0, j.input[0], j.input[1], j.input[2], j.input[3], j.input[4],
j.alog, j.bias, j.state, j.out, j.idx, j.cu, j.accepted, j.init,
static_cast<KdaMeta>(j));
}
}
extern "C" int r4d_rad_kda_update(const RadArgs* a, RadStream stream) { return body(a, stream); }
+40
View File
@@ -0,0 +1,40 @@
// r4d_kv_len_trim.hip - r4d_rad_kv_len_trim: a batch's per-sequence context lengths less `trim`.
//
// The 31B's prefill overlap runs attention per slice of a one-sequence step: slice A's rows are the
// step's first rows, so its attention must see the context ending at its own last row, not the
// step's (rows past it are not yet in the cache, and their positions are counted from the end).
// `trim` is the rows after the slice, a runtime count. A launch sees its op's parameters collapsed
// to the band's upper bound (RadArgs.p), so the count is the extent of operand `tail`, those rows'
// positions, whose values are never read; the ranged parameter only picks the band.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include <cstdint>
namespace {
__global__ __launch_bounds__(64) void kv_len_trim_kernel(const int32_t* __restrict__ in,
int32_t* __restrict__ out, int n,
int trim) {
const int i = (int)threadIdx.x;
if (i < n) {
const int v = in[i] - trim;
out[i] = v > 0 ? v : 0;
}
}
} // namespace
extern "C" int r4d_rad_kv_len_trim(const RadArgs* a, RadStream stream) {
const RadTensor* in = r4d_opt(a, 0);
const RadTensor* tail = r4d_opt(a, 1);
const RadTensor* out = r4d_opt(a, 2);
if (!in || !tail || !out || !in->data || !out->data) return R4D_NO(RAD_E_INVAL);
if (in->dtype != RAD_I32 || out->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_numel(in);
if (n < 1 || n > 64 || r4d_numel(out) < n) return R4D_NO(RAD_E_SHAPE);
const long long trim = tail->rank ? r4d_numel(tail) : 0;
if (trim < 0 || trim > 0x7fffffffLL) return R4D_NO(RAD_E_SHAPE);
return R4D_EMIT(stream, kv_len_trim_kernel, dim3(1), dim3(64), 0, (const int32_t*)in->data,
(int32_t*)out->data, (int)n, (int)trim);
}
+17
View File
@@ -1197,6 +1197,23 @@ extern "C" int r4d_rad_unrelayout_moe_w4_mod4(const RadParam* p, int n_p, int op
return moew4_unrelayout_by(moe_view_mod4, p, n_p, operand, enc, sel, src, src_bytes, pl, n);
}
extern "C" int r4d_rad_layout_moe_mxfp4(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout*) {
if (operand != 2 && operand != 3 && operand != 6 && operand != 7) return RAD_E_UNSUPPORTED;
if (!r4d_enc::affine(enc, RAD_FP4E2M1, RAD_E8M0, 1, 32)) return RAD_E_DTYPE;
MoeView v;
const int rc = moe_view(p, n_p, operand, &v);
if (rc != RAD_OK) return rc;
const long long N = r4d_pgeti_or(v.p, v.n, "N", 0), K = r4d_pgeti_or(v.p, v.n, "K", 0);
const bool scale = operand == 3 || operand == 7;
if (n != 1 || !pl || !sel || !selects(enc, sel, n, scale ? "scale" : "codes") ||
!dims(pl[0], N, scale ? K / 32 : K) || K % 128) return RAD_E_SHAPE;
/* The exact selected canonical plane, not a relayout: it remains readable in place
* from the container or a mapped host pool. Unsupported is the ABI spelling for that. */
return RAD_E_UNSUPPORTED;
}
extern "C" int r4d_rad_layout_moe_fp8(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
+153
View File
@@ -252,6 +252,11 @@ enum {
kExThreads = 256,
kZMax = 16, /* the passes of one tile spread over at most this many blocks */
kZGrid = 256, /* ... and only while the grid is smaller than this */
kMmMT = 128, /* expand_mm: rows a tile, 32 a wave */
kMmNT = 256, /* expand_mm: columns a tile, 128 a wave */
kMmJC = 32, /* expand_mm: j a staged step */
kMmWaves = 8, /* 4 (rows) x 2 (columns) over the tile */
kMmThreads = kMmWaves * 32,
};
struct ShrinkTArgs {
@@ -590,6 +595,119 @@ __global__ __launch_bounds__(kExThreads) void lora_expand_tiled_kernel(ExpandTAr
}
}
/* lora_expand_mm: the same delta on the WMMA, t rounded to bf16, for the passes whose rows are
* many and mostly of one slot (an image or video generator's). One block a (256 columns, 128 rows),
* eight waves, wave w the 32 rows at 32 (w >> 1) and the 128 columns at 128 (w & 1): 2 x 8 WMMA
* tiles. Each 32-wide j step stages t's [128 rows][32 j] (rounded to bf16) and B[s]'s [256 columns]
* [32 j] in LDS, read by every wave; B's fragment is the WMMA's A operand (16 n x 16 j) and t's its
* B (16 j x 16 m), so lane l's eight outputs are row l % 16 of its m tile at columns 8 (l / 16) ..
* +7 -- eight neighbours in y. Rows of a slot not in the pass are staged as zeros and not stored. */
template <int YDT, bool V>
__global__ __launch_bounds__(kMmThreads) void lora_expand_mm_kernel(ExpandTArgs T) {
__shared__ uint16_t ts[kMmMT][kMmJC + 8]; /* +8: rows land on different banks */
__shared__ uint16_t bs[kMmNT][kMmJC + 8];
__shared__ int mm_slot[kMmMT], mm_list[kMmMT];
__shared__ int mm_n;
const ExpandArgs& A = T.b;
const int tid = (int)threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int col = lane & 15, half = lane >> 4;
const long long nb = (long long)blockIdx.x * kMmNT;
const int mb = (int)blockIdx.y * kMmMT;
const int wm = 32 * (wave >> 1), wn = 128 * (wave & 1);
for (int i = tid; i < kMmMT; i += kMmThreads) {
int s = -1;
if (mb + i < T.M) {
s = A.slot[(long long)(mb + i) * A.slot_st];
if (s < 0 || s >= A.S) s = -1;
}
mm_slot[i] = s;
}
__syncthreads();
if (tid == 0) mm_n = distinct_slots(mm_slot, mm_list, kMmMT);
__syncthreads();
const int npass = mm_n;
for (int p = 0; p < npass; ++p) {
const int s = mm_list[p];
const uint16_t* bp = A.lb + (long long)s * A.lb_s0;
lr_v8f acc[2][8];
for (int b = 0; b < 2; ++b)
for (int a = 0; a < 8; ++a) acc[b][a] = (lr_v8f)(0.0f);
for (int j0 = 0; j0 < A.R; j0 += kMmJC) {
__syncthreads(); /* the last step's readers are done */
/* t: 128 rows x 32 j, one row's 32 a pair of lanes */
for (int i = tid; i < kMmMT * 2; i += kMmThreads) {
const int r = i >> 1, h = (i & 1) * 16;
const bool on = mm_slot[r] == s;
const long long row = (long long)(mb + r) * A.t_rs;
for (int e = 0; e < 16; ++e) {
const int j = j0 + h + e;
ts[r][h + e] = on && j < A.R ? f2bf(A.t[row + (long long)j * A.t_cs]) : (uint16_t)0;
}
}
/* B[s]: 256 columns x 32 j, one column's 32 a pair of lanes */
for (int i = tid; i < kMmNT * 2; i += kMmThreads) {
const int c = i >> 1, h = (i & 1) * 16;
const long long n = nb + c;
lr_v8s f[2];
ld_pool16<V>(bp + (n < A.N ? n : 0) * A.lb_s1, j0 + h, A.R, A.lb_s2, n < A.N, f);
for (int e = 0; e < 16; ++e) bs[c][h + e] = (uint16_t)f[e >> 3][e & 7];
}
__syncthreads();
lr_v8s tf[2][2];
for (int b = 0; b < 2; ++b)
for (int q = 0; q < 2; ++q)
for (int e = 0; e < 8; ++e)
tf[b][q][e] = (short)ts[wm + 16 * b + col][16 * half + 8 * q + e];
for (int a = 0; a < 8; ++a) {
lr_v8s bf[2];
for (int q = 0; q < 2; ++q)
for (int e = 0; e < 8; ++e)
bf[q][e] = (short)bs[wn + 16 * a + col][16 * half + 8 * q + e];
for (int b = 0; b < 2; ++b) {
acc[b][a] = wmma_bf16(bf[0], tf[b][0], acc[b][a]);
acc[b][a] = wmma_bf16(bf[1], tf[b][1], acc[b][a]);
}
}
}
for (int b = 0; b < 2; ++b) {
const int ml = wm + 16 * b + col;
if (mm_slot[ml] != s) continue;
const long long m = mb + ml;
for (int a = 0; a < 8; ++a) {
const long long n0 = nb + wn + 16 * a + 8 * half;
const long long o = m * A.y_rs + n0 * A.y_cs;
const float* scp = A.sc + (long long)s * A.sc_rs;
if (YDT == kBF16 && A.y_cs == 1 && n0 + 8 <= A.N && (((uintptr_t)A.y + 2 * o) & 15) == 0) {
lr_v8s* yp = (lr_v8s*)((uint16_t*)A.y + o);
lr_v8s yv = *yp;
for (int e = 0; e < 8; ++e)
yv[e] = (short)f2bf(bf2f((uint16_t)yv[e]) + scp[(n0 + e) * A.sc_cs] * acc[b][a][e]);
*yp = yv;
continue;
}
for (int e = 0; e < 8; ++e) {
const long long n = n0 + e;
if (n >= A.N) continue;
const float d = scp[n * A.sc_cs] * acc[b][a][e];
const long long oe = m * A.y_rs + n * A.y_cs;
if (YDT == kBF16) {
uint16_t* y = (uint16_t*)A.y + oe;
*y = f2bf(bf2f(*y) + d);
} else if (YDT == kF16) {
uint16_t* y = (uint16_t*)A.y + oe;
*y = f32_to_f16(f16_to_f32(*y) + d);
} else {
float* y = (float*)A.y + oe;
*y = *y + d;
}
}
}
}
}
}
/* ---------------------------------------------------------------- operand reading (host) */
/* `t` read as [rows, cols]: the trailing axes that span `cols` must be one dense run, the leading
@@ -885,6 +1003,13 @@ static void launch_expand_tiled(const ExpandTArgs& P, dim3 grid, RadStream strea
(hipStream_t)stream, P);
}
template <int YDT, bool V>
static void launch_expand_mm(const ExpandTArgs& P, dim3 grid, RadStream stream) {
(void)stream;
R4D_KLAUNCH(R4D_KNAME(lora_expand_mm_kernel<YDT, V>), grid, dim3(kMmThreads),
(hipStream_t)stream, P);
}
} /* namespace r4d_lora */
extern "C" {
@@ -1003,4 +1128,32 @@ int r4d_rad_lora_expand_tiled(const RadArgs* a, RadStream stream) {
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
/* lora_expand_mm: one block a (256 columns, 128 rows); expand_operands reads the same operands. */
int r4d_rad_lora_expand_mm(const RadArgs* a, RadStream stream) {
using namespace r4d_lora;
ExpandArgs P{};
int ydt = 0;
int64_t M = 0;
const int rc = expand_operands(a, &P, &ydt, &M);
if (rc != RAD_OK || M <= 0) return rc;
const int64_t rt = (M + kMmMT - 1) / kMmMT, nt = (P.N + kMmNT - 1) / kMmNT;
if (rt > 65535 || nt > 0x7fffffff) return RAD_E_SHAPE;
ExpandTArgs T{};
T.b = P;
T.M = (int)M;
T.Z = 1;
const bool v = P.lb_s2 == 1 && (uintptr_t)P.lb % 16 == 0 && P.lb_s1 % 8 == 0 &&
P.lb_s0 % 8 == 0;
const dim3 grid((unsigned)nt, (unsigned)rt, 1u);
switch (ydt) {
case kBF16: v ? launch_expand_mm<kBF16, true>(T, grid, stream)
: launch_expand_mm<kBF16, false>(T, grid, stream); break;
case kF16: v ? launch_expand_mm<kF16, true>(T, grid, stream)
: launch_expand_mm<kF16, false>(T, grid, stream); break;
default: v ? launch_expand_mm<kF32, true>(T, grid, stream)
: launch_expand_mm<kF32, false>(T, grid, stream); break;
}
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
} /* extern "C" */
+1091
View File
File diff suppressed because it is too large. Load diff
+635
View File
@@ -0,0 +1,635 @@
/* GLM's mHC, kept separate from the Qwen gated-residual kernels. The GLM shape
* projects in parallel before one workgroup per token forms the Sinkhorn matrix.
* Mixing weights are declared f32; activations are bf16, coefficients stay f32. */
#include <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_emit.h"
#include <climits>
#include <cstdlib>
#include <cstring>
#include <cstdint>
namespace {
__device__ float warp_sum(float v) {
for (int d = 16; d; d >>= 1) v += __shfl_down(v, d, 32);
return v;
}
// The final collapsed output is large enough to hold the projection partials
// until the finishing kernel has read them. Align within each pitched row.
__device__ float* partials(uint16_t* x, long row, long pitch) {
return reinterpret_cast<float*>((reinterpret_cast<uintptr_t>(x + row * pitch) + 3) &
~uintptr_t(3));
}
// Where projection partial (row, coefficient j, chunk) lives: inside the collapsed output's rows
// (mhc_pre), or a separate [rows][chunk][stride] matrix (mhc_pre_partial writes this rank's chunks
// from `first`, mhc_pre_finish reads every rank's after the gather). Kernels differ in address only.
// `pad` clears a Dense chunk's slots past the last partial, so the gathered payload is defined.
struct InX {
uint16_t* x;
long xp;
int chunks;
__device__ float* at(long row, int j, int chunk) const {
return partials(x, row, xp) + j * chunks + chunk;
}
__device__ void pad(long, int, int) const {}
};
struct Dense {
float* p;
long pp;
int stride, first;
__device__ float* at(long row, int j, int chunk) const {
return p + row * pp + (long)(chunk - first) * stride + j;
}
__device__ void pad(long row, int last, int chunk) const {
for (int j = last + 1; j < stride; ++j) *at(row, j, chunk) = 0;
}
};
template <class Out>
__global__ void mhc_partial_kernel(const uint16_t* h, const float* fn, Out out, int width, int mix,
int chunk0, long hp, long fp) {
__shared__ float sums[4];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int j = blockIdx.y, chunk = chunk0 + blockIdx.x;
const long row = blockIdx.z;
float sum = 0;
for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) {
const float v = bf16_to_f32(h[row * hp + i]);
sum += v * (j == mix ? v : fn[(long)j * fp + i]);
}
sum = warp_sum(sum);
if (!lane) sums[wave] = sum;
__syncthreads();
if (!tid) {
*out.at(row, j, chunk) = sums[0] + sums[1] + sums[2] + sums[3];
if (j == mix) out.pad(row, mix, chunk);
}
}
// Prefill reuses each input across four coefficients and each F32 mixing weight across four BF16
// token rows. Every output keeps mhc_partial_kernel's accumulation and reduction order.
template <class Out>
__global__ void mhc_partial_rows4_coeff4_kernel(const uint16_t* h, const float* fn, Out out,
int width, int mix, int chunk0, long hp, long fp,
long rows) {
__shared__ float sums[4][4][4];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int first_j = blockIdx.y * 4, chunk = chunk0 + blockIdx.x;
const long first = (long)blockIdx.z * 4;
float sum[4][4]{};
for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) {
float weight[4];
#pragma unroll
for (int q = 0; q < 4; ++q)
weight[q] = first_j + q < mix ? fn[(long)(first_j + q) * fp + i] : 0;
#pragma unroll
for (int r = 0; r < 4; ++r)
if (first + r < rows) {
const float v = bf16_to_f32(h[(first + r) * hp + i]);
#pragma unroll
for (int q = 0; q < 4; ++q)
if (first_j + q <= mix) sum[q][r] += v * (first_j + q == mix ? v : weight[q]);
}
}
#pragma unroll
for (int q = 0; q < 4; ++q)
if (first_j + q <= mix) {
#pragma unroll
for (int r = 0; r < 4; ++r) {
sum[q][r] = warp_sum(sum[q][r]);
if (!lane) sums[q][r][wave] = sum[q][r];
}
}
__syncthreads();
if (tid < 16) {
const int q = tid / 4, r = tid % 4;
if (first_j + q <= mix && first + r < rows) {
*out.at(first + r, first_j + q, chunk) =
sums[q][r][0] + sums[q][r][1] + sums[q][r][2] + sums[q][r][3];
if (first_j + q == mix) out.pad(first + r, mix, chunk);
}
}
}
// The collapsed read x[i] = sum_j pre[j] * h[j*n + i] eight columns a thread, in 16-byte loads
// and stores. Each element keeps the scalar loop's order (from zero, j ascending), so its bits
// are the same; false when the rows are not 16-byte aligned, and the caller runs its own loop.
__device__ __forceinline__ bool mix_rows_vec(const uint16_t* hr, uint16_t* xr, const float* pre,
int n, int hc, int tid, int nt) {
if ((((uintptr_t)hr | (uintptr_t)xr) & 15) || (n & 7)) return false;
for (int i = tid * 8; i < n; i += nt * 8) {
float v[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
for (int j = 0; j < hc; ++j) {
const uint4 q = *reinterpret_cast<const uint4*>(hr + (long)j * n + i);
const uint32_t w[4] = { q.x, q.y, q.z, q.w };
#pragma unroll
for (int e = 0; e < 8; ++e)
v[e] += pre[j] * bf16_to_f32((uint16_t)(w[e >> 1] >> (16 * (e & 1))));
}
uint32_t o[4];
#pragma unroll
for (int e = 0; e < 4; ++e)
o[e] = (uint32_t)f32_to_bf16(v[2 * e]) | ((uint32_t)f32_to_bf16(v[2 * e + 1]) << 16);
*reinterpret_cast<uint4*>(xr + i) = uint4{ o[0], o[1], o[2], o[3] };
}
return true;
}
// The projection partials four slots a lane. The kernels above give each of 128 threads one slot
// s, the sum over the chunk's columns s, s+128, ... in order; here lane L holds slots 4L..4L+3,
// so a row is read 8 bytes and a weight 16 bytes a load, and one wave does a whole block's work.
// Their reduction is replayed exactly: warp_sum pairs slot l with l+16, l+8, l+4, l+2 and l+1,
// here lanes +4, +2, +1 and then the lane's own slots, and the four waves' sums, at lanes 0, 8,
// 16 and 24, are added in order. R rows and four coefficients a wave, four independent waves a
// block, no barrier.
template <class Out, int R>
__global__ __launch_bounds__(128) void mhc_partial_vec_kernel(const uint16_t* h, const float* fn,
Out out, int mix, int chunk0,
int count, long hp, long fp,
long rows, long items) {
const int lane = threadIdx.x & 31;
const long item = (long)blockIdx.x * 4 + (threadIdx.x >> 5);
if (item >= items) return;
const int groups = (mix + 4) / 4;
const int chunk = chunk0 + (int)(item % count);
const int first_j = (int)((item / count) % groups) * 4;
const long first = item / count / groups * R;
float acc[4][R][4]{};
for (int t = 0; t < 16; ++t) {
const int col = chunk * 2048 + t * 128 + lane * 4;
float w[4][4];
#pragma unroll
for (int q = 0; q < 4; ++q) {
const float4 v =
first_j + q < mix
? *reinterpret_cast<const float4*>(fn + (long)(first_j + q) * fp + col)
: float4{ 0, 0, 0, 0 };
w[q][0] = v.x;
w[q][1] = v.y;
w[q][2] = v.z;
w[q][3] = v.w;
}
#pragma unroll
for (int r = 0; r < R; ++r)
if (first + r < rows) {
const uint2 hv = *reinterpret_cast<const uint2*>(h + (first + r) * hp + col);
const float v[4] = { bf16_to_f32((uint16_t)hv.x),
bf16_to_f32((uint16_t)(hv.x >> 16)),
bf16_to_f32((uint16_t)hv.y),
bf16_to_f32((uint16_t)(hv.y >> 16)) };
#pragma unroll
for (int q = 0; q < 4; ++q)
if (first_j + q <= mix) {
#pragma unroll
for (int u = 0; u < 4; ++u)
acc[q][r][u] += v[u] * (first_j + q == mix ? v[u] : w[q][u]);
}
}
}
#pragma unroll
for (int q = 0; q < 4; ++q)
if (first_j + q <= mix) {
#pragma unroll
for (int r = 0; r < R; ++r)
if (first + r < rows) {
float c[4];
#pragma unroll
for (int u = 0; u < 4; ++u) {
float a = acc[q][r][u];
a += __shfl_down(a, 4, 32);
a += __shfl_down(a, 2, 32);
a += __shfl_down(a, 1, 32);
c[u] = a;
}
const float e0 = c[0] + c[2], e1 = c[1] + c[3], f = e0 + e1;
const float s1 = __shfl(f, 8, 32), s2 = __shfl(f, 16, 32),
s3 = __shfl(f, 24, 32);
if (!lane) {
*out.at(first + r, first_j + q, chunk) = f + s1 + s2 + s3;
if (first_j + q == mix) out.pad(first + r, mix, chunk);
}
}
}
}
// The geometries without the chunk split: one workgroup a row projects the residual itself from
// `fn`, then mixes and collapses it.
__global__ void mhc_pre_kernel(const uint16_t* h, const float* fn, const float* scale,
const float* base, uint16_t* x, float* post, float* comb, int n,
int hc, int iterations, float eps, float heps, long hp, long fp,
long xp, long pp, long cp) {
__shared__ float sums[8], inverse, coefficients[80], pre[8], c[64];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const long r = blockIdx.x;
const int width = hc * n, mix = hc * (hc + 2);
float ss = 0;
for (int i = tid; i < width; i += 256) {
const float v = bf16_to_f32(h[r * hp + i]);
ss += v * v;
}
ss = warp_sum(ss);
if (!lane) sums[wave] = ss;
__syncthreads();
if (!tid) {
float s = 0;
for (int i = 0; i < 8; ++i) s += sums[i];
inverse = rsqrtf(s / (float)width + eps);
}
__syncthreads();
for (int j = wave; j < mix; j += 8) {
float dot = 0;
for (int i = lane; i < width; i += 32)
dot += bf16_to_f32(h[r * hp + i]) * fn[(long)j * fp + i];
dot = warp_sum(dot);
if (!lane) coefficients[j] = dot * inverse;
}
__syncthreads();
if (!tid) {
for (int j = 0; j < hc; ++j) {
pre[j] = 1.0f / (1.0f + expf(-(coefficients[j] * scale[0] + base[j]))) + heps;
post[r * pp + j] =
2.0f / (1.0f + expf(-(coefficients[hc + j] * scale[1] + base[hc + j])));
}
for (int j = 0; j < hc; ++j) {
float mx = -INFINITY;
for (int k = 0; k < hc; ++k) {
const int q = 2 * hc + j * hc + k;
c[j * hc + k] = coefficients[q] * scale[2] + base[q];
mx = fmaxf(mx, c[j * hc + k]);
}
float sum = 0;
for (int k = 0; k < hc; ++k) {
c[j * hc + k] = expf(c[j * hc + k] - mx);
sum += c[j * hc + k];
}
for (int k = 0; k < hc; ++k) c[j * hc + k] = c[j * hc + k] / sum + heps;
}
for (int it = 0; it < iterations; ++it) {
if (it)
for (int j = 0; j < hc; ++j) {
float sum = 0;
for (int k = 0; k < hc; ++k) sum += c[j * hc + k];
for (int k = 0; k < hc; ++k) c[j * hc + k] /= sum + heps;
}
for (int k = 0; k < hc; ++k) {
float sum = 0;
for (int j = 0; j < hc; ++j) sum += c[j * hc + k];
for (int j = 0; j < hc; ++j) c[j * hc + k] /= sum + heps;
}
}
for (int j = 0; j < hc * hc; ++j) comb[r * cp + j] = c[j];
}
__syncthreads();
if (mix_rows_vec(h + r * hp, x + r * xp, pre, n, hc, tid, 256)) return;
for (int i = tid; i < n; i += 256) {
float v = 0;
for (int j = 0; j < hc; ++j) v += pre[j] * bf16_to_f32(h[r * hp + j * n + i]);
x[r * xp + i] = f32_to_bf16(v);
}
}
// One wave handles GLM's 4x4 Sinkhorn matrix. Keep row/column sums in the
// scalar reference order; the other rows never participate in these shuffles.
// Writes post and comb; returns pre[lane] in lanes 0..3.
template <class In>
__device__ __forceinline__ float glm_warp_mix(int lane, long row, const float* scale,
const float* base, float* post, float* comb,
int iterations, float eps, float heps, long pp,
long cp, const In& in) {
float inverse = 0;
if (!lane) {
float ss = 0;
for (int i = 0; i < 8; ++i) ss += *in.at(row, 24, i);
inverse = rsqrtf(ss / 16384.0f + eps);
}
inverse = __shfl(inverse, 0, 32);
float dot = 0;
if (lane < 24) {
float v[8];
for (int i = 0; i < 8; ++i) v[i] = *in.at(row, lane, i);
// The existing eight-chunk warp reduction pairs 0/4, 2/6, 1/5, 3/7.
dot = ((v[0] + v[4]) + (v[2] + v[6])) + ((v[1] + v[5]) + (v[3] + v[7]));
}
const float coefficient = dot * inverse;
const float post_coefficient = __shfl(coefficient, (lane + 4) & 31, 32);
const float matrix_coefficient = __shfl(coefficient, (lane + 8) & 31, 32);
float pre = 0;
if (lane < 4) {
pre = 1.0f / (1.0f + expf(-(coefficient * scale[0] + base[lane]))) + heps;
post[row * pp + lane] =
2.0f / (1.0f + expf(-(post_coefficient * scale[1] + base[4 + lane])));
}
float value = lane < 16 ? matrix_coefficient * scale[2] + base[8 + lane] : 0;
const int row_base = lane & ~3, col = lane & 3;
float mx = -INFINITY;
#pragma unroll
for (int j = 0; j < 4; ++j) mx = fmaxf(mx, __shfl(value, row_base + j, 32));
value = expf(value - mx);
float sum = 0;
#pragma unroll
for (int j = 0; j < 4; ++j) sum += __shfl(value, row_base + j, 32);
value = value / sum + heps;
for (int it = 0; it < iterations; ++it) {
if (it) {
sum = 0;
#pragma unroll
for (int j = 0; j < 4; ++j) sum += __shfl(value, row_base + j, 32);
value /= sum + heps;
}
sum = 0;
#pragma unroll
for (int j = 0; j < 4; ++j) sum += __shfl(value, col + 4 * j, 32);
value /= sum + heps;
}
if (lane < 16) comb[row * cp + lane] = value;
return pre;
}
// glm_warp_mix on wave 0, then the collapsed read over the whole block: one wave writing 4096
// columns a row would be most of a decode step's mhc_pre.
template <class In>
__global__ __launch_bounds__(256) void mhc_pre_glm_wide_kernel(
const uint16_t* h, const float* scale, const float* base, uint16_t* x, float* post, float* comb,
int iterations, float eps, float heps, long hp, long xp, long pp, long cp, In in) {
__shared__ float spre[4];
const int tid = threadIdx.x;
const long row = blockIdx.x;
if (tid < 32) {
const float pre =
glm_warp_mix(tid, row, scale, base, post, comb, iterations, eps, heps, pp, cp, in);
if (tid < 4) spre[tid] = pre;
}
__syncthreads();
const float pre[4] = { spre[0], spre[1], spre[2], spre[3] };
if (mix_rows_vec(h + row * hp, x + row * xp, pre, 4096, 4, tid, 256)) return;
for (int i = tid; i < 4096; i += 256) {
float v = 0;
v += pre[0] * bf16_to_f32(h[row * hp + i]);
v += pre[1] * bf16_to_f32(h[row * hp + 4096 + i]);
v += pre[2] * bf16_to_f32(h[row * hp + 8192 + i]);
v += pre[3] * bf16_to_f32(h[row * hp + 12288 + i]);
x[row * xp + i] = f32_to_bf16(v);
}
}
__global__ void mhc_post_kernel(const uint16_t* x, const uint16_t* h, const float* post,
const float* comb, uint16_t* out, int n, int hc, long xp, long hp,
long pp, long cp, long op) {
const long r = blockIdx.y;
const int q = blockIdx.x * blockDim.x + threadIdx.x;
if (q >= n * hc) return;
const int k = q / n, i = q % n;
float v = 0;
for (int j = 0; j < hc; ++j)
v += comb[r * cp + j * hc + k] * bf16_to_f32(h[r * hp + j * n + i]);
v += post[r * pp + k] * bf16_to_f32(x[r * xp + i]);
out[r * op + q] = f32_to_bf16(v);
}
// mhc_post at four streams, eight columns of every output stream a thread: each input word is
// loaded once instead of once per output stream. Every output keeps mhc_post_kernel's order.
__global__ void mhc_post_vec_kernel(const uint16_t* x, const uint16_t* h, const float* post,
const float* comb, uint16_t* out, int n, long xp, long hp,
long pp, long cp, long op) {
const long r = blockIdx.y;
const int i = (blockIdx.x * blockDim.x + threadIdx.x) * 8;
if (i >= n) return;
float hv[4][8], xv[8];
auto unpack = [](const uint16_t* p, float* v) {
const uint4 q = *reinterpret_cast<const uint4*>(p);
const uint32_t w[4] = { q.x, q.y, q.z, q.w };
#pragma unroll
for (int e = 0; e < 8; ++e) v[e] = bf16_to_f32((uint16_t)(w[e >> 1] >> (16 * (e & 1))));
};
#pragma unroll
for (int j = 0; j < 4; ++j) unpack(h + r * hp + (long)j * n + i, hv[j]);
unpack(x + r * xp + i, xv);
#pragma unroll
for (int k = 0; k < 4; ++k) {
float c[4];
#pragma unroll
for (int j = 0; j < 4; ++j) c[j] = comb[r * cp + j * 4 + k];
const float pk = post[r * pp + k];
uint32_t o[4];
#pragma unroll
for (int e = 0; e < 8; e += 2) {
float v0 = 0, v1 = 0;
#pragma unroll
for (int j = 0; j < 4; ++j) {
v0 += c[j] * hv[j][e];
v1 += c[j] * hv[j][e + 1];
}
v0 += pk * xv[e];
v1 += pk * xv[e + 1];
o[e >> 1] = (uint32_t)f32_to_bf16(v0) | ((uint32_t)f32_to_bf16(v1) << 16);
}
*reinterpret_cast<uint4*>(out + r * op + (long)k * n + i) = uint4{ o[0], o[1], o[2], o[3] };
}
}
__global__ void mhc_contract_kernel(const uint16_t* h, uint16_t* x, int n, int hc, long hp,
long xp) {
const long r = blockIdx.y;
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n) return;
float v = 0;
for (int j = 0; j < hc; ++j) v += bf16_to_f32(h[r * hp + j * n + i]);
x[r * xp + i] = f32_to_bf16(v / (float)hc);
}
bool matrix(const RadTensor& t, uint32_t dt, long rows, long cols) {
return t.data && t.dtype == dt && t.rank == 2 && t.shape[0] == rows && t.shape[1] == cols &&
t.stride[1] == 1 && t.stride[0] >= cols;
}
bool vector(const RadTensor& t, long n) {
return t.data && t.dtype == RAD_F32 && t.rank == 1 && t.shape[0] == n && t.stride[0] == 1;
}
bool geometry(const RadArgs* a, int* n, int* hc) {
const long nn = r4d_geti_or(a, "n", 0), hh = r4d_geti_or(a, "hc", 0);
if (nn < 1 || nn > 16384 || hh < 2 || hh > 8) return false;
*n = (int)nn;
*hc = (int)hh;
return true;
}
// GLM's split projection: eight 2048-column chunks of the 16384-wide residual, 24 coefficients
// and the sum of squares each. A Dense chunk holds those 25 partials in kPartStride slots.
constexpr int kChunkCols = 2048, kPartStride = 28;
template <class Out>
int emit_partials(RadStream stream, const RadTensor& h, const RadTensor& fn, Out out, int n, int hc,
int chunk0, int count, long rows) {
/* From 2 rows the four-slot form, on 16-byte weight and 8-byte residual rows; GLM's
* 2048-column chunks only. Measured cold on gfx1201 at GLM's shape: one row a wave leads up
* to 16 rows (13 us against 20 to 36 for the one-slot kernels), two rows from 48 (20 against
* 22 us, at 128 rows 34 against 39, at 2048 391 against 500); four rows a wave trail two at
* every count. */
const bool vec_aligned = ((uintptr_t)fn.data & 15) == 0 && fn.stride[0] % 4 == 0 &&
((uintptr_t)h.data & 7) == 0 && h.stride[0] % 4 == 0 &&
hc * n % kChunkCols == 0;
if (vec_aligned && rows >= 2) {
const int mix = hc * (hc + 2), groups = (mix + 4) / 4;
#define MHC_VEC(RR) \
do { \
const long items = (long)count * groups * ((rows + RR - 1) / RR); \
return R4D_EMIT(stream, (mhc_partial_vec_kernel<Out, RR>), \
dim3((unsigned)((items + 3) / 4)), dim3(128), 0, (const uint16_t*)h.data, \
(const float*)fn.data, out, mix, chunk0, count, (long)h.stride[0], \
(long)fn.stride[0], rows, items); \
} while (0)
if (rows >= 32) MHC_VEC(2);
MHC_VEC(1);
#undef MHC_VEC
}
/* Otherwise four rows and four coefficients a block from 32 rows, one row and one coefficient
* below. */
constexpr long kRows4Min = 32;
if (rows >= kRows4Min)
return R4D_EMIT(stream, (mhc_partial_rows4_coeff4_kernel<Out>),
dim3(count, (hc * (hc + 2) + 4) / 4, (unsigned)((rows + 3) / 4)), dim3(128),
0, (const uint16_t*)h.data, (const float*)fn.data, out, hc * n,
hc * (hc + 2), chunk0, (long)h.stride[0], (long)fn.stride[0], rows);
return R4D_EMIT(stream, (mhc_partial_kernel<Out>),
dim3(count, hc * (hc + 2) + 1, (unsigned)rows), dim3(128), 0,
(const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2),
chunk0, (long)h.stride[0], (long)fn.stride[0]);
}
// The finishing dispatch. `split` says the partials exist (in `in`); without them
// mhc_pre_kernel projects the residual itself from `fn`.
template <class In>
int emit_finish(RadStream stream, const RadTensor& h, const float* fn, long fp, const RadTensor& s,
const RadTensor& b, const RadTensor& x, const RadTensor& p, const RadTensor& c,
int n, int hc, int iters, float eps, float heps, long rows, bool split, In in) {
/* The warp mix at every row count: byte-identical to the scalar one and a quarter of its time
* at one to six rows. */
if (split)
return R4D_EMIT(stream, (mhc_pre_glm_wide_kernel<In>), dim3((unsigned)rows), dim3(256), 0,
(const uint16_t*)h.data, (const float*)s.data, (const float*)b.data,
(uint16_t*)x.data, (float*)p.data, (float*)c.data, iters, eps, heps,
(long)h.stride[0], (long)x.stride[0], (long)p.stride[0], (long)c.stride[0],
in);
return R4D_EMIT(stream, mhc_pre_kernel, dim3((unsigned)rows), dim3(256), 0,
(const uint16_t*)h.data, fn, (const float*)s.data, (const float*)b.data,
(uint16_t*)x.data, (float*)p.data, (float*)c.data, n, hc, iters, eps, heps,
(long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0], (long)c.stride[0]);
}
bool coefficients(const RadArgs* a, long* iters, float* eps, float* heps) {
*iters = r4d_geti_or(a, "iterations", 0);
*eps = (float)r4d_getf(a, "eps", 0);
*heps = (float)r4d_getf(a, "hc_eps", 0);
return *iters >= 1 && *iters <= 256 && std::isfinite(*eps) && std::isfinite(*heps) &&
*eps > 0 && *heps >= 0;
}
// mhc_pre_partial and mhc_pre_finish serve GLM's split geometry only.
bool glm_chunks(const RadArgs* a, int n, int hc) {
return n == 4096 && hc == 4 && r4d_geti_or(a, "chunk", 0) == kChunkCols;
}
int pre_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 7) return RAD_E_INVAL;
int n, hc;
if (!geometry(a, &n, &hc)) return RAD_E_SHAPE;
long iters;
float eps, heps;
if (!coefficients(a, &iters, &eps, &heps)) return RAD_E_SHAPE;
const auto &h = a->t[0], &fn = a->t[1], &s = a->t[2], &b = a->t[3];
const auto &x = a->t[4], &p = a->t[5], &c = a->t[6];
if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > INT_MAX) return RAD_E_SHAPE;
const long rows = h.shape[0];
if (!matrix(h, RAD_BF16, rows, hc * n) || !matrix(fn, RAD_F32, hc * (hc + 2), hc * n) ||
!vector(s, 3) || !vector(b, hc * (hc + 2)) || !matrix(x, RAD_BF16, rows, n) ||
!matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc))
return RAD_E_SHAPE;
const int chunks = (hc * n + kChunkCols - 1) / kChunkCols;
const bool split =
n == 4096 && hc == 4 && rows <= 65535 && (hc * (hc + 2) + 1) * chunks * 4 + 2 <= n * 2;
const InX in{ (uint16_t*)x.data, (long)x.stride[0], chunks };
if (split) {
const int rc = emit_partials(stream, h, fn, in, n, hc, 0, chunks, rows);
if (rc < 0) return rc;
}
return emit_finish(stream, h, (const float*)fn.data, (long)fn.stride[0], s, b, x, p, c, n, hc,
(int)iters, eps, heps, rows, split, in);
}
int partial_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 3) return RAD_E_INVAL;
int n, hc;
if (!geometry(a, &n, &hc) || !glm_chunks(a, n, hc)) return RAD_E_SHAPE;
const int total = hc * n / kChunkCols;
const long first = r4d_geti_or(a, "first", -1), count = r4d_geti_or(a, "chunks", 0);
if (first < 0 || count < 1 || first + count > total) return RAD_E_SHAPE;
const auto &h = a->t[0], &fn = a->t[1], &part = a->t[2];
if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > 65535) return RAD_E_SHAPE;
const long rows = h.shape[0];
if (!matrix(h, RAD_BF16, rows, hc * n) || !matrix(fn, RAD_F32, hc * (hc + 2), hc * n) ||
!matrix(part, RAD_F32, rows, count * kPartStride))
return RAD_E_SHAPE;
const Dense out{ (float*)part.data, (long)part.stride[0], kPartStride, (int)first };
return emit_partials(stream, h, fn, out, n, hc, (int)first, (int)count, rows);
}
int finish_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 7) return RAD_E_INVAL;
int n, hc;
if (!geometry(a, &n, &hc) || !glm_chunks(a, n, hc)) return RAD_E_SHAPE;
long iters;
float eps, heps;
if (!coefficients(a, &iters, &eps, &heps)) return RAD_E_SHAPE;
const int chunks = hc * n / kChunkCols;
const auto &part = a->t[0], &h = a->t[1], &s = a->t[2], &b = a->t[3];
const auto &x = a->t[4], &p = a->t[5], &c = a->t[6];
if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > 65535) return RAD_E_SHAPE;
const long rows = h.shape[0];
if (!matrix(part, RAD_F32, rows, chunks * kPartStride) || !matrix(h, RAD_BF16, rows, hc * n) ||
!vector(s, 3) || !vector(b, hc * (hc + 2)) || !matrix(x, RAD_BF16, rows, n) ||
!matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc))
return RAD_E_SHAPE;
const Dense in{ (float*)part.data, (long)part.stride[0], kPartStride, 0 };
return emit_finish(stream, h, nullptr, 0, s, b, x, p, c, n, hc, (int)iters, eps, heps, rows,
true, in);
}
int post_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 5) return RAD_E_INVAL;
int n, hc;
if (!geometry(a, &n, &hc)) return RAD_E_SHAPE;
const auto &x = a->t[0], &h = a->t[1], &p = a->t[2], &c = a->t[3], &o = a->t[4];
if (x.rank != 2 || x.shape[0] < 1 || x.shape[0] > 65535) return RAD_E_SHAPE;
const long rows = x.shape[0];
if (!matrix(x, RAD_BF16, rows, n) || !matrix(h, RAD_BF16, rows, hc * n) ||
!matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc) ||
!matrix(o, RAD_BF16, rows, hc * n) || o.data == h.data)
return RAD_E_SHAPE;
const auto aligned = [](const RadTensor& t) {
return ((uintptr_t)t.data & 15) == 0 && t.stride[0] % 8 == 0;
};
if (hc == 4 && n % 8 == 0 && aligned(x) && aligned(h) && aligned(o))
return R4D_EMIT(stream, mhc_post_vec_kernel, dim3((n / 8 + 255) / 256, (unsigned)rows),
dim3(256), 0, (const uint16_t*)x.data, (const uint16_t*)h.data,
(const float*)p.data, (const float*)c.data, (uint16_t*)o.data, n,
(long)x.stride[0], (long)h.stride[0], (long)p.stride[0], (long)c.stride[0],
(long)o.stride[0]);
return R4D_EMIT(stream, mhc_post_kernel, dim3((n * hc + 255) / 256, (unsigned)rows), dim3(256),
0, (const uint16_t*)x.data, (const uint16_t*)h.data, (const float*)p.data,
(const float*)c.data, (uint16_t*)o.data, n, hc, (long)x.stride[0],
(long)h.stride[0], (long)p.stride[0], (long)c.stride[0], (long)o.stride[0]);
}
int contract_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 2) return RAD_E_INVAL;
int n, hc;
if (!geometry(a, &n, &hc)) return RAD_E_SHAPE;
const auto &h = a->t[0], &x = a->t[1];
if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > 65535) return RAD_E_SHAPE;
const long rows = h.shape[0];
if (!matrix(h, RAD_BF16, rows, hc * n) || !matrix(x, RAD_BF16, rows, n)) return RAD_E_SHAPE;
return R4D_EMIT(stream, mhc_contract_kernel, dim3((n + 255) / 256, (unsigned)rows), dim3(256),
0, (const uint16_t*)h.data, (uint16_t*)x.data, n, hc, (long)h.stride[0],
(long)x.stride[0]);
}
}
extern "C" int r4d_rad_mhc_pre(const RadArgs* a, RadStream stream) { return pre_body(a, stream); }
extern "C" int r4d_rad_mhc_pre_partial(const RadArgs* a, RadStream stream) {
return partial_body(a, stream);
}
extern "C" int r4d_rad_mhc_pre_finish(const RadArgs* a, RadStream stream) {
return finish_body(a, stream);
}
extern "C" int r4d_rad_mhc_post(const RadArgs* a, RadStream stream) { return post_body(a, stream); }
extern "C" int r4d_rad_mhc_contract(const RadArgs* a, RadStream stream) {
return contract_body(a, stream);
}
+666
View File
@@ -0,0 +1,666 @@
/* Absorbed MLA keeps a single 512-wide latent per token. Decode splits the
* selected history across waves, then merges FP32 softmax statistics. It never
* materializes per-head K/V in the growing cache. */
#include <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_emit.h"
#include "r4d_gdn_wmma.h"
#include <algorithm>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <atomic>
namespace {
struct ProjectMeta {
long xr, xh, wp, yr, yh;
int rows, heads;
};
/* Absorption streams adjacent latent columns; expansion reduces a contiguous weight row. R rows
* a thread (absorb) or a wave (expand): each weight element is loaded once for R rows. Every row's
* sum runs over j in the same order whatever R is (expand: each lane's share in ascending j, then
* r4d_xor_sum<32>), so a row's bytes do not depend on the batch it is in. A tail group past the
* last row reads that row again and stores nothing for it. */
template <int R>
__global__ void project_absorb_rows(const uint16_t* x, const uint16_t* w, uint16_t* y,
ProjectMeta m) {
const int col = blockIdx.x * 128 + threadIdx.x, head = blockIdx.y, r0 = blockIdx.z * R;
if (col >= 512) return;
const uint16_t* xr[R];
#pragma unroll
for (int r = 0; r < R; ++r) xr[r] = x + (long)min(r0 + r, m.rows - 1) * m.xr + head * m.xh;
float sum[R];
#pragma unroll
for (int r = 0; r < R; ++r) sum[r] = 0;
for (int j = 0; j < 256; ++j) {
const float wv = bf16_to_f32(w[((long)head * 512 + j) * m.wp + col]);
#pragma unroll
for (int r = 0; r < R; ++r) sum[r] = fmaf(bf16_to_f32(xr[r][j]), wv, sum[r]);
}
#pragma unroll
for (int r = 0; r < R; ++r)
if (r0 + r < m.rows) y[(long)(r0 + r) * m.yr + head * m.yh + col] = f32_to_bf16(sum[r]);
}
template <int R>
__global__ void project_expand_rows(const uint16_t* x, const uint16_t* w, uint16_t* y,
ProjectMeta m) {
const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y,
r0 = blockIdx.z * R;
const uint16_t* xr[R];
#pragma unroll
for (int r = 0; r < R; ++r) xr[r] = x + (long)min(r0 + r, m.rows - 1) * m.xr + head * m.xh;
const uint16_t* const wr = w + ((long)head * 512 + 256 + col) * m.wp;
float sum[R];
#pragma unroll
for (int r = 0; r < R; ++r) sum[r] = 0;
for (int j = lane; j < 512; j += 32) {
const float wv = bf16_to_f32(wr[j]);
#pragma unroll
for (int r = 0; r < R; ++r) sum[r] = fmaf(bf16_to_f32(xr[r][j]), wv, sum[r]);
}
float mine = 0;
#pragma unroll
for (int r = 0; r < R; ++r) {
sum[r] = r4d_xor_sum<32>(sum[r]);
if (lane == r) mine = sum[r];
}
if (lane < R && r0 + lane < m.rows)
y[(long)(r0 + lane) * m.yr + head * m.yh + col] = f32_to_bf16(mine);
}
int project_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 3) return RAD_E_INVAL;
RadTensor x = a->t[0], y = a->t[2];
const auto& w = a->t[1];
const char* mode = r4d_gets(a, "mode");
const bool absorb = mode && !std::strcmp(mode, "absorb"),
expand = mode && !std::strcmp(mode, "expand");
const long h = r4d_geti_or(a, "heads", 0);
auto heads_view = [&](RadTensor& t, long width) {
if (h > 0 && t.rank == 2 && t.shape[1] == h * width) {
t.rank = 3;
t.shape[1] = h;
t.shape[2] = width;
t.stride[2] = t.stride[1];
t.stride[1] *= width;
}
};
heads_view(x, absorb ? 256 : 512);
heads_view(y, absorb ? 512 : 256);
if (x.dtype != RAD_BF16 || w.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE;
if (!x.data || !w.data || !y.data) return RAD_E_INVAL;
if ((!absorb && !expand) || h < 1 || h > 64 || r4d_geti_or(a, "head_dim", 0) != 256 ||
r4d_geti_or(a, "latent_dim", 0) != 512 || x.rank != 3 || w.rank != 2 || y.rank != 3 ||
x.shape[0] < 1 || x.shape[0] > 65535 || x.shape[1] != h ||
x.shape[2] != (absorb ? 256 : 512) || w.shape[0] != h * 512 || w.shape[1] != 512 ||
y.shape[0] != x.shape[0] || y.shape[1] != h || y.shape[2] != (absorb ? 512 : 256) ||
x.stride[2] != 1 || w.stride[1] != 1 || y.stride[2] != 1 || x.stride[1] < x.shape[2] ||
x.stride[0] < h * x.stride[1] || w.stride[0] < 512 || y.stride[1] < y.shape[2] ||
y.stride[0] < h * y.stride[1])
return RAD_E_SHAPE;
const ProjectMeta m{ x.stride[0], x.stride[1], w.stride[0], y.stride[0],
y.stride[1], (int)x.shape[0], (int)h };
const auto* xp = (const uint16_t*)x.data;
const auto* wp = (const uint16_t*)w.data;
auto* yp = (uint16_t*)y.data;
/* The largest of 8, 4, 2 and 1 rows a group that the batch fills. */
const int R = m.rows >= 8 ? 8 : m.rows >= 4 ? 4 : m.rows >= 2 ? 2 : 1;
#define MLA_PROJECT_ROWS(RR) \
do { \
const unsigned groups = (unsigned)((m.rows + RR - 1) / RR); \
if (absorb) \
return R4D_EMIT(stream, (project_absorb_rows<RR>), dim3(4, h, groups), dim3(128), 0, \
xp, wp, yp, m); \
return R4D_EMIT(stream, (project_expand_rows<RR>), dim3(64, h, groups), dim3(128), 0, xp, \
wp, yp, m); \
} while (0)
if (R == 8) MLA_PROJECT_ROWS(8);
if (R == 4) MLA_PROJECT_ROWS(4);
if (R == 2) MLA_PROJECT_ROWS(2);
MLA_PROJECT_ROWS(1);
#undef MLA_PROJECT_ROWS
}
constexpr int D = 512, PART = D + 2;
constexpr int64_t scratch_bytes = 512ll * PART * 4;
constexpr int64_t matrix_scratch_bytes = 2048ll * PART * 4;
/* r4d_mla_matrix_pin_form: 0 is the launcher's rule (vector key loads where the cache is
* aligned), 1 the element-wise key load. */
int g_mla_matrix_form = 0;
struct Meta {
long qr, qh, kp, kt, bp, bc, lp, orr, oh;
int rows, heads, blocks, bs, pages, splits;
float scale;
};
/* RADIANCE_MLA_CONFLICT_STATS: per device, the 16-token passes the matrix row ran, how many of them
* were a pair's second pass, and the chunks of the max(length) raster a pass-free pairing would
* run. Read back by r4d_mla_matrix_stats, and printed every 1024th counted launch. */
__device__ unsigned long long g_mla_stats[3];
__device__ void load_latent(const uint16_t* p, float (&v)[16]) {
if (!((uintptr_t)p & 15)) {
const uint4 a = *(const uint4*)p, b = *(const uint4*)(p + 8);
const uint32_t packed[8] = { a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w };
#pragma unroll
for (int j = 0; j < 16; ++j)
v[j] = bf16_to_f32((uint16_t)(packed[j / 2] >> (16 * (j & 1))));
} else {
#pragma unroll
for (int j = 0; j < 16; ++j) v[j] = bf16_to_f32(p[j]);
}
}
__global__ __launch_bounds__(128) void attend(const uint16_t* q, const uint16_t* kv, const int* bt,
const int* len, uint16_t* out, float* scratch,
Meta m) {
const int lane = threadIdx.x & 31, head = blockIdx.y * 4 + (threadIdx.x >> 5), r = blockIdx.x,
split = blockIdx.z;
if (head >= m.heads) return;
const int live = min(max(len[(long)r * m.lp], 0), m.blocks * m.bs);
const int begin = (int)((long)live * split / m.splits),
end = (int)((long)live * (split + 1) / m.splits);
float query[16], value[16] = {};
load_latent(q + (long)r * m.qr + (long)head * m.qh + lane * 16, query);
float max_score = -INFINITY, den = 0;
for (int token = begin; token < end; ++token) {
const int page = bt[(long)r * m.bp + (token / m.bs) * m.bc];
if (page < 0 || page >= m.pages) continue;
float key[16];
load_latent(kv + (long)page * m.kp + (token % m.bs) * m.kt + lane * 16, key);
float score = 0;
#pragma unroll
for (int j = 0; j < 16; ++j) score += query[j] * key[j];
score = r4d_wave_sum(score) * m.scale;
const bool higher = score > max_score;
const float weight = expf(higher ? max_score - score : score - max_score);
if (higher) {
#pragma unroll
for (int j = 0; j < 16; ++j) value[j] = value[j] * weight + key[j];
den = den * weight + 1;
max_score = score;
} else {
#pragma unroll
for (int j = 0; j < 16; ++j) value[j] += key[j] * weight;
den += weight;
}
}
if (m.splits == 1) {
#pragma unroll
for (int j = 0; j < 16; ++j)
out[(long)r * m.orr + (long)head * m.oh + lane * 16 + j] =
f32_to_bf16(den > 0 ? value[j] / den : 0);
} else {
float* dst = scratch + (((long)r * m.heads + head) * m.splits + split) * PART;
#pragma unroll
for (int j = 0; j < 16; ++j) dst[lane * 16 + j] = value[j];
if (!lane) {
dst[D] = max_score;
dst[D + 1] = den;
}
}
}
__global__ __launch_bounds__(128) void merge(const float* scratch, uint16_t* out, Meta m) {
const int lane = threadIdx.x & 31, head = blockIdx.y * 4 + (threadIdx.x >> 5), r = blockIdx.x;
if (head >= m.heads) return;
const float* src = scratch + ((long)r * m.heads + head) * m.splits * PART;
float max_score = -INFINITY;
for (int s = 0; s < m.splits; ++s)
if (src[s * PART + D + 1] > 0) max_score = fmaxf(max_score, src[s * PART + D]);
float value[16] = {}, den = 0;
for (int s = 0; s < m.splits; ++s) {
const float part_den = src[s * PART + D + 1];
if (!(part_den > 0)) continue;
const float w = expf(src[s * PART + D] - max_score);
den += part_den * w;
#pragma unroll
for (int j = 0; j < 16; ++j) value[j] += src[s * PART + lane * 16 + j] * w;
}
#pragma unroll
for (int j = 0; j < 16; ++j)
out[(long)r * m.orr + (long)head * m.oh + lane * 16 + j] =
f32_to_bf16(den > 0 ? value[j] / den : 0);
}
/* Heads are the matrix rows, so all sixteen share each latent load even when
* each query selected different pages. Splitting P into BF16 high/low parts
* preserves FP32 softmax precision without a materialized per-head KV cache.
*
* PAIR fills the sixteen rows with eight heads of two neighbouring requests
* (rows 0-7 request r, rows 8-15 request r+1). A key is loaded once when both
* requests address the same cache row at that table position, as consecutive
* queries of one sequence do; each half masks columns that are not its own,
* which carries the causal edge. Where the two tables name different rows the
* chunk runs a second pass with the second request's keys.
*
* UNION pairs by page instead of by position: past the DSA budget each request
* selects its own blocks, neighbours share most of them at shifted positions,
* and the positional pairing would run nearly every chunk twice. The walk is
* request r's table in its own order (so r sums exactly as it does unpaired at
* one split), each entry carrying where r+1's table names the same page, then
* the pages only r+1 names, in r+1's order. Every chunk runs once. */
constexpr int kUnionBlocks = 520, kUnionSlots = 1024;
__device__ __forceinline__ unsigned union_slot(int page) {
return ((unsigned)page * 2654435761u) >> 22;
}
/* STATS is its own instance: counting inside the loop costs the paired tile spilled VGPRs. */
template <bool PAIR, bool WIDE, bool UNION, bool STATS>
__global__ __launch_bounds__(128) void attend_matrix(const uint16_t* q, const uint16_t* kv,
const int* bt, const int* len, uint16_t* out,
float* scratch, Meta m) {
static_assert(PAIR || !UNION, "the union pairs two requests");
static_assert(16 * 520 * sizeof(uint16_t) >= (2 * kUnionSlots + 2 * kUnionBlocks) * sizeof(int),
"the union's hash lives in the key tile");
__shared__ __align__(16) uint16_t query[16 * 520], keys[16 * 520], prob_hi[16 * 24],
prob_lo[16 * 24];
__shared__ float score[16 * 16], maximum[16], denominator[16], alpha[16];
__shared__ long source[16];
__shared__ long own[PAIR ? 32 : 1];
__shared__ short pair_of[UNION ? kUnionBlocks : 1], only_b[UNION ? kUnionBlocks : 1];
__shared__ int union_count[UNION ? 4 : 1], union_end;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int r = PAIR ? blockIdx.x * 2 : blockIdx.x, h0 = blockIdx.y * (PAIR ? 8 : 16),
split = blockIdx.z;
int live = min(max(len[(long)r * m.lp], 0), m.blocks * m.bs), live_pair[2] = { live, 0 };
if constexpr (PAIR) {
if (r + 1 < m.rows) live_pair[1] = min(max(len[(long)(r + 1) * m.lp], 0), m.blocks * m.bs);
live = max(live_pair[0], live_pair[1]);
}
for (int j = tid; j < 16 * 512; j += 128) {
if constexpr (PAIR) {
const int row = j / 512, request = r + row / 8;
query[row * 520 + j % 512] =
request < m.rows ? q[(long)request * m.qr + (long)(h0 + row % 8) * m.qh + j % 512]
: 0;
} else
query[(j / 512) * 520 + j % 512] =
q[(long)r * m.qr + (long)(h0 + j / 512) * m.qh + j % 512];
}
if (tid < 16) {
maximum[tid] = -INFINITY;
denominator[tid] = 0;
}
v8f value[8];
#pragma unroll
for (int nt = 0; nt < 8; ++nt) value[nt] = (v8f){ 0 };
const int* const bt_a = bt + (long)r * m.bp;
const int* const bt_b = bt + (long)(r + 1) * m.bp;
int blocks_a = 0;
if constexpr (UNION) {
/* The key tile is free until the first chunk: an open-addressed page -> lowest r entry
* hash, the lowest r+1 entry naming each r entry's page, and each r+1 entry's match. */
int* const slot_page = (int*)keys;
int* const slot_first = slot_page + kUnionSlots;
int* const first_b = slot_first + kUnionSlots;
int* const match = first_b + kUnionBlocks;
blocks_a = (live_pair[0] + m.bs - 1) / m.bs;
const int blocks_b = (live_pair[1] + m.bs - 1) / m.bs;
for (int i = tid; i < kUnionSlots; i += 128) {
slot_page[i] = -1;
slot_first[i] = INT_MAX;
}
for (int i = tid; i < blocks_a; i += 128) first_b[i] = INT_MAX;
if (!tid) union_end = live_pair[0];
__syncthreads();
for (int i = tid; i < blocks_a; i += 128) {
const int page = bt_a[(long)i * m.bc];
if (page < 0 || page >= m.pages) continue;
for (unsigned at = union_slot(page);; at = (at + 1) & (kUnionSlots - 1)) {
const int seen = atomicCAS(&slot_page[at], -1, page);
if (seen == -1 || seen == page) {
atomicMin(&slot_first[at], i);
break;
}
}
}
__syncthreads();
for (int j = tid; j < blocks_b; j += 128) {
const int page = bt_b[(long)j * m.bc];
int found = -1;
if (page >= 0 && page < m.pages)
for (unsigned at = union_slot(page); slot_page[at] != -1;
at = (at + 1) & (kUnionSlots - 1))
if (slot_page[at] == page) {
found = slot_first[at];
break;
}
match[j] = found;
if (found >= 0) atomicMin(&first_b[found], j);
}
__syncthreads();
for (int i = tid; i < blocks_a; i += 128)
pair_of[i] = (short)(first_b[i] == INT_MAX ? -1 : first_b[i]);
/* r+1's own pages in its table order: slots from a ballot prefix, not an atomic, so the
* walk (and the summation order) is the same on every run. */
int appended = 0;
for (int j0 = 0; j0 < blocks_b; j0 += 128) {
const int j = j0 + tid;
bool only = false;
if (j < blocks_b) {
const int page = bt_b[(long)j * m.bc];
only = page >= 0 && page < m.pages && (match[j] < 0 || first_b[match[j]] != j);
}
const unsigned long long ballot = __ballot(only);
if (!lane) union_count[wave] = (int)__popcll(ballot);
__syncthreads();
int before = appended, total = appended;
#pragma unroll
for (int w = 0; w < 4; ++w) {
before += w < wave ? union_count[w] : 0;
total += union_count[w];
}
if (only) {
const int at = before + (int)__popcll(ballot & ((1ull << lane) - 1ull));
only_b[at] = (short)j;
const int seen = min(m.bs, live_pair[1] - j * m.bs);
atomicMax(&union_end, (blocks_a + at) * m.bs + seen);
} else if (j < blocks_b && match[j] >= 0 && first_b[match[j]] == j)
atomicMax(&union_end, match[j] * m.bs + min(m.bs, live_pair[1] - j * m.bs));
appended = total;
__syncthreads();
}
live = union_end;
}
const int begin = (int)((long)live * split / m.splits),
end = (int)((long)live * (split + 1) / m.splits);
__syncthreads();
for (int start = begin; start < end; start += 16) {
bool second = false;
if constexpr (UNION) {
if (tid < 16) {
const int token = start + tid, entry = token / m.bs, offset = token % m.bs;
long row[2] = { -1, -1 };
if (token < end) {
const int at_a = entry < blocks_a ? entry : -1;
const int at_b = entry < blocks_a ? pair_of[entry] : only_b[entry - blocks_a];
const int page = at_a >= 0 ? bt_a[(long)at_a * m.bc] : bt_b[(long)at_b * m.bc];
if (page >= 0 && page < m.pages) {
const long at = (long)page * m.kp + offset * m.kt;
if (at_a >= 0 && at_a * m.bs + offset < live_pair[0]) row[0] = at;
if (at_b >= 0 && at_b * m.bs + offset < live_pair[1]) row[1] = at;
}
}
own[tid] = row[0];
own[16 + tid] = row[1];
source[tid] = row[0] >= 0 ? row[0] : row[1];
}
__syncthreads();
} else if constexpr (PAIR) {
bool conflict = false;
if (tid < 16) {
const int token = start + tid;
long row[2];
#pragma unroll
for (int k = 0; k < 2; ++k) {
const int page = token < end && token < live_pair[k]
? bt[(long)(r + k) * m.bp + (token / m.bs) * m.bc]
: -1;
row[k] = page >= 0 && page < m.pages ? (long)page * m.kp + (token % m.bs) * m.kt
: -1;
own[k * 16 + tid] = row[k];
}
source[tid] = row[0] >= 0 ? row[0] : row[1];
conflict = row[0] >= 0 && row[1] >= 0 && row[0] != row[1];
}
second = __syncthreads_or(conflict);
if (STATS && second && !tid) {
atomicAdd(&g_mla_stats[0], 1ull);
atomicAdd(&g_mla_stats[1], 1ull);
}
} else {
if (tid < 16) {
const int token = start + tid;
const int page = token < end ? bt[(long)r * m.bp + (token / m.bs) * m.bc] : -1;
source[tid] =
page >= 0 && page < m.pages ? (long)page * m.kp + (token % m.bs) * m.kt : -1;
}
__syncthreads();
}
for (int pass = 0; pass < (second ? 2 : 1); ++pass) {
if constexpr (PAIR)
if (pass) {
if (tid < 16) {
const long first = own[tid], other = own[16 + tid];
source[tid] = first >= 0 && other >= 0 && first != other ? other : -1;
}
__syncthreads();
}
if constexpr (WIDE) {
/* Unconditional loads (an absent row reads row 0 and is zeroed after) so all
* eight are in flight before the first wait. */
uint4 part[8];
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int flat = tid + j * 128;
const long at = source[flat >> 6];
part[j] = *(const uint4*)(kv + (at >= 0 ? at : 0) + (flat & 63) * 8);
if (at < 0) part[j] = make_uint4(0, 0, 0, 0);
}
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int flat = tid + j * 128;
*(uint4*)(keys + (flat >> 6) * 520 + (flat & 63) * 8) = part[j];
}
} else {
for (int j = tid; j < 16 * 512; j += 128) {
const int token = j / 512, col = j % 512;
keys[token * 520 + col] = source[token] >= 0 ? kv[source[token] + col] : 0;
}
}
__syncthreads();
if (!wave) {
v8f dot = { 0 };
#pragma unroll
for (int d = 0; d < 512; d += 16)
dot = mma(frag(query, 520, 0, d, lane), frag(keys, 520, 0, d, lane), dot);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int head = (lane >> 4) * 8 + j, col = lane & 15;
bool visible = source[col] >= 0;
if constexpr (PAIR)
visible = visible && own[(lane >> 4) * 16 + col] == source[col];
score[head * 16 + col] = visible ? dot[j] * m.scale : -INFINITY;
}
}
__syncthreads();
if (tid < 16) {
float mx = maximum[tid];
for (int j = 0; j < 16; ++j) mx = fmaxf(mx, score[tid * 16 + j]);
const float a = isfinite(mx) ? expf(maximum[tid] - mx) : 1;
float den = denominator[tid] * a;
for (int j = 0; j < 16; ++j) {
const float p =
isfinite(score[tid * 16 + j]) ? expf(score[tid * 16 + j] - mx) : 0;
const uint16_t hi = f32_to_bf16(p);
prob_hi[tid * 24 + j] = hi;
prob_lo[tid * 24 + j] = f32_to_bf16(p - bf16_to_f32(hi));
den += p;
}
maximum[tid] = mx;
denominator[tid] = den;
alpha[tid] = a;
}
// Read before the in-place transpose overwrites keys. Query remains resident.
uint16_t held[64];
#pragma unroll
for (int j = 0; j < 64; ++j) {
const int flat = tid + j * 128;
held[j] = keys[(flat / 512) * 520 + flat % 512];
}
__syncthreads();
#pragma unroll
for (int j = 0; j < 64; ++j) {
const int flat = tid + j * 128;
keys[(flat % 512) * 16 + flat / 512] = held[j];
}
__syncthreads();
const auto hi = frag(prob_hi, 24, 0, 0, lane), lo = frag(prob_lo, 24, 0, 0, lane);
#pragma unroll
for (int nt = 0; nt < 8; ++nt) {
#pragma unroll
for (int j = 0; j < 8; ++j) value[nt][j] *= alpha[(lane >> 4) * 8 + j];
const auto v = frag(keys, 16, wave * 128 + nt * 16, 0, lane);
value[nt] = mma(hi, v, value[nt]);
value[nt] = mma(lo, v, value[nt]);
}
__syncthreads();
}
}
#pragma unroll
for (int nt = 0; nt < 8; ++nt) {
const int col = wave * 128 + nt * 16 + (lane & 15);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int row = (lane >> 4) * 8 + j, request = PAIR ? r + (lane >> 4) : r,
head = PAIR ? h0 + j : h0 + row;
if (PAIR && request >= m.rows) continue;
if (m.splits == 1) {
const float den = denominator[row];
out[(long)request * m.orr + (long)head * m.oh + col] =
f32_to_bf16(den > 0 ? value[nt][j] / den : 0);
} else
scratch[(((long)request * m.heads + head) * m.splits + split) * PART + col] =
value[nt][j];
}
}
if (m.splits > 1 && tid < 16) {
const int request = PAIR ? r + tid / 8 : r, head = PAIR ? h0 + tid % 8 : h0 + tid;
if (!PAIR || request < m.rows) {
float* dst = scratch + (((long)request * m.heads + head) * m.splits + split) * PART;
dst[D] = maximum[tid];
dst[D + 1] = denominator[tid];
}
}
if (STATS && !tid) {
const int whole = max(live_pair[0], live_pair[1]);
const int raster =
(int)((long)whole * (split + 1) / m.splits) - (int)((long)whole * split / m.splits);
const unsigned long long chunks = (unsigned long long)(end - begin + 15) / 16;
atomicAdd(&g_mla_stats[0], chunks);
atomicAdd(&g_mla_stats[2], (unsigned long long)(raster + 15) / 16);
}
}
bool env_on(const char* name) {
const char* e = std::getenv(name);
return e && *e && *e != '0';
}
void read_stats(unsigned long long (&v)[3], bool reset) {
v[0] = v[1] = v[2] = 0;
if (hipMemcpyFromSymbol(v, HIP_SYMBOL(g_mla_stats), sizeof v, 0, hipMemcpyDeviceToHost) !=
hipSuccess)
return;
const unsigned long long zero[3] = {};
if (reset)
(void)hipMemcpyToSymbol(HIP_SYMBOL(g_mla_stats), zero, sizeof zero, 0,
hipMemcpyHostToDevice);
}
/* A server has no point at which to read the counters: running totals every 1024th counted launch.
* Not at exit, where a HIP call meets a runtime that is tearing down; not inside a graph capture,
* which a blocking copy would break. */
void report_stats(RadStream stream) {
static std::atomic<unsigned> launches{ 0 };
if (++launches % 1024) return;
hipStreamCaptureStatus capture = hipStreamCaptureStatusNone;
if (hipStreamIsCapturing((hipStream_t)stream, &capture) != hipSuccess ||
capture != hipStreamCaptureStatusNone)
return;
int device = 0;
if (hipGetDevice(&device) != hipSuccess) return;
unsigned long long v[3];
read_stats(v, false);
if (!v[2]) return;
std::fprintf(stderr,
"r4d mla_attn_matrix device %d: %llu passes over %llu raster chunks, "
"%llu second passes (%.3fx)\n",
device, v[0], v[2], v[1], (double)v[0] / (double)v[2]);
}
template <bool MATRIX>
int body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 5) return RAD_E_INVAL;
const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &o = a->t[4];
if (q.dtype != RAD_BF16 || kv.dtype != RAD_BF16 || o.dtype != RAD_BF16 || bt.dtype != RAD_I32 ||
len.dtype != RAD_I32)
return RAD_E_DTYPE;
for (int i = 0; i < 5; ++i)
if (!a->t[i].data) return RAD_E_INVAL;
const long heads = r4d_geti_or(a, "heads", 0), bs = r4d_geti_or(a, "block_size", 0);
const float scale = (float)r4d_getf(a, "scale", 0);
if (r4d_geti_or(a, "latent_dim", 0) != D || heads < 1 || heads > 64 || bs < 1 || bs > 256 ||
!std::isfinite(scale) || scale <= 0 || q.rank != 3 || q.shape[0] < 1 ||
q.shape[0] > 65535 || q.shape[1] != heads || q.shape[2] != D || q.stride[2] != 1 ||
q.stride[1] < D || q.stride[0] < heads * q.stride[1] || kv.rank != 4 || kv.shape[0] < 1 ||
kv.shape[0] > INT_MAX || kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] != D ||
kv.stride[3] != 1 || kv.stride[2] < D || kv.stride[0] < bs * kv.stride[2] || bt.rank != 2 ||
bt.shape[0] != q.shape[0] || bt.shape[1] < 1 || bt.shape[1] > INT_MAX / bs ||
bt.stride[1] < 1 || bt.stride[0] < bt.shape[1] * bt.stride[1] || len.rank != 1 ||
len.shape[0] != q.shape[0] || len.stride[0] < 1 || o.rank != 3 ||
o.shape[0] != q.shape[0] || o.shape[1] != heads || o.shape[2] != D || o.stride[2] != 1 ||
o.stride[1] < D || o.stride[0] < heads * o.stride[1])
return RAD_E_SHAPE;
if (MATRIX && heads % 8) return RAD_E_UNSUPPORTED;
const bool pair = MATRIX && heads % 16;
const long jobs = MATRIX ? (pair ? (q.shape[0] + 1) / 2 * (heads / 8) : q.shape[0] * heads / 16)
: q.shape[0] * heads;
int splits = (int)std::min(MATRIX ? 64l : 16l, ((MATRIX ? 64 : 256) + jobs - 1) / jobs);
const long minimum = MATRIX ? 16 : 64;
splits = (int)std::max(1l, std::min((long)splits, (bt.shape[1] * bs + minimum - 1) / minimum));
if (!a->scratch || a->scratch_bytes < (MATRIX ? matrix_scratch_bytes : scratch_bytes))
splits = 1;
// Vectors need every cache row on a sixteen-byte boundary.
const bool wide = g_mla_matrix_form != 1 && !((uintptr_t)kv.data & 15) && !(kv.stride[0] % 8) &&
!(kv.stride[2] % 8);
/* The union's LDS lists hold a table of at most kUnionBlocks entries; a wider table takes the
* positional pairing. */
const bool by_page = bt.shape[1] <= kUnionBlocks;
const bool stats = MATRIX && env_on("RADIANCE_MLA_CONFLICT_STATS");
Meta m{ q.stride[0], q.stride[1], kv.stride[0], kv.stride[2],
bt.stride[0], bt.stride[1], len.stride[0], o.stride[0],
o.stride[1], (int)q.shape[0], (int)heads, (int)bt.shape[1],
(int)bs, (int)kv.shape[0], splits, scale };
int rc;
if constexpr (MATRIX) {
#define MATRIX_EMIT(P, W, U, S, X, Y) \
R4D_EMIT(stream, (attend_matrix<P, W, U, S>), dim3(X, Y, m.splits), dim3(128), 0, \
(const uint16_t*)q.data, (const uint16_t*)kv.data, (const int*)bt.data, \
(const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m)
#define MATRIX_LAUNCH(P, W, U, X, Y) \
(stats ? MATRIX_EMIT(P, W, U, true, X, Y) : MATRIX_EMIT(P, W, U, false, X, Y))
if (pair && by_page)
rc = wide ? MATRIX_LAUNCH(true, true, true, (m.rows + 1) / 2, m.heads / 8)
: MATRIX_LAUNCH(true, false, true, (m.rows + 1) / 2, m.heads / 8);
else if (pair)
rc = wide ? MATRIX_LAUNCH(true, true, false, (m.rows + 1) / 2, m.heads / 8)
: MATRIX_LAUNCH(true, false, false, (m.rows + 1) / 2, m.heads / 8);
else
rc = wide ? MATRIX_LAUNCH(false, true, false, m.rows, m.heads / 16)
: MATRIX_LAUNCH(false, false, false, m.rows, m.heads / 16);
#undef MATRIX_LAUNCH
#undef MATRIX_EMIT
} else
rc = R4D_EMIT(stream, attend, dim3(m.rows, (m.heads + 3) / 4, m.splits), dim3(128), 0,
(const uint16_t*)q.data, (const uint16_t*)kv.data, (const int*)bt.data,
(const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m);
if (rc == RAD_OK && splits > 1)
rc = R4D_EMIT(stream, merge, dim3(m.rows, (m.heads + 3) / 4), dim3(128), 0,
(const float*)a->scratch, (uint16_t*)o.data, m);
if (rc == RAD_OK && stats) report_stats(stream);
return rc;
}
}
extern "C" int r4d_rad_mla_attn(const RadArgs* a, RadStream stream) {
return body<false>(a, stream);
}
extern "C" int r4d_rad_mla_attn_matrix(const RadArgs* a, RadStream stream) {
return body<true>(a, stream);
}
extern "C" int r4d_rad_mla_project(const RadArgs* a, RadStream stream) {
return project_body(a, stream);
}
extern "C" int64_t r4d_rad_mla_attn_scratch(const RadArgs*) { return scratch_bytes; }
extern "C" int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*) { return matrix_scratch_bytes; }
extern "C" void r4d_mla_matrix_pin_form(int form) { g_mla_matrix_form = form; }
/* Test hook: the current device's RADIANCE_MLA_CONFLICT_STATS counters since the last call (passes,
* second passes, raster chunks), then zeroed. */
extern "C" void r4d_mla_matrix_stats(unsigned long long* out) {
unsigned long long v[3];
(void)hipDeviceSynchronize();
read_stats(v, true);
if (out) std::memcpy(out, v, sizeof v);
}
+518 -44
View File
@@ -28,6 +28,7 @@
#include "r4d_common.h"
#include "rad_yarn.h"
#include "r4d_fp8_wmma.h"
#include "r4d_chain.h"
#include <algorithm>
#include <cmath>
@@ -61,7 +62,9 @@ __device__ __forceinline__ float block_sum(float v, float* lds) {
// ids stay global, a rank subtracts the offset, and another rank's token takes the zero-row path.
// Summing the ranks reconstructs x. `mult` scales every entry with one rounding (Gemma's
// sqrt(hidden)); 1 is a plain copy.
__global__ __launch_bounds__(kThreads) void embed_lookup_kernel(
//
// The body; embed_lookup_kernel and its chained form wrap it (its blocks return early).
__device__ __forceinline__ void embed_lookup_body(
const int32_t* __restrict__ tok, const uint16_t* __restrict__ wte, uint16_t* __restrict__ x,
uint32_t n_embd, int32_t n_vocab, int32_t vocab_off, uint32_t x_ld, float mult) {
const uint32_t m = blockIdx.x;
@@ -79,6 +82,19 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_kernel(
for (uint32_t i = threadIdx.x; i < n_embd; i += kThreads) dst[i] = f32_to_bf16(bf16_to_f32(src[i]) * mult);
}
#define R4D_EL_PARAMS const int32_t* __restrict__ tok, const uint16_t* __restrict__ wte, \
uint16_t* __restrict__ x, uint32_t n_embd, int32_t n_vocab, int32_t vocab_off, uint32_t x_ld, \
float mult
__global__ __launch_bounds__(kThreads) void embed_lookup_kernel(R4D_EL_PARAMS) {
embed_lookup_body(tok, wte, x, n_embd, n_vocab, vocab_off, x_ld, mult);
}
__global__ __launch_bounds__(kThreads) void r4dchain_embed_lookup(R4D_EL_PARAMS) {
r4d_chain_wait();
embed_lookup_body(tok, wte, x, n_embd, n_vocab, vocab_off, x_ld, mult);
r4d_chain_done();
}
#undef R4D_EL_PARAMS
// ---------------------------------------------------------------------------- embed_lookup_q
// ref_embed_lookup_q. x[m] = bf16(wte[id] * scale), from a table of E4M3 codes with one scale (Q)
// or plain bf16; an absent scale is one. This is the n-gram table's gather
@@ -137,7 +153,9 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_q_kernel(
// ref_gather_rows. Like the embedding gather, with the same negative-index rule, but the source
// row pitch is the caller's: it gathers from padded activation buffers (one logits row per
// sequence out of a prefill chunk).
__global__ __launch_bounds__(kThreads) void gather_rows_kernel(
//
// The body; gather_rows_kernel and its chained form wrap it (its blocks return early).
__device__ __forceinline__ void gather_rows_body(
const uint16_t* __restrict__ x, const int32_t* __restrict__ idx, uint16_t* __restrict__ y,
uint32_t n, int32_t src_rows, uint32_t x_ld, uint32_t y_ld) {
const uint32_t m = blockIdx.x;
@@ -150,6 +168,17 @@ __global__ __launch_bounds__(kThreads) void gather_rows_kernel(
const uint16_t* __restrict__ src = x + (size_t)r * x_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads) dst[i] = src[i];
}
#define R4D_GR_PARAMS const uint16_t* __restrict__ x, const int32_t* __restrict__ idx, \
uint16_t* __restrict__ y, uint32_t n, int32_t src_rows, uint32_t x_ld, uint32_t y_ld
__global__ __launch_bounds__(kThreads) void gather_rows_kernel(R4D_GR_PARAMS) {
gather_rows_body(x, idx, y, n, src_rows, x_ld, y_ld);
}
__global__ __launch_bounds__(kThreads) void r4dchain_gather_rows(R4D_GR_PARAMS) {
r4d_chain_wait();
gather_rows_body(x, idx, y, n, src_rows, x_ld, y_ld);
r4d_chain_done();
}
#undef R4D_GR_PARAMS
// ---------------------------------------------------------------- byte row gather / scatter
//
@@ -206,12 +235,14 @@ __global__ __launch_bounds__(kThreads) void scatter_rows_u8_kernel(
__device__ __forceinline__ float act_f32(uint16_t v) { return bf16_to_f32(v); }
__device__ __forceinline__ float act_f32(float v) { return v; }
// The body; rmsnorm_kernel and its chained form wrap it below (the cliff rows return early).
template <bool WF32, uint32_t THR, typename TX = uint16_t>
__global__ __launch_bounds__(THR) void rmsnorm_kernel(
__device__ __forceinline__ void rmsnorm_body(
const TX* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y,
uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t y_ld) {
uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t y_ld, uint32_t M) {
__shared__ float lds[THR / kWave];
const uint32_t m = blockIdx.x;
if (m >= M) return; // a row the launch added past the full-card cliff (r4d_cliff_rows)
const TX* __restrict__ xr = x + (size_t)m * x_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
@@ -225,15 +256,78 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel(
}
}
#define R4D_RN_PARAMS const TX* __restrict__ x, const void* __restrict__ w, \
uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, \
uint32_t y_ld, uint32_t M
template <bool WF32, uint32_t THR, typename TX = uint16_t>
__global__ __launch_bounds__(THR) void rmsnorm_kernel(R4D_RN_PARAMS) {
rmsnorm_body<WF32, THR, TX>(x, w, y, n, eps, wadd, mult, x_ld, y_ld, M);
}
template <bool WF32, uint32_t THR, typename TX = uint16_t>
__global__ __launch_bounds__(THR) void r4dchain_rmsnorm(R4D_RN_PARAMS) {
r4d_chain_wait();
rmsnorm_body<WF32, THR, TX>(x, w, y, n, eps, wadd, mult, x_ld, y_ld, M);
r4d_chain_done();
}
#undef R4D_RN_PARAMS
// ---------------------------------------------------------------------------- add_rmsnorm
// x = x + a, rounded as `add` rounds it, then y = rmsnorm(x) over the x just written, computed as
// rmsnorm_kernel computes it: the same width (r4d_act_threads), the same columns a thread, the same
// block_sum. A thread re-reads only the x it wrote itself, so no barrier separates the passes.
// Byte-identical to `add` followed by `rmsnorm`, on x and on y.
template <bool WF32, uint32_t THR>
__device__ __forceinline__ void add_rmsnorm_body(
uint16_t* __restrict__ x, const uint16_t* __restrict__ a, const void* __restrict__ w,
uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, float mult, uint32_t x_ld,
uint32_t a_ld, uint32_t y_ld, uint32_t M) {
__shared__ float lds[THR / kWave];
const uint32_t m = blockIdx.x;
if (m >= M) return; // a row the launch added past the full-card cliff (r4d_cliff_rows)
uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
const uint16_t* __restrict__ ar = a + (size_t)m * a_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
float ss = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const uint16_t h = f32_to_bf16(bf16_to_f32(xr[i]) + bf16_to_f32(ar[i]));
xr[i] = h;
const float v = bf16_to_f32(h);
ss += v * v;
}
ss = block_sum<THR / kWave>(ss, lds);
const float s = rsqrtf(ss / (float)n + eps);
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const float g = !w ? 1.0f : WF32 ? ((const float*)w)[i] : bf16_to_f32(((const uint16_t*)w)[i]);
yr[i] = f32_to_bf16(bf16_to_f32(xr[i]) * s * (g + wadd) * mult);
}
}
#define R4D_ARN_PARAMS uint16_t* __restrict__ x, const uint16_t* __restrict__ a, \
const void* __restrict__ w, uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, \
float mult, uint32_t x_ld, uint32_t a_ld, uint32_t y_ld, uint32_t M
template <bool WF32, uint32_t THR>
__global__ __launch_bounds__(THR) void add_rmsnorm_kernel(R4D_ARN_PARAMS) {
add_rmsnorm_body<WF32, THR>(x, a, w, y, n, eps, wadd, mult, x_ld, a_ld, y_ld, M);
}
template <bool WF32, uint32_t THR>
__global__ __launch_bounds__(THR) void r4dchain_add_rmsnorm(R4D_ARN_PARAMS) {
r4d_chain_wait();
add_rmsnorm_body<WF32, THR>(x, a, w, y, n, eps, wadd, mult, x_ld, a_ld, y_ld, M);
r4d_chain_done();
}
#undef R4D_ARN_PARAMS
// ---------------------------------------------------------------------------- rmsnorm_p
// ref_rmsnorm_p: y = x * rsqrt(mean(x^2) + eps), rmsnorm with no gain. Gemma's attention applies
// it to V (llama.cpp's ggml_rms_norm(V, eps)), which has no checkpoint gain. Accumulates exactly as
// rmsnorm does, so the two agree bit for bit where rmsnorm's gain is one.
__global__ __launch_bounds__(kThreads) void rmsnorm_p_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
uint32_t n, float eps, uint32_t x_ld, uint32_t y_ld) {
uint32_t n, float eps, uint32_t x_ld, uint32_t y_ld, uint32_t M) {
__shared__ float lds[kThreads / kWave];
const uint32_t m = blockIdx.x;
if (m >= M) return; // a row the launch added past the full-card cliff (r4d_cliff_rows)
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
float ss = 0.0f;
@@ -354,6 +448,30 @@ __global__ __launch_bounds__(kThreads) void logit_softcap_kernel_f32(
yr[i] = cap * tanhf(xr[i] / cap);
}
/* The chained forms of both legs (RadKernelChainFn): the same loop between the wait and the add. */
__global__ __launch_bounds__(kThreads) void r4dchain_logit_softcap(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) {
r4d_chain_wait();
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = blockIdx.y * kThreads + threadIdx.x; i < n; i += gridDim.y * kThreads)
yr[i] = f32_to_bf16(cap * tanhf(bf16_to_f32(xr[i]) / cap));
r4d_chain_done();
}
__global__ __launch_bounds__(kThreads) void r4dchain_logit_softcap_f32(
const float* __restrict__ x, float* __restrict__ y,
uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) {
r4d_chain_wait();
const uint32_t m = blockIdx.x;
const float* __restrict__ xr = x + (size_t)m * x_ld;
float* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = blockIdx.y * kThreads + threadIdx.x; i < n; i += gridDim.y * kThreads)
yr[i] = cap * tanhf(xr[i] / cap);
r4d_chain_done();
}
/* Blocks per softcap row: eight elements a thread, at most 64 blocks. */
static uint32_t softcap_blocks_per_row(int n) {
uint32_t b = (uint32_t)((n + kThreads * 8 - 1) / (kThreads * 8));
@@ -570,6 +688,86 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8_kernel(
}
}
// The fp8_v4 store: K as kv_store_fp8 writes it, V as int4 in groups of 32 with an f16 scale
// (absmax / 7). Four columns a thread as above, so a group of 32 is 8 lanes; head_dim is a multiple
// of 32, so a group never straddles two heads. A token's row is `row` bytes. K6 is the k6_v4 store:
// K as int6 in groups of 32 (absmax / 31) in the row layout of abi/rad_builder.h's RAD_KVQ_K6V4, V
// as above after it.
template <int K6>
__global__ __launch_bounds__(kThreads) void kv_store_fp8v4_kernel(
const uint16_t* __restrict__ k, const uint16_t* __restrict__ v,
const int32_t* __restrict__ slot, uint8_t* __restrict__ kv,
uint32_t head_dim, uint32_t kv_heads, uint32_t block_size, uint32_t n_blocks,
uint32_t k_ld, uint32_t v_ld, float k_inv, float v_inv, uint32_t row) {
const uint32_t t = blockIdx.x;
const int32_t s = slot[t];
if (s < 0 || (uint32_t)s / block_size >= n_blocks) return;
const uint32_t blk = (uint32_t)s / block_size, off = (uint32_t)s % block_size;
const size_t slot_base = ((size_t)blk * kv_heads * block_size + (size_t)off) * row;
const size_t head_step = (size_t)block_size * row;
for (uint32_t j = threadIdx.x * 4u; j < kv_heads * head_dim; j += kThreads * 4u) {
const uint32_t h = j / head_dim, d = j % head_dim;
uint8_t* __restrict__ c = kv + slot_base + (size_t)h * head_step;
float kf[4], vf[4];
#pragma unroll
for (int e = 0; e < 4; ++e) {
kf[e] = bf16_to_f32(k[(size_t)t * k_ld + j + (uint32_t)e]) * k_inv;
vf[e] = bf16_to_f32(v[(size_t)t * v_ld + j + (uint32_t)e]) * v_inv;
}
const uint32_t voff = K6 ? head_dim * 3 / 4 : head_dim;
const uint32_t vsoff = K6 ? head_dim * 21 / 16 : head_dim * 3 / 2;
if constexpr (K6) {
// A group of 32 is 8 lanes; its scale absmax / 31 in f16, codes 6-bit two's complement.
float kmax = fmaxf(fmaxf(fabsf(kf[0]), fabsf(kf[1])), fmaxf(fabsf(kf[2]), fabsf(kf[3])));
for (int m = 4; m >= 1; m >>= 1) kmax = fmaxf(kmax, __shfl_xor(kmax, m, 32));
// Clamped so 31 times it stays an f16 (65504): a group gone inf
// or NaN decodes finite, as the E4M3 form's clamp to 448 does.
const __fp16 k16 = (__fp16)fminf(kmax / 31.0f, 2112.0f);
const float ksc = (float)k16;
uint32_t q[4];
#pragma unroll
for (int e = 0; e < 4; ++e) {
const float r = ksc > 0.0f ? rintf(kf[e] / ksc) : 0.0f;
q[e] = (uint32_t)((int)fminf(fmaxf(r, -31.0f), 31.0f)) & 0x3Fu;
}
*(uint16_t*)(c + d / 2) = (uint16_t)((q[0] & 15u) | ((q[1] & 15u) << 4) |
((q[2] & 15u) << 8) | ((q[3] & 15u) << 12));
// The high bits of dims x..x+3 of a 16-dim chunk (x = d % 16 in 0, 4, 8, 12): bits
// 0-3 of bytes x/2 and x/2+1 for x < 8, bits 4-7 of bytes (x-8)/2 and (x-8)/2+1 for
// x >= 8. The lane two over holds the dims eight on, so the lower lane writes both.
const uint32_t hb = ((q[0] >> 4) | ((q[1] >> 4) << 2)) | ((((q[2] >> 4) | ((q[3] >> 4) << 2))) << 8);
const uint32_t up = (uint32_t)__shfl_xor((int)hb, 2, 32);
if ((d & 15u) < 8u)
*(uint16_t*)(c + head_dim / 2 + (d / 16) * 4 + (d & 7u) / 2) = (uint16_t)(hb | (up << 4));
if ((d & 31u) == 0)
*(uint16_t*)(c + head_dim * 5 / 4 + (d / 32) * 2) = __builtin_bit_cast(uint16_t, k16);
} else {
int pk = 0;
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf[0], -448.0f), 448.0f),
fminf(fmaxf(kf[1], -448.0f), 448.0f), pk, false);
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf[2], -448.0f), 448.0f),
fminf(fmaxf(kf[3], -448.0f), 448.0f), pk, true);
*(uint32_t*)(c + d) = (uint32_t)pk;
}
float amax = fmaxf(fmaxf(fabsf(vf[0]), fabsf(vf[1])), fmaxf(fabsf(vf[2]), fabsf(vf[3])));
for (int m = 4; m >= 1; m >>= 1) amax = fmaxf(amax, __shfl_xor(amax, m, 32));
// Clamped so 7 times it stays an f16: see the K scale above.
const __fp16 s16 = (__fp16)fminf(amax / 7.0f, 8188.0f);
const float sc = (float)s16;
uint32_t q[4];
#pragma unroll
for (int e = 0; e < 4; ++e) {
const float r = sc > 0.0f ? rintf(vf[e] / sc) : 0.0f;
q[e] = (uint32_t)((int)fminf(fmaxf(r, -7.0f), 7.0f)) & 0xFu;
}
*(uint16_t*)(c + voff + d / 2) = (uint16_t)(q[0] | (q[1] << 4) | (q[2] << 8) | (q[3] << 12));
if ((d & 31u) == 0)
*(uint16_t*)(c + vsoff + (d / 32) * 2) = __builtin_bit_cast(uint16_t, s16);
}
}
} // namespace
// ================================================================================ entry points
@@ -579,11 +777,13 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8_kernel(
/* The plugin entry and r4d.h's long-stream entry share this body. */
static int embed_lookup_bf16_emit(long tok, long wte, long x, int M, int n_embd, int n_vocab,
int vocab_off, int x_ld, float mult, RadStream stream) {
int vocab_off, int x_ld, float mult, RadStream stream,
bool chain = false) {
if (!tok || !wte || !x) return -1;
if (M <= 0 || n_embd <= 0 || n_vocab <= 0 || vocab_off < 0) return -2;
if (!x_ld) x_ld = n_embd;
return R4D_EMIT(stream, embed_lookup_kernel, dim3((uint32_t)M), dim3(kThreads), 0,
return R4D_EMIT(stream, (chain ? r4dchain_embed_lookup : embed_lookup_kernel),
dim3((uint32_t)M), dim3(kThreads), 0,
(const int32_t*)tok, (const uint16_t*)wte,
(uint16_t*)x, (uint32_t)n_embd, (int32_t)n_vocab, (int32_t)vocab_off,
(uint32_t)x_ld, mult) == RAD_OK ? 0 : -4;
@@ -622,12 +822,13 @@ extern "C" int r4d_embed_lookup_bf16_scaled(long tok, long wte, long x, int M, i
}
static int gather_rows_bf16_emit(long x, long idx, long y, int M, int n, int src_rows,
int x_ld, int y_ld, RadStream stream) {
int x_ld, int y_ld, RadStream stream, bool chain = false) {
if (!x || !idx || !y) return -1;
if (M <= 0 || n <= 0 || src_rows <= 0) return -2;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
return R4D_EMIT(stream, gather_rows_kernel, dim3((uint32_t)M), dim3(kThreads), 0,
return R4D_EMIT(stream, (chain ? r4dchain_gather_rows : gather_rows_kernel),
dim3((uint32_t)M), dim3(kThreads), 0,
(const uint16_t*)x, (const int32_t*)idx,
(uint16_t*)y, (uint32_t)n, (int32_t)src_rows,
(uint32_t)x_ld, (uint32_t)y_ld) == RAD_OK ? 0 : -4;
@@ -680,8 +881,18 @@ extern "C" int r4d_scatter_rows_u8(long v, long idx, long x, int M, int n, int d
// `w_f32` selects an f32 or bf16 gain; a null `w` is a gain of one. `mult` scales the row before
// its single rounding.
/* `chain`: the chained form, at decode heights (r4d_rad_rmsnorm passes the row's resolved
* parameter; every other caller none). */
static int rmsnorm_mult_launch(long x, long w, long y, int M, int n, float eps, float wadd,
float mult, int w_f32, int x_ld, int y_ld, long stream,
bool chain);
extern "C" int r4d_rmsnorm_mult_bf16(long x, long w, long y, int M, int n, float eps, float wadd,
float mult, int w_f32, int x_ld, int y_ld, long stream) {
return rmsnorm_mult_launch(x, w, y, M, n, eps, wadd, mult, w_f32, x_ld, y_ld, stream, false);
}
static int rmsnorm_mult_launch(long x, long w, long y, int M, int n, float eps, float wadd,
float mult, int w_f32, int x_ld, int y_ld, long stream,
bool chain) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!x_ld) x_ld = n;
@@ -691,10 +902,14 @@ extern "C" int r4d_rmsnorm_mult_bf16(long x, long w, long y, int M, int n, float
// columns a thread folds into the sum of squares and the fused kernel must be byte-identical
// to this one followed by the quantiser.
const int thr = r4d_act_threads(M, n);
// A drafter's 256-row head norm at 256 threads is exactly a full card; step past the cliff.
const bool ch = chain && M <= 64;
#define R4D_RN_T(wf, T) \
hipLaunchKernelGGL((rmsnorm_kernel<wf, T>), dim3((uint32_t)M), dim3(T), 0, \
hipLaunchKernelGGL((ch ? r4dchain_rmsnorm<wf, T> : rmsnorm_kernel<wf, T>), \
dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), \
dim3(T), 0, \
(hipStream_t)stream, (const uint16_t*)x, (const void*)w, (uint16_t*)y, \
(uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, (uint32_t)y_ld)
(uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M)
#define R4D_RN(wf) \
do { if (thr == 1024) R4D_RN_T(wf, 1024); \
else if (thr == 512) R4D_RN_T(wf, 512); \
@@ -720,9 +935,10 @@ extern "C" int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps,
if (M <= 0 || n <= 0) return -2;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(rmsnorm_p_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
hipLaunchKernelGGL(rmsnorm_p_kernel, dim3(r4d_cliff_rows((uint32_t)M, 1, kThreads / kWave)),
dim3(kThreads), 0, (hipStream_t)stream,
(const uint16_t*)x, (uint16_t*)y, (uint32_t)n, eps,
(uint32_t)x_ld, (uint32_t)y_ld);
(uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -757,9 +973,11 @@ extern "C" int r4d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld
// y[m, i] = v over an [M, n] extent with a row pitch, for a rank with nothing to compute whose
// downstream reader (an all-reduce, a residual) still needs a defined buffer. A memset cannot
// handle the pitch or a two-byte value.
__global__ __launch_bounds__(kThreads) void fill_kernel(uint16_t* __restrict__ y, uint32_t n,
uint32_t y_ld, uint16_t v) {
uint16_t* __restrict__ yr = y + (size_t)blockIdx.x * y_ld;
// T is the element's bits: uint16_t for bf16, uint32_t for f32.
template<typename T>
__global__ __launch_bounds__(kThreads) void fill_kernel(T* __restrict__ y, uint32_t n,
uint32_t y_ld, T v) {
T* __restrict__ yr = y + (size_t)blockIdx.x * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads) yr[i] = v;
}
@@ -774,19 +992,33 @@ extern "C" int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long s
if (!y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(fill_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(uint16_t*)y, (uint32_t)n, (uint32_t)y_ld, f32_to_bf16_host(value));
hipLaunchKernelGGL(fill_kernel<uint16_t>, dim3((uint32_t)M), dim3(kThreads), 0,
(hipStream_t)stream, (uint16_t*)y, (uint32_t)n, (uint32_t)y_ld,
f32_to_bf16_host(value));
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap,
int x_ld, int y_ld, long stream) {
extern "C" int r4d_fill_f32(long y, int M, int n, int y_ld, float value, long stream) {
if (!y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!y_ld) y_ld = n;
uint32_t bits;
std::memcpy(&bits, &value, sizeof bits);
hipLaunchKernelGGL(fill_kernel<uint32_t>, dim3((uint32_t)M), dim3(kThreads), 0,
(hipStream_t)stream, (uint32_t*)y, (uint32_t)n, (uint32_t)y_ld, bits);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* `chain`: the chained form (the plugin entry, where the row resolved with `chain`). */
static int logit_softcap_bf16_emit(long x, long y, int M, int n, float cap,
int x_ld, int y_ld, long stream, bool chain) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!(cap > 0.0f)) return -3;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(logit_softcap_kernel, dim3((uint32_t)M, softcap_blocks_per_row(n)),
hipLaunchKernelGGL((chain ? r4dchain_logit_softcap : logit_softcap_kernel),
dim3((uint32_t)M, softcap_blocks_per_row(n)),
dim3(kThreads), 0,
(hipStream_t)stream,
(const uint16_t*)x, (uint16_t*)y, (uint32_t)n, cap,
@@ -794,14 +1026,20 @@ extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap,
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap,
int x_ld, int y_ld, long stream) {
extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap,
int x_ld, int y_ld, long stream) {
return logit_softcap_bf16_emit(x, y, M, n, cap, x_ld, y_ld, stream, false);
}
static int logit_softcap_f32_emit(long x, long y, int M, int n, float cap,
int x_ld, int y_ld, long stream, bool chain) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!(cap > 0.0f)) return -3;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(logit_softcap_kernel_f32, dim3((uint32_t)M, softcap_blocks_per_row(n)),
hipLaunchKernelGGL((chain ? r4dchain_logit_softcap_f32 : logit_softcap_kernel_f32),
dim3((uint32_t)M, softcap_blocks_per_row(n)),
dim3(kThreads), 0,
(hipStream_t)stream,
(const float*)x, (float*)y, (uint32_t)n, cap,
@@ -809,6 +1047,11 @@ extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap,
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap,
int x_ld, int y_ld, long stream) {
return logit_softcap_f32_emit(x, y, M, n, cap, x_ld, y_ld, stream, false);
}
extern "C" int r4d_scale_bf16(long x, long s, uint32_t s_dt, long y, int M, int n,
int x_ld, int y_ld, long stream) {
if (!x || !s || !y) return -1;
@@ -997,6 +1240,99 @@ __global__ __launch_bounds__(kThreads) void logits_gemm_kernel(
}
}
// The same projection with each wave taking four whole vocabulary columns, for a head where the
// 256-thread block per column is the cost: at n_embd 4096 a thread of that kernel makes two 16-byte
// weight loads before the block-wide sum, and each row widens both operands for its own product.
//
// BYTE-IDENTICAL to logits_gemm_kernel: lane l of a wave runs, in turn, threads 32q + l of that
// kernel's block for q = 0..7 -- the same 8-wide k chunks, each summed from 0 and added to the
// thread's accumulator in k order -- reduces each q with the same lane butterfly, and adds the
// eight wave sums in q order from 0. Only where the threads run changes, and bf16 widens to f32
// exactly, so each weight is widened once for every row and each activation once for every
// column. A q's loads (four columns and up to kLgRows rows, two chunks each) are issued before its
// arithmetic.
constexpr uint32_t kLgCols = 4, kLgKi = 2; // columns a wave; 2048-wide chunks of n_embd 4096
__global__ __launch_bounds__(kThreads) void logits_gemm_cols_kernel(
const uint16_t* __restrict__ a, const uint16_t* __restrict__ w, float* __restrict__ c,
uint32_t M, uint32_t N, uint32_t a_ld, uint32_t c_ld) {
constexpr uint32_t C = kLgCols, KI = kLgKi, K = KI * kThreads * kLgVec, V = KI * kLgVec;
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
const uint32_t j0 = (blockIdx.x * kWaves + wave) * C;
if (j0 >= N) return;
for (uint32_t r0 = 0; r0 < M; r0 += kLgRows) {
const uint32_t nr = (M - r0) < kLgRows ? (M - r0) : kLgRows;
float v[C][kLgRows];
#pragma unroll
for (uint32_t x = 0; x < C; ++x)
#pragma unroll
for (uint32_t i = 0; i < kLgRows; ++i) v[x][i] = 0.0f;
#pragma unroll 1
for (uint32_t q = 0; q < kWaves; ++q) {
const uint32_t k0 = (q * kWave + lane) * kLgVec;
uint4 wv[C][KI], av[kLgRows][KI];
#pragma unroll
for (uint32_t x = 0; x < C; ++x) {
const uint16_t* wr = w + (size_t)(j0 + x < N ? j0 + x : N - 1) * K + k0;
#pragma unroll
for (uint32_t t = 0; t < KI; ++t)
wv[x][t] = *(const uint4*)(wr + t * kThreads * kLgVec);
}
#pragma unroll
for (uint32_t i = 0; i < kLgRows; ++i) {
if (i >= nr) break;
const uint16_t* ar = a + (size_t)(r0 + i) * a_ld + k0;
#pragma unroll
for (uint32_t t = 0; t < KI; ++t)
av[i][t] = *(const uint4*)(ar + t * kThreads * kLgVec);
}
float wf[C][V];
#pragma unroll
for (uint32_t x = 0; x < C; ++x)
#pragma unroll
for (uint32_t t = 0; t < KI; ++t) {
const uint32_t ww[4] = { wv[x][t].x, wv[x][t].y, wv[x][t].z, wv[x][t].w };
#pragma unroll
for (uint32_t p = 0; p < kLgVec; ++p)
wf[x][t * kLgVec + p] = bf16_to_f32((uint16_t)(ww[p / 2] >> (16 * (p & 1))));
}
#pragma unroll
for (uint32_t i = 0; i < kLgRows; ++i) {
if (i >= nr) break;
float af[V];
#pragma unroll
for (uint32_t t = 0; t < KI; ++t) {
const uint32_t aw[4] = { av[i][t].x, av[i][t].y, av[i][t].z, av[i][t].w };
#pragma unroll
for (uint32_t p = 0; p < kLgVec; ++p)
af[t * kLgVec + p] = bf16_to_f32((uint16_t)(aw[p / 2] >> (16 * (p & 1))));
}
#pragma unroll
for (uint32_t x = 0; x < C; ++x) {
float acc = 0.0f;
#pragma unroll
for (uint32_t t = 0; t < KI; ++t) {
float s = 0.0f;
#pragma unroll
for (uint32_t p = 0; p < kLgVec; ++p)
s += af[t * kLgVec + p] * wf[x][t * kLgVec + p];
acc += s;
}
v[x][i] += r4d_wave_sum(acc);
}
}
}
#pragma unroll
for (uint32_t x = 0; x < C; ++x) {
float out = 0.0f;
#pragma unroll
for (uint32_t i = 0; i < kLgRows; ++i)
if (i == lane) out = v[x][i];
if (lane < nr && j0 + x < N) c[(size_t)(r0 + lane) * c_ld + j0 + x] = out;
}
}
}
} // namespace
// a [M][K] bf16, `a_ld` elements a row (0 = K)
@@ -1015,6 +1351,21 @@ extern "C" int r4d_logits_gemm_bf16(long a, long w, long c, int M, int K, int N,
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// The column form; n_embd must be 4096 and an activation row whole 16 bytes.
extern "C" int r4d_logits_gemm_bf16_cols(long a, long w, long c, int M, int K, int N, int a_ld,
int c_ld, long stream) {
if (!a || !w || !c) return -1;
if (M <= 0 || N <= 0) return -2;
if (!a_ld) a_ld = K;
if (!c_ld) c_ld = N;
if (K != (int)(kLgKi * kThreads * kLgVec) || a_ld % (int)kLgVec) return -3;
const uint32_t per = kWaves * kLgCols;
hipLaunchKernelGGL(logits_gemm_cols_kernel, dim3(((uint32_t)N + per - 1) / per), dim3(kThreads),
0, (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)w, (float*)c,
(uint32_t)M, (uint32_t)N, (uint32_t)a_ld, (uint32_t)c_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// ============================================================== the plugin ABI entry points
//
// Unpacking RadArgs and deriving row pitches belongs to the kernel library (libr4d/r4d_args.h).
@@ -1068,9 +1419,11 @@ extern "C" int r4d_rad_embed_lookup(const RadArgs* a, RadStream stream) {
if (M <= 0 || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE);
const float mult = (float)r4d_getf(a, "mult", 1.0);
/* The chained form at decode heights, where the row resolved with `chain`. */
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
return embed_lookup_bf16_emit(r4d_addr(tok), r4d_addr(wte), r4d_addr(x),
(int)M, (int)n_embd, (int)n_vocab, (int)voff, (int)x_ld,
mult, stream) == 0 ? RAD_OK : RAD_E_DEVICE;
mult, stream, ch) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ embed_lookup_q */
@@ -1133,9 +1486,10 @@ extern "C" int r4d_rad_gather_rows(const RadArgs* a, RadStream stream) {
if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || src <= 0 || r4d_numel(idx) < M) return R4D_NO(RAD_E_SHAPE);
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
return gather_rows_bf16_emit(r4d_addr(x), r4d_addr(idx), r4d_addr(y),
(int)M, (int)n, (int)src, (int)x_ld, (int)y_ld,
stream) == 0 ? RAD_OK : RAD_E_DEVICE;
stream, ch) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ byte rows */
@@ -1226,8 +1580,10 @@ extern "C" int r4d_rad_cast(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, CS_X);
const RadTensor* y = r4d_opt(a, CS_Y);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(x));
R4D_NEED(dt_bf16(y));
/* A copy at the dtype both sides share: bf16, or f32 (a latent kept aside and put back). */
if (x->dtype != y->dtype || (x->dtype != RAD_BF16 && x->dtype != RAD_F32))
return R4D_NO(RAD_E_DTYPE);
const long long es = x->dtype == RAD_F32 ? 4 : 2;
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
@@ -1239,7 +1595,7 @@ extern "C" int r4d_rad_cast(const RadArgs* a, RadStream s) {
* while the source holds the live rows, so the source need only have at least as many. */
if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE);
return r4d_p2p_copy2d(r4d_addr(y), r4d_addr(x), y_ld * 2, x_ld * 2, n * 2, M,
return r4d_p2p_copy2d(r4d_addr(y), r4d_addr(x), y_ld * es, x_ld * es, n * es, M,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
}
@@ -1255,7 +1611,7 @@ static int rmsnorm_x_f32(const float* x, const void* w, uint16_t* y, int M, int
#define R4D_RNF_T(wf, T) \
hipLaunchKernelGGL((rmsnorm_kernel<wf, T, float>), dim3((uint32_t)M), dim3(T), 0, \
(hipStream_t)stream, x, w, y, (uint32_t)n, eps, wadd, mult, \
(uint32_t)x_ld, (uint32_t)y_ld)
(uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M)
#define R4D_RNF(wf) \
do { if (thr == 1024) R4D_RNF_T(wf, 1024); \
else if (thr == 512) R4D_RNF_T(wf, 512); \
@@ -1288,10 +1644,11 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
const long long y_ld = r4d_rows_pitch(y, n, &My);
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
return r4d_rmsnorm_mult_bf16(r4d_addr(x), 0, r4d_addr(y), (int)M, (int)n,
return rmsnorm_mult_launch(r4d_addr(x), 0, r4d_addr(y), (int)M, (int)n,
(float)r4d_getf(a, "eps", 1e-6), 0.0f,
(float)r4d_getf(a, "mult", 1.0), 0, (int)x_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
(long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0) == 0
? RAD_OK : RAD_E_DEVICE;
}
if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE);
/* The gain may be f32 (as plugins declare norm gains) or bf16; its width is read off the
@@ -1313,10 +1670,65 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
return rmsnorm_x_f32((const float*)x->data, w->data, (uint16_t*)y->data, (int)M, (int)n,
eps, wadd, (float)r4d_getf(a, "mult", 1.0), w_f32, (int)x_ld,
(int)y_ld, s);
return r4d_rmsnorm_mult_bf16(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n, eps, wadd,
return rmsnorm_mult_launch(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n, eps, wadd,
(float)r4d_getf(a, "mult", 1.0),
w_f32, (int)x_ld, (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK
: RAD_E_DEVICE;
w_f32, (int)x_ld, (int)y_ld, (long)(uintptr_t)s,
r4d_geti_or(a, "chain", 0) != 0) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ add_rmsnorm */
enum { AN_X = 0, AN_A, AN_W, AN_Y };
extern "C" int r4d_rad_add_rmsnorm(const RadArgs* a, RadStream s) {
int emit_rc = RAD_OK;
const RadTensor* x = r4d_opt(a, AN_X);
const RadTensor* ad = r4d_opt(a, AN_A);
const RadTensor* w = r4d_opt(a, AN_W);
const RadTensor* y = r4d_opt(a, AN_Y);
if (!x || !ad || !w || !y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(x));
R4D_NEED(dt_bf16(ad));
R4D_NEED(dt_bf16(y));
if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE);
if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
const bool w_f32 = w->dtype == RAD_F32;
const long long n = r4d_geti_or(a, "n", r4d_dim(w, (int)w->rank - 1));
if (n <= 0 || r4d_numel(w) < n) return R4D_NO(RAD_E_SHAPE);
long long M = 0, Ma = 0, My = 0;
const long long x_ld = r4d_rows_pitch(x, n, &M);
const long long a_ld = r4d_rows_pitch(ad, n, &Ma);
const long long y_ld = r4d_rows_pitch(y, n, &My);
if (x_ld < 0 || a_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || Ma < M || My < M) return R4D_NO(RAD_E_SHAPE);
const float eps = (float)r4d_getf(a, "eps", 1e-6);
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
const float mult = (float)r4d_getf(a, "mult", 1.0);
/* rmsnorm's width, from the same table (see r4d_rmsnorm_mult_bf16) */
const int thr = r4d_act_threads((int)M, (int)n);
/* The chained form at decode heights, where the row resolved with `chain`. */
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
#define R4D_AN_T(wf, T) \
emit_rc = ch \
? R4D_EMIT(s, (r4dchain_add_rmsnorm<wf, T>), \
dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), dim3(T), 0, \
(uint16_t*)r4d_wp(x), (const uint16_t*)r4d_p(ad), r4d_p(w), \
(uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, \
(uint32_t)a_ld, (uint32_t)y_ld, (uint32_t)M) \
: R4D_EMIT(s, (add_rmsnorm_kernel<wf, T>), \
dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), dim3(T), 0, \
(uint16_t*)r4d_wp(x), (const uint16_t*)r4d_p(ad), r4d_p(w), \
(uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, \
(uint32_t)a_ld, (uint32_t)y_ld, (uint32_t)M)
#define R4D_AN(wf) \
do { if (thr == 1024) R4D_AN_T(wf, 1024); \
else if (thr == 512) R4D_AN_T(wf, 512); \
else R4D_AN_T(wf, 256); } while (0)
if (w_f32) R4D_AN(true);
else R4D_AN(false);
#undef R4D_AN
#undef R4D_AN_T
return emit_rc;
}
/* ------------------------------------------------------------------ rmsnorm_p */
@@ -1486,7 +1898,7 @@ extern "C" int r4d_rad_sigmoid(const RadArgs* a, RadStream s) {
extern "C" int r4d_rad_fill(const RadArgs* a, RadStream s) {
const RadTensor* y = r4d_opt(a, 0);
if (!y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(y));
if (y->dtype != RAD_BF16 && y->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
long long M = 0;
@@ -1494,8 +1906,9 @@ extern "C" int r4d_rad_fill(const RadArgs* a, RadStream s) {
if (y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0) return R4D_NO(RAD_E_SHAPE);
const double v = r4d_getf(a, "value", 0.0);
return r4d_fill_bf16(r4d_addr(y), (int)M, (int)n, (int)y_ld, (float)v,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
const int e = (y->dtype == RAD_F32 ? r4d_fill_f32 : r4d_fill_bf16)(
r4d_addr(y), (int)M, (int)n, (int)y_ld, (float)v, (long)(uintptr_t)s);
return e == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ logit_softcap */
@@ -1523,11 +1936,13 @@ extern "C" int r4d_rad_logit_softcap(const RadArgs* a, RadStream s) {
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
/* The chained form at decode heights, where the row resolved with `chain`. */
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
const int rc = leg_bf16
? r4d_logit_softcap_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
(int)x_ld, (int)y_ld, (long)(uintptr_t)s)
: r4d_logit_softcap_f32(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
(int)x_ld, (int)y_ld, (long)(uintptr_t)s);
? logit_softcap_bf16_emit(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
(int)x_ld, (int)y_ld, (long)(uintptr_t)s, ch)
: logit_softcap_f32_emit(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
(int)x_ld, (int)y_ld, (long)(uintptr_t)s, ch);
return rc == 0 ? RAD_OK : RAD_E_DEVICE;
}
@@ -1709,7 +2124,7 @@ struct KvStoreGeom {
long long head_dim, block_size, kv_heads, n_blocks, k_ld, v_ld, T;
};
static int kv_store_geom(const RadArgs* a, KvStoreGeom* g) {
static int kv_store_geom(const RadArgs* a, KvStoreGeom* g, long long row_per_hd16 = 32) {
g->k = r4d_opt(a, KS_K);
g->v = r4d_opt(a, KS_V);
g->sm = r4d_opt(a, KS_SLOT);
@@ -1728,7 +2143,7 @@ static int kv_store_geom(const RadArgs* a, KvStoreGeom* g) {
* disagrees. */
if (g->kv->rank != 4) return R4D_NO(RAD_E_SHAPE);
if (g->kv->shape[1] != g->kv_heads || g->kv->shape[2] != g->block_size ||
g->kv->shape[3] != 2 * g->head_dim) return R4D_NO(RAD_E_SHAPE);
g->kv->shape[3] != g->head_dim * row_per_hd16 / 16) return R4D_NO(RAD_E_SHAPE);
g->n_blocks = g->kv->shape[0];
const long long lane = g->kv_heads * g->head_dim;
@@ -1774,6 +2189,37 @@ extern "C" int r4d_rad_kv_store_fp8(const RadArgs* a, RadStream stream) {
(float)ks, (float)vs, stream) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* The fp8_v4 and k6_v4 stores: the cache's last extent is a token's row, 25 or 22 * head_dim / 16
* bytes. */
static int kv_store_q4(const RadArgs* a, RadStream stream, int k6) {
const long long r16 = k6 ? 22 : 25;
KvStoreGeom g{};
const int rc = kv_store_geom(a, &g, r16);
if (rc != RAD_OK) return rc;
if (g.kv->dtype != RAD_F8E4M3) return R4D_NO(RAD_E_DTYPE);
if (g.head_dim % 32) return R4D_NO(RAD_E_SHAPE);
const double ks = r4d_getf(a, "k_scale", 1.0);
const double vs = r4d_getf(a, "v_scale", 1.0);
if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL);
long long k_ld = g.k_ld ? g.k_ld : g.kv_heads * g.head_dim;
long long v_ld = g.v_ld ? g.v_ld : g.kv_heads * g.head_dim;
if (k6)
return R4D_EMIT(stream, kv_store_fp8v4_kernel<1>, dim3((uint32_t)g.T), dim3(kThreads), 0,
(const uint16_t*)r4d_addr(g.k), (const uint16_t*)r4d_addr(g.v),
(const int32_t*)r4d_addr(g.sm), (uint8_t*)r4d_addr(g.kv),
(uint32_t)g.head_dim, (uint32_t)g.kv_heads, (uint32_t)g.block_size,
(uint32_t)g.n_blocks, (uint32_t)k_ld, (uint32_t)v_ld, (float)(1.0 / ks),
(float)(1.0 / vs), (uint32_t)(g.head_dim * r16 / 16)) == RAD_OK ? RAD_OK : RAD_E_DEVICE;
return R4D_EMIT(stream, kv_store_fp8v4_kernel<0>, dim3((uint32_t)g.T), dim3(kThreads), 0,
(const uint16_t*)r4d_addr(g.k), (const uint16_t*)r4d_addr(g.v),
(const int32_t*)r4d_addr(g.sm), (uint8_t*)r4d_addr(g.kv),
(uint32_t)g.head_dim, (uint32_t)g.kv_heads, (uint32_t)g.block_size,
(uint32_t)g.n_blocks, (uint32_t)k_ld, (uint32_t)v_ld, (float)(1.0 / ks),
(float)(1.0 / vs), (uint32_t)(g.head_dim * r16 / 16)) == RAD_OK ? RAD_OK : RAD_E_DEVICE;
}
extern "C" int r4d_rad_kv_store_fp8v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 0); }
extern "C" int r4d_rad_kv_store_k6v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 1); }
/* ------------------------------------------------------------------ logits_gemm
*
* gemm_nt's arithmetic with `n_vocab`/`n_embd` for N/K, but writing f32 (see the kernel above).
@@ -1810,3 +2256,31 @@ extern "C" int r4d_rad_logits_gemm(const RadArgs* a, RadStream s) {
(int)n_vocab, (int)x_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* logits_gemm_bf16_cols: the operands and checks above, then the column form at the n_embd of its
* row's constraint, with the activation's rows whole 16 bytes. */
extern "C" int r4d_rad_logits_gemm_cols(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, LG_X);
const RadTensor* w = r4d_opt(a, LG_W);
const RadTensor* y = r4d_opt(a, LG_Y);
if (!x || !w || !y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(x));
R4D_NEED(dt_bf16(w));
if (y->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE);
const long long n_vocab = r4d_geti_or(a, "n_vocab", r4d_dim(w, 0));
const long long n_embd = r4d_geti_or(a, "n_embd", r4d_dim(w, 1));
if (n_vocab <= 0 || n_embd != 4096) return R4D_NO(RAD_E_SHAPE);
if (w->rank != 2 || w->shape[0] != n_vocab || w->shape[1] != n_embd)
return R4D_NO(RAD_E_SHAPE);
long long M = 0, My = 0;
const long long x_ld = r4d_rows_pitch(x, n_embd, &M);
const long long y_ld = r4d_rows_pitch(y, n_vocab, &My);
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16) || x_ld % 8)
return R4D_NO(RAD_E_ALIGN);
return r4d_logits_gemm_bf16_cols(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n_embd,
(int)n_vocab, (int)x_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
}
+90 -254
View File
@@ -43,6 +43,8 @@
#include "r4d_plugin.h"
#include "r4d_emit.h"
#include "r4d_gemm_args.h"
#include "r4d_moe_sort.h"
#include "r4d_moe_gather.h"
#include <hip/hip_bf16.h>
@@ -57,11 +59,20 @@
namespace {
constexpr uint32_t kWave = 32;
/* Expert-count ceiling, a hard limit of these kernels: the router keeps a lane's logits in
* registers (MAXOWN) and both scatter forms keep n_expert + 1 counters in LDS. 512 covers
* Qwen3.8-Flash-Next (512 experts of 640, top-10) for 4 KiB of scatter LDS and a second router
* instantiation. */
constexpr uint32_t kMaxExpert = 512;
using r4d_moesort::kMaxExpert;
using r4d_moesort::kMaxProtect;
using r4d_moesort::Protect;
using r4d_moesort::sort_place;
using r4d_moesort::protect_of;
using r4d_moesort::kScatterSmall;
using r4d_moesort::ScatterLds;
using r4d_moesort::wave_incl_scan_i32;
using r4d_moesort::scatter_small_place;
using r4d_moesort::kScatWaves;
using r4d_moesort::scatter_small_kernel;
using r4d_moegather::kGatherSlots;
using r4d_moegather::kGatherSelfT;
using r4d_moegather::gather_kernel;
constexpr uint32_t kBlock = 128; // the fp8 scale block, along K and along N
/* Run-map entry that owns no expert: rows above `off[n_expert]` are dropped slots whose output must
* be zeroed. Declared here because the GEMM reads it; the map is built further down. */
@@ -152,27 +163,6 @@ __device__ __forceinline__ uint32_t wave_min_u32(uint32_t b) {
* `router_topk_scatter_kernel` run this same code from a different grid, byte-identically. */
/* In the fused kernel a row also hands its slots to the sort through `e`: each slot's expert
* relative to the slice, or -1 for another rank's. The standalone selection passes a null `e`. */
/* Protected experts of a slice, sorted last. A layer may keep a few experts (those whose output
* dwarfs the rest) at higher precision, and one grouped GEMM takes one weight format, so the sort
* places their runs after all others, in the listed order, and two GEMMs serve [0, n - p) and
* [n - p, n) of the offsets. Local indices, strictly ascending; p <= kMaxProtect. With none, an
* expert's place is itself. */
constexpr uint32_t kMaxProtect = 8;
struct Protect {
uint32_t n;
uint16_t e[kMaxProtect];
};
/* Local expert `e`'s place in the sort: the protected ones last, the rest closed up in order. */
__device__ __forceinline__ int32_t sort_place(int32_t e, uint32_t n_local, const Protect& p) {
int32_t below = 0;
for (uint32_t j = 0; j < p.n; ++j) {
if ((int32_t)p.e[j] == e) return (int32_t)(n_local - p.n + j);
below += (int32_t)p.e[j] < e;
}
return e - below;
}
struct SlotSink {
int32_t* e;
int32_t base;
@@ -292,123 +282,8 @@ __global__ __launch_bounds__(NW * kWave) void router_topk_kernel(
/* ================================================================== moe_scatter
*
* The small form: one workgroup does the whole sort, for T <= kScatterSmall, which covers every
* decode and verify step (eight sequences at depth 3 and top_k 10 is T = 320), in one launch
* instead of three. Histogram in LDS, offsets an exclusive prefix over n_expert <= kMaxExpert
* counts, and each slot placed by its rank inside its expert's run.
*
* On one workgroup the critical path (barriers, serial LDS chains) is the cost, not the work:
*
* - The prefix is a DPP scan inside each wave plus one exchange of wave totals through LDS: one
* barrier per tile of 32 counts per wave (at most two tiles at eight waves for 512 experts).
* - Placement groups first and orders after. The histogram atomic hands each slot a ticket in its
* expert's run (arrival order); slots are gathered into runs in ticket order, then each slot's
* place is the number of the run's slots with a lower index. That count is as long as the run
* (a row picks an expert at most once), far shorter than counting all earlier slots.
*
* Stable and byte-identical: a slot's place is its position among the same expert's slots in
* ascending i, as in the reference, whatever the ticket order. Every barrier orders LDS only, so
* none waits on or invalidates the vector memory path. */
constexpr uint32_t kScatterSmall = 1024;
constexpr uint32_t kScatWaves = 8; /* the standalone sort: 256 threads */
/* The small sort's LDS (about 16 KiB), defined once for the standalone and fused kernels. NW is the
* workgroup's wave count, which sizes the scan's exchange. */
template <uint32_t NW>
struct ScatterLds {
static constexpr uint32_t kTiles = (kMaxExpert + NW * kWave - 1) / (NW * kWave);
int32_t e[kScatterSmall]; /* the slot list: expert in the slice, or -1 */
int32_t tk[kScatterSmall]; /* the slot's ticket inside its expert's run */
int32_t run[kScatterSmall]; /* slots grouped by expert, tickets' order */
int32_t cnt[kMaxExpert + 1];
int32_t off[kMaxExpert + 1];
int32_t wt[kTiles][NW]; /* each wave's total, a slot per tile */
};
/* Inclusive prefix sum over a wave32 with DPP row shifts: four steps within each 16-lane row, then
* the upper row adds the lower row's total. Lanes shifted in from outside the row read zero
* (bound_ctrl). */
__device__ __forceinline__ int32_t wave_incl_scan_i32(int32_t x, uint32_t lane) {
x += __builtin_amdgcn_update_dpp(0, x, 0x111, 0xF, 0xF, true); /* row_shr:1 */
x += __builtin_amdgcn_update_dpp(0, x, 0x112, 0xF, 0xF, true); /* row_shr:2 */
x += __builtin_amdgcn_update_dpp(0, x, 0x114, 0xF, 0xF, true); /* row_shr:4 */
x += __builtin_amdgcn_update_dpp(0, x, 0x118, 0xF, 0xF, true); /* row_shr:8 */
const int32_t lo = __builtin_amdgcn_readlane(x, 15);
return lane >= 16u ? x + lo : x;
}
/* The sort, from a filled slot list on: histogram, offsets and counts, placement. The caller has
* written `sl.e[0, T)` and zeroed `sl.cnt[0, n_expert)`, followed by a barrier. Shared by the
* standalone sort and the fused kernel. The workgroup is exactly NW waves. */
template <uint32_t NW>
__device__ __forceinline__ void scatter_small_place(
int32_t* __restrict__ sorted, int32_t* __restrict__ off, int32_t* __restrict__ cnt,
uint32_t T, uint32_t n_expert, ScatterLds<NW>& sl) {
const uint32_t tid = threadIdx.x, lane = tid % kWave, wave = tid / kWave;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e >= 0) sl.tk[i] = atomicAdd(&sl.cnt[e], 1);
}
lds_barrier();
/* Every thread sums all NW wave totals, so `carry` (finally the live slot count) is the same
* in every thread. */
int32_t carry = 0;
for (uint32_t b = 0, t = 0; b < n_expert; b += NW * kWave, ++t) {
const uint32_t e = b + tid;
const int32_t v = (e < n_expert) ? sl.cnt[e] : 0;
const int32_t x = wave_incl_scan_i32(v, lane);
if (lane == kWave - 1) sl.wt[t][wave] = x;
lds_barrier();
int32_t below = 0, tot = 0;
#pragma unroll
for (uint32_t k = 0; k < NW; ++k) {
const int32_t c = sl.wt[t][k];
below += (k < wave) ? c : 0;
tot += c;
}
if (e < n_expert) {
const int32_t o = carry + below + x - v; /* inclusive -> exclusive */
sl.off[e] = o;
off[e] = o;
cnt[e] = v;
}
carry += tot;
}
if (tid == 0) off[n_expert] = carry;
lds_barrier();
for (uint32_t i = (uint32_t)carry + tid; i < T; i += blockDim.x) sorted[i] = -1;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e >= 0) sl.run[sl.off[e] + sl.tk[i]] = (int32_t)i;
}
lds_barrier();
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e < 0) continue;
const int32_t o = sl.off[e], n = sl.cnt[e];
int32_t rank = 0;
for (int32_t k = 0; k < n; ++k) rank += sl.run[o + k] < (int32_t)i;
sorted[o + rank] = (int32_t)i;
}
}
__global__ __launch_bounds__(kScatWaves * kWave) void scatter_small_kernel(
const int32_t* __restrict__ ids, int32_t* __restrict__ sorted, int32_t* __restrict__ off,
int32_t* __restrict__ cnt, uint32_t T, uint32_t n_expert, int32_t base, Protect prot) {
__shared__ ScatterLds<kScatWaves> sl;
const uint32_t tid = threadIdx.x;
for (uint32_t e = tid; e < n_expert; e += blockDim.x) sl.cnt[e] = 0;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = ids[i] - base;
sl.e[i] = (e >= 0 && e < (int32_t)n_expert) ? sort_place(e, n_expert, prot) : -1;
}
lds_barrier();
scatter_small_place(sorted, off, cnt, T, n_expert, sl);
}
* The small form is one workgroup and the sort of r4d_moe_sort.h; the general form below takes
* three passes. */
/* ================================================================== router_topk + moe_scatter
*
* One launch for the pair: at decode each half is a single 256-thread workgroup moving about a
@@ -520,11 +395,12 @@ __global__ __launch_bounds__(kMaxExpert) void scatter_scan_kernel(
/* Placement and tail. Each routed slot goes to its expert's offset plus the expert's count in
* earlier tiles plus its rank in this tile. Sorted rows past the live count are -1; no placement
* lands there (all placed slots are below `off[n_expert]`), so each thread writes its own index
* without races. */
* without races. INV also writes each slot's row, -1 when dropped (scatter_small_place). */
template <bool INV>
__global__ __launch_bounds__(kScatterTile) void scatter_place_kernel(
const int32_t* __restrict__ ids, const int32_t* __restrict__ bcnt,
const int32_t* __restrict__ off, int32_t* __restrict__ sorted,
uint32_t T, uint32_t n_expert, int32_t base, Protect prot) {
uint32_t T, uint32_t n_expert, int32_t base, Protect prot, int32_t* __restrict__ inv) {
__shared__ int32_t s_id[kScatterTile];
const uint32_t tid = threadIdx.x, b = blockIdx.x;
const uint32_t i = b * kScatterTile + tid;
@@ -536,12 +412,15 @@ __global__ __launch_bounds__(kScatterTile) void scatter_place_kernel(
const uint32_t live = (uint32_t)off[n_expert];
if (i >= live && i < T) sorted[i] = -1;
__syncthreads();
if constexpr (INV) if (i < T && e < 0) inv[i] = -1;
if (i >= T || e < 0) return;
/* Rank within the tile: earlier slots of this tile with the same expert. A serial scan of at
* most 256 LDS words per thread, the price of stability. */
int32_t rank = 0;
for (uint32_t j = 0; j < tid; ++j) rank += (s_id[j] == e);
sorted[off[e] + bcnt[(size_t)b * n_expert + e] + rank] = (int32_t)i;
const int32_t at = off[e] + bcnt[(size_t)b * n_expert + e] + rank;
sorted[at] = (int32_t)i;
if constexpr (INV) inv[i] = at;
}
/* ================================================================== the 4-bit expert weight
@@ -2155,78 +2034,6 @@ __global__ void gather_scatter_kernel(const int32_t* __restrict__ sorted,
if (f >= 0 && f < (int32_t)T) inv[f] = (int32_t)i;
}
/* The slot table is hoisted: `inv[t * top_k + j]` and `ew[t * ew_ld + j]` do not depend on the
* column, and read inside the column loop each `inv` load would serialise the `ye` load behind it
* (110 dependent latencies per layer at decode). Read once into LDS, the `ye` loads pipeline.
*
* The column range is also split over blocks, since decode has one token. Neither change touches
* the sum: each column's slots are still summed in ascending order within one block. */
constexpr uint32_t kGatherSlots = 64;
/* When small, the inverse permutation is built in this kernel and the two prepass kernels are not
* launched. A block owns one token, so it scans `sorted` for entries in [t*top_k, (t+1)*top_k),
* giving exactly the table `inv` would hold. Every block repeats the scan, so the launcher caps it
* (r4d_rad_moe_gather); at decode T = 40 and the scan is one pass, against two dependent dispatches
* (~2.1 us each) of single-block kernels.
*
* `sorted == nullptr` selects the prepass path, used at prefill. */
constexpr uint32_t kGatherSelfT = 512;
template <uint32_t NTHR>
__global__ __launch_bounds__(NTHR) void gather_kernel(
const uint16_t* __restrict__ ye, const uint16_t* __restrict__ ew,
const int32_t* __restrict__ inv, uint16_t* __restrict__ y,
uint32_t M, uint32_t n, uint32_t top_k, uint32_t ye_ld, uint32_t ew_ld, uint32_t y_ld,
const int32_t* __restrict__ sorted, uint32_t T,
const uint16_t* __restrict__ sh, const uint16_t* __restrict__ sg,
uint32_t sh_ld, uint32_t sg_ld, int sig) {
__shared__ int32_t s_i[kGatherSlots];
__shared__ float s_w[kGatherSlots];
const uint32_t t = blockIdx.x;
if (t >= M) return;
const bool cached = top_k <= kGatherSlots;
/* The shared arm's scalar, read once per block as scale_rows reads it once per row. */
float gate = 0.0f;
if (sh) {
const float v0 = bf16_to_f32(sg[(size_t)t * sg_ld]);
gate = sig ? (1.0f / (1.0f + __expf(-v0))) : v0;
}
if (sorted) {
/* An unclaimed slot must read -1, so fill and scan are separated by a barrier (as the
* prepass is two kernels). */
for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) s_i[j] = -1;
__syncthreads();
const int32_t lo = (int32_t)(t * top_k), hi = lo + (int32_t)top_k;
for (uint32_t i = threadIdx.x; i < T; i += NTHR) {
const int32_t f = sorted[i];
if (f >= lo && f < hi) s_i[f - lo] = (int32_t)i;
}
for (uint32_t j = threadIdx.x; j < top_k; j += NTHR)
s_w[j] = bf16_to_f32(ew[(size_t)t * ew_ld + j]);
__syncthreads();
} else if (cached) {
for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) {
s_i[j] = inv[t * top_k + j];
s_w[j] = bf16_to_f32(ew[(size_t)t * ew_ld + j]);
}
__syncthreads();
}
for (uint32_t c = blockIdx.y * NTHR + threadIdx.x; c < n; c += NTHR * gridDim.y) {
float acc = 0.0f;
for (uint32_t j = 0; j < top_k; ++j) {
const int32_t i = cached ? s_i[j] : inv[t * top_k + j];
if (i < 0) continue;
const float wj = cached ? s_w[j] : bf16_to_f32(ew[(size_t)t * ew_ld + j]);
acc += wj * bf16_to_f32(ye[(size_t)i * ye_ld + c]);
}
const uint16_t g = f32_to_bf16(acc);
if (!sh) { y[(size_t)t * y_ld + c] = g; continue; }
/* The shared arm, folded with the unfused pair's two narrows: `scale_rows` reads the gather
* as bf16 and narrows its own product before adding. */
const uint16_t p = f32_to_bf16(bf16_to_f32(sh[(size_t)t * sh_ld + c]) * gate);
y[(size_t)t * y_ld + c] = f32_to_bf16(bf16_to_f32(p) + bf16_to_f32(g));
}
}
/* ---- prefill gather: a wave per token, eight columns per lane ---------------------------------
*
* At prefill this op reads `ye` (105 MB per layer at a 2048 chunk of Qwen3.8-Flash-Next on four
@@ -2397,27 +2204,6 @@ extern "C" int r4d_rad_router_topk(const RadArgs* a, RadStream s) {
return RAD_OK;
}
/* `protect`, a comma list of local expert indices: strictly ascending, inside the slice, at most
* kMaxProtect. Absent or empty is none. */
static int protect_of(const RadArgs* a, long long n_local, Protect* p) {
*p = Protect{};
const char* s = r4d_gets(a, "protect");
if (!s) return RAD_OK;
long long prev = -1;
while (*s) {
char* end = nullptr;
const long long v = std::strtoll(s, &end, 10);
if (end == s || v <= prev || v >= n_local || p->n >= kMaxProtect)
return R4D_NO(RAD_E_SHAPE);
p->e[p->n++] = (uint16_t)v;
prev = v;
s = end;
if (*s == ',') ++s;
else if (*s) return R4D_NO(RAD_E_SHAPE);
}
return RAD_OK;
}
/* The pair in one launch. Operands are the two ops' own, selection first: logits -> expert_ids,
* expert_w, sorted_tok, expert_offset, expert_count. The checks are the two shims' checks.
*
@@ -2518,7 +2304,8 @@ extern "C" int64_t r4d_rad_moe_scatter_scratch(const RadArgs* a) {
return n_tile * n_expert * (long long)sizeof(int32_t);
}
extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) {
/* moe_scatter, and with `inv` (moe_scatter_inv's fifth operand) the inverse beside it. */
static int moe_scatter_body(const RadArgs* a, RadStream s, const RadTensor* inv) {
const RadTensor* ids = r4d_opt(a, 0);
const RadTensor* sorted = r4d_opt(a, 1);
const RadTensor* off = r4d_opt(a, 2);
@@ -2543,15 +2330,24 @@ extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) {
const int prc = protect_of(a, n_expert, &prot);
if (prc != RAD_OK) return prc;
if (inv && (inv->dtype != RAD_I32 || !r4d_contig(inv) || r4d_numel(inv) < T))
return R4D_NO(RAD_E_SHAPE);
const int32_t* idp = (const int32_t*)ids->data;
int32_t* sp = (int32_t*)sorted->data;
int32_t* op = (int32_t*)off->data;
int32_t* cp = (int32_t*)cnt->data;
int32_t* ip = inv ? (int32_t*)inv->data : nullptr;
if (T <= (long long)kScatterSmall) {
hipLaunchKernelGGL(scatter_small_kernel, dim3(1), dim3(256), 0, (hipStream_t)s,
idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, (int32_t)base,
prot);
if (ip)
hipLaunchKernelGGL(scatter_small_kernel<true>, dim3(1), dim3(kScatWaves * kWave), 0,
(hipStream_t)s, idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert,
(int32_t)base, prot, ip);
else
hipLaunchKernelGGL(scatter_small_kernel<false>, dim3(1), dim3(kScatWaves * kWave), 0,
(hipStream_t)s, idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert,
(int32_t)base, prot, ip);
R4D_MOE_CHK();
return RAD_OK;
}
@@ -2568,13 +2364,30 @@ extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) {
hipLaunchKernelGGL(scatter_scan_kernel, dim3(1), dim3(kMaxExpert), 0, (hipStream_t)s,
bcnt, op, cp, (uint32_t)n_tile, (uint32_t)n_expert);
R4D_MOE_CHK();
hipLaunchKernelGGL(scatter_place_kernel, dim3((unsigned)n_tile), dim3(kScatterTile), 0,
(hipStream_t)s, idp, bcnt, op, sp, (uint32_t)T, (uint32_t)n_expert,
(int32_t)base, prot);
if (ip)
hipLaunchKernelGGL(scatter_place_kernel<true>, dim3((unsigned)n_tile), dim3(kScatterTile),
0, (hipStream_t)s, idp, bcnt, op, sp, (uint32_t)T, (uint32_t)n_expert,
(int32_t)base, prot, ip);
else
hipLaunchKernelGGL(scatter_place_kernel<false>, dim3((unsigned)n_tile), dim3(kScatterTile),
0, (hipStream_t)s, idp, bcnt, op, sp, (uint32_t)T, (uint32_t)n_expert,
(int32_t)base, prot, ip);
R4D_MOE_CHK();
return RAD_OK;
}
extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) {
return moe_scatter_body(a, s, nullptr);
}
/* moe_scatter that also writes, for every slot, its row in `sorted_tok` (-1 when dropped): the
* table moe_gather_inv reads instead of rebuilding it from `sorted_tok`. Same sort, same scratch. */
extern "C" int r4d_rad_moe_scatter_inv(const RadArgs* a, RadStream s) {
const RadTensor* inv = r4d_opt(a, 4);
if (!inv) return R4D_NO(RAD_E_INVAL);
return moe_scatter_body(a, s, inv);
}
/* The weight-table operand from the core's tensor. A zero leading stride marks a pointer array
* (abi/rad_runtime.h, RAD_WTAB); otherwise it is a stacked plane with the stride in elements of the
* weight's dtype (bytes for E4M3). */
@@ -3220,7 +3033,9 @@ extern "C" int64_t r4d_rad_moe_gather_scratch(const RadArgs* a) {
return M * top_k * (long long)sizeof(int32_t);
}
extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
/* moe_gather, or with `given` moe_gather_inv, whose third operand is the inverse moe_scatter_inv
* wrote: no prepass and no self-scan, and the same kernel at the same T, so the same sums. */
static int moe_gather_body(const RadArgs* a, RadStream s, bool given) {
const RadTensor* ye = r4d_opt(a, 0);
const RadTensor* ew = r4d_opt(a, 1);
const RadTensor* sorted = r4d_opt(a, 2);
@@ -3232,7 +3047,7 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
const long long n = r4d_geti_or(a, "n", 0);
const long long top_k = r4d_geti_or(a, "top_k", 0);
if (n <= 0 || top_k <= 0) return R4D_NO(RAD_E_SHAPE);
if (ye->dtype != RAD_BF16 || ew->dtype != RAD_BF16 || Y->dtype != RAD_BF16)
if (ye->dtype != RAD_BF16 || (ew->dtype != RAD_BF16 && ew->dtype != RAD_F32) || Y->dtype != RAD_BF16)
return R4D_NO(RAD_E_DTYPE);
if (sorted->dtype != RAD_I32 || !r4d_contig(sorted)) return R4D_NO(RAD_E_STRIDE);
/* The shared arm is a pair: the plane and its per-row gate, or neither. */
@@ -3253,12 +3068,14 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
/* SELF: small enough for the gather to build its own slot table, skipping the two prepass
* kernels (see gather_kernel). Bounded on T because each of the M*gy blocks repeats the scan;
* at the cap it is under half a megabyte of L2 traffic. Prefill takes the prepass. */
const bool self = T <= (long long)kGatherSelfT && top_k <= (long long)kGatherSlots;
* at the cap it is under half a megabyte of L2 traffic. Prefill takes the prepass. A given
* table replaces both, and `small` keeps the kernel choice the self-scan would make. */
const bool small = T <= (long long)kGatherSelfT && top_k <= (long long)kGatherSlots;
const bool self = small && !given;
const int64_t need = self ? 0 : T * (long long)sizeof(int32_t);
int32_t* inv = nullptr;
if (!self) {
const int64_t need = self || given ? 0 : T * (long long)sizeof(int32_t);
int32_t* inv = given ? (int32_t*)sorted->data : nullptr;
if (!self && !given) {
if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH);
inv = (int32_t*)a->scratch;
const unsigned blocks = (unsigned)((T + 255) / 256);
@@ -3288,7 +3105,7 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
auto al16 = [](const void* p, long long ld) {
return ((uintptr_t)p % 16) == 0 && ld % (long long)kGatherWideCols == 0;
};
const bool wide_ok = !self && top_k <= (long long)kGatherWideSlots &&
const bool wide_ok = ew->dtype == RAD_BF16 && !small && top_k <= (long long)kGatherWideSlots &&
n % (long long)kGatherWideCols == 0 && al16(ye->data, ye_ld) &&
al16(Y->data, y_ld) && (!sh || al16(sh->data, sh_ld));
const int gpin = g_moe_gather_pin;
@@ -3310,6 +3127,17 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
}
const unsigned gy = (unsigned)((n + 255) / 256);
if (ew->dtype == RAD_F32) {
hipLaunchKernelGGL(
(gather_kernel<256, true>), dim3((unsigned)M, gy), dim3(256), 0, (hipStream_t)s,
(const uint16_t*)ye->data, ew->data, inv, (uint16_t*)Y->data, (uint32_t)M, (uint32_t)n,
(uint32_t)top_k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld,
self ? (const int32_t*)sorted->data : nullptr, (uint32_t)T,
sh ? (const uint16_t*)sh->data : nullptr, sh ? (const uint16_t*)sg->data : nullptr,
(uint32_t)sh_ld, (uint32_t)sg_ld, sig);
R4D_MOE_CHK();
return RAD_OK;
}
hipLaunchKernelGGL((gather_kernel<256>), dim3((unsigned)M, gy), dim3(256), 0, (hipStream_t)s,
(const uint16_t*)ye->data, (const uint16_t*)ew->data, inv,
(uint16_t*)Y->data, (uint32_t)M, (uint32_t)n, (uint32_t)top_k,
@@ -3322,6 +3150,14 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
return RAD_OK;
}
extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
return moe_gather_body(a, s, false);
}
extern "C" int r4d_rad_moe_gather_inv(const RadArgs* a, RadStream s) {
return moe_gather_body(a, s, true);
}
extern "C" int r4d_rad_scale_rows(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, 0);
const RadTensor* sc = r4d_opt(a, 1);
+92
View File
@@ -0,0 +1,92 @@
// r4d_moe_gather.h -- moe_gather's kernel for decode and short passes, beside its launcher in
// r4d_moe.hip; tests/r4d_emu runs it from here against the inverse the sort writes.
#pragma once
#include <hip/hip_runtime.h>
#include <cstdint>
#include "r4d_common.h"
// Internal linkage, as the unit's own definition had.
namespace r4d_moegather {
namespace {
/* The slot table is hoisted: `inv[t * top_k + j]` and `ew[t * ew_ld + j]` do not depend on the
* column, and read inside the column loop each `inv` load would serialise the `ye` load behind it
* (110 dependent latencies per layer at decode). Read once into LDS, the `ye` loads pipeline.
*
* The column range is also split over blocks, since decode has one token. Neither change touches
* the sum: each column's slots are still summed in ascending order within one block. */
constexpr uint32_t kGatherSlots = 64;
/* When small, the inverse permutation is built in this kernel and the two prepass kernels are not
* launched. A block owns one token, so it scans `sorted` for entries in [t*top_k, (t+1)*top_k),
* giving exactly the table `inv` would hold. Every block repeats the scan, so the launcher caps it
* (r4d_rad_moe_gather); at decode T = 40 and the scan is one pass, against two dependent dispatches
* (~2.1 us each) of single-block kernels.
*
* `sorted == nullptr` selects the prepass path, used at prefill. */
constexpr uint32_t kGatherSelfT = 512;
template <bool F32>
__device__ float gather_weight(const void* ew, size_t i) {
if constexpr (F32) return ((const float*)ew)[i];
else return bf16_to_f32(((const uint16_t*)ew)[i]);
}
template <uint32_t NTHR, bool F32 = false>
__global__ __launch_bounds__(NTHR) void gather_kernel(
const uint16_t* __restrict__ ye, const void* __restrict__ ew,
const int32_t* __restrict__ inv, uint16_t* __restrict__ y,
uint32_t M, uint32_t n, uint32_t top_k, uint32_t ye_ld, uint32_t ew_ld, uint32_t y_ld,
const int32_t* __restrict__ sorted, uint32_t T,
const uint16_t* __restrict__ sh, const uint16_t* __restrict__ sg,
uint32_t sh_ld, uint32_t sg_ld, int sig) {
__shared__ int32_t s_i[kGatherSlots];
__shared__ float s_w[kGatherSlots];
const uint32_t t = blockIdx.x;
if (t >= M) return;
const bool cached = top_k <= kGatherSlots;
/* The shared arm's scalar, read once per block as scale_rows reads it once per row. */
float gate = 0.0f;
if (sh) {
const float v0 = bf16_to_f32(sg[(size_t)t * sg_ld]);
gate = sig ? (1.0f / (1.0f + __expf(-v0))) : v0;
}
if (sorted) {
/* An unclaimed slot must read -1, so fill and scan are separated by a barrier (as the
* prepass is two kernels). */
for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) s_i[j] = -1;
__syncthreads();
const int32_t lo = (int32_t)(t * top_k), hi = lo + (int32_t)top_k;
for (uint32_t i = threadIdx.x; i < T; i += NTHR) {
const int32_t f = sorted[i];
if (f >= lo && f < hi) s_i[f - lo] = (int32_t)i;
}
for (uint32_t j = threadIdx.x; j < top_k; j += NTHR)
s_w[j] = gather_weight<F32>(ew, (size_t)t * ew_ld + j);
__syncthreads();
} else if (cached) {
for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) {
s_i[j] = inv[t * top_k + j];
s_w[j] = gather_weight<F32>(ew, (size_t)t * ew_ld + j);
}
__syncthreads();
}
for (uint32_t c = blockIdx.y * NTHR + threadIdx.x; c < n; c += NTHR * gridDim.y) {
float acc = 0.0f;
for (uint32_t j = 0; j < top_k; ++j) {
const int32_t i = cached ? s_i[j] : inv[t * top_k + j];
if (i < 0) continue;
const float wj = cached ? s_w[j] : gather_weight<F32>(ew, (size_t)t * ew_ld + j);
if constexpr (F32) acc = fmaf(wj, bf16_to_f32(ye[(size_t)i * ye_ld + c]), acc);
else acc += wj * bf16_to_f32(ye[(size_t)i * ye_ld + c]);
}
const uint16_t g = f32_to_bf16(acc);
if (!sh) { y[(size_t)t * y_ld + c] = g; continue; }
/* The shared arm, folded with the unfused pair's two narrows: `scale_rows` reads the gather
* as bf16 and narrows its own product before adding. */
const uint16_t p = f32_to_bf16(bf16_to_f32(sh[(size_t)t * sh_ld + c]) * gate);
y[(size_t)t * y_ld + c] = f32_to_bf16(bf16_to_f32(p) + bf16_to_f32(g));
}
}
} // namespace
} // namespace r4d_moegather
File diff suppressed because it is too large. Load diff
+198
View File
@@ -0,0 +1,198 @@
// r4d_moe_sort.h -- the routed slots' stable counting sort in one workgroup, shared by every
// kernel that ends in it: moe_scatter's small form and router_topk_scatter (r4d_moe.hip), and
// GLM's router_sigmoid_topk_scatter (r4d_glm.hip). One definition, so a fused selection and the
// standalone sort place every slot alike; tests/r4d_emu runs it from here.
#pragma once
#include <hip/hip_runtime.h>
#include <cstdint>
#include <cstdlib>
#include "r4d_args.h"
#include "r4d_common.h"
// Internal linkage, as each unit's own definitions had: the same code generation in every kernel
// that takes the sort.
namespace r4d_moesort {
namespace {
constexpr uint32_t kSortWave = 32;
/* Expert-count ceiling, a hard limit of these kernels: the router keeps a lane's logits in
* registers (MAXOWN) and both scatter forms keep n_expert + 1 counters in LDS. 512 covers
* Qwen3.8-Flash-Next (512 experts of 640, top-10) for 4 KiB of scatter LDS and a second router
* instantiation. */
constexpr uint32_t kMaxExpert = 512;
/* Protected experts of a slice, sorted last. A layer may keep a few experts (those whose output
* dwarfs the rest) at higher precision, and one grouped GEMM takes one weight format, so the sort
* places their runs after all others, in the listed order, and two GEMMs serve [0, n - p) and
* [n - p, n) of the offsets. Local indices, strictly ascending; p <= kMaxProtect. With none, an
* expert's place is itself. */
constexpr uint32_t kMaxProtect = 8;
struct Protect {
uint32_t n;
uint16_t e[kMaxProtect];
};
/* Local expert `e`'s place in the sort: the protected ones last, the rest closed up in order. */
__device__ __forceinline__ int32_t sort_place(int32_t e, uint32_t n_local, const Protect& p) {
int32_t below = 0;
for (uint32_t j = 0; j < p.n; ++j) {
if ((int32_t)p.e[j] == e) return (int32_t)(n_local - p.n + j);
below += (int32_t)p.e[j] < e;
}
return e - below;
}
/* `protect`, a comma list of local expert indices: strictly ascending, inside the slice, at most
* kMaxProtect. Absent or empty is none. */
inline int protect_of(const RadArgs* a, long long n_local, Protect* p) {
*p = Protect{};
const char* s = r4d_gets(a, "protect");
if (!s) return RAD_OK;
long long prev = -1;
while (*s) {
char* end = nullptr;
const long long v = std::strtoll(s, &end, 10);
if (end == s || v <= prev || v >= n_local || p->n >= kMaxProtect)
return R4D_NO(RAD_E_SHAPE);
p->e[p->n++] = (uint16_t)v;
prev = v;
s = end;
if (*s == ',') ++s;
else if (*s) return R4D_NO(RAD_E_SHAPE);
}
return RAD_OK;
}
/* ================================================================== the small sort
*
* One workgroup does the whole sort, for T <= kScatterSmall, which covers every decode and verify
* step (eight sequences at depth 3 and top_k 10 is T = 320), in one launch instead of three.
* Histogram in LDS, offsets an exclusive prefix over n_expert <= kMaxExpert counts, and each slot
* placed by its rank inside its expert's run.
*
* On one workgroup the critical path (barriers, serial LDS chains) is the cost, not the work:
*
* - The prefix is a DPP scan inside each wave plus one exchange of wave totals through LDS: one
* barrier per tile of 32 counts per wave (at most two tiles at eight waves for 512 experts).
* - Placement groups first and orders after. The histogram atomic hands each slot a ticket in its
* expert's run (arrival order); slots are gathered into runs in ticket order, then each slot's
* place is the number of the run's slots with a lower index. That count is as long as the run
* (a row picks an expert at most once), far shorter than counting all earlier slots.
*
* Stable and byte-identical: a slot's place is its position among the same expert's slots in
* ascending i, as in the reference, whatever the ticket order. Every barrier orders LDS only, so
* none waits on or invalidates the vector memory path. */
constexpr uint32_t kScatterSmall = 1024;
/* The small sort's LDS (about 16 KiB), defined once for the standalone and fused kernels. NW is the
* workgroup's wave count, which sizes the scan's exchange. */
template <uint32_t NW>
struct ScatterLds {
static constexpr uint32_t kTiles = (kMaxExpert + NW * kSortWave - 1) / (NW * kSortWave);
int32_t e[kScatterSmall]; /* the slot list: expert in the slice, or -1 */
int32_t tk[kScatterSmall]; /* the slot's ticket inside its expert's run */
int32_t run[kScatterSmall]; /* slots grouped by expert, tickets' order */
int32_t cnt[kMaxExpert + 1];
int32_t off[kMaxExpert + 1];
int32_t wt[kTiles][NW]; /* each wave's total, a slot per tile */
};
/* Inclusive prefix sum over a wave32 with DPP row shifts: four steps within each 16-lane row, then
* the upper row adds the lower row's total. Lanes shifted in from outside the row read zero
* (bound_ctrl). */
__device__ __forceinline__ int32_t wave_incl_scan_i32(int32_t x, uint32_t lane) {
x += __builtin_amdgcn_update_dpp(0, x, 0x111, 0xF, 0xF, true); /* row_shr:1 */
x += __builtin_amdgcn_update_dpp(0, x, 0x112, 0xF, 0xF, true); /* row_shr:2 */
x += __builtin_amdgcn_update_dpp(0, x, 0x114, 0xF, 0xF, true); /* row_shr:4 */
x += __builtin_amdgcn_update_dpp(0, x, 0x118, 0xF, 0xF, true); /* row_shr:8 */
const int32_t lo = __builtin_amdgcn_readlane(x, 15);
return lane >= 16u ? x + lo : x;
}
/* The sort, from a filled slot list on: histogram, offsets and counts, placement. The caller has
* written `sl.e[0, T)` and zeroed `sl.cnt[0, n_expert)`, followed by a barrier. Shared by the
* standalone sort and the fused kernels. The workgroup is exactly NW waves.
*
* INV also writes the inverse: `inv[i]` is slot i's row in `sorted`, -1 for a dropped slot, the
* table moe_gather would otherwise build from `sorted`. */
template <uint32_t NW, bool INV = false>
__device__ __forceinline__ void scatter_small_place(
int32_t* __restrict__ sorted, int32_t* __restrict__ off, int32_t* __restrict__ cnt,
uint32_t T, uint32_t n_expert, ScatterLds<NW>& sl, int32_t* __restrict__ inv = nullptr) {
const uint32_t tid = threadIdx.x, lane = tid % kSortWave, wave = tid / kSortWave;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e >= 0) sl.tk[i] = atomicAdd(&sl.cnt[e], 1);
}
lds_barrier();
/* Every thread sums all NW wave totals, so `carry` (finally the live slot count) is the same
* in every thread. */
int32_t carry = 0;
for (uint32_t b = 0, t = 0; b < n_expert; b += NW * kSortWave, ++t) {
const uint32_t e = b + tid;
const int32_t v = (e < n_expert) ? sl.cnt[e] : 0;
const int32_t x = wave_incl_scan_i32(v, lane);
if (lane == kSortWave - 1) sl.wt[t][wave] = x;
lds_barrier();
int32_t below = 0, tot = 0;
#pragma unroll
for (uint32_t k = 0; k < NW; ++k) {
const int32_t c = sl.wt[t][k];
below += (k < wave) ? c : 0;
tot += c;
}
if (e < n_expert) {
const int32_t o = carry + below + x - v; /* inclusive -> exclusive */
sl.off[e] = o;
off[e] = o;
cnt[e] = v;
}
carry += tot;
}
if (tid == 0) off[n_expert] = carry;
lds_barrier();
for (uint32_t i = (uint32_t)carry + tid; i < T; i += blockDim.x) sorted[i] = -1;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e >= 0) sl.run[sl.off[e] + sl.tk[i]] = (int32_t)i;
}
lds_barrier();
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e < 0) {
if constexpr (INV) inv[i] = -1;
continue;
}
const int32_t o = sl.off[e], n = sl.cnt[e];
int32_t rank = 0;
for (int32_t k = 0; k < n; ++k) rank += sl.run[o + k] < (int32_t)i;
sorted[o + rank] = (int32_t)i;
if constexpr (INV) inv[i] = o + rank;
}
}
/* moe_scatter's small form: the slot list from `ids`, then the sort. A template only so a unit that
* includes this header and does not launch it compiles no kernel. */
constexpr uint32_t kScatWaves = 8; /* 256 threads */
template <bool INV>
__global__ __launch_bounds__(kScatWaves * kSortWave) void scatter_small_kernel(
const int32_t* __restrict__ ids, int32_t* __restrict__ sorted, int32_t* __restrict__ off,
int32_t* __restrict__ cnt, uint32_t T, uint32_t n_expert, int32_t base, Protect prot,
int32_t* __restrict__ inv) {
__shared__ ScatterLds<kScatWaves> sl;
const uint32_t tid = threadIdx.x;
for (uint32_t e = tid; e < n_expert; e += blockDim.x) sl.cnt[e] = 0;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = ids[i] - base;
sl.e[i] = (e >= 0 && e < (int32_t)n_expert) ? sort_place(e, n_expert, prot) : -1;
}
lds_barrier();
scatter_small_place<kScatWaves, INV>(sorted, off, cnt, T, n_expert, sl, inv);
}
} // namespace
} // namespace r4d_moesort
+9
View File
@@ -56,6 +56,15 @@ static __device__ __forceinline__ void r4d_mxfp4_unpack8(unsigned int wv, int d,
unsigned int* lo, unsigned int* hi) {
r4d_mxfp4_unpack8_t(wv, kMxfp4Mag[d][0], kMxfp4Mag[d][1], lo, hi);
}
// Row d = 0 as immediates, for kernels that fold the E8M0 scale in F32 and need the exact e2m1
// values: no table load, v_perm_b32 takes the two words as literals. tests/r4d_emu/test_moemx
// holds them to row 0 of the table.
#define R4D_MXFP4_MAG0_LO 0x3c383000u
#define R4D_MXFP4_MAG0_HI 0x4c484440u
static __device__ __forceinline__ void r4d_mxfp4_unpack8_exact(unsigned int wv, unsigned int* lo,
unsigned int* hi) {
r4d_mxfp4_unpack8_t(wv, R4D_MXFP4_MAG0_LO, R4D_MXFP4_MAG0_HI, lo, hi);
}
// The activation scale a row's accumulator is carried in, for the per-(row, 128 of K) grid: the
// last non-zero entry of `row` at or before block `kb`, or 1 if none. A zero-scale block has zero
+139
View File
@@ -67,6 +67,9 @@ enum {
* these rows' layout hooks refuse a bf16 head, and the bf16 row has no hook for a scaled
* one. */
R4D_PRIO_LOGITS_FP8 = 60,
/* The bf16 head's column form, above the block-per-column row whose bytes it gives, at the
* n_embd it is built for. */
R4D_PRIO_LOGITS_COLS = 55,
/* Runtime LoRA: the tiled rows serve a subset of the scalar rows' dtypes at every M, so they
* must outrank them to be reached; the scalar rows keep f16 / f32 activations (no exact WMMA)
@@ -91,6 +94,12 @@ extern "C" {
int r4d_rad_attn_prefill_h256_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_fp8v4(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_v4_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_k6v4(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_k6v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_k6_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_bf16 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_bf16 (const RadArgs*, RadStream);
@@ -104,6 +113,21 @@ int r4d_rad_attn_prefill_h256_gqa2_bf16 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa2_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs*);
/* Gemma 3 sliding window (r4d_attn_paged_h128_gqa2w.hip): head_dim 128, 2 queries per KV head,
* window >= 1. Decode (q_len*gqa <= 64) and windowed prefill, as the h256/gqa2 pair above. */
int r4d_rad_attn_prefill_h128_gqa2w_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h128_gqa2w_bf16 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa2w_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa2w_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa2w_scratch(const RadArgs*);
/* attn_paged_qrow on the split-KV decode kernel: the h256/gqa2 decode with q at its own pitch, and
* head_dim 128 at gqa 8 as the gqa-4 kernel with two query groups a kv head (R4DArgs::kv_rep). */
int r4d_rad_attn_qrow_decode_h256_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_qrow_decode_h256_gqa2_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_qrow_decode_h256_gqa2_scratch(const RadArgs*);
int r4d_rad_attn_qrow_h128_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_qrow_h128_gqa8_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_qrow_h128_gqa8_scratch(const RadArgs*);
/* Paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV head, any window, causal or not
* (r4d_attn_paged_window.hip): one entry point per geometry and cache dtype, every q_len and any q
* row pitch, so they serve both attn_paged and attn_paged_qrow. */
@@ -143,6 +167,7 @@ int r4d_rad_lora_expand (const RadArgs*, RadStream);
int r4d_rad_lora_shrink_wmma (const RadArgs*, RadStream);
int64_t r4d_rad_lora_shrink_wmma_scratch(const RadArgs*);
int r4d_rad_lora_expand_tiled (const RadArgs*, RadStream);
int r4d_rad_lora_expand_mm (const RadArgs*, RadStream);
int r4d_rad_attn_vit (const RadArgs*, RadStream);
int r4d_rad_attn_dense (const RadArgs*, RadStream);
int r4d_rad_seg_sinusoid (const RadArgs*, RadStream);
@@ -151,6 +176,10 @@ int r4d_rad_seg_sinusoid (const RadArgs*, RadStream);
* (an image decoder's mid block). */
int r4d_rad_attn_prefix_self (const RadArgs*, RadStream);
int r4d_rad_attn_dense_h128 (const RadArgs*, RadStream);
int r4d_rad_attn_cross (const RadArgs*, RadStream);
int r4d_rad_table_add (const RadArgs*, RadStream);
int r4d_rad_mix_rows (const RadArgs*, RadStream);
int r4d_rad_chan_stats (const RadArgs*, RadStream);
int r4d_rad_attn_dense_wide (const RadArgs*, RadStream);
/* The image generator's other ops (r4d_gen.hip). */
int r4d_rad_ln_mod (const RadArgs*, RadStream);
@@ -162,13 +191,17 @@ int r4d_rad_lane_gather (const RadArgs*, RadStream);
int r4d_rad_lane_store (const RadArgs*, RadStream);
int r4d_rad_randn_lanes (const RadArgs*, RadStream);
int r4d_rad_flow_euler (const RadArgs*, RadStream);
int r4d_rad_kd_input (const RadArgs*, RadStream);
int r4d_rad_kd_step (const RadArgs*, RadStream);
int r4d_rad_chan_affine (const RadArgs*, RadStream);
int r4d_rad_conv2d_nhwc (const RadArgs*, RadStream);
int r4d_rad_im2col_nhwc (const RadArgs*, RadStream);
int r4d_rad_l2norm_chan (const RadArgs*, RadStream);
int r4d_rad_d2s_add (const RadArgs*, RadStream);
int r4d_rad_s2d_avg_add (const RadArgs*, RadStream);
int r4d_rad_to_rgba8 (const RadArgs*, RadStream);
int r4d_rad_gelu_tanh (const RadArgs*, RadStream);
int r4d_rad_gelu_quick (const RadArgs*, RadStream);
int r4d_rad_scatter_add_rows (const RadArgs*, RadStream);
/* r4d_audio.hip */
int r4d_rad_conv1d (const RadArgs*, RadStream);
@@ -191,6 +224,7 @@ int r4d_rad_interleave2 (const RadArgs*, RadStream);
int r4d_rad_attn_dense_small_h256 (const RadArgs*, RadStream);
int r4d_rad_iota (const RadArgs*, RadStream);
int r4d_rad_cu_repeat (const RadArgs*, RadStream);
int r4d_rad_int_affine (const RadArgs*, RadStream);
/* r4d_video.hip */
int r4d_rad_rms_mod (const RadArgs*, RadStream);
int r4d_rad_rms_mod_quant_fp8 (const RadArgs*, RadStream);
@@ -210,6 +244,21 @@ int r4d_rad_tconv_dw (const RadArgs*, RadStream);
int r4d_rad_resize_bilinear (const RadArgs*, RadStream);
int r4d_rad_patch_fold (const RadArgs*, RadStream);
int r4d_rad_flow_renoise (const RadArgs*, RadStream);
int r4d_rad_rope_split (const RadArgs*, RadStream);
int r4d_rad_head_gate (const RadArgs*, RadStream);
int r4d_rad_ltx_guide (const RadArgs*, RadStream);
int r4d_rad_pixel_norm (const RadArgs*, RadStream);
int r4d_rad_d2s3d (const RadArgs*, RadStream);
int r4d_rad_s2d3d (const RadArgs*, RadStream);
int r4d_rad_pix_patch (const RadArgs*, RadStream);
int r4d_rad_patch_pix8 (const RadArgs*, RadStream);
int r4d_rad_vol_index (const RadArgs*, RadStream);
int r4d_rad_attn_na3d (const RadArgs*, RadStream);
int r4d_rad_tile_grid (const RadArgs*, RadStream);
int r4d_rad_tile_crop (const RadArgs*, RadStream);
int r4d_rad_tile_stitch (const RadArgs*, RadStream);
int r4d_rad_stft_logmel (const RadArgs*, RadStream);
int r4d_rad_bwe_up (const RadArgs*, RadStream);
/* r4d_vsa.hip: video sparse attention's selection (scratch for the tile means) and attention. */
int r4d_rad_vsa_select (const RadArgs*, RadStream);
int64_t r4d_rad_vsa_select_scratch (const RadArgs*);
@@ -269,6 +318,24 @@ int64_t r4d_rad_attn_decode_h256_gqa6_scratch(const RadArgs*);
* kernel; see attn_decode_gq_h256_gqa6_fp8kv. */
int r4d_rad_attn_decode_gq_h256_gqa6_fp8(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa6_bf16(const RadArgs*, RadStream);
/* The fp8_v4 and k6_v4 caches on both: prefill, decode, and decode with the gate and quantiser in
* the merge (R4D_ATTN_V4 in r4d_attn_paged_gqa8.hip). */
int r4d_rad_attn_prefill_h256_gqa12_fp8v4(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa12_fp8v4(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa12_fp8v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa12_fp8v4_scratch(const RadArgs*);
int r4d_rad_attn_prefill_h256_gqa12_k6v4(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa12_k6v4(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa12_k6v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa12_k6v4_scratch(const RadArgs*);
int r4d_rad_attn_prefill_h256_gqa6_fp8v4(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa6_fp8v4(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa6_fp8v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa6_fp8v4_scratch(const RadArgs*);
int r4d_rad_attn_prefill_h256_gqa6_k6v4(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa6_k6v4(const RadArgs*, RadStream);
int r4d_rad_attn_decode_gq_h256_gqa6_k6v4(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa6_k6v4_scratch(const RadArgs*);
/* -- gated delta net (r4d_gdn_*.hip) -- */
int r4d_rad_gdn_chunk_scan (const RadArgs*, RadStream);
@@ -285,6 +352,16 @@ int r4d_rad_dflash_select (const RadArgs*, RadStream);
/* -- the gated residual (r4d_hc_bf16.hip) -- */
int r4d_rad_hc_enter (const RadArgs*, RadStream);
int r4d_rad_hc_project (const RadArgs*, RadStream);
int r4d_rad_mhc_pre(const RadArgs*, RadStream);
int r4d_rad_mhc_pre_partial(const RadArgs*, RadStream);
int r4d_rad_mhc_pre_finish(const RadArgs*, RadStream);
int r4d_rad_kda_update(const RadArgs*, RadStream);
int r4d_rad_moe_mxfp4(const RadArgs*, RadStream);
int r4d_rad_layout_moe_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_mhc_post(const RadArgs*, RadStream);
int r4d_rad_mhc_contract(const RadArgs*, RadStream);
int r4d_rad_mtp_enter (const RadArgs*, RadStream);
int64_t r4d_rad_mtp_enter_scratch(const RadArgs*);
int r4d_rad_hc_read (const RadArgs*, RadStream);
@@ -318,6 +395,7 @@ int r4d_rad_ar_twoshot_4rank_ti8 (const RadArgs*, RadStream);
int r4d_rad_ar_ln_init(const RadParam*, int, int rank, int world, void** out);
int r4d_rad_ar_ln_had_quant_i8(const RadArgs*, RadStream);
int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs*, RadStream);
int r4d_rad_ar_rmsnorm_had_quant_i8g(const RadArgs*, RadStream);
int r4d_rad_ar_hc_write(const RadArgs*, RadStream);
/* ar_hc_write at four ranks, exact wire only, on an instance of the wide family keyed by its own
* M bound. */
@@ -396,8 +474,15 @@ int64_t r4d_rad_moe_gather_scratch (const RadArgs*);
/* -- quantisation, norms and the fusions (r4d_*quant*.hip, r4d_qk_norm_rope_gate.hip) -- */
int r4d_rad_quant_act_i8 (const RadArgs*, RadStream);
int r4d_rad_qkv_norm_rope (const RadArgs*, RadStream);
int r4d_rad_kv_len_trim (const RadArgs*, RadStream);
int r4d_rad_add_rmsnorm (const RadArgs*, RadStream);
int r4d_rad_prefetch (const RadArgs*, RadStream);
int r4d_rad_layout_any(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_qkv_norm_rope_kv_store(const RadArgs*, RadStream);
int r4d_rad_gelu_mul_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_ar_rmsnorm_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs*, RadStream);
int r4d_rad_rmsnorm_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_had_quant_act_i8 (const RadArgs*, RadStream);
int r4d_rad_rmsnorm_had_quant_i8 (const RadArgs*, RadStream);
@@ -405,6 +490,8 @@ int r4d_rad_gated_had_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_gdn_gated_norm_hq_i8 (const RadArgs*, RadStream);
int r4d_rad_qk_norm_rope_gate (const RadArgs*, RadStream);
int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs*, RadStream);
int r4d_rad_qk_norm_rope_gate_kv_store_fp8v4(const RadArgs*, RadStream);
int r4d_rad_qk_norm_rope_gate_kv_store_k6v4(const RadArgs*, RadStream);
int r4d_rad_rope_table (const RadArgs*, RadStream);
/* -- block-scaled fp8, and the device sampler (r4d_gemm_fp8*.hip / r4d_fp8_layout.cpp) --
@@ -427,8 +514,10 @@ int r4d_rad_quant_act_fp8 (const RadArgs*, RadStream);
int r4d_rad_had_quant_act_fp8 (const RadArgs*, RadStream);
int r4d_rad_givens_rotate (const RadArgs*, RadStream);
int r4d_rad_rmsnorm_quant_fp8(const RadArgs*, RadStream);
int r4d_rad_rmsnorm_had_quant_i8g(const RadArgs*, RadStream);
int r4d_rad_gated_quant_fp8 (const RadArgs*, RadStream);
int r4d_rad_gated_had_quant_fp8(const RadArgs*, RadStream);
int r4d_rad_gated_had_quant_i8g(const RadArgs*, RadStream);
int r4d_rad_gate_quant_fp8 (const RadArgs*, RadStream);
int r4d_rad_gram_accum (const RadArgs*, RadStream);
/* The same accumulator over a plain bf16 activation, no scale operand. */
@@ -592,6 +681,35 @@ int r4d_rad_fill (const RadArgs*, RadStream);
int r4d_rad_logit_softcap (const RadArgs*, RadStream);
int r4d_rad_scale (const RadArgs*, RadStream);
int r4d_rad_silu_mul (const RadArgs*, RadStream);
int r4d_rad_swiglu_clamped(const RadArgs*, RadStream);
int r4d_rad_swiglu_clamped_quant_fp8(const RadArgs*, RadStream);
int r4d_rad_dsa_pool(const RadArgs*, RadStream);
int r4d_shape_dsa_pool(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_dsa_query(const RadArgs*, RadStream);
int r4d_rad_fp8_f32scale(const RadArgs*, RadStream);
int r4d_rad_moe_fp8_f32scale(const RadArgs*, RadStream);
int r4d_layout_fp8_f32scale(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_shape_dsa_query(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_gemm_nt_f32(const RadArgs*, RadStream);
int r4d_shape_gemm_nt_f32(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_mla_project(const RadArgs*, RadStream);
int r4d_shape_mla_project(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_dsa_score(const RadArgs*, RadStream);
int r4d_shape_dsa_score(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_mla_attn(const RadArgs*, RadStream);
int64_t r4d_rad_mla_attn_scratch(const RadArgs*);
int r4d_rad_mla_attn_matrix(const RadArgs*, RadStream);
int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*);
int r4d_shape_mla_attn(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_router_sigmoid_topk(const RadArgs*, RadStream);
int r4d_shape_router_sigmoid_topk(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_router_sigmoid_topk_scatter(const RadArgs*, RadStream);
int r4d_rad_moe_scatter_inv(const RadArgs*, RadStream);
int r4d_shape_moe_scatter_inv(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_moe_gather_inv(const RadArgs*, RadStream);
int r4d_shape_moe_gather_inv(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_router_sigmoid_topk_scatter(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_gelu_mul (const RadArgs*, RadStream);
int r4d_rad_rope (const RadArgs*, RadStream);
/* -- the vision tower's ops (r4d_vit_bf16.hip) -- */
@@ -603,7 +721,10 @@ int r4d_rad_gemm_nt_bias (const RadArgs*, RadStream);
int r4d_rad_gemm_f32_nt_bias(const RadArgs*, RadStream);
int r4d_rad_kv_store (const RadArgs*, RadStream);
int r4d_rad_kv_store_fp8 (const RadArgs*, RadStream);
int r4d_rad_kv_store_fp8v4 (const RadArgs*, RadStream);
int r4d_rad_kv_store_k6v4 (const RadArgs*, RadStream);
int r4d_rad_logits_gemm (const RadArgs*, RadStream);
int r4d_rad_logits_gemm_cols(const RadArgs*, RadStream);
/* -- the decomposed sampler chain (r4d_sample_stages_f32.hip) --
*
@@ -642,9 +763,17 @@ int r4d_shape_scatter_rows_u8(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_cast (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_rmsnorm (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_hc_enter (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_mhc_pre(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mhc_pre_partial(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mhc_pre_finish(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_kda_update(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_moe_mxfp4(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mhc_post(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mhc_contract(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mtp_enter (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_hc_read (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_hc_write (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_hc_project (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_binary (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_mul_weight (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_scatter_rows_bf16(const RadParam*, int, int operand, RadOpdDesc*);
@@ -673,6 +802,9 @@ int r4d_shape_attn_paged (const RadParam*, int, int operand, RadOpdDesc*)
int r4d_shape_attn_paged_gate_quant(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_qk_norm_rope_gate (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_qk_norm_rope_gate_kv_store(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_qkv_norm_rope (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_qkv_norm_rope_kv_store(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_add_rmsnorm(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_rope_table (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_gdn_gated_rmsnorm (const RadParam*, int, int operand, RadOpdDesc*);
@@ -680,6 +812,7 @@ int r4d_shape_all_reduce (const RadParam*, int, int operand, RadOpdDes
int r4d_shape_all_gather (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_ar_ln_had_quant_i8 (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_ar_rmsnorm_quant_fp8 (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_ar_rmsnorm_had_quant_i8g (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_ar_hc_write (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_ar_gather_hc_write (const RadParam*, int, int operand, RadOpdDesc*);
@@ -710,6 +843,8 @@ int r4d_shape_gdn_gated_norm_had_quant_i8(const RadParam*, int, int operand,
int r4d_shape_quant_act_fp8 (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_rmsnorm_quant_fp8 (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_gated_quant_fp8 (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_rmsnorm_had_quant_i8g (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_gated_had_quant_i8g (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_gate_quant_fp8 (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_gram_accum (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_qsa_block_key (const RadParam*, int, int operand, RadOpdDesc*);
@@ -736,10 +871,14 @@ int r4d_shape_dflash_select (const RadParam*, int, int operand, RadOpdDesc*);
* Pure host code, like r4d_rows.cpp, r4d_layout.cpp and r4d_shapes.cpp. */
int r4d_fuse_rmsnorm_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gated_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_swiglu_clamped_quant_fp8(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_router_sigmoid_topk_scatter(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gate_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gemm_nt_q_gated (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_qkv_norm_rope_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_add_rmsnorm(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_ar_rmsnorm_quant_fp8(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_ar_gather_hc_write (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_attn_paged_gate_quant(const RadParam*, int, uint64_t, int, RadFuseStep*);
+83
View File
@@ -0,0 +1,83 @@
// r4d_prefetch.hip - r4d_rad_prefetch: read a weight's leading bytes into the on-die cache.
//
// A decode step at a few rows streams each weight once from memory, and the all-reduce between two
// GEMMs leaves memory idle for its whole round trip: ~20 us at a DFlash2 verify's 8 rows on 4x
// R9700. A read issued on the second lane in that window puts the next GEMM's first bytes in the
// 64 MB Infinity Cache, and the GEMM then streams them from there. On four cards (a microbenchmark
// of the 8-row two-shot and a GEMM-like stream of a cold 29 MB weight, 2026-10-17) 16 MB read beside
// the all-reduce took a layer from 84.0 us to 70.1; the same read on the same stream gained nothing.
//
// It writes nothing at all. Each lane folds its loads into one word and hands it to an empty
// `asm volatile`, which the compiler can neither drop nor see into, so the loads stay.
//
// Nothing here reaches HIP's runtime. The fold once went to a word hipMalloc'ed on the first
// launch, in the middle of a pass; then to a `__device__` word, which HIP's runtime registers and
// places itself (the engine records only fat binaries and functions). That word cost ~8% of a
// DFlash2 step (321 tok/s against 348 in one A/B on 4x R9700, 2026-10-17, every prefetch size
// alike), not through extra hardware queues (every image held 16 on the four cards); the
// mechanism is not pinned down. Neither form was the cause of the fresh-server divergence the
// reads beside a prefill bring (rad_arch.h, kPrefetchRows): with no word at all it is still there.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_chain.h"
#include "r4d_emit.h"
#include <cstdint>
namespace {
__global__ __launch_bounds__(256) void prefetch_kernel(const int4* __restrict__ p, size_t n16) {
const size_t tid = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
const size_t nt = (size_t)gridDim.x * blockDim.x;
unsigned acc = 0;
for (size_t i = tid; i < n16; i += nt) {
const int4 v = p[i];
acc ^= (unsigned)(v.x ^ v.y ^ v.z ^ v.w);
}
asm volatile("" ::"v"(acc));
}
/* The chained form (RadKernelChainFn): it waits for the kernels before it on its queue, as every
* chained form does, but adds its blocks to the counter at once, before reading: nothing after it
* reads anything it writes, so the next kernel need not wait for its reads. Issued on lane 0
* between a GEMM and the collective after it (where launches chain), it starts reading as the
* GEMM's last block ends, with no event between the queues and no barrier bit on the GEMM. */
__global__ __launch_bounds__(256) void r4dchain_prefetch(const int4* __restrict__ p, size_t n16) {
r4d_chain_wait();
r4d_chain_done();
const size_t tid = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
const size_t nt = (size_t)gridDim.x * blockDim.x;
unsigned acc = 0;
for (size_t i = tid; i < n16; i += nt) {
const int4 v = p[i];
acc ^= (unsigned)(v.x ^ v.y ^ v.z ^ v.w);
}
asm volatile("" ::"v"(acc));
}
} // namespace
extern "C" int r4d_rad_layout_any(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*) {
return RAD_LAYOUT_ANY;
}
extern "C" int r4d_rad_prefetch(const RadArgs* a, RadStream stream) {
const RadTensor* w = r4d_opt(a, 0);
if (!w || !w->data) return R4D_NO(RAD_E_INVAL);
long long bytes = r4d_geti_or(a, "bytes", 0);
if (bytes <= 0) return RAD_OK;
// Never past what the tensor says it holds, where its dtype says how wide an element is.
const int bits = rad_dtype_bits(w->dtype);
if (bits > 0) {
long long n = 1;
for (uint32_t i = 0; i < w->rank; ++i) n *= w->shape[i];
const long long have = n * bits / 8;
if (have > 0 && bytes > have) bytes = have;
}
if ((uintptr_t)w->data % 16) return R4D_NO(RAD_E_ALIGN);
int nb = r4d_cfg_prefetch_nb(a);
if (nb < 1) nb = 64;
const bool ch = r4d_geti_or(a, "chain", 0) != 0;
return R4D_EMIT(stream, (ch ? r4dchain_prefetch : prefetch_kernel), dim3((unsigned)nb), dim3(256), 0,
(const int4*)w->data, (size_t)(bytes / 16));
}
+89 -3
View File
@@ -49,10 +49,11 @@ struct QkKvStore {
void* cache;
int v_pitch, block_size, n_blocks;
float k_inv, v_inv;
int row; /* fp8_v4 / k6_v4: a token's bytes in a page, 25 or 22 * HD / 16 */
};
/* The cache forms KV selects. */
enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2 };
enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2, QK_KV_F8V4 = 3, QK_KV_K6V4 = 4 };
/* KV folds kv_store in: a k head's block, holding the token's rotated k one element per lane, also
* writes that element and the head's v element into the cache at the token's slot, as E4M3 with
@@ -153,14 +154,53 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
if (sl >= 0 && (uint32_t)sl / (uint32_t)kvs.block_size < (uint32_t)kvs.n_blocks) {
const uint32_t blk = (uint32_t)sl / (uint32_t)kvs.block_size;
const uint32_t off = (uint32_t)sl % (uint32_t)kvs.block_size;
const size_t at = ((size_t)blk * nkv * kvs.block_size + off) * 2 * HD +
(size_t)lh * kvs.block_size * 2 * HD;
const size_t rowb = (KV == QK_KV_F8V4 || KV == QK_KV_K6V4) ? (size_t)kvs.row : (size_t)(2 * HD);
const size_t at = ((size_t)blk * nkv * kvs.block_size + off) * rowb +
(size_t)lh * kvs.block_size * rowb;
const __hip_bfloat16 kb = __float2bfloat16(res);
const __hip_bfloat16 vb = kvs.v[(size_t)tok * kvs.v_pitch + (size_t)lh * HD + t];
if constexpr (KV == QK_KV_BF16) {
__hip_bfloat16* c = (__hip_bfloat16*)kvs.cache + at;
c[t] = kb;
c[HD + t] = vb;
} else if constexpr (KV == QK_KV_F8V4 || KV == QK_KV_K6V4) {
// fp8_v4: K as the E4M3 form writes it. k6_v4: K as int6 in groups of 32 (one wave)
// with an f16 scale, absmax / 31, in kv_store_k6v4's layout. V as int4 in groups of 32
// with an f16 scale, absmax / 7. The even lane of a pair writes the pair's nibble byte.
unsigned char* c = (unsigned char*)kvs.cache + at;
const float kf = __bfloat162float(kb) * kvs.k_inv;
constexpr int voff = KV == QK_KV_K6V4 ? HD * 3 / 4 : HD;
constexpr int vsoff = KV == QK_KV_K6V4 ? HD * 21 / 16 : HD * 3 / 2;
if constexpr (KV == QK_KV_K6V4) {
float kmax = fabsf(kf);
for (int m = 16; m >= 1; m >>= 1) kmax = fmaxf(kmax, __shfl_xor(kmax, m, 32));
const __fp16 k16 = (__fp16)fminf(kmax / 31.0f, 2112.0f); // finite codes, as kv_store_k6v4
const float ksc = (float)k16;
const float r = ksc > 0.0f ? rintf(kf / ksc) : 0.0f;
const int q = ((int)fminf(fmaxf(r, -31.0f), 31.0f)) & 0x3F;
const int qn = __shfl_xor(q & 15, 1, 32);
if ((t & 1) == 0) c[t / 2] = (unsigned char)((q & 15) | (qn << 4));
// High bits: a pair's four into bits 0-3 at its even lane, then the pair eight dims on
// into bits 4-7; lane 2j of a 16-dim chunk writes byte j.
const int h01 = (q >> 4) | (__shfl_xor(q >> 4, 1, 32) << 2);
const int hb = h01 | (__shfl_xor(h01, 8, 32) << 4);
if ((t & 1) == 0 && (t & 15) < 8) c[HD / 2 + (t / 16) * 4 + (t & 7) / 2] = (unsigned char)hb;
if ((t & 31) == 0) *(uint16_t*)(c + HD * 5 / 4 + (t / 32) * 2) = __builtin_bit_cast(uint16_t, k16);
} else {
const int pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf, -448.0f), 448.0f), 0.0f,
0, false);
c[t] = (unsigned char)(pk & 0xFF);
}
const float vf = __bfloat162float(vb) * kvs.v_inv;
float amax = fabsf(vf);
for (int m = 16; m >= 1; m >>= 1) amax = fmaxf(amax, __shfl_xor(amax, m, 32));
const __fp16 s16 = (__fp16)fminf(amax / 7.0f, 8188.0f); // finite codes, as kv_store_fp8v4
const float sc = (float)s16;
const float r = sc > 0.0f ? rintf(vf / sc) : 0.0f;
const int q = ((int)fminf(fmaxf(r, -7.0f), 7.0f)) & 0xF;
const int qn = __shfl_xor(q, 1, 32);
if ((t & 1) == 0) c[voff + t / 2] = (unsigned char)(q | (qn << 4));
if ((t & 31) == 0) *(uint16_t*)(c + vsoff + (t / 32) * 2) = __builtin_bit_cast(uint16_t, s16);
} else {
unsigned char* c = (unsigned char*)kvs.cache + at;
const float kf = __bfloat162float(kb) * kvs.k_inv;
@@ -346,6 +386,52 @@ extern "C" int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs* args, RadStream
: qk_body<QK_KV_FP8>(args, stream, kvs);
}
/* The fp8_v4 and k6_v4 forms: the same operands, the cache [n_blocks, kv_heads, block_size,
* 25 or 22 * HD / 16] E4M3-typed bytes (fp8_v4: E4M3 K; k6_v4: int6 K; both int4 V, f16 scales). */
static int qk_kv_q4(const RadArgs* args, RadStream stream, int k6) {
const long long r16 = k6 ? 22 : 25;
const RadTensor* k = r4d_opt(args, QK_K);
const RadTensor* qg = r4d_opt(args, QK_QGATE);
const RadTensor* v = r4d_opt(args, QK_V);
const RadTensor* sm = r4d_opt(args, QK_SLOT);
const RadTensor* kv = r4d_opt(args, QK_CACHE);
if (!k || !v || !sm || !kv) return R4D_NO(RAD_E_INVAL);
if (v->dtype != RAD_BF16 || sm->dtype != RAD_I32 || kv->dtype != RAD_F8E4M3)
return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(sm) || !r4d_contig(kv)) return R4D_NO(RAD_E_STRIDE);
const long long hd = r4d_geti_or(args, "head_dim", 0);
const long long nkv = r4d_geti_or(args, "n_head_kv", 0);
const long long bs = r4d_geti_or(args, "block_size", 0);
if (hd <= 0 || nkv <= 0 || bs <= 0 || hd % 32) return R4D_NO(RAD_E_SHAPE);
if (kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs || kv->shape[3] != hd * r16 / 16)
return R4D_NO(RAD_E_SHAPE);
const long long M = qg ? qg->shape[0] : k->shape[0];
long long Mv = 0;
const long long v_ld = r4d_rows_pitch(v, nkv * hd, &Mv);
if (v_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (Mv < M || r4d_numel(sm) != M) return R4D_NO(RAD_E_SHAPE);
const double ks = r4d_getf(args, "k_scale", 1.0);
const double vs = r4d_getf(args, "v_scale", 1.0);
if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL);
QkKvStore kvs{};
kvs.v = (const __hip_bfloat16*)r4d_p(v);
kvs.slot = (const int32_t*)r4d_p(sm);
kvs.cache = r4d_wp(kv);
kvs.v_pitch = (int)v_ld;
kvs.block_size = (int)bs;
kvs.n_blocks = (int)kv->shape[0];
kvs.k_inv = 1.0f / (float)ks;
kvs.v_inv = 1.0f / (float)vs;
kvs.row = (int)(hd * r16 / 16);
return k6 ? qk_body<QK_KV_K6V4>(args, stream, kvs) : qk_body<QK_KV_F8V4>(args, stream, kvs);
}
extern "C" int r4d_rad_qk_norm_rope_gate_kv_store_fp8v4(const RadArgs* args, RadStream stream) {
return qk_kv_q4(args, stream, 0);
}
extern "C" int r4d_rad_qk_norm_rope_gate_kv_store_k6v4(const RadArgs* args, RadStream stream) {
return qk_kv_q4(args, stream, 1);
}
// The cos/sin plane the fused prologue reads: one launch a step, against `rope`'s one per layer.
// `qk_norm_rope_gate` takes a table, not a theta, so this row is what makes it usable.
//
+206 -31
View File
@@ -18,13 +18,23 @@
// `x0*s + x1*c`), under the library's -ffp-contract=off.
//
// `v_from_k` is Gemma's global class: k == v, so v is the value norm of the raw k, taken before the
// k norm overwrites it, in the order the unfused block issues them.
// k norm overwrites it, in the order the unfused block issues them. `v_norm` 0 leaves v as it is
// (a Qwen3-shaped layer, the DFlash2 drafter's: q and k normed, v not), so the launch is the two
// norms and two rotaries, and with the store v's heads only store.
//
// `qkv_norm_rope_kv_store` is the same launch followed by `kv_store`: the block of a k head (and of
// a v head) ends holding its token's finished head, so it also writes it into the paged cache at
// the token's slot, converted as kv_store converts it (E4M3: times the inverse descale, clamped to
// +-448, v_cvt_pk_fp8_f32 four columns a lane; bf16: the values as they are). The head is staged in
// LDS for that, since the fp8 store packs four neighbouring columns a lane. Byte-identical to the
// pair at either cache width; the k, v and q rows are still written, as the pair leaves them.
//
// Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "r4d_chain.h"
#include <cstdint>
#include <algorithm>
#include <cstring>
@@ -52,10 +62,12 @@ __device__ __forceinline__ float head_ss(const uint16_t* __restrict__ x, uint32_
return s;
}
// The rotary over a normed head staged in `nb`, written to `out`: rope_kernel's body for pair i.
// The rotary over a normed head staged in `nb`, written to `out` (and to `st` when the head is also
// stored): rope_kernel's body for pair i.
template <uint32_t HD>
__device__ __forceinline__ void rotate(const uint16_t* __restrict__ nb, uint16_t* __restrict__ out,
float p0, uint32_t rot, uint32_t nfreq, int den, float theta) {
float p0, uint32_t rot, uint32_t nfreq, int den, float theta,
uint16_t* __restrict__ st) {
const uint32_t half = rot / 2, t = threadIdx.x;
if (t < half) {
float inv = 1.0f / powf(theta, (float)(2 * t) / (float)den);
@@ -64,33 +76,101 @@ __device__ __forceinline__ void rotate(const uint16_t* __restrict__ nb, uint16_t
float c, s;
sincosf(ang, &s, &c);
const float x0 = bf2f(nb[t]), x1 = bf2f(nb[t + half]);
out[t] = f32_to_bf16(x0 * c - x1 * s);
out[t + half] = f32_to_bf16(x0 * s + x1 * c);
const uint16_t y0 = f32_to_bf16(x0 * c - x1 * s), y1 = f32_to_bf16(x0 * s + x1 * c);
out[t] = y0;
out[t + half] = y1;
if (st) { st[t] = y0; st[t + half] = y1; }
}
for (uint32_t i = rot + t; i < HD; i += HD) { // the unrotated tail
out[i] = nb[i];
if (st) st[i] = nb[i];
}
}
// One head into the paged cache at element offset `off` (r4d_model_bf16.hip's kv_store kernels):
// KV 1 an E4M3 cache, four columns a lane as kv_store_fp8_kernel converts them; KV 2 a bf16 cache,
// the values as they are. `src` is the head in LDS, complete before the call.
template <uint32_t HD, int KV>
__device__ __forceinline__ void kv_put(void* __restrict__ kv, size_t off,
const uint16_t* __restrict__ src, float inv) {
const uint32_t t = threadIdx.x;
if (KV == 1) {
if (t < HD / 4) {
const uint32_t d = t * 4u;
float f[4];
#pragma unroll
for (int e = 0; e < 4; ++e) f[e] = bf2f(src[d + (uint32_t)e]) * inv;
// clamped because v_cvt_pk_fp8_f32 returns NaN out of range instead of saturating
int pk = 0;
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(f[0], -448.0f), 448.0f),
fminf(fmaxf(f[1], -448.0f), 448.0f), pk, false);
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(f[2], -448.0f), 448.0f),
fminf(fmaxf(f[3], -448.0f), 448.0f), pk, true);
*(uint32_t*)((uint8_t*)kv + off + d) = (uint32_t)pk;
}
} else if (KV == 2) {
for (uint32_t i = t; i < HD; i += HD) ((uint16_t*)kv)[off + i] = src[i];
}
for (uint32_t i = rot + t; i < HD; i += HD) out[i] = nb[i]; // the unrotated tail
}
// blockIdx.y: [0, nq) a query head, [nq, nq+nkv) a key head (and with VK its value, from the raw
// key), [nq+nkv, nq+2nkv) a value head normalised in place (without VK).
template <uint32_t HD, bool WF32, bool VK>
__global__ __launch_bounds__(HD) void qkv_norm_rope_kernel(
//
// KV 1 or 2 also stores each k and v head into the paged cache [n_blocks, nkv, block_size, 2*HD]
// at slot[m] (k at column 0, v at HD), for rows m < n_slot whose slot is in range; KV 0 stores
// nothing and ignores the cache arguments.
// The body: its blocks return early (rows past the cliff, value heads), so the chained form
// (r4d_chain.h) wraps it below rather than bracketing it in place.
template <uint32_t HD, bool WF32, bool VK, int KV>
__device__ __forceinline__ void qkv_norm_rope_body(
uint16_t* __restrict__ q, uint16_t* __restrict__ k, uint16_t* __restrict__ v,
const int32_t* __restrict__ pos, const void* __restrict__ qw, const void* __restrict__ kw,
uint32_t nq, uint32_t nkv, uint32_t pq, uint32_t pk, uint32_t pv,
uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd,
uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos) {
uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos,
uint32_t m_rows, const int32_t* __restrict__ slot, void* __restrict__ kvc, uint32_t n_slot,
uint32_t block_size, uint32_t n_blocks, float k_inv, float v_inv, uint32_t vnorm) {
__shared__ float l1[HD / kWave], l2[HD / kWave];
__shared__ uint16_t nb[HD];
__shared__ uint16_t sb[KV ? HD : 1]; // the head this block stores
__shared__ uint16_t vb[(KV && VK) ? HD : 1]; // and, under VK, the value from the raw k
const uint32_t m = blockIdx.x, hh = blockIdx.y, t = threadIdx.x;
if (m >= m_rows) return; // a row the launch added past the full-card cliff (r4d_cliff_rows)
const float div = rscale != 0.0f ? rscale : 1.0f;
// rope rotates only the rows its positions cover; a row past them is normed and not rotated
const float p0 = m < n_pos ? (float)pos[m] / div : 0.0f;
// The row's cache slot, as kv_store reads it: a negative or out-of-range slot stores nothing.
// Uniform over the block, so the barriers below are too.
size_t base = 0;
bool put = false;
if (KV && m < n_slot) {
const int32_t sl = slot[m];
if (sl >= 0 && (uint32_t)sl / block_size < n_blocks) {
put = true;
base = ((size_t)((uint32_t)sl / block_size) * nkv * block_size +
(size_t)((uint32_t)sl % block_size)) * 2 * HD;
}
}
const size_t head_step = (size_t)block_size * 2 * HD;
if (hh >= nq + nkv) { // a value head, in place: rmsnorm_p
uint16_t* __restrict__ x = v + (size_t)m * v_ld + (size_t)(hh - nq - nkv) * HD;
const float s = rsqrtf(head_ss<HD>(x, pv, l1) / (float)HD + eps);
__syncthreads(); // every thread has read x before any writes it
for (uint32_t i = t; i < HD; i += HD) x[i] = f32_to_bf16(bf2f(x[i]) * s);
if (hh >= nq + nkv) { // a value head, in place: rmsnorm_p (or, without v_norm, only stored)
const uint32_t h = hh - nq - nkv;
uint16_t* __restrict__ x = v + (size_t)m * v_ld + (size_t)h * HD;
if (vnorm) {
const float s = rsqrtf(head_ss<HD>(x, pv, l1) / (float)HD + eps);
__syncthreads(); // every thread has read x before any writes it
for (uint32_t i = t; i < HD; i += HD) {
const uint16_t y = f32_to_bf16(bf2f(x[i]) * s);
x[i] = y;
if (KV) sb[i] = y;
}
} else if (KV) {
for (uint32_t i = t; i < HD; i += HD) sb[i] = x[i];
}
if (KV && put) {
__syncthreads();
kv_put<HD, KV>(kvc, base + (size_t)h * head_step + HD, sb, v_inv);
}
return;
}
const bool isq = hh < nq;
@@ -102,7 +182,11 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel(
if (VK && !isq) { // v = rmsnorm_p(raw k), before the k norm rewrites k
uint16_t* __restrict__ vo = v + (size_t)m * v_ld + (size_t)h * HD;
const float sv = rsqrtf(head_ss<HD>(x, pv, l2) / (float)HD + eps);
for (uint32_t i = t; i < HD; i += HD) vo[i] = f32_to_bf16(bf2f(x[i]) * sv);
for (uint32_t i = t; i < HD; i += HD) {
const uint16_t y = f32_to_bf16(bf2f(x[i]) * sv);
vo[i] = y;
if (KV && VK) vb[i] = y;
}
}
const float s = rsqrtf(head_ss<HD>(x, isq ? pq : pk, l1) / (float)HD + eps);
for (uint32_t i = t; i < HD; i += HD) {
@@ -110,16 +194,47 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel(
nb[i] = f32_to_bf16(bf2f(x[i]) * s * (g + wadd));
}
__syncthreads(); // the normed head is complete before any pair reads across it
if (m < n_pos) rotate<HD>(nb, x, p0, rot, nfreq, den, theta);
else for (uint32_t i = t; i < HD; i += HD) x[i] = nb[i];
uint16_t* const st = (KV && !isq) ? sb : nullptr;
if (m < n_pos) rotate<HD>(nb, x, p0, rot, nfreq, den, theta, st);
else for (uint32_t i = t; i < HD; i += HD) { x[i] = nb[i]; if (st) st[i] = nb[i]; }
if (KV && !isq && put) {
__syncthreads(); // the stored head (and VK's value) complete in LDS
kv_put<HD, KV>(kvc, base + (size_t)h * head_step, sb, k_inv);
if (VK) kv_put<HD, KV>(kvc, base + (size_t)h * head_step + HD, vb, v_inv);
}
}
#define R4D_QNR_PARAMS uint16_t* __restrict__ q, uint16_t* __restrict__ k, uint16_t* __restrict__ v, \
const int32_t* __restrict__ pos, const void* __restrict__ qw, const void* __restrict__ kw, \
uint32_t nq, uint32_t nkv, uint32_t pq, uint32_t pk, uint32_t pv, \
uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd, \
uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos, \
uint32_t m_rows, const int32_t* __restrict__ slot, void* __restrict__ kvc, uint32_t n_slot, \
uint32_t block_size, uint32_t n_blocks, float k_inv, float v_inv, uint32_t vnorm
#define R4D_QNR_ARGS q, k, v, pos, qw, kw, nq, nkv, pq, pk, pv, q_ld, k_ld, v_ld, eps, wadd, rot, nfreq, \
den, theta, rscale, n_pos, m_rows, slot, kvc, n_slot, block_size, n_blocks, k_inv, v_inv, vnorm
// The plain kernel, and the chained one (r4dchain*, r4d_chain.h) wrapping the same body.
template <uint32_t HD, bool WF32, bool VK, int KV>
__global__ __launch_bounds__(HD) void qkv_norm_rope_kernel(R4D_QNR_PARAMS) {
qkv_norm_rope_body<HD, WF32, VK, KV>(R4D_QNR_ARGS);
}
template <uint32_t HD, bool WF32, bool VK, int KV>
__global__ __launch_bounds__(HD) void r4dchain_qkv_norm_rope(R4D_QNR_PARAMS) {
r4d_chain_wait();
qkv_norm_rope_body<HD, WF32, VK, KV>(R4D_QNR_ARGS);
r4d_chain_done();
}
#undef R4D_QNR_ARGS
#undef R4D_QNR_PARAMS
} // namespace
// ============================================================== the plugin ABI entry point
enum { QN_Q = 0, QN_K, QN_V, QN_POS, QN_QW, QN_KW };
// ============================================================== the plugin ABI entry points
enum { QN_Q = 0, QN_K, QN_V, QN_POS, QN_QW, QN_KW, QN_SLOT, QN_CACHE };
extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) {
// Both ops' launch: `store` reads qkv_norm_rope_kv_store's slot mapping and cache (operands 6, 7)
// and its kv_store parameters.
static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store) {
int emit_rc = RAD_OK;
const RadTensor* q = r4d_opt(a, QN_Q);
const RadTensor* k = r4d_opt(a, QN_K);
@@ -136,8 +251,12 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) {
const long long nkv = r4d_geti_or(a, "n_head_kv", 0);
const long long rot = r4d_geti_or(a, "rotary_dim", hd);
const long long vk = r4d_geti_or(a, "v_from_k", 0);
if (hd != 256 && hd != 512) return R4D_NO(RAD_E_SHAPE);
if (nq <= 0 || nkv <= 0 || rot <= 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
// v_norm 0: no value norm (Gemma 3; a Qwen3-shaped layer such as the DFlash2 drafter's): the v
// heads are left out of the grid, or with the store only store.
const long long vn = r4d_geti_or(a, "v_norm", 1);
if (hd != 128 && hd != 256 && hd != 512) return R4D_NO(RAD_E_SHAPE);
if (vk && !vn) return R4D_NO(RAD_E_INVAL); // v from k is v's norm
if (nq < 0 || nkv <= 0 || rot <= 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(qw) != hd || r4d_numel(kw) != hd) return R4D_NO(RAD_E_SHAPE);
const char* mode = r4d_gets(a, "mode");
if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED);
@@ -153,34 +272,90 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) {
const long long rot_l = (den == hd && rot < hd) ? hd : rot;
long long M = 0, Mk = 0, Mv = 0;
const long long q_ld = r4d_rows_pitch(q, nq * hd, &M);
/* n_head 0: the k (and v) heads alone, q neither read nor written (a context pass's keys) */
const long long q_ld = nq ? r4d_rows_pitch(q, nq * hd, &M) : 0;
const long long k_ld = r4d_rows_pitch(k, nkv * hd, &Mk);
const long long v_ld = r4d_rows_pitch(v, nkv * hd, &Mv);
if (q_ld < 0 || k_ld < 0 || v_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (!nq) M = Mk;
const long long Mp = r4d_numel(ps);
if (Mp <= 0 || M < Mp || Mk != M || Mv != M) return R4D_NO(RAD_E_SHAPE);
// The standalone kernels' widths, from the same function: rmsnorm (one row per head) at
// r4d_act_threads(rows, head_dim), rmsnorm_p at 256.
const uint32_t pq = (uint32_t)std::min<long long>(r4d_act_threads((int)(M * nq), (int)hd), hd);
const uint32_t pq = nq ? (uint32_t)std::min<long long>(r4d_act_threads((int)(M * nq), (int)hd), hd)
: (uint32_t)hd;
const uint32_t pk = (uint32_t)std::min<long long>(r4d_act_threads((int)(M * nkv), (int)hd), hd);
const uint32_t pv = (uint32_t)std::min<long long>(256, hd);
const float eps = (float)r4d_getf(a, "eps", 1e-6);
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
const float theta = (float)r4d_getf(a, "theta", 10000.0);
const float rsc = (float)r4d_getf(a, "scale", 1.0);
const dim3 grid((uint32_t)M, (uint32_t)(nq + nkv + (vk ? 0 : nkv)));
/* v's own heads: normed (and stored), stored only, or with neither nothing to do */
const uint32_t heads = (uint32_t)(nq + nkv + ((vk || (!vn && !store)) ? 0 : nkv));
// A tp-4 verify of the 31B is 16 rows x 16 heads of 8 wavefronts: exactly a full card, the
// cliff r4d_cliff_rows steps past with one idle row.
const dim3 grid(r4d_cliff_rows((uint32_t)M, heads, (uint32_t)(hd / kWave)), heads);
const bool chain = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; /* RadKernelChainFn, decode */
#define R4D_QNR_T(HD, WF, VK) emit_rc = R4D_EMIT(stream, (qkv_norm_rope_kernel<HD, WF, VK>), grid, dim3(HD), 0, \
// The store's geometry, checked as kv_store_geom checks it (r4d_model_bf16.hip).
int kvw = 0; // 0 none, 1 E4M3, 2 bf16
const RadTensor* sm = nullptr;
const RadTensor* kv = nullptr;
long long bs = 0, nblk = 0, nslot = 0;
float kinv = 1.0f, vinv = 1.0f;
if (store) {
sm = r4d_opt(a, QN_SLOT);
kv = r4d_opt(a, QN_CACHE);
if (!sm || !kv) return R4D_NO(RAD_E_INVAL);
if (sm->dtype != RAD_I32 || !r4d_contig(sm) || !r4d_contig(kv)) return R4D_NO(RAD_E_STRIDE);
bs = r4d_geti_or(a, "block_size", 0);
if (bs <= 0 || kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs ||
kv->shape[3] != 2 * hd)
return R4D_NO(RAD_E_SHAPE);
nblk = kv->shape[0];
nslot = r4d_numel(sm);
if (nslot <= 0 || nslot > M) return R4D_NO(RAD_E_SHAPE);
if (kv->dtype == RAD_F8E4M3) {
const double ks = r4d_getf(a, "k_scale", 1.0), vs = r4d_getf(a, "v_scale", 1.0);
if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL);
kinv = 1.0f / (float)ks;
vinv = 1.0f / (float)vs;
kvw = 1;
} else if (kv->dtype == RAD_BF16) {
kvw = 2;
} else {
return R4D_NO(RAD_E_DTYPE);
}
}
#define R4D_QNR_T(HD, WF, VK, KV) emit_rc = chain ? R4D_QNR_C(HD, WF, VK, KV, true) : R4D_QNR_C(HD, WF, VK, KV, false)
#define R4D_QNR_C(HD, WF, VK, KV, CH) R4D_EMIT(stream, (CH ? r4dchain_qkv_norm_rope<HD, WF, VK, KV> : qkv_norm_rope_kernel<HD, WF, VK, KV>), grid, dim3(HD), 0, \
(uint16_t*)r4d_wp(q), (uint16_t*)r4d_wp(k), (uint16_t*)r4d_wp(v), (const int32_t*)r4d_p(ps), \
r4d_p(qw), r4d_p(kw), (uint32_t)nq, (uint32_t)nkv, pq, pk, pv, (uint32_t)q_ld, (uint32_t)k_ld, \
(uint32_t)v_ld, eps, wadd, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp)
(uint32_t)v_ld, eps, wadd, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp, \
(uint32_t)M, (const int32_t*)(sm ? r4d_p(sm) : nullptr), (void*)(kv ? r4d_wp(kv) : nullptr), \
(uint32_t)nslot, (uint32_t)bs, (uint32_t)nblk, kinv, vinv, (uint32_t)(vn ? 1 : 0))
#define R4D_QNR_KV(HD, WF, VK) \
do { if (kvw == 1) R4D_QNR_T(HD, WF, VK, 1); else if (kvw == 2) R4D_QNR_T(HD, WF, VK, 2); \
else R4D_QNR_T(HD, WF, VK, 0); } while (0)
#define R4D_QNR(HD) \
do { if (qw->dtype == RAD_F32) { if (vk) R4D_QNR_T(HD, true, true); else R4D_QNR_T(HD, true, false); } \
else { if (vk) R4D_QNR_T(HD, false, true); else R4D_QNR_T(HD, false, false); } } while (0)
if (hd == 256) R4D_QNR(256);
else R4D_QNR(512);
do { if (qw->dtype == RAD_F32) { if (vk) R4D_QNR_KV(HD, true, true); else R4D_QNR_KV(HD, true, false); } \
else { if (vk) R4D_QNR_KV(HD, false, true); else R4D_QNR_KV(HD, false, false); } } while (0)
if (hd == 128) R4D_QNR(128);
else if (hd == 256) R4D_QNR(256);
else R4D_QNR(512);
#undef R4D_QNR
#undef R4D_QNR_KV
#undef R4D_QNR_T
#undef R4D_QNR_C
return emit_rc;
}
extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) {
return qkv_norm_rope_launch(a, stream, false);
}
extern "C" int r4d_rad_qkv_norm_rope_kv_store(const RadArgs* a, RadStream stream) {
return qkv_norm_rope_launch(a, stream, true);
}
+60 -28
View File
@@ -65,15 +65,28 @@ static inline int lds_cap_of() {
return v;
}
/* The order key, by the op's `signed` parameter: the unsigned order (Signed = false, the
* default) or the signed one. Key 0 means "no block" in both. */
template <bool Signed> __device__ __forceinline__ uint32_t keyof(float v, int page);
/* Order key. Scores are >= 0 or -inf, and non-negative float bit patterns order as unsigned.
* `+1` keeps a live score of exactly zero above key 0, which means "no block". The clamp is a
* select, not fmaxf: fmaxf(-0.0f, 0.0f) may return -0.0f, whose sign bit would rank it above
* every positive score. */
__device__ __forceinline__ uint32_t keyof(float v, int page) {
template <> __device__ __forceinline__ uint32_t keyof<false>(float v, int page) {
if (page < 0 || !(v > -1e30f)) return 0u;
return __float_as_uint(v > 0.0f ? v : 0.0f) + 1u;
}
/* Signed order key, for indexers whose scores can be negative (GLM's head gates): the float's
* total order over all 32 bits. Absent pages and nonfinite scores are key 0, which no finite
* score maps to (only NaN bit patterns would); both signed zeros map to one key, so they tie. */
template <> __device__ __forceinline__ uint32_t keyof<true>(float v, int page) {
if (page < 0 || !__builtin_isfinite(v)) return 0u;
const uint32_t bits = v == 0 ? 0u : __float_as_uint(v);
return (bits & 0x80000000u) ? ~bits : (bits ^ 0x80000000u);
}
/* Scans run in registers on DPP (five steps per wave, r4d_common.h); only wave totals go through
* LDS, instead of step-doubling LDS rounds with barriers that wait on up to 32 waves.
*
@@ -115,6 +128,7 @@ __device__ __forceinline__ void counts_before(const uint32_t* wsum, int lane, in
* block table and complete-block count. The per-query bound is (pos + 1) / ratio: block b is
* entirely in the query's past when b * ratio + ratio - 1 <= pos. At decode this equals the
* sequence's complete count. */
template <bool Signed>
__global__ __launch_bounds__(kThreads) void qsa_select_kernel(
const float* __restrict__ score, const int32_t* __restrict__ bt,
const int32_t* __restrict__ nc, const int32_t* __restrict__ pos,
@@ -153,7 +167,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel(
if (cached) {
for (int b0 = 0; b0 < n; b0 += kThreads) {
const int b = b0 + t;
if (b < n) sh_key[b] = keyof(sc[b], tb[b]);
if (b < n) sh_key[b] = keyof<Signed>(sc[b], tb[b]);
}
__syncthreads();
}
@@ -168,7 +182,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel(
__syncthreads();
const uint32_t mask = (shift == 24) ? 0u : (0xFFFFFFFFu << (shift + 8));
for (int b = t; b < n; b += kThreads) {
const uint32_t k = cached ? sh_key[b] : keyof(sc[b], tb[b]);
const uint32_t k = cached ? sh_key[b] : keyof<Signed>(sc[b], tb[b]);
if (k != 0u && (k & mask) == (fixed & mask))
atomicAdd(&hist[(k >> shift) & 255u], 1u);
}
@@ -214,7 +228,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel(
for (int b0 = 0; b0 < n; b0 += kThreads) {
const int b = b0 + t;
uint32_t k = 0;
if (b < n) k = cached ? sh_key[b] : keyof(sc[b], tb[b]);
if (b < n) k = cached ? sh_key[b] : keyof<Signed>(sc[b], tb[b]);
const bool hi = k != 0u && (n <= topk || k > T);
const bool eq = k != 0u && n > topk && k == T;
@@ -297,7 +311,14 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel(
* count) does not depend on the digit split, and the emit is the same. r4d_selftest compares the
* two byte for byte. */
constexpr int kWideBits = 12; /* the first digit */
constexpr int kWideShift = 31 - kWideBits; /* a key's bit 31 is clear: see keyof */
/* The first digit's shift, by key order. */
template <bool Signed> struct WideKey;
template <> struct WideKey<false> {
static constexpr int kWideShift = 31 - kWideBits; /* a key's bit 31 is clear: see keyof */
};
template <> struct WideKey<true> {
static constexpr int kWideShift = 32 - kWideBits; /* the signed key uses all 32 bits */
};
constexpr int kWideBins = 1 << kWideBits;
constexpr int kWideCand = kWideBins - kBins; /* keys the second pass may collect */
constexpr int kWidePer = kWideBins / kThreads; /* first-digit bins a thread scans */
@@ -377,6 +398,7 @@ __device__ __forceinline__ void lds_kth(const uint32_t* keys, int cnt, uint32_t
*need = want;
}
template <bool Signed>
__global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel(
const float* __restrict__ score, const int32_t* __restrict__ bt,
const int32_t* __restrict__ nc, const int32_t* __restrict__ pos,
@@ -402,6 +424,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel(
const int m = blockIdx.x;
const int t = threadIdx.x;
const int lane = t & (kWave - 1), wave = t >> 5;
constexpr int kWideShift = WideKey<Signed>::kWideShift;
if (t == 0) sh_seq = 0;
__syncthreads();
@@ -426,7 +449,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel(
for (int i = t; i < kSamp; i += kThreads) {
const int r = i / kSampRun, j = i % kSampRun;
const long b = (long)r * (n - kSampRun) / (kSampRuns - 1) + j;
samp[i] = keyof(sc[b], tb[b]);
samp[i] = keyof<Signed>(sc[b], tb[b]);
}
__syncthreads();
uint32_t ms = (uint32_t)(((uint64_t)topk * 2u * kSamp + (uint64_t)n - 1u) / (uint64_t)n) + 8u;
@@ -448,14 +471,14 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel(
if (vec && bb + kPer <= n) {
const float4 s0 = *(const float4*)(sc + bb), s1 = *(const float4*)(sc + bb + 4);
const int4 p0 = *(const int4*)(tb + bb), p1 = *(const int4*)(tb + bb + 4);
kk[0] = keyof(s0.x, p0.x); kk[1] = keyof(s0.y, p0.y);
kk[2] = keyof(s0.z, p0.z); kk[3] = keyof(s0.w, p0.w);
kk[4] = keyof(s1.x, p1.x); kk[5] = keyof(s1.y, p1.y);
kk[6] = keyof(s1.z, p1.z); kk[7] = keyof(s1.w, p1.w);
kk[0] = keyof<Signed>(s0.x, p0.x); kk[1] = keyof<Signed>(s0.y, p0.y);
kk[2] = keyof<Signed>(s0.z, p0.z); kk[3] = keyof<Signed>(s0.w, p0.w);
kk[4] = keyof<Signed>(s1.x, p1.x); kk[5] = keyof<Signed>(s1.y, p1.y);
kk[6] = keyof<Signed>(s1.z, p1.z); kk[7] = keyof<Signed>(s1.w, p1.w);
} else {
#pragma unroll
for (int e = 0; e < kPer; ++e)
kk[e] = bb + e < n ? keyof(sc[bb + e], tb[bb + e]) : 0u;
kk[e] = bb + e < n ? keyof<Signed>(sc[bb + e], tb[bb + e]) : 0u;
}
uint32_t mine = 0;
#pragma unroll
@@ -514,7 +537,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel(
for (int i = t; i < kWideBins; i += kThreads) wide[i] = 0;
__syncthreads();
for (int b = t; b < n; b += kThreads) {
const uint32_t k = keyof(sc[b], tb[b]);
const uint32_t k = keyof<Signed>(sc[b], tb[b]);
if (k != 0u) atomicAdd(&wide[k >> kWideShift], 1u);
}
__syncthreads();
@@ -565,7 +588,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel(
uint32_t n_in = 0;
for (int b0 = 0; b0 < n; b0 += kThreads) {
const int b = b0 + t;
const uint32_t k = b < n ? keyof(sc[b], tb[b]) : 0u;
const uint32_t k = b < n ? keyof<Signed>(sc[b], tb[b]) : 0u;
const bool abv = k != 0u && (k >> kWideShift) > B;
const bool inb = k != 0u && (k >> kWideShift) == B;
const unsigned long long ma = __ballot(abv), mi = __ballot(inb);
@@ -594,7 +617,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel(
__syncthreads();
} else if (inlds) {
for (int b = t; b < n; b += kThreads) {
const uint32_t k = keyof(sc[b], tb[b]);
const uint32_t k = keyof<Signed>(sc[b], tb[b]);
if (k != 0u && (k >> kWideShift) == B) cand[atomicAdd(&sh_cnt, 1u)] = k;
}
__syncthreads();
@@ -602,7 +625,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel(
const int ncand = (merged || inlds) ? (int)sh_cnt : n;
const uint32_t* const keys = merged ? mkey : cand;
/* ---- the other 19 bits: digits of 8, 8 and 3. */
/* ---- the other 19 bits: digits of 8, 8 and 3 (20 bits and 8, 8, 4 when signed). */
const int shifts[3] = { kWideShift - 8, kWideShift - 16, 0 };
const int widths[3] = { 8, 8, kWideShift - 16 };
#pragma unroll
@@ -613,7 +636,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel(
for (int i = t; i < kBins; i += kThreads) hist[i] = 0;
__syncthreads();
for (int i = t; i < ncand; i += kThreads) {
const uint32_t k = (merged || inlds) ? keys[i] : keyof(sc[i], tb[i]);
const uint32_t k = (merged || inlds) ? keys[i] : keyof<Signed>(sc[i], tb[i]);
if (k != 0u && (k & hm) == (fixed & hm)) atomicAdd(&hist[(k >> shift) & dm], 1u);
}
__syncthreads();
@@ -687,7 +710,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel(
for (int b0 = 0; b0 < ((merged || sampled) ? 0 : n); b0 += kThreads) {
const int b = b0 + t;
uint32_t k = 0;
if (b < n) k = keyof(sc[b], tb[b]);
if (b < n) k = keyof<Signed>(sc[b], tb[b]);
const bool hi = k != 0u && (n <= topk || k > T);
const bool eq = k != 0u && n > topk && k == T;
@@ -887,6 +910,7 @@ __device__ __forceinline__ ParTake par_take(ParEmit& e, uint32_t k, int lane, in
}
/* ---- pass one: every chunk's own top-k, as (key, block index) in block order. */
template <bool Signed>
__global__ __launch_bounds__(kLocalThreads) void qsa_local_kernel(
const float* __restrict__ score, const int32_t* __restrict__ bt,
const int32_t* __restrict__ nc, const int32_t* __restrict__ pos,
@@ -921,7 +945,7 @@ __global__ __launch_bounds__(kLocalThreads) void qsa_local_kernel(
const float* sc = score + (size_t)m * s_ld;
const int32_t* tb = bt + (size_t)seq * t_ld;
for (int i = t; i < cn; i += LT) sh_key[i] = keyof(sc[lo + i], tb[lo + i]);
for (int i = t; i < cn; i += LT) sh_key[i] = keyof<Signed>(sc[lo + i], tb[lo + i]);
__syncthreads();
ParEmit e{ wsum, &sh_hi, &sh_ord, 0u, 0u, 0u, cn <= topk };
@@ -955,6 +979,7 @@ __global__ __launch_bounds__(kLocalThreads) void qsa_local_kernel(
}
/* ---- pass two: merge the chunk lists and emit the page-id table. */
template <bool Signed>
__global__ __launch_bounds__(kMergeThreads) void qsa_merge_kernel(
const uint32_t* __restrict__ ck, const int32_t* __restrict__ ci,
const int32_t* __restrict__ cc, const int32_t* __restrict__ bt,
@@ -1071,6 +1096,8 @@ static inline int64_t par_scratch_bytes(long long topk) {
// cu [nseq+1] i32, cumulative query counts: which sequence a query row belongs to
// sel [M][topk+1] i32, `o_ld` elements a row (0 = topk+1); -1 padded
// nsel [M] i32
// Signed selects the key order (keyof), from the op's `signed` parameter.
template <bool Signed>
static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long cu, long sel,
long nsel, long seqused, int M, int nb, int topk, int ratio,
int nseq, int s_ld, int t_ld, int o_ld,
@@ -1093,13 +1120,14 @@ static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long
uint32_t* ck = (uint32_t*)scratch;
int32_t* ci = (int32_t*)(ck + (size_t)kParM * kParWMax * topk);
int32_t* cc = ci + (size_t)kParM * kParWMax * topk;
const int rc = R4D_EMIT(stream, qsa_local_kernel, dim3((unsigned)nchunk, (unsigned)M),
dim3(kLocalThreads), (size_t)chunk * sizeof(uint32_t),
const int rc = R4D_EMIT(stream, qsa_local_kernel<Signed>,
dim3((unsigned)nchunk, (unsigned)M), dim3(kLocalThreads),
(size_t)chunk * sizeof(uint32_t),
(const float*)score, (const int32_t*)bt, (const int32_t*)nc,
(const int32_t*)pos, (const int32_t*)cu, ck, ci, cc, nb, topk,
ratio, nseq, s_ld, t_ld, chunk);
if (rc != RAD_OK) return rc;
return R4D_EMIT(stream, qsa_merge_kernel, dim3((unsigned)M), dim3(kMergeThreads),
return R4D_EMIT(stream, qsa_merge_kernel<Signed>, dim3((unsigned)M), dim3(kMergeThreads),
(size_t)nchunk * topk * sizeof(uint32_t), (const uint32_t*)ck,
(const int32_t*)ci, (const int32_t*)cc, (const int32_t*)bt,
(const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu,
@@ -1109,7 +1137,8 @@ static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long
/* A wide launch (prefill chunk, key cache off) takes the wide kernel. */
if (g_qsa_select_form == 2 || (g_qsa_select_form == 0 && M > kCacheMaxM)) {
return R4D_EMIT(stream, qsa_select_wide_kernel, dim3((unsigned)M), dim3(kThreads), 0,
return R4D_EMIT(stream, qsa_select_wide_kernel<Signed>, dim3((unsigned)M),
dim3(kThreads), 0,
(const float*)score, (const int32_t*)bt, (const int32_t*)nc,
(const int32_t*)pos, (const int32_t*)cu, (int32_t*)sel,
(int32_t*)nsel, (int32_t*)seqused, nb, topk, ratio, nseq, s_ld, t_ld,
@@ -1119,7 +1148,7 @@ static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long
/* Never more than the table width. */
int cap = (M <= kCacheMaxM) ? lds_cap_of() : 0;
if (cap > nb) cap = nb;
return R4D_EMIT(stream, qsa_select_kernel, dim3((unsigned)M), dim3(kThreads),
return R4D_EMIT(stream, qsa_select_kernel<Signed>, dim3((unsigned)M), dim3(kThreads),
(size_t)cap * sizeof(uint32_t), (const float*)score, (const int32_t*)bt,
(const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu,
(int32_t*)sel, (int32_t*)nsel,
@@ -1151,7 +1180,9 @@ extern "C" int r4d_rad_qsa_select(const RadArgs* a, RadStream stream) {
if (sc->rank != 2 || bt->rank != 2 || se->rank != 2) return R4D_NO(RAD_E_SHAPE);
const long long topk = r4d_geti_or(a, "topk", 0);
const long long ratio = r4d_geti_or(a, "ratio", 0);
const long long sgn = r4d_geti_or(a, "signed", 0);
if (topk <= 0 || ratio <= 0) return R4D_NO(RAD_E_INVAL);
if (sgn != 0 && sgn != 1) return R4D_NO(RAD_E_INVAL);
/* nb = min of the two widths, as in r4d_qsa_score_bf16.hip. */
const long long M = sc->shape[0];
const long long nb = bt->shape[1] < sc->shape[1] ? bt->shape[1] : sc->shape[1];
@@ -1167,10 +1198,11 @@ extern "C" int r4d_rad_qsa_select(const RadArgs* a, RadStream stream) {
const long long sp = r4d_row_pitch(sc), tp = r4d_row_pitch(bt), op = r4d_row_pitch(se);
if (sp < 0 || tp < 0 || op < 0) return R4D_NO(RAD_E_STRIDE);
/* Scratch is optional: without enough, the non-split kernels run. */
return r4d_qsa_select_bf16_emit(r4d_addr(sc), r4d_addr(bt), r4d_addr(nc), r4d_addr(po),
r4d_addr(cu), r4d_addr(se), r4d_addr(ns), r4d_addr(su),
(int)M, (int)nb, (int)topk, (int)ratio, (int)nseq,
(int)sp, (int)tp, (int)op, a->scratch, a->scratch_bytes,
stream);
auto* const emit = sgn ? r4d_qsa_select_bf16_emit<true> : r4d_qsa_select_bf16_emit<false>;
return emit(r4d_addr(sc), r4d_addr(bt), r4d_addr(nc), r4d_addr(po),
r4d_addr(cu), r4d_addr(se), r4d_addr(ns), r4d_addr(su),
(int)M, (int)nb, (int)topk, (int)ratio, (int)nseq,
(int)sp, (int)tp, (int)op, a->scratch, a->scratch_bytes,
stream);
}
+31 -7
View File
@@ -25,6 +25,7 @@
#include "r4d_fp8_args.h"
#include "r4d_fp8_wmma.h"
#include "r4d_fwht.h"
#include "r4d_chain.h"
namespace {
@@ -43,10 +44,14 @@ constexpr uint32_t kGroup = 128;
//
// I8 is the same quantiser at int8 codes (quant_act_i8g, had_quant_act_i8g): scale amax/127,
// round-to-nearest-even into -127..127, same row-major layout and per-(row, 128) scales.
template <bool ROT, bool I8 = false>
__global__ __launch_bounds__(kThreads) void quant_act_fp8_kernel(
//
// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); no block returns
// early. quant_act_fp8_kernel and r4dchain_quant_act_fp8 below are the plain and chained forms.
template <bool ROT, bool I8 = false, bool CHAIN = false>
__device__ __forceinline__ void quant_act_fp8_body(
const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s,
uint32_t K, uint32_t nkb, uint32_t x_ld, uint32_t q_ld, uint32_t s_ld) {
if (CHAIN) r4d_chain_wait();
const uint32_t row = blockIdx.x;
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
const size_t xrow = (size_t)row * x_ld;
@@ -92,8 +97,21 @@ __global__ __launch_bounds__(kThreads) void quant_act_fp8_kernel(
// of the accumulators. The caller must own K rounded up to 4 bytes of `q`.
if (c0 < K) *(uint32_t*)(q + qrow + c0) = (uint32_t)pk;
}
if (CHAIN) r4d_chain_done();
}
#define R4D_QAF_PARAMS const uint16_t* __restrict__ x, uint8_t* __restrict__ q, \
float* __restrict__ s, uint32_t K, uint32_t nkb, uint32_t x_ld, uint32_t q_ld, uint32_t s_ld
template <bool ROT, bool I8 = false>
__global__ __launch_bounds__(kThreads) void quant_act_fp8_kernel(R4D_QAF_PARAMS) {
quant_act_fp8_body<ROT, I8, false>(x, q, s, K, nkb, x_ld, q_ld, s_ld);
}
template <bool ROT, bool I8 = false>
__global__ __launch_bounds__(kThreads) void r4dchain_quant_act_fp8(R4D_QAF_PARAMS) {
quant_act_fp8_body<ROT, I8, true>(x, q, s, K, nkb, x_ld, q_ld, s_ld);
}
#undef R4D_QAF_PARAMS
} // namespace
extern "C" int r4d_quant_act_fp8_group(void) { return (int)kGroup; }
@@ -105,7 +123,7 @@ extern "C" int r4d_quant_act_fp8_group(void) { return (int)kGroup; }
// `rot` runs the 128-wide Hadamard first and additionally requires K % 128 == 0 (see the kernel).
static int quant_act_fp8_launch(long a, long q, long s, int M, int K,
int x_ld, int q_ld, int s_ld, RadStream stream, bool rot,
bool i8 = false) {
bool i8 = false, bool chain = false) {
int emit_rc = RAD_OK;
if (!a || !q || !s) return -1;
if (M <= 0 || K <= 0) return -2;
@@ -115,10 +133,15 @@ static int quant_act_fp8_launch(long a, long q, long s, int M, int K,
if (!q_ld) q_ld = K;
const int nkb = (K + (int)kGroup - 1) / (int)kGroup;
if (!s_ld) s_ld = nkb;
/* The chained form at decode heights, where the row resolved with `chain`. */
const bool ch = chain && M <= 64;
#define R4D_QA(ROT_, I8_) \
R4D_EMIT(stream, (quant_act_fp8_kernel<ROT_, I8_>), dim3((uint32_t)M), dim3(kThreads), 0, \
(const uint16_t*)a, (uint8_t*)q, (float*)s, (uint32_t)K, (uint32_t)nkb, \
(uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld)
(ch ? R4D_EMIT(stream, (r4dchain_quant_act_fp8<ROT_, I8_>), dim3((uint32_t)M), \
dim3(kThreads), 0, (const uint16_t*)a, (uint8_t*)q, (float*)s, (uint32_t)K, \
(uint32_t)nkb, (uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld) \
: R4D_EMIT(stream, (quant_act_fp8_kernel<ROT_, I8_>), dim3((uint32_t)M), \
dim3(kThreads), 0, (const uint16_t*)a, (uint8_t*)q, (float*)s, (uint32_t)K, \
(uint32_t)nkb, (uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld))
if (i8) emit_rc = rot ? R4D_QA(true, true) : R4D_QA(false, true);
else emit_rc = rot ? R4D_QA(true, false) : R4D_QA(false, false);
#undef R4D_QA
@@ -163,7 +186,8 @@ static int rad_quant_act_fp8(const RadArgs* a, RadStream stream, bool rot, bool
const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc);
if (xp < 0 || qp < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE);
const int e = quant_act_fp8_launch(r4d_addr(x), r4d_addr(q), r4d_addr(sc), (int)M, (int)K,
(int)xp, (int)qp, (int)sp, stream, rot, i8);
(int)xp, (int)qp, (int)sp, stream, rot, i8,
r4d_geti_or(a, "chain", 0) != 0);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
+29 -5
View File
@@ -11,13 +11,17 @@
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "r4d_chain.h"
#include <hip/hip_bf16.h>
#include <cstdint>
template <int THR>
__global__ __launch_bounds__(THR) void r4d_quant_act_i8_kernel(
/* CHAIN: the chained form's wait and add (r4d_chain.h) around the same body; no block returns
* early. */
template <int THR, bool CHAIN = false>
__device__ __forceinline__ void r4d_quant_act_i8_body(
const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S,
int K) {
if (CHAIN) r4d_chain_wait();
const int row = blockIdx.x;
const __hip_bfloat16* a = A + (size_t)row * K;
signed char* q = Q + (size_t)row * K;
@@ -47,6 +51,20 @@ __global__ __launch_bounds__(THR) void r4d_quant_act_i8_kernel(
const int t = __float2int_rn(v);
q[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
}
if (CHAIN) r4d_chain_done();
}
template <int THR>
__global__ __launch_bounds__(THR) void r4d_quant_act_i8_kernel(
const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S,
int K) {
r4d_quant_act_i8_body<THR, false>(A, Q, S, K);
}
template <int THR>
__global__ __launch_bounds__(THR) void r4dchain_quant_act_i8(
const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S,
int K) {
r4d_quant_act_i8_body<THR, true>(A, Q, S, K);
}
// ---------------------------------------------------------------------------------------------
@@ -126,9 +144,15 @@ extern "C" int r4d_rad_quant_act_i8(const RadArgs* args, RadStream stream) {
const int thr = r4d_act_threads((int)M, (int)K); // the workgroup width, from M
if (!as) {
#define R4D_QAI8_LAUNCH(T) emit_rc = R4D_EMIT(stream, (r4d_quant_act_i8_kernel<T>), \
dim3((int)M), dim3(T), 0, (const __hip_bfloat16*)r4d_p(x), (signed char*)r4d_wp(q), \
(float*)r4d_wp(sc), (int)K)
/* The chained form where the row resolved with `chain`, at decode heights. */
const bool chain = r4d_geti_or(args, "chain", 0) != 0 && M <= 64;
#define R4D_QAI8_LAUNCH(T) emit_rc = chain \
? R4D_EMIT(stream, (r4dchain_quant_act_i8<T>), dim3((int)M), dim3(T), 0, \
(const __hip_bfloat16*)r4d_p(x), (signed char*)r4d_wp(q), (float*)r4d_wp(sc), \
(int)K) \
: R4D_EMIT(stream, (r4d_quant_act_i8_kernel<T>), dim3((int)M), dim3(T), 0, \
(const __hip_bfloat16*)r4d_p(x), (signed char*)r4d_wp(q), (float*)r4d_wp(sc), \
(int)K)
switch (thr) {
case 128: R4D_QAI8_LAUNCH(128); break;
case 256: R4D_QAI8_LAUNCH(256); break;
+794 -1
View File
@@ -28,11 +28,13 @@
// pass reads its own writes back.
//
// Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip.
#include "r4d_chain.h"
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "r4d_ar_seq.h"
#include "r4d_ar_wide.h"
#include <cstdint>
namespace {
@@ -123,6 +125,30 @@ __device__ __forceinline__ float scalar_of(const void* sc, uint32_t f32) {
return f32 ? ((const float*)sc)[0] : bf2f(((const uint16_t*)sc)[0]);
}
// The exact all-reduce's fold of one 16-byte word (eight bf16): every source's word loaded first,
// then per element fp32 from 0.0f, the sources in ascending rank, one rounding through
// bf16_hi_rne_nan -- ar_vsum's arithmetic, so the word is the standalone exact all-reduce's.
template <int WS>
__device__ __forceinline__ int4 fold_word8(const int4* const* src4, size_t k) {
int4 v[WS];
#pragma unroll
for (int r = 0; r < WS; ++r) v[r] = src4[r][k];
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 uint16_t* pv = reinterpret_cast<const uint16_t*>(&v[r]);
#pragma unroll
for (int j = 0; j < 8; ++j) acc[j] += bf2f(pv[j]);
}
int4 a;
uint16_t* pa = reinterpret_cast<uint16_t*>(&a);
#pragma unroll
for (int j = 0; j < 8; ++j) pa[j] = (uint16_t)(bf16_hi_rne_nan(acc[j]) >> 16);
return a;
}
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR>
__global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
@@ -148,6 +174,113 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel(
ybuf, l2, lm);
}
// The same kernel at decode heights (THR 1024, n <= 1024 * EPT), with every operand of the row
// loaded in one go before the first reduction. The kernel above reads the row again in each pass,
// each read behind a barrier, so a row costs three dependent memory round trips; on gfx1201 that
// held the kernel at 11 us at any height against a 4.2 us launch floor, and this form at 8.2 us
// (4x R9700, 1 to 16 rows of 5376, 2026-10-17). Every pass partitions the row the same way (thread
// t takes columns t, t+THR, ...), so each thread keeps its own columns in registers and none needs
// another's; only the fragment-order store crosses threads, through `ybuf` as before. The sums,
// the order they are taken in and every element's arithmetic are junction_row's, so the bytes are.
// One row of it, for this kernel and for the all-reduce's tail (ar_rmsnorm_quant_i8_tail_kernel).
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, uint32_t EPT>
__device__ __forceinline__ void junction_reg_row(
const uint16_t* __restrict__ xr, uint16_t* __restrict__ rr, const void* __restrict__ w,
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32,
signed char* __restrict__ qr, float* __restrict__ Sr, uint16_t* __restrict__ yr, uint32_t n,
float eps, float wadd, uint16_t* ybuf, float* l1, float* l2, float* lm) {
const uint32_t tid = threadIdx.x;
uint16_t xv[EPT], rv[EPT];
float gp[EPT], gw[EPT];
#pragma unroll
for (uint32_t e = 0; e < EPT; ++e) {
const uint32_t i = tid + e * THR;
xv[e] = 0; rv[e] = 0; gp[e] = 0.0f; gw[e] = 0.0f;
if (i < n) {
xv[e] = xr[i];
if (RES) rv[e] = rr[i];
if (POST) gp[e] = gain(wp, i, WF32) + wadd;
gw[e] = gain(w, i, WF32) + wadd;
}
}
const float sv = SCL ? scalar_of(sc, sc_f32) : 1.0f;
// ---- the post-norm's sum of squares, over the branch output
float s1 = 0.0f;
if (POST) {
float ss = 0.0f;
#pragma unroll
for (uint32_t e = 0; e < EPT; ++e)
if (tid + e * THR < n) { const float v = bf2f(xv[e]); ss += v * v; }
s1 = rsqrtf(block_sum<THR / kWave>(ss, l1) / (float)n + eps);
}
// ---- the junction (post-norm, add, scalar), stored, and the norm's sum of squares over it
float ss2 = 0.0f;
#pragma unroll
for (uint32_t e = 0; e < EPT; ++e) {
const uint32_t i = tid + e * THR;
if (i < n) {
uint16_t v = xv[e];
if (RES) {
if (POST) v = f32_to_bf16(bf2f(v) * s1 * gp[e]);
v = f32_to_bf16(bf2f(rv[e]) + bf2f(v));
if (SCL) v = f32_to_bf16(bf2f(v) * sv);
rr[i] = v;
}
xv[e] = v;
const float f = bf2f(v);
ss2 += f * f;
}
}
const float s2 = rsqrtf(block_sum<THR / kWave>(ss2, l2) / (float)n + eps);
// ---- the norm output, rounded to bf16 as the standalone norm stores it, and its absmax
float m = 0.0f;
#pragma unroll
for (uint32_t e = 0; e < EPT; ++e) {
const uint32_t i = tid + e * THR;
if (i < n) {
const uint16_t y = f32_to_bf16(bf2f(xv[e]) * s2 * gw[e]);
ybuf[i] = y;
if (yr) yr[i] = y;
m = fmaxf(m, fabsf(bf2f(y)));
}
}
m = r4d_wave_max(m);
if ((tid & 31) == 0) lm[tid >> 5] = m;
__syncthreads(); // also publishes ybuf to every thread
m = lm[0];
#pragma unroll
for (uint32_t i = 1; i < THR / kWave; i++) m = fmaxf(m, lm[i]);
const float scale = fmaxf(m, 1e-8f) / 127.f;
const float inv = 1.f / scale;
if (tid == 0) *Sr = scale;
// ---- the codes, in junction_row's fragment order
for (uint32_t i = tid; i < n; i += THR) {
const uint32_t s = i >> 4, j = i & 15;
const uint32_t src = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3);
const int t = __float2int_rn(bf2f(ybuf[src]) * inv);
qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
}
}
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, uint32_t EPT>
__global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32,
signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo,
uint32_t n, float eps, float wadd, uint32_t x_ld, uint32_t r_ld, uint32_t y_ld) {
extern __shared__ uint16_t ybuf[];
__shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave];
const uint32_t row = blockIdx.x;
junction_reg_row<WF32, RES, POST, SCL, THR, EPT>(
x + (size_t)row * x_ld, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sc, sc_f32,
q + (size_t)row * n, S + row, yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, ybuf,
l1, l2, lm);
}
// ---------------------------------------------------------------------------------------------
// The same junction with the two-rank all-reduce that precedes it: the branch output is a rank's
// partial sum of a column-sharded linear (o_proj, down_proj), and the post-norm is of the whole
@@ -157,6 +290,9 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel(
// commutes, so both ranks agree) during the post-norm's sum-of-squares pass. A block owns whole
// rows, one per block at decode.
#define R4D_ARQ8_SPIN_MAX 4000000000ULL
/* The all-reduce's tail form serves up to this many rows: a block a row beside the transport's,
* far under one block a CU on the cards it runs on. */
#define R4D_ARQ8_TAIL_MAX_ROWS 32
__device__ __forceinline__ void arq8_store_rel(unsigned int* p, unsigned int v) {
__hip_atomic_store(p, v, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM);
@@ -223,6 +359,467 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
}
}
// ---------------------------------------------------------------------------------------------
// The same junction with the four-rank all-reduce in front: the wide family's exact one-shot
// (r4d_ar_oneshot_Nrank_exact.hip) with the junction as its epilogue, as ar_hc_write_4rank is that
// one-shot with hc_write. Up to the reduce it is that one-shot's transport step for step (the same
// seq take over R4D_AR_WIDE_MAX_BLOCKS counters, the same handshake value 2*s, the same (parity,
// source) slots), so it shares an instance with the standalone all_reduce on one stream
// (r4d_ar_wide.h). Two things differ, both for the junction:
//
// * A block owns whole rows, the two-rank fused form's partition, since a post-norm's sum of
// squares closes over one row. Every rank runs the same grid over the same M, so block b's
// words are the same words on every rank and the per-block handshake pairs them.
// * The reduce is element by element in the norm's partition (thread t folds columns t, t+THR,
// ...), so the post-norm's sum of squares is the standalone norm's. Each element is ar_vsum's
// arithmetic exactly: fp32 from 0.0f, the ranks in ascending order, one rounding to bf16 as the
// __hip_bfloat16 cast rounds (bf16_hi_rne_nan). So the reduced row is the standalone exact
// all-reduce's to the bit, and what follows is rmsnorm_quant_i8's junction over it.
//
// In place is safe for the reason the hc_write form gives: a thread reads every source of an element
// before it stores it, its block pushed that element to every peer before the handshake, and no peer
// reads this rank's `x`.
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, int WS>
__global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_wide_kernel(
uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32,
signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo,
R4DArWidePeers<int4, WS - 1> peers, const int4* __restrict__ my_base,
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, int M, uint32_t n,
float eps, float wadd, uint32_t r_ld, uint32_t y_ld, int slot_stride16, int rank, int drain,
int acq, int pub, long long* gate, unsigned int* gate_ctr) {
constexpr int NPEERS = WS - 1;
extern __shared__ uint16_t ybuf[];
__shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave];
__shared__ unsigned int s_seq, s_slot;
const int b = (int)blockIdx.x, nb = (int)gridDim.x;
const uint32_t tid = threadIdx.x;
const int r0 = (int)(((long)b * M) / nb), r1 = (int)(((long)(b + 1) * M) / nb);
const long long gate_word = r4d_ar_link_word(gate, tid);
r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); /* device-resident, replay-safe */
const unsigned int s = s_seq;
const int parity = (int)s_slot;
/* push my rows into every peer's (parity, my rank) slot; `x` is a tight [M][n] of bf16 */
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;
const int wpr = (int)(n >> 3);
const int4* const in4 = (const int4*)x;
for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) {
const int4 v = in4[k];
#pragma unroll
for (int p = 0; p < NPEERS; ++p) ps[p][k] = v;
}
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s, drain, acq, pub);
/* The one-shot's release: the fold and the junction behind it are local VRAM traffic, so the
* last block past its handshake ends the engine's hold on the link (r4d_ar_seq.h). Every block
* owns at least one row and takes exactly one handshake, so every path reaches it. */
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, tid);
/* the sources in ascending global rank, this rank's own from `x` (its own slot is never
* written), the peers' from their slots in my scratch */
const int4* src4[WS];
#pragma unroll
for (int r = 0; r < WS; ++r)
src4[r] = r == rank ? (const int4*)x
: my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16;
const float sv = SCL ? scalar_of(sc, sc_f32) : 1.0f;
for (int row = r0; row < r1; ++row) {
const size_t o = (size_t)row * n;
uint16_t* __restrict__ xr = x + o;
/* The fold a 16-byte word a thread, every source's word in flight at once (the peers' are
* in fine-grained memory, a round trip each), stored back into `x`; then the post-norm's
* sum of squares over the stored row in the norm's partition. Per element it is the fold
* fold_word8 documents, and the sum reads the same rounded values in the same order, so
* the bytes are those of the fold and the sum taken in one pass. */
for (int k = (int)tid; k < wpr; k += (int)THR)
((int4*)xr)[k] = fold_word8<WS>(src4, (size_t)row * wpr + k);
float ss = 0.0f;
if (POST) {
__syncthreads(); /* the folded row, read across the block's threads */
for (uint32_t i = tid; i < n; i += THR) { const float v = bf2f(xr[i]); ss += v * v; }
}
float s1 = 0.0f;
if (POST) s1 = rsqrtf(block_sum<THR / kWave>(ss, l1) / (float)n + eps);
else __syncthreads(); /* junction_row reads the folded row across threads too */
junction_row<WF32, RES, POST, SCL, THR>(
xr, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sv, q + (size_t)row * n, S + row,
yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, s1, ybuf, l2, lm);
__syncthreads(); /* the planes and ybuf are re-used by the next row this block owns */
}
}
// ---------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------
// The junction as the tail of the standalone exact two-shot, in one launch. Blocks [0, nbt) run
// r4d_ar_twoshot_wide_exact_kernel's body over x in place (r4d_ar_twoshot_Nrank_exact.hip): the same
// shards, words, fold (fp32 from 0.0f in ascending rank, one rounding) and handshakes, so x ends as
// the standalone all-reduce leaves it; each then counts itself in on a word of the instance's
// counter allocation, at agent scope behind a release. Blocks [nbt, nbt + M) are the junction, one
// row each as rmsnorm_quant_i8_reg_kernel runs it (junction_reg_row, the same width and partition):
// each waits for every transport block's count, acquires, and runs its row; the last of them zeroes
// both counts for the next launch. So the junction takes neither a cross-card handshake nor a
// launch of its own: the pair's bytes, one dependent launch fewer. Blocks are dispatched in index
// order, so the transport blocks are resident before any junction block spins; the grid is kept far
// under one block a CU.
//
// tail[0] counts the transport blocks done, tail[1] the junction blocks done; both start at zero
// (the counter allocation is zeroed at init) and the last junction block returns them there.
// The body: transport blocks return after their part, so the chained form (r4d_chain.h) wraps
// it below. The last junction block resets the tail counters inside the body, before the chained
// form's add, so the next launch on the instance never sees them mid-reset.
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t EPT, int WS>
__device__ __forceinline__ void ar_rmsnorm_quant_i8_tail_body(
uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32,
signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo,
R4DArWidePeers<int4, WS - 1> peers, const int4* __restrict__ my_base,
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs,
unsigned int* __restrict__ tail, int M, uint32_t n, float eps, float wadd, uint32_t r_ld,
uint32_t y_ld, int slot_stride16, int rank, int nbt, int drain, int acq, int pub,
long long* gate, unsigned int* gate_ctr) {
constexpr uint32_t THR = 1024;
constexpr int NPEERS = WS - 1;
extern __shared__ uint16_t ybuf[];
__shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave];
__shared__ unsigned int s_seq, s_slot;
const int b = (int)blockIdx.x, tid = (int)threadIdx.x, nt = (int)THR;
if (b < nbt) {
// ---- the standalone exact two-shot, x in place, block b of nbt
const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid);
r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot);
const unsigned int s = s_seq;
const int parity = (int)s_slot;
int4* const x4 = (int4*)x;
const int n16 = (int)(((long)M * n) >> 3);
const int base = n16 / WS, rem = n16 % WS;
const int sh_max = base + (rem ? 1 : 0);
#define R4D_TT_OFF(o) ((o) * base + ((o) < rem ? (o) : rem))
#define R4D_TT_LEN(o) (base + ((o) < rem ? 1 : 0))
const int wd = (sh_max + nbt - 1) / nbt;
const int w0 = b * wd;
int w1 = w0 + wd; if (w1 > sh_max) w1 = 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;
for (int p = 0; p < NPEERS; ++p) {
const int owner = peers.rank[p];
const int4* src = x4 + (size_t)R4D_TT_OFF(owner);
int4* dst = pa[p];
const int lim = w1 < R4D_TT_LEN(owner) ? w1 : R4D_TT_LEN(owner);
for (int k = w0 + tid; k < lim; k += nt) dst[k] = src[k];
}
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s - 1u, drain, acq, pub);
const int4* src[WS];
#pragma unroll
for (int r = 0; r < WS; ++r)
src[r] = (r == rank) ? (x4 + (size_t)R4D_TT_OFF(rank))
: (my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16);
int4* my_out = x4 + (size_t)R4D_TT_OFF(rank);
const int my_lim = w1 < R4D_TT_LEN(rank) ? w1 : R4D_TT_LEN(rank);
for (int k = w0 + tid; k < my_lim; k += nt) {
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 = src[r][k];
const __hip_bfloat16* pv = reinterpret_cast<const __hip_bfloat16*>(&v);
#pragma unroll
for (int j = 0; j < 8; ++j) acc[j] += r4d_ar_to_f(pv[j]);
}
int4 o;
__hip_bfloat16* po = reinterpret_cast<__hip_bfloat16*>(&o);
#pragma unroll
for (int j = 0; j < 8; ++j) r4d_ar_from_f(acc[j], po[j]);
my_out[k] = o;
#pragma unroll
for (int p = 0; p < NPEERS; ++p) pa[p][sh_max + k] = o;
}
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s, drain, acq, pub);
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nbt, (unsigned int)tid);
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 = x4 + (size_t)R4D_TT_OFF(owner);
const int lim = w1 < R4D_TT_LEN(owner) ? w1 : R4D_TT_LEN(owner);
for (int k = w0 + tid; k < lim; k += nt) dst[k] = srcB[k];
}
#undef R4D_TT_OFF
#undef R4D_TT_LEN
// ---- every word this block stored in x, published, then counted in
__syncthreads();
if (tid == 0) {
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
__hip_atomic_fetch_add(&tail[0], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
}
return;
}
// ---- the junction, row b - nbt, once x is whole on this card
const int row = b - nbt;
if (tid == 0) {
unsigned long long z = 0;
while (__hip_atomic_load(&tail[0], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) <
(unsigned int)nbt) {
__builtin_amdgcn_s_sleep(1);
if (++z > R4D_AR_SPIN_MAX) __builtin_trap();
}
}
__syncthreads();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
junction_reg_row<WF32, RES, POST, SCL, THR, EPT>(
x + (size_t)row * n, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sc, sc_f32,
q + (size_t)row * n, S + row, yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, ybuf,
l1, l2, lm);
__syncthreads();
if (tid == 0) {
const unsigned int prev =
__hip_atomic_fetch_add(&tail[1], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
if (prev + 1u == (unsigned int)M) {
__hip_atomic_store(&tail[0], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
__hip_atomic_store(&tail[1], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
}
}
}
#define R4D_ARQ8T_PARAMS uint16_t* __restrict__ x, uint16_t* __restrict__ res, \
const void* __restrict__ w, const void* __restrict__ wp, const void* __restrict__ sc, \
uint32_t sc_f32, signed char* __restrict__ q, float* __restrict__ S, \
uint16_t* __restrict__ yo, R4DArWidePeers<int4, WS - 1> peers, \
const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, \
unsigned int* __restrict__ seq_ctrs, unsigned int* __restrict__ tail, int M, uint32_t n, \
float eps, float wadd, uint32_t r_ld, uint32_t y_ld, int slot_stride16, int rank, int nbt, \
int drain, int acq, int pub, long long* gate, unsigned int* gate_ctr
#define R4D_ARQ8T_ARGS x, res, w, wp, sc, sc_f32, q, S, yo, peers, my_base, my_flags, seq_ctrs, tail, \
M, n, eps, wadd, r_ld, y_ld, slot_stride16, rank, nbt, drain, acq, pub, gate, gate_ctr
// The plain kernel, and the chained one (r4dchain*): its wait comes before anything, the sequence
// take included, so a block of the next launch on the instance never starts ahead of this one's.
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t EPT, int WS>
__global__ __launch_bounds__(1024) void ar_rmsnorm_quant_i8_tail_kernel(R4D_ARQ8T_PARAMS) {
ar_rmsnorm_quant_i8_tail_body<WF32, RES, POST, SCL, EPT, WS>(R4D_ARQ8T_ARGS);
}
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t EPT, int WS>
__global__ __launch_bounds__(1024) void r4dchain_ar_rmsnorm_quant_i8_tail(R4D_ARQ8T_PARAMS) {
r4d_chain_wait();
ar_rmsnorm_quant_i8_tail_body<WF32, RES, POST, SCL, EPT, WS>(R4D_ARQ8T_ARGS);
r4d_chain_done();
}
#undef R4D_ARQ8T_ARGS
#undef R4D_ARQ8T_PARAMS
// ---------------------------------------------------------------------------------------------
// The junction with the all-reduce split around it (`sp`): reduce-scatter, the junction on the rows
// this rank owns, all-gather of what the next GEMM reads. Rank r owns rows [r0(r), r0(r) + nr(r)),
// M split as evenly as the rank order allows, and block b serves local row b of every rank:
//
// 1. it pushes this rank's partial sums of each peer's local row b into that peer's slot (bf16,
// the two-shot's first hop) and takes the handshake;
// 2. on its own row it folds the four partials in rank order -- r4d_ar_to_f, f32, rank 0 first,
// r4d_ar_from_f, the standalone exact all-reduce's fold, so the same bf16 sum -- and runs the
// junction on it in the register form at the standalone norm's width (r4d_act_threads), each
// thread holding the columns the standalone's does, so every sum is the standalone's; it
// stores the residual row and pushes the row's int8 codes and scale (and with `gres` the
// residual row) into every peer's slot past the first hop's region, then takes the handshake;
// 3. it copies the peers' local row b of codes and scales (and residual) into place.
//
// So every rank leaves q and S on every row, byte for byte the chain's (all_reduce, then
// rmsnorm_quant_i8), and the residual on its own rows only -- on every row with `gres`. `x` keeps
// this rank's partial sums: nothing past the junction reads the reduced branch output. Against the
// tail form the second hop carries int8 instead of bf16 and no block waits beside the transport;
// one launch at a time on 4x R9700 (2026-10-19) it took 22.9 against 24.5 us at 8 rows of 5376,
// 30.8 against 34.9 at 16, 72.3 against 89.2 at 64, and 19.8 against the one-shot's 21.9 at 4.
template <uint32_t EPT, uint32_t THR, int WS>
__device__ __forceinline__ void ar_rmsnorm_quant_i8_sp_body(
const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32, uint32_t wf32,
uint32_t gres, signed char* __restrict__ q, float* __restrict__ S,
R4DArWidePeers<int4, WS - 1> peers, const int4* __restrict__ my_base,
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, int M, uint32_t n,
float eps, float wadd, uint32_t r_ld, int slot_stride16, int rank, int drain, int acq, int pub,
long long* gate, unsigned int* gate_ctr) {
constexpr int NPEERS = WS - 1;
extern __shared__ uint16_t ybuf[];
signed char* const cbuf = (signed char*)(ybuf + n);
__shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave];
__shared__ unsigned int s_seq, s_slot;
const int b = (int)blockIdx.x;
const uint32_t tid = threadIdx.x;
const long long gate_word = r4d_ar_link_word(gate, tid);
r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot);
const unsigned int s = s_seq;
const int parity = (int)s_slot;
const int base = M / WS, rem = M % WS;
#define R4D_SP_R0(r) ((r) * base + ((r) < rem ? (r) : rem))
#define R4D_SP_NR(r) (base + ((r) < rem ? 1 : 0))
const int n16 = (int)(n >> 3), c16 = (int)(n >> 4);
const size_t offB = (size_t)(base + (rem ? 1 : 0)) * n16; /* past the first hop's rows */
const size_t rowB = (size_t)c16 + 1 + (gres ? n16 : 0); /* codes, a scale word, residual */
const size_t my_slot = ((size_t)parity * WS + rank) * (size_t)slot_stride16;
// ---- the first hop: this rank's partials of each peer's local row b
for (int p = 0; p < NPEERS; ++p) {
const int d = peers.rank[p];
if (b >= R4D_SP_NR(d)) continue;
const int4* src = (const int4*)(x + (size_t)(R4D_SP_R0(d) + b) * n);
int4* dst = peers.scratch[p] + my_slot + (size_t)b * n16;
for (int k = (int)tid; k < n16; k += (int)THR) dst[k] = src[k];
}
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s - 1u, drain, acq, pub);
if (b < R4D_SP_NR(rank)) {
const int row = R4D_SP_R0(rank) + b;
const __hip_bfloat16* srcs[WS];
#pragma unroll
for (int r = 0; r < WS; ++r)
srcs[r] = r == rank ? (const __hip_bfloat16*)(x + (size_t)row * n)
: (const __hip_bfloat16*)(my_base + ((size_t)parity * WS + r) *
(size_t)slot_stride16 + (size_t)b * n16);
uint16_t* const rr = res + (size_t)row * r_ld;
uint16_t xv[EPT], rv[EPT];
float gp[EPT], gw[EPT];
#pragma unroll
for (uint32_t e = 0; e < EPT; ++e) {
const uint32_t i = tid + e * THR;
xv[e] = 0; rv[e] = 0; gp[e] = 0.0f; gw[e] = 0.0f;
if (i < n) {
float acc = 0.0f;
#pragma unroll
for (int r = 0; r < WS; ++r) acc += r4d_ar_to_f(srcs[r][i]);
__hip_bfloat16 o;
r4d_ar_from_f(acc, o);
__builtin_memcpy(&xv[e], &o, 2);
rv[e] = rr[i];
gp[e] = gain(wp, i, wf32) + wadd;
gw[e] = gain(w, i, wf32) + wadd;
}
}
const float sv = sc ? scalar_of(sc, sc_f32) : 1.0f;
// ---- junction_reg_row's passes over the folded row: the post-norm's sum of squares,
// the post-norm, add and scalar with the norm's sum of squares, the norm and its absmax
float ss = 0.0f;
#pragma unroll
for (uint32_t e = 0; e < EPT; ++e)
if (tid + e * THR < n) { const float v = bf2f(xv[e]); ss += v * v; }
const float s1 = rsqrtf(block_sum<THR / kWave>(ss, l1) / (float)n + eps);
float ss2 = 0.0f;
#pragma unroll
for (uint32_t e = 0; e < EPT; ++e) {
const uint32_t i = tid + e * THR;
if (i < n) {
uint16_t v = f32_to_bf16(bf2f(xv[e]) * s1 * gp[e]);
v = f32_to_bf16(bf2f(rv[e]) + bf2f(v));
if (sc) v = f32_to_bf16(bf2f(v) * sv);
rr[i] = v;
xv[e] = v;
const float f = bf2f(v);
ss2 += f * f;
}
}
const float s2 = rsqrtf(block_sum<THR / kWave>(ss2, l2) / (float)n + eps);
float m = 0.0f;
#pragma unroll
for (uint32_t e = 0; e < EPT; ++e) {
const uint32_t i = tid + e * THR;
if (i < n) {
const uint16_t y = f32_to_bf16(bf2f(xv[e]) * s2 * gw[e]);
ybuf[i] = y;
m = fmaxf(m, fabsf(bf2f(y)));
}
}
m = r4d_wave_max(m);
if ((tid & 31) == 0) lm[tid >> 5] = m;
__syncthreads(); // also publishes ybuf to every thread
m = lm[0];
#pragma unroll
for (uint32_t i = 1; i < THR / kWave; i++) m = fmaxf(m, lm[i]);
const float scale = fmaxf(m, 1e-8f) / 127.f;
const float inv = 1.f / scale;
// ---- the codes, in junction_row's fragment order, into LDS
for (uint32_t i = tid; i < n; i += THR) {
const uint32_t sg = i >> 4, j = i & 15;
const uint32_t src = (sg << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3);
const int t = __float2int_rn(bf2f(ybuf[src]) * inv);
cbuf[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
}
__syncthreads(); // the codes, and this block's residual row in memory, whole
// ---- the second hop: the row's codes and scale (and residual) to every peer, and here
const int4* const c4 = (const int4*)cbuf;
int4* const q4 = (int4*)(q + (size_t)row * n);
int4* dB[NPEERS];
#pragma unroll
for (int p = 0; p < NPEERS; ++p) dB[p] = peers.scratch[p] + my_slot + offB + (size_t)b * rowB;
for (int k = (int)tid; k < c16; k += (int)THR) {
const int4 v = c4[k];
q4[k] = v;
#pragma unroll
for (int p = 0; p < NPEERS; ++p) dB[p][k] = v;
}
if (gres) {
const int4* const r4 = (const int4*)rr;
for (int k = (int)tid; k < n16; k += (int)THR) {
const int4 v = r4[k];
#pragma unroll
for (int p = 0; p < NPEERS; ++p) dB[p][c16 + 1 + k] = v;
}
}
if (tid == 0) {
S[row] = scale;
const int4 sw = make_int4(__float_as_int(scale), 0, 0, 0);
#pragma unroll
for (int p = 0; p < NPEERS; ++p) dB[p][c16] = sw;
}
}
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s, drain, acq, pub);
r4d_ar_link_landed(gate, gate_word, gate_ctr, gridDim.x, tid);
// ---- the peers' local row b, codes and scale (and residual), into place
for (int p = 0; p < NPEERS; ++p) {
const int sr = peers.rank[p];
if (b >= R4D_SP_NR(sr)) continue;
const int4* const src = my_base + ((size_t)parity * WS + sr) * (size_t)slot_stride16 + offB +
(size_t)b * rowB;
const int row = R4D_SP_R0(sr) + b;
int4* const q4 = (int4*)(q + (size_t)row * n);
for (int k = (int)tid; k < c16; k += (int)THR) q4[k] = src[k];
if (gres) {
int4* const r4 = (int4*)(res + (size_t)row * r_ld);
for (int k = (int)tid; k < n16; k += (int)THR) r4[k] = src[c16 + 1 + k];
}
if (tid == 0) S[row] = __int_as_float(src[c16].x);
}
#undef R4D_SP_R0
#undef R4D_SP_NR
}
#define R4D_ARQ8S_PARAMS const uint16_t* __restrict__ x, uint16_t* __restrict__ res, \
const void* __restrict__ w, const void* __restrict__ wp, const void* __restrict__ sc, \
uint32_t sc_f32, uint32_t wf32, uint32_t gres, signed char* __restrict__ q, \
float* __restrict__ S, R4DArWidePeers<int4, WS - 1> peers, const int4* __restrict__ my_base, \
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, int M, uint32_t n, \
float eps, float wadd, uint32_t r_ld, int slot_stride16, int rank, int drain, int acq, int pub, \
long long* gate, unsigned int* gate_ctr
#define R4D_ARQ8S_ARGS x, res, w, wp, sc, sc_f32, wf32, gres, q, S, peers, my_base, my_flags, \
seq_ctrs, M, n, eps, wadd, r_ld, slot_stride16, rank, drain, acq, pub, gate, gate_ctr
template <uint32_t EPT, uint32_t THR, int WS>
__global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_sp_kernel(R4D_ARQ8S_PARAMS) {
ar_rmsnorm_quant_i8_sp_body<EPT, THR, WS>(R4D_ARQ8S_ARGS);
}
template <uint32_t EPT, uint32_t THR, int WS>
__global__ __launch_bounds__(THR) void r4dchain_ar_rmsnorm_quant_i8_sp(R4D_ARQ8S_PARAMS) {
r4d_chain_wait();
ar_rmsnorm_quant_i8_sp_body<EPT, THR, WS>(R4D_ARQ8S_ARGS);
r4d_chain_done();
}
#undef R4D_ARQ8S_ARGS
#undef R4D_ARQ8S_PARAMS
} // namespace
// ============================================================== the plugin ABI entry point
@@ -276,13 +873,34 @@ extern "C" int r4d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream stream) {
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
const uint32_t scf = sc ? (sc->dtype == RAD_F32) : 0u;
// The decode form keeps a thread's columns in registers, EPT of them: at 1024 threads (to 32
// rows) and at 512 (33 to 72-120 rows, r4d_act_threads), the same partition and arithmetic as
// the re-read form at that width, so the same bytes. At 512 it serves the multi-user verify
// (five to fifteen users of a DFlash2 verify, 8 rows a user), where the re-read form took ~14 us
// a junction under --profile-ops at 64 rows of 5376.
const int ept = !r4d_cfg_rmsq8_reg(a) ? 0
: thr == 1024 ? (n <= 4096 ? 4 : n <= 6144 ? 6 : n <= 8192 ? 8 : 0)
: thr == 512 ? (n <= 4096 ? 8 : n <= 6144 ? 12 : n <= 8192 ? 16 : 0)
: 0;
#define R4D_RQI8_T(WF, RS, PO, SC, T) emit_rc = R4D_EMIT(stream, \
(rmsnorm_quant_i8_kernel<WF, RS, PO, SC, T>), dim3((uint32_t)M), dim3(T), lds, \
(const uint16_t*)r4d_p(x), (uint16_t*)r4d_wp(rs), r4d_p(w), r4d_p(wp), r4d_p(sc), scf, \
(signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, \
(uint32_t)xp, (uint32_t)rp, (uint32_t)yp)
#define R4D_RQI8_R(WF, RS, PO, SC, T, E) emit_rc = R4D_EMIT(stream, \
(rmsnorm_quant_i8_reg_kernel<WF, RS, PO, SC, T, E>), dim3((uint32_t)M), dim3(T), lds, \
(const uint16_t*)r4d_p(x), (uint16_t*)r4d_wp(rs), r4d_p(w), r4d_p(wp), r4d_p(sc), scf, \
(signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, \
(uint32_t)xp, (uint32_t)rp, (uint32_t)yp)
#define R4D_RQI8(WF, RS, PO, SC) \
do { if (thr == 1024) R4D_RQI8_T(WF, RS, PO, SC, 1024); \
do { if (thr == 1024 && ept == 4) R4D_RQI8_R(WF, RS, PO, SC, 1024, 4); \
else if (thr == 1024 && ept == 6) R4D_RQI8_R(WF, RS, PO, SC, 1024, 6); \
else if (thr == 1024 && ept == 8) R4D_RQI8_R(WF, RS, PO, SC, 1024, 8); \
else if (thr == 512 && ept == 8) R4D_RQI8_R(WF, RS, PO, SC, 512, 8); \
else if (thr == 512 && ept == 12) R4D_RQI8_R(WF, RS, PO, SC, 512, 12); \
else if (thr == 512 && ept == 16) R4D_RQI8_R(WF, RS, PO, SC, 512, 16); \
else if (thr == 1024) R4D_RQI8_T(WF, RS, PO, SC, 1024); \
else if (thr == 512) R4D_RQI8_T(WF, RS, PO, SC, 512); \
else if (thr == 256) R4D_RQI8_T(WF, RS, PO, SC, 256); \
else return R4D_NO(RAD_E_INVAL); } while (0)
@@ -296,6 +914,7 @@ extern "C" int r4d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream stream) {
else R4D_RQI8_W(false);
#undef R4D_RQI8_W
#undef R4D_RQI8
#undef R4D_RQI8_R
#undef R4D_RQI8_T
return emit_rc;
}
@@ -350,3 +969,177 @@ extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long
#undef R4D_ARQ8_T
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// The four-rank form's launch. The IPC arguments are r4d_ar_oneshot_4rank_exact's -- each peer's
// scratch and flags in ascending peer rank, this rank's own, the device-resident sequence counters
// and the per-source slot stride -- and the rest is the junction's. The checks are the wide
// launchers' (rank range, the message inside one slot, the grid inside the flag array, every
// allocation's extent), returned as codes rather than thrown, for the reason this file gives.
// The all-reduce is the one-shot. With `tail_nbt` blocks (positive) it is instead the standalone two-shot over words on that many blocks with the junction as its tail,
// a block a row (ar_rmsnorm_quant_i8_tail_kernel), counting on the two words at `tail_ctr`.
extern "C" int r4d_ar_rmsnorm_quant_i8_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 x, long res, long w, long wp, long sc,
int sc_f32, long y, long q, long s, int M, int n,
float eps, float wadd, int w_f32, int r_ld, int y_ld,
int rank, long stream, int nblocks, int drain, int acq,
int pub, long gate, long gate_ctr,
long tail_ctr, int tail_nbt, int chain, int sp) {
constexpr int WS = 4, NPEERS = WS - 1;
const long ps[NPEERS] = { peer_scratch0, peer_scratch1, peer_scratch2 };
const long pf[NPEERS] = { peer_flags0, peer_flags1, peer_flags2 };
if (!x || !w || !q || !s) return -1;
if (!my_scratch || !my_flags || !seq_ctrs) return -1;
if (gate && !gate_ctr) return -1; /* the release counts blocks in the instance's counter */
if (rank < 0 || rank >= WS) return -1;
if (M <= 0 || n <= 0) return -2;
if (n % 16) return -3;
if ((wp || sc) && !res) return -5;
if ((size_t)n * sizeof(uint16_t) > 60 * 1024) return -6;
if ((long)M * n / 8 > slot_stride16) return -7; /* the message inside one source slot */
if (!r_ld) r_ld = n;
if (!y_ld) y_ld = n;
R4DArWidePeers<int4, NPEERS> peers{};
for (int i = 0; i < NPEERS; ++i) {
if (!ps[i] || !pf[i]) return -1;
peers.scratch[i] = (int4*)ps[i];
peers.flags[i] = (unsigned int*)pf[i];
peers.rank[i] = i < rank ? i : i + 1; /* ascending global rank, this one removed */
}
int nb = nblocks < 1 ? 1 : nblocks;
if (nb > M) nb = M; /* a block owns whole rows */
if (nb > R4D_AR_WIDE_MAX_BLOCKS) nb = R4D_AR_WIDE_MAX_BLOCKS;
try {
const long slot_bytes = 2L * WS * slot_stride16 * 16;
const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int);
r4d_ar_check_extent(my_scratch, slot_bytes, "ar_rmsnorm_quant_i8", "my_scratch");
r4d_ar_check_extent(my_flags, flag_bytes, "ar_rmsnorm_quant_i8", "my_flags");
r4d_ar_check_extent(seq_ctrs, 2L * R4D_AR_WIDE_MAX_BLOCKS * (long)sizeof(unsigned int),
"ar_rmsnorm_quant_i8", "seq_ctrs");
for (int i = 0; i < NPEERS; ++i) {
r4d_ar_check_extent(ps[i], slot_bytes, "ar_rmsnorm_quant_i8", "peer scratch");
r4d_ar_check_extent(pf[i], flag_bytes, "ar_rmsnorm_quant_i8", "peer flags");
}
} catch (...) {
return -8;
}
const int thr = r4d_act_threads(M, n);
const size_t lds = (size_t)n * sizeof(uint16_t);
/* The all-reduce split around the junction (ar_rmsnorm_quant_i8_sp_kernel): `sp` 1, or 2 with
* the residual gathered too. A block a local row, ceil(M / 4) of them; its two hops in the slot
* the message would fill. Where it cannot run (no residual or post-norm, a width without a
* register form, rows past the flag array or the slot, a residual pitch off 16 bytes) the
* forms below run instead, which leave every byte this one does and more. It leaves no bf16
* norm output, so one asked for (`y`) takes those forms too. */
if (sp > 0 && res && wp && !y) {
const int ep = thr == 1024 ? (n <= 4096 ? 4 : n <= 6144 ? 6 : n <= 8192 ? 8 : 0)
: thr == 512 ? (n <= 4096 ? 8 : n <= 6144 ? 12 : n <= 8192 ? 16 : 0) : 0;
const int nbs = (M + WS - 1) / WS;
const long need = (long)nbs * (n / 8) + (long)nbs * (n / 16 + 1 + (sp == 2 ? n / 8 : 0));
if (ep > 0 && nbs <= R4D_AR_WIDE_MAX_BLOCKS && need <= slot_stride16 &&
(sp != 2 || r_ld % 8 == 0)) {
try {
const long fb = (long)nbs * WS * (long)sizeof(unsigned int);
r4d_ar_check_extent(my_flags, fb, "ar_rmsnorm_quant_i8", "my_flags");
for (int i = 0; i < NPEERS; ++i)
r4d_ar_check_extent(pf[i], fb, "ar_rmsnorm_quant_i8", "peer flags");
} catch (...) {
return -8;
}
const size_t lds_sp = (size_t)n * (sizeof(uint16_t) + 1);
#define R4D_ARQ8S_K(E, T) \
hipLaunchKernelGGL((chain ? r4dchain_ar_rmsnorm_quant_i8_sp<E, T, WS> \
: ar_rmsnorm_quant_i8_sp_kernel<E, T, WS>), \
dim3((uint32_t)nbs), dim3(T), lds_sp, (hipStream_t)stream, \
(const uint16_t*)x, (uint16_t*)res, (const void*)w, \
(const void*)wp, (const void*)sc, (uint32_t)sc_f32, \
(uint32_t)w_f32, (uint32_t)(sp == 2), (signed char*)q, (float*)s, \
peers, (const int4*)my_scratch, (unsigned int*)my_flags, \
(unsigned int*)seq_ctrs, M, (uint32_t)n, eps, wadd, \
(uint32_t)r_ld, (int)slot_stride16, rank, drain, acq, pub, \
(long long*)gate, (unsigned int*)gate_ctr)
if (thr == 1024 && ep == 4) R4D_ARQ8S_K(4, 1024);
else if (thr == 1024 && ep == 6) R4D_ARQ8S_K(6, 1024);
else if (thr == 1024) R4D_ARQ8S_K(8, 1024);
else if (ep == 8) R4D_ARQ8S_K(8, 512);
else if (ep == 12) R4D_ARQ8S_K(12, 512);
else R4D_ARQ8S_K(16, 512);
#undef R4D_ARQ8S_K
return hipGetLastError() == hipSuccess ? 0 : -4;
}
}
/* The junction as the standalone two-shot's tail (ar_rmsnorm_quant_i8_tail_kernel): at the
* junction's register width (1024 threads), up to R4D_ARQ8_TAIL_MAX_ROWS rows. */
const int ept = n <= 4096 ? 4 : n <= 6144 ? 6 : n <= 8192 ? 8 : 0;
if (tail_nbt > 0 && tail_ctr && thr == 1024 && ept > 0 && M <= R4D_ARQ8_TAIL_MAX_ROWS &&
tail_nbt <= R4D_AR_WIDE_MAX_BLOCKS) {
try {
r4d_ar_check_extent(my_flags, (long)tail_nbt * WS * (long)sizeof(unsigned int),
"ar_rmsnorm_quant_i8", "my_flags");
r4d_ar_check_extent(tail_ctr, 2L * (long)sizeof(unsigned int), "ar_rmsnorm_quant_i8",
"tail counters");
for (int i = 0; i < NPEERS; ++i)
r4d_ar_check_extent(pf[i], (long)tail_nbt * WS * (long)sizeof(unsigned int),
"ar_rmsnorm_quant_i8", "peer flags");
} catch (...) {
return -8;
}
#define R4D_ARQ8T_K(WF, RS, PO, SC, E) \
hipLaunchKernelGGL((chain ? r4dchain_ar_rmsnorm_quant_i8_tail<WF, RS, PO, SC, E, WS> \
: ar_rmsnorm_quant_i8_tail_kernel<WF, RS, PO, SC, E, WS>), \
dim3((uint32_t)(tail_nbt + M)), dim3(1024), lds, (hipStream_t)stream, \
(uint16_t*)x, (uint16_t*)res, (const void*)w, (const void*)wp, \
(const void*)sc, (uint32_t)sc_f32, (signed char*)q, (float*)s, \
(uint16_t*)y, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \
(unsigned int*)seq_ctrs, (unsigned int*)tail_ctr, M, (uint32_t)n, eps, \
wadd, (uint32_t)r_ld, (uint32_t)y_ld, (int)slot_stride16, rank, \
tail_nbt, drain, acq, pub, (long long*)gate, (unsigned int*)gate_ctr)
#define R4D_ARQ8T_E(WF, RS, PO, SC) \
do { if (ept == 4) R4D_ARQ8T_K(WF, RS, PO, SC, 4); \
else if (ept == 6) R4D_ARQ8T_K(WF, RS, PO, SC, 6); \
else R4D_ARQ8T_K(WF, RS, PO, SC, 8); } while (0)
#define R4D_ARQ8T_W(WF) \
do { if (!res) R4D_ARQ8T_E(WF, false, false, false); \
else if (!wp && !sc) R4D_ARQ8T_E(WF, true, false, false); \
else if (wp && !sc) R4D_ARQ8T_E(WF, true, true, false); \
else if (wp && sc) R4D_ARQ8T_E(WF, true, true, true); \
else R4D_ARQ8T_E(WF, true, false, true); } while (0)
if (w_f32) R4D_ARQ8T_W(true);
else R4D_ARQ8T_W(false);
#undef R4D_ARQ8T_W
#undef R4D_ARQ8T_E
#undef R4D_ARQ8T_K
return hipGetLastError() == hipSuccess ? 0 : -4;
}
#define R4D_ARQ8W_T(WF, RS, PO, SC, T) \
hipLaunchKernelGGL((ar_rmsnorm_quant_i8_wide_kernel<WF, RS, PO, SC, T, WS>), dim3((uint32_t)nb), \
dim3(T), lds, (hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, \
(const void*)w, (const void*)wp, (const void*)sc, (uint32_t)sc_f32, \
(signed char*)q, (float*)s, (uint16_t*)y, peers, (const int4*)my_scratch, \
(unsigned int*)my_flags, (unsigned int*)seq_ctrs, M, (uint32_t)n, eps, \
wadd, (uint32_t)r_ld, (uint32_t)y_ld, (int)slot_stride16, rank, drain, acq, \
pub, (long long*)gate, (unsigned int*)gate_ctr)
#define R4D_ARQ8W(WF, RS, PO, SC) \
do { if (thr == 1024) R4D_ARQ8W_T(WF, RS, PO, SC, 1024); \
else if (thr == 512) R4D_ARQ8W_T(WF, RS, PO, SC, 512); \
else R4D_ARQ8W_T(WF, RS, PO, SC, 256); } while (0)
#define R4D_ARQ8W_W(WF) \
do { if (!res) R4D_ARQ8W(WF, false, false, false); \
else if (!wp && !sc) R4D_ARQ8W(WF, true, false, false); \
else if (wp && !sc) R4D_ARQ8W(WF, true, true, false); \
else if (wp && sc) R4D_ARQ8W(WF, true, true, true); \
else R4D_ARQ8W(WF, true, false, true); } while (0)
if (w_f32) R4D_ARQ8W_W(true);
else R4D_ARQ8W_W(false);
#undef R4D_ARQ8W_W
#undef R4D_ARQ8W
#undef R4D_ARQ8W_T
return hipGetLastError() == hipSuccess ? 0 : -4;
}
+1785 -39
View File
File diff suppressed because it is too large. Load diff
+54 -8
View File
@@ -48,6 +48,7 @@
#include "r4d_common.h"
#include "r4d_fp8_wmma.h"
#include "r4d_fp8_lm.h"
#include "r4d_chain.h"
#include <hip/hip_bf16.h>
#include <cstdint>
@@ -120,8 +121,10 @@ __device__ __forceinline__ unsigned long long tk_round(unsigned long long* t) {
return m;
}
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. A wave past the
// chunks returns early; there is no barrier in it.
template <int PT>
__global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stage1_kernel(
__device__ __forceinline__ void r4d_rowtopk_stage1_body(
const unsigned short* __restrict__ Y, unsigned long long* __restrict__ P,
int N, int RC, int NCH, int CH) {
// WPB independent waves per block, each on its own chunk, sharing nothing. Grouping them only
@@ -179,6 +182,20 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stag
if (lane == 0) out[r] = w;
}
}
template <int PT>
__global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stage1_kernel(
const unsigned short* __restrict__ Y, unsigned long long* __restrict__ P,
int N, int RC, int NCH, int CH) {
r4d_rowtopk_stage1_body<PT>(Y, P, N, RC, NCH, CH);
}
template <int PT>
__global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4dchain_rowtopk_stage1(
const unsigned short* __restrict__ Y, unsigned long long* __restrict__ P,
int N, int RC, int NCH, int CH) {
r4d_chain_wait();
r4d_rowtopk_stage1_body<PT>(Y, P, N, RC, NCH, CH);
r4d_chain_done();
}
// `off` is the first global column this rank's plane stands for, and `OP` the optional (id, value)
// pair plane an all-gather moves: eight bytes an entry, an int32 id in the first float slot, the
@@ -188,7 +205,8 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stag
// An empty slot is not token `off`. A chunk that ran out of candidates leaves a zero key; OI gets
// column 0 for it, without the offset, so a pad cannot look like this rank's first real token. The
// pair plane writes -1, the sentinel the merge drops (not -INFINITY, a valid masked logit).
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_stage2_kernel(
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below.
__device__ __forceinline__ void r4d_rowtopk_stage2_body(
const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI,
float* __restrict__ OP, int off, int R, int n) {
const int m = blockIdx.x;
@@ -220,6 +238,18 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_stage2_kernel(
}
}
}
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_stage2_kernel(
const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI,
float* __restrict__ OP, int off, int R, int n) {
r4d_rowtopk_stage2_body(P, OV, OI, OP, off, R, n);
}
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4dchain_rowtopk_stage2(
const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI,
float* __restrict__ OP, int off, int R, int n) {
r4d_chain_wait();
r4d_rowtopk_stage2_body(P, OV, OI, OP, off, R, n);
r4d_chain_done();
}
// Chunks are a multiple of eight columns so stage 1 stays on the vector load; the last one is
// clamped to N rather than padded (a padded tail would need a mask per element). The caller sizes
@@ -239,7 +269,7 @@ int r4d_rowtopk_bf16_chunks(int N, int NCH) {
// so ranks can agree on a global top-R without gathering the plane.
static int rowtopk_bf16_sharded_emit(long y, long partial, long outv, long outi, long outp,
int M, int N, int R, int RC, int NCH, int PT1, int off,
RadStream stream) {
RadStream stream, bool chain = false) {
int emit_rc = RAD_OK;
// R <= PT2 is what makes stage 2 exact for any candidates; a real limit, so checked, not
// clamped.
@@ -248,7 +278,8 @@ static int rowtopk_bf16_sharded_emit(long y, long partial, long outv, long outi,
return R4D_NO(RAD_E_SHAPE);
const int CH = rowtopk_chunk_width(N, NCH);
const int nch = (N + CH - 1) / CH;
#define R4D_TK_S1(PT) emit_rc = R4D_EMIT(stream, (r4d_rowtopk_stage1_kernel<PT>), \
#define R4D_TK_S1(PT) emit_rc = R4D_EMIT(stream, (chain ? r4dchain_rowtopk_stage1<PT> \
: r4d_rowtopk_stage1_kernel<PT>), \
dim3((nch + R4D_TOPK_WPB - 1) / R4D_TOPK_WPB, M), \
dim3(R4D_TOPK_WAVE * R4D_TOPK_WPB), 0, \
(const unsigned short*)y, (unsigned long long*)partial, N, RC, nch, CH)
@@ -261,7 +292,8 @@ static int rowtopk_bf16_sharded_emit(long y, long partial, long outv, long outi,
}
#undef R4D_TK_S1
if (emit_rc != RAD_OK) return emit_rc;
return R4D_EMIT(stream, r4d_rowtopk_stage2_kernel, dim3(M), dim3(R4D_TOPK_WAVE), 0,
return R4D_EMIT(stream, (chain ? r4dchain_rowtopk_stage2 : r4d_rowtopk_stage2_kernel), dim3(M),
dim3(R4D_TOPK_WAVE), 0,
(const unsigned long long*)partial, (float*)outv, (int*)outi,
(float*)outp, off, R, nch * RC);
}
@@ -284,7 +316,8 @@ __device__ __forceinline__ unsigned long long tk_key_f32(float v, unsigned id) {
return ((unsigned long long)u << 32) | (unsigned)(0xFFFFFFFFu - id);
}
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_merge_kernel(
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below.
__device__ __forceinline__ void r4d_rowtopk_merge_body(
const float* __restrict__ G, float* __restrict__ OV, int* __restrict__ OI, int R, int n) {
const int m = blockIdx.x;
const int lane = threadIdx.x;
@@ -309,6 +342,16 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_merge_kernel(
}
}
}
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_merge_kernel(
const float* __restrict__ G, float* __restrict__ OV, int* __restrict__ OI, int R, int n) {
r4d_rowtopk_merge_body(G, OV, OI, R, n);
}
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4dchain_rowtopk_merge(
const float* __restrict__ G, float* __restrict__ OV, int* __restrict__ OI, int R, int n) {
r4d_chain_wait();
r4d_rowtopk_merge_body(G, OV, OI, R, n);
r4d_chain_done();
}
// ============================================================== logit_rerank
//
@@ -490,9 +533,11 @@ extern "C" int r4d_rad_rowtopk(const RadArgs* a, RadStream stream) {
if (r4d_numel(pairs) < M * R * 2) return R4D_NO(RAD_E_SHAPE);
}
/* The chained forms at decode heights, where the row resolved with `chain`. */
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
return rowtopk_bf16_sharded_emit(r4d_addr(x), (long)(uintptr_t)a->scratch, r4d_addr(val),
r4d_addr(idx), pairs ? r4d_addr(pairs) : 0,
(int)M, (int)N, (int)R, RC, NCH, PT1, (int)off, stream);
(int)M, (int)N, (int)R, RC, NCH, PT1, (int)off, stream, ch);
}
/* ------------------------------------------------------------------ row_topk_merge
@@ -519,7 +564,8 @@ extern "C" int r4d_rad_rowtopk_merge(const RadArgs* a, RadStream s) {
if (r4d_numel(idx) < M * R || r4d_numel(val) < M * R) return R4D_NO(RAD_E_SHAPE);
/* R <= PT2 makes the merge exact for any candidates (one lane can hold the whole answer). */
return R4D_EMIT(s, r4d_rowtopk_merge_kernel, dim3((unsigned)M),
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
return R4D_EMIT(s, (ch ? r4dchain_rowtopk_merge : r4d_rowtopk_merge_kernel), dim3((unsigned)M),
dim3(R4D_TOPK_WAVE), 0, (const float*)g->data, (float*)val->data,
(int*)idx->data, (int)R, (int)(W * R));
}
+86 -16
View File
@@ -35,6 +35,7 @@
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_chain.h"
#include <cfloat>
@@ -140,7 +141,8 @@ __device__ __forceinline__ float block_max(float v, float* lds) {
// ---------------------------------------------------------------------------- sample_temp
// ref_sample_temp. temp <= 0 leaves the row alone: greedy is `sample_argmax`, and a temperature of
// zero silently meaning something else would make the chain unreadable.
__global__ __launch_bounds__(kThreads) void temp_kernel(
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below.
__device__ __forceinline__ void temp_body(
float* __restrict__ lg, const SP* __restrict__ sp, uint32_t n_vocab, uint32_t lg_ld) {
const uint32_t m = blockIdx.x;
const float t = sp[m].temp;
@@ -150,6 +152,16 @@ __global__ __launch_bounds__(kThreads) void temp_kernel(
for (uint32_t i = threadIdx.x + blockIdx.y * kThreads; i < n_vocab; i += kThreads * gridDim.y)
row[i] *= inv;
}
__global__ __launch_bounds__(kThreads) void temp_kernel(
float* __restrict__ lg, const SP* __restrict__ sp, uint32_t n_vocab, uint32_t lg_ld) {
temp_body(lg, sp, n_vocab, lg_ld);
}
__global__ __launch_bounds__(kThreads) void r4dchain_sample_temp(
float* __restrict__ lg, const SP* __restrict__ sp, uint32_t n_vocab, uint32_t lg_ld) {
r4d_chain_wait();
temp_body(lg, sp, n_vocab, lg_ld);
r4d_chain_done();
}
// ---------------------------------------------------------------------------- sample_mask
// ref_sample_mask. A set bit means allowed: the mask is the grammar's admissible set. Word w bit b
@@ -461,7 +473,9 @@ __device__ uint32_t radix_select(const float* __restrict__ row, uint32_t n, uint
return prefix;
}
__global__ __launch_bounds__(kTopkThreads) void topk_kernel(
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. A greedy row's whole
// block returns early, together.
__device__ __forceinline__ void topk_body(
const float* __restrict__ lg, const SP* __restrict__ sp,
int32_t* __restrict__ ci, float* __restrict__ cv, uint32_t* __restrict__ pr,
uint32_t n_vocab, uint32_t n_cand, uint32_t lg_ld, uint32_t ci_ld, uint32_t cv_ld,
@@ -630,6 +644,22 @@ __global__ __launch_bounds__(kTopkThreads) void topk_kernel(
}
}
}
__global__ __launch_bounds__(kTopkThreads) void topk_kernel(
const float* __restrict__ lg, const SP* __restrict__ sp,
int32_t* __restrict__ ci, float* __restrict__ cv, uint32_t* __restrict__ pr,
uint32_t n_vocab, uint32_t n_cand, uint32_t lg_ld, uint32_t ci_ld, uint32_t cv_ld,
uint32_t pr_ld, int32_t vocab_off, uint32_t pad) {
topk_body(lg, sp, ci, cv, pr, n_vocab, n_cand, lg_ld, ci_ld, cv_ld, pr_ld, vocab_off, pad);
}
__global__ __launch_bounds__(kTopkThreads) void r4dchain_sample_topk(
const float* __restrict__ lg, const SP* __restrict__ sp,
int32_t* __restrict__ ci, float* __restrict__ cv, uint32_t* __restrict__ pr,
uint32_t n_vocab, uint32_t n_cand, uint32_t lg_ld, uint32_t ci_ld, uint32_t cv_ld,
uint32_t pr_ld, int32_t vocab_off, uint32_t pad) {
r4d_chain_wait();
topk_body(lg, sp, ci, cv, pr, n_vocab, n_cand, lg_ld, ci_ld, cv_ld, pr_ld, vocab_off, pad);
r4d_chain_done();
}
// ---------------------------------------------------------------------------- sample_logprobs
// ref_sample_logprobs. For a row with RAD_SP_LOGPROBS: [max, sum of exp(l - max), k (id, logit)
@@ -909,7 +939,9 @@ __global__ __launch_bounds__(kThreads) void narrow_kernel(
// the comparison never chooses one, and the fallback must not either.
//
// A greedy row is not touched: its token is the argmax's, written before the chain ran.
__global__ __launch_bounds__(kThreads) void pick_kernel(
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. Its returns are
// a whole block's, or every thread but the walker's after the last barrier.
__device__ __forceinline__ void pick_body(
const int32_t* __restrict__ ci, const float* __restrict__ cv, const SP* __restrict__ sp,
int32_t* __restrict__ tok, uint32_t n_cand, uint32_t ci_ld, uint32_t cv_ld) {
__shared__ float red[kWaves];
@@ -947,6 +979,18 @@ __global__ __launch_bounds__(kThreads) void pick_kernel(
}
tok[m] = chosen >= 0 ? chosen : last;
}
__global__ __launch_bounds__(kThreads) void pick_kernel(
const int32_t* __restrict__ ci, const float* __restrict__ cv, const SP* __restrict__ sp,
int32_t* __restrict__ tok, uint32_t n_cand, uint32_t ci_ld, uint32_t cv_ld) {
pick_body(ci, cv, sp, tok, n_cand, ci_ld, cv_ld);
}
__global__ __launch_bounds__(kThreads) void r4dchain_sample_pick(
const int32_t* __restrict__ ci, const float* __restrict__ cv, const SP* __restrict__ sp,
int32_t* __restrict__ tok, uint32_t n_cand, uint32_t ci_ld, uint32_t cv_ld) {
r4d_chain_wait();
pick_body(ci, cv, sp, tok, n_cand, ci_ld, cv_ld);
r4d_chain_done();
}
// ---------------------------------------------------------------------------- sample_merge_topk
// The vocab-parallel merge. Each rank runs top-k over its own lm_head shard and the candidate sets
@@ -956,7 +1000,8 @@ __global__ __launch_bounds__(kThreads) void pick_kernel(
//
// One block per row, with the top-k's packed (key, ~id) word, so descending order and the lower-id
// tie rule come from the same code. n_in is world_size * n_cand, a few thousand.
__global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel(
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below.
__device__ __forceinline__ void merge_topk_body(
const uint32_t* __restrict__ gt, const SP* __restrict__ sp,
int32_t* __restrict__ ci, float* __restrict__ cv,
uint32_t n_in, uint32_t n_cand, uint32_t gt_ld, uint32_t ci_ld, uint32_t cv_ld, uint32_t pad) {
@@ -1020,6 +1065,20 @@ __global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel(
ov[r] = __builtin_bit_cast(float, (key & 0x80000000u) ? (key & 0x7fffffffu) : ~key);
}
}
__global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel(
const uint32_t* __restrict__ gt, const SP* __restrict__ sp,
int32_t* __restrict__ ci, float* __restrict__ cv,
uint32_t n_in, uint32_t n_cand, uint32_t gt_ld, uint32_t ci_ld, uint32_t cv_ld, uint32_t pad) {
merge_topk_body(gt, sp, ci, cv, n_in, n_cand, gt_ld, ci_ld, cv_ld, pad);
}
__global__ __launch_bounds__(kTopkThreads) void r4dchain_sample_merge_topk(
const uint32_t* __restrict__ gt, const SP* __restrict__ sp,
int32_t* __restrict__ ci, float* __restrict__ cv,
uint32_t n_in, uint32_t n_cand, uint32_t gt_ld, uint32_t ci_ld, uint32_t cv_ld, uint32_t pad) {
r4d_chain_wait();
merge_topk_body(gt, sp, ci, cv, n_in, n_cand, gt_ld, ci_ld, cv_ld, pad);
r4d_chain_done();
}
} // namespace
@@ -1031,12 +1090,13 @@ __global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel(
static uint32_t host_pow2(uint32_t v) { uint32_t p = 1; while (p < v) p <<= 1; return p; }
static int r4d_sample_temp_f32(long lg, long params, int M, int n_vocab, int lg_ld,
long stream) {
long stream, bool chain = false) {
if (!lg || !params) return R4D_NO(RAD_E_INVAL);
if (M <= 0 || n_vocab <= 0) return R4D_NO(RAD_E_SHAPE);
if (!lg_ld) lg_ld = n_vocab;
const uint32_t gy = ((uint32_t)n_vocab + kThreads - 1) / kThreads;
hipLaunchKernelGGL(temp_kernel, dim3((uint32_t)M, gy > 256u ? 256u : gy), dim3(kThreads), 0,
hipLaunchKernelGGL((chain ? r4dchain_sample_temp : temp_kernel),
dim3((uint32_t)M, gy > 256u ? 256u : gy), dim3(kThreads), 0,
(hipStream_t)stream, (float*)lg, (const SP*)params,
(uint32_t)n_vocab, (uint32_t)lg_ld);
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
@@ -1120,7 +1180,7 @@ static int r4d_sample_logprobs_f32(long lg, long params, long stats, int M, int
static int r4d_sample_topk_f32(long lg, long params, long cand_idx, long cand_val, long pairs,
int M, int n_vocab, int n_cand,
int lg_ld, int ci_ld, int cv_ld, int pr_ld, int vocab_off,
long stream) {
long stream, bool chain = false) {
if (!lg || !params || !cand_idx || !cand_val) return R4D_NO(RAD_E_INVAL);
if (M <= 0 || n_vocab <= 0 || n_cand <= 0) return R4D_NO(RAD_E_SHAPE);
if ((uint32_t)n_cand > kMaxCand) return R4D_NO(RAD_E_SHAPE);
@@ -1129,7 +1189,8 @@ static int r4d_sample_topk_f32(long lg, long params, long cand_idx, long cand_va
if (!cv_ld) cv_ld = n_cand;
if (!pr_ld) pr_ld = 2 * n_cand;
const uint32_t pad = host_pow2((uint32_t)n_cand);
hipLaunchKernelGGL(topk_kernel, dim3((uint32_t)M), dim3(kTopkThreads),
hipLaunchKernelGGL((chain ? r4dchain_sample_topk : topk_kernel), dim3((uint32_t)M),
dim3(kTopkThreads),
pad * sizeof(unsigned long long), (hipStream_t)stream,
(const float*)lg, (const SP*)params, (int32_t*)cand_idx, (float*)cand_val,
(uint32_t*)pairs,
@@ -1154,12 +1215,14 @@ static int r4d_sample_narrow_f32(long cand_idx, long cand_val, long params, int
}
static int r4d_sample_pick_f32(long cand_idx, long cand_val, long params, long tok,
int M, int n_cand, int ci_ld, int cv_ld, long stream) {
int M, int n_cand, int ci_ld, int cv_ld, long stream,
bool chain = false) {
if (!cand_idx || !cand_val || !params || !tok) return R4D_NO(RAD_E_INVAL);
if (M <= 0 || n_cand <= 0) return R4D_NO(RAD_E_SHAPE);
if (!ci_ld) ci_ld = n_cand;
if (!cv_ld) cv_ld = n_cand;
hipLaunchKernelGGL(pick_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
hipLaunchKernelGGL((chain ? r4dchain_sample_pick : pick_kernel), dim3((uint32_t)M),
dim3(kThreads), 0, (hipStream_t)stream,
(const int32_t*)cand_idx, (const float*)cand_val, (const SP*)params,
(int32_t*)tok, (uint32_t)n_cand, (uint32_t)ci_ld, (uint32_t)cv_ld);
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
@@ -1167,7 +1230,8 @@ static int r4d_sample_pick_f32(long cand_idx, long cand_val, long params, long t
static int r4d_sample_merge_topk_f32(long gathered, long params, long cand_idx, long cand_val,
int M, int n_in, int n_cand,
int gt_ld, int ci_ld, int cv_ld, long stream) {
int gt_ld, int ci_ld, int cv_ld, long stream,
bool chain = false) {
if (!gathered || !params || !cand_idx || !cand_val) return R4D_NO(RAD_E_INVAL);
if (M <= 0 || n_in <= 0 || n_cand <= 0) return R4D_NO(RAD_E_SHAPE);
if ((uint32_t)n_in > kMaxCand) return R4D_NO(RAD_E_SHAPE);
@@ -1175,7 +1239,8 @@ static int r4d_sample_merge_topk_f32(long gathered, long params, long cand_idx,
if (!ci_ld) ci_ld = n_cand;
if (!cv_ld) cv_ld = n_cand;
const uint32_t pad = host_pow2((uint32_t)n_in);
hipLaunchKernelGGL(merge_topk_kernel, dim3((uint32_t)M), dim3(kTopkThreads),
hipLaunchKernelGGL((chain ? r4dchain_sample_merge_topk : merge_topk_kernel), dim3((uint32_t)M),
dim3(kTopkThreads),
pad * sizeof(unsigned long long), (hipStream_t)stream,
(const uint32_t*)gathered, (const SP*)params,
(int32_t*)cand_idx, (float*)cand_val,
@@ -1243,8 +1308,10 @@ extern "C" int r4d_rad_sample_temp(const RadArgs* a, RadStream s) {
R4D_NEED(logits_of(a, &lg, &M, &nv, &ld));
const RadTensor* pr = r4d_opt(a, V_PARAMS);
R4D_NEED(params_ok(pr, M));
/* The chained form at decode heights, where the row resolved with `chain`. */
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
return r4d_sample_temp_f32(r4d_addr(lg), r4d_addr(pr), (int)M, (int)nv, (int)ld,
(long)(uintptr_t)s);
(long)(uintptr_t)s, ch);
}
extern "C" int r4d_rad_sample_mask(const RadArgs* a, RadStream s) {
@@ -1378,10 +1445,11 @@ extern "C" int r4d_rad_sample_topk(const RadArgs* a, RadStream s) {
}
const long long voff = r4d_pgeti_or(a->p, a->n_p, "vocab_off", 0);
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
return r4d_sample_topk_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(ci), r4d_addr(cv),
pp ? r4d_addr(pp) : 0,
(int)M, (int)nv, (int)n_cand, (int)ld, (int)ci_ld, (int)cv_ld,
(int)pr_ld, (int)voff, (long)(uintptr_t)s);
(int)pr_ld, (int)voff, (long)(uintptr_t)s, ch);
}
/* ------------------------------------------------------------------ the narrowing stages */
@@ -1439,9 +1507,10 @@ extern "C" int r4d_rad_sample_pick(const RadArgs* a, RadStream s) {
if (M <= 0 || Mv < M || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE);
R4D_NEED(params_ok(pr, M));
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
return r4d_sample_pick_f32(r4d_addr(ci), r4d_addr(cv), r4d_addr(pr), r4d_addr(tok),
(int)M, (int)n_cand, (int)ci_ld, (int)cv_ld,
(long)(uintptr_t)s);
(long)(uintptr_t)s, ch);
}
/* ------------------------------------------------------------------ merge_topk */
@@ -1474,7 +1543,8 @@ extern "C" int r4d_rad_sample_merge_topk(const RadArgs* a, RadStream s) {
const long long n_in = per_row / 2;
if (n_in <= 0 || n_in > (int)kMaxCand) return R4D_NO(RAD_E_SHAPE);
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
return r4d_sample_merge_topk_f32(r4d_addr(gt), r4d_addr(pr), r4d_addr(ci), r4d_addr(cv),
(int)M, (int)n_in, (int)n_cand, (int)per_row, (int)ci_ld,
(int)cv_ld, (long)(uintptr_t)s);
(int)cv_ld, (long)(uintptr_t)s, ch);
}
+7806 -141
View File
File diff suppressed because it is too large. Load diff
+320 -4
View File
@@ -66,6 +66,7 @@
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include "r4d_plugin.h"
#include "rad_sample.h"
@@ -315,11 +316,11 @@ extern "C" int r4d_shape_cast(const RadParam* p, int n_p, int operand,
const int64_t M = pi(p, n_p, "M");
const int64_t n = pi(p, n_p, "n");
/* Three rows serve the op, bf16 -> bf16 (a strided row copy), bf16 -> f32 and bf16 -> f16,
* and the shims refuse any other pair, so another pair is declined here. */
/* The rows serve bf16 -> bf16 and f32 -> f32 (strided row copies), bf16 -> f32, bf16 -> f16
* and f32 -> bf16, and the shims refuse any other pair, so another pair is declined here. */
const uint32_t f = dt_par(p, n_p, "from"), t = dt_par(p, n_p, "to");
if (f != (uint32_t)RAD_BF16 ||
(t != (uint32_t)RAD_BF16 && t != (uint32_t)RAD_F32 && t != (uint32_t)RAD_F16))
const uint32_t bf = (uint32_t)RAD_BF16, f32 = (uint32_t)RAD_F32, f16 = (uint32_t)RAD_F16;
if (!(f == bf && (t == bf || t == f32 || t == f16)) && !(f == f32 && (t == bf || t == f32)))
return RAD_E_UNSUPPORTED;
const RadOpdDesc l[] = { opd(f, M, n), opd(t, M, n) };
R4D_PICK(l);
@@ -339,6 +340,20 @@ extern "C" int r4d_shape_rmsnorm(const RadParam* p, int n_p, int operand,
R4D_PICK(l);
}
/* add_rmsnorm -- rmsnorm's operands with the addend after x. */
extern "C" int r4d_shape_add_rmsnorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t n = pi(p, n_p, "n");
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = {
opd(D, M, n),
opd(D, M, n),
opd((uint32_t)RAD_F32, n),
opd(D, M, n),
};
R4D_PICK(l);
}
/* ---- the vision tower's (r4d_vit_bf16.hip). Every optional operand is passed: the norm's bias and
* the GEMM's residual are the same code with a branch taken, so this covers both forms. */
extern "C" int r4d_shape_layernorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
@@ -364,6 +379,91 @@ extern "C" int r4d_shape_gemm_nt_bias(const RadParam* p, int n_p, int operand, R
R4D_PICK(l);
}
extern "C" int r4d_shape_moe_mxfp4(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K");
const int64_t N1 = rad_param_geti(p, n_p, "N_odd", N), K1 = rad_param_geti(p, n_p, "K_odd", K);
const int64_t ne = pi(p, n_p, "n_expert"), top = pi(p, n_p, "top_k");
const char* order = rad_param_gets(p, n_p, "a_order", "");
const int64_t ar = !std::strcmp(order, "sorted") ? M * top : M;
const int64_t nk = std::max(K, K1), nn = std::max(N, N1);
RadOpdDesc s0 = opd((uint32_t)RAD_U8, (ne + 1) / 2, N, K / 32);
RadOpdDesc s1 = opd((uint32_t)RAD_U8, ne / 2, N1, K1 / 32);
s0.fill = s1.fill = RAD_FILL_INDEX;
s0.idx_const = s1.idx_const = 127;
const RadOpdDesc l[] = { opd((uint32_t)RAD_F8E4M3, ar, nk),
opd((uint32_t)RAD_F32, ar, nk / 128),
opd((uint32_t)RAD_FP4E2M1, (ne + 1) / 2, N, K),
s0,
opd_idx(M * top, 0, M * top),
opd_idx(ne + 1, 0, M * top + 1),
opd((uint32_t)RAD_FP4E2M1, ne / 2, N1, K1),
s1,
opd((uint32_t)RAD_BF16, M * top, nn) };
R4D_PICK(l);
}
extern "C" int r4d_shape_kda_update(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const char* form = rad_param_gets(p, n_p, "state_form", "");
if (!std::strcmp(form, "anchor")) return RAD_E_UNSUPPORTED;
const int64_t M = pi(p, n_p, "M"), H = pi(p, n_p, "heads");
const int64_t K = pi(p, n_p, "head_k"), V = pi(p, n_p, "head_v");
const uint32_t D = dt_act(p, n_p, "dtype");
const char* mode = rad_param_gets(p, n_p, "mode", "");
const int64_t history = !std::strcmp(mode, "verify") ? M : 1;
const RadOpdDesc l[] = {
opd(D, M, H, K), opd(D, M, H, K), opd(D, M, H, V), opd(D, M, H, K), opd(D, M, H),
opd((uint32_t)RAD_F32, H), opd((uint32_t)RAD_F32, H * K),
opd((uint32_t)RAD_F32, history + 1, H, V, K),
opd_idx(1, history, history + 1, -1, RAD_OPD_F_IDX_UNIQUE),
opd_idx(2, 0, M, -1, RAD_OPD_F_IDX_CU),
opd_idx(1, 0, 0, 1), opd_idx(1, 0, 0, 1), opd(D, M, H, V),
};
R4D_PICK(l);
}
extern "C" int r4d_shape_mhc_pre(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc");
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, hc * n), opd((uint32_t)RAD_F32, hc * (hc + 2), hc * n),
opd((uint32_t)RAD_F32, 3), opd((uint32_t)RAD_F32, hc * (hc + 2)), opd(D, M, n),
opd((uint32_t)RAD_F32, M, hc), opd((uint32_t)RAD_F32, M, hc * hc) };
R4D_PICK(l);
}
/* The partial matrix: per chunk the hc*(hc+2) coefficient partials and the sum of squares, padded to
* a multiple of four floats (docs/OPS.md). */
static int64_t mhc_part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; }
extern "C" int r4d_shape_mhc_pre_partial(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc");
const int64_t chunks = pi(p, n_p, "chunks");
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, hc * n), opd((uint32_t)RAD_F32, hc * (hc + 2), hc * n),
opd((uint32_t)RAD_F32, M, chunks * mhc_part_stride(hc)) };
R4D_PICK(l);
}
extern "C" int r4d_shape_mhc_pre_finish(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc");
const int64_t chunk = pi(p, n_p, "chunk");
const int64_t chunks = chunk > 0 ? hc * n / chunk : 0;
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd((uint32_t)RAD_F32, M, chunks * mhc_part_stride(hc)),
opd(D, M, hc * n), opd((uint32_t)RAD_F32, 3), opd((uint32_t)RAD_F32, hc * (hc + 2)),
opd(D, M, n), opd((uint32_t)RAD_F32, M, hc), opd((uint32_t)RAD_F32, M, hc * hc) };
R4D_PICK(l);
}
extern "C" int r4d_shape_mhc_post(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc");
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, n), opd(D, M, hc * n), opd((uint32_t)RAD_F32, M, hc),
opd((uint32_t)RAD_F32, M, hc * hc), opd(D, M, hc * n) };
R4D_PICK(l);
}
extern "C" int r4d_shape_mhc_contract(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc");
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, hc * n), opd(D, M, n) };
R4D_PICK(l);
}
/* ---- the gated residual (r4d_hc_bf16.hip's three shims). `inject` and `group` default on, so a
* query naming neither describes what every trunk connection runs; 0 for either describes one of
* the two exceptions: the final mixer, and a read whose consumer wants bf16. */
@@ -394,6 +494,19 @@ extern "C" int r4d_shape_hc_write(const RadParam* p, int n_p, int operand, RadOp
R4D_PICK(l);
}
/* hc_project's three: the bf16 stream (in place), the layer's unit f32 direction, and the int32
* per-row switch. The switch is an index domain: 0 or 1. */
extern "C" int r4d_shape_hc_project(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc");
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = {
opd(D, M, hc * n), /* h, in place */
opd((uint32_t) RAD_F32, n), /* v */
opd_idx(M, 1, 1, 0), /* on: 0 or 1 */
};
R4D_PICK(l);
}
/* hc_write's operands with the all-reduce in front; `y` is also the message. */
extern "C" int r4d_shape_ar_hc_write(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return r4d_shape_hc_write(p, n_p, operand, out);
@@ -496,6 +609,84 @@ extern "C" int r4d_shape_silu_mul(const RadParam* p, int n_p, int operand,
const RadOpdDesc l[] = { opd(D, M, 2 * n), opd(D, M, n) };
R4D_PICK(l);
}
extern "C" int r4d_shape_router_sigmoid_topk(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), ne = pi(p, n_p, "n_expert"), k = pi(p, n_p, "top_k");
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, ne), opd((uint32_t)RAD_F32, ne), opd_idx(M, k, ne),
opd(D, M, k) };
R4D_PICK(l);
}
extern "C" int r4d_shape_router_sigmoid_topk_scatter(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), ne = pi(p, n_p, "n_expert"), k = pi(p, n_p, "top_k");
const int64_t nl = pi(p, n_p, "n_local", ne);
if (ne <= 0 || ne > 512 || k <= 0 || k > ne || nl <= 0 || nl > ne || M * k > 1024)
return RAD_E_UNSUPPORTED;
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, ne),
opd((uint32_t)RAD_F32, ne),
opd_idx(M, k, ne),
opd(D, M, k),
opd((uint32_t)RAD_I32, M * k),
opd((uint32_t)RAD_I32, nl + 1),
opd((uint32_t)RAD_I32, nl),
opd((uint32_t)RAD_BF16, M, 1),
opd((uint32_t)RAD_I32, M * k) };
R4D_PICK(l);
}
extern "C" int r4d_shape_dsa_pool(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), ratio = pi(p, n_p, "ratio");
const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M * ratio, 2 * n),
opd((uint32_t)RAD_F32, ratio, n),
opd((uint32_t)RAD_F8E4M3, M, n),
opd((uint32_t)RAD_F32, M, 1),
opd_none(),
opd_none() };
R4D_PICK(l);
}
extern "C" int r4d_shape_dsa_query(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M, n), opd((uint32_t)RAD_F8E4M3, M, n),
opd((uint32_t)RAD_F32, M, 1) };
R4D_PICK(l);
}
extern "C" int r4d_shape_mla_project(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), h = pi(p, n_p, "heads"), d = pi(p, n_p, "head_dim"),
l = pi(p, n_p, "latent_dim");
const char* mode = r4d_pgets(p, n_p, "mode");
const bool absorb = mode && !std::strcmp(mode, "absorb"),
expand = mode && !std::strcmp(mode, "expand");
if (!absorb && !expand) return RAD_E_UNSUPPORTED;
const RadOpdDesc list[] = { opd((uint32_t)RAD_BF16, M, h, absorb ? d : l),
opd((uint32_t)RAD_BF16, h * 2 * d, l),
opd((uint32_t)RAD_BF16, M, h, absorb ? l : d) };
R4D_PICK(list);
}
extern "C" int r4d_shape_dsa_score(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), H = pi(p, n_p, "heads");
const int64_t B = pi(p, n_p, "blocks"), S = pi(p, n_p, "seqs"), pages = S * B;
const RadOpdDesc l[] = { opd((uint32_t)RAD_F8E4M3, M, H, n),
opd((uint32_t)RAD_F32, M, H),
opd((uint32_t)RAD_F32, M, H),
opd((uint32_t)RAD_F8E4M3, pages, n),
opd((uint32_t)RAD_F32, pages),
opd_idx(S, B, pages),
opd_idx(S + 1, 0, M, -1, RAD_OPD_F_IDX_CU),
opd_idx(S, 0, 0, B),
opd((uint32_t)RAD_F32, M, B),
opd_none() };
R4D_PICK(l);
}
extern "C" int r4d_shape_mla_attn(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), D = pi(p, n_p, "latent_dim"), H = pi(p, n_p, "heads");
const int64_t B = pi(p, n_p, "blocks"), bs = pi(p, n_p, "block_size"),
pages = std::max((int64_t)2, B * M);
const uint32_t dt = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(dt, M, H, D), opd(dt, pages, 1, bs, D), opd_idx(M, B, pages),
opd_idx(M, 0, 0, B * bs), opd(dt, M, H, D) };
R4D_PICK(l);
}
extern "C" int r4d_shape_rope(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
@@ -900,6 +1091,48 @@ extern "C" int r4d_shape_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p,
R4D_PICK(l);
}
/* qkv_norm_rope -- separate q [M, n_head * head_dim], k and v [M, n_head_kv * head_dim] (dense
* here; the shim also takes each as a slice of a wider row), the positions, and the q and k gains,
* f32 as every architecture plugin declares them (shim in r4d_qkv_norm_rope.hip). As for `rope`,
* a position is not a lookup: the kernel takes sincos of position x frequency, so it is drawn over
* a context's range, where the angles a decode step sees are, not over the band's rows. */
extern "C" int r4d_shape_qkv_norm_rope(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t hd = pi(p, n_p, "head_dim");
const int64_t nq = pi(p, n_p, "n_head");
const int64_t nkv = pi(p, n_p, "n_head_kv");
const RadOpdDesc l[] = {
/* at n_head 0 the kernel reads no q; it is passed as k's buffer, so drawn like k */
opd((uint32_t)RAD_BF16, M, (nq ? nq : nkv) * hd),
opd((uint32_t)RAD_BF16, M, nkv * hd),
opd((uint32_t)RAD_BF16, M, nkv * hd),
opd_idx(M, 0, 32768),
opd((uint32_t)RAD_F32, hd),
opd((uint32_t)RAD_F32, hd),
};
R4D_PICK(l);
}
/* qkv_norm_rope_kv_store -- qkv_norm_rope's six, then kv_store's slot mapping (unique slots, as
* the engine hands them) and its paged cache, sized as kv_store's description sizes it. */
extern "C" int r4d_shape_qkv_norm_rope_kv_store(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
if (operand < 6) return r4d_shape_qkv_norm_rope(p, n_p, operand, out);
const int64_t M = pi(p, n_p, "M");
const int64_t hd = pi(p, n_p, "head_dim");
const int64_t kvh = pi(p, n_p, "n_head_kv");
const int64_t bs = pi(p, n_p, "block_size");
const uint32_t KV = dt_act(p, n_p, "kv_dtype");
if (M <= 0 || bs <= 0) return RAD_E_UNSUPPORTED;
const int64_t nb = (M + bs - 1) / bs + 2;
const RadOpdDesc l[] = {
opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), opd_none(),
opd_idx(M, 0, nb * bs, -1, RAD_OPD_F_IDX_UNIQUE),
opd(KV, nb, kvh, bs, 2 * hd),
};
R4D_PICK(l);
}
/* rope_table -- the cos/sin plane the fused prologue reads (shim in r4d_qk_norm_rope_gate.hip). */
extern "C" int r4d_shape_rope_table(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
@@ -1015,11 +1248,35 @@ extern "C" int r4d_shape_ar_rmsnorm_quant_fp8(const RadParam* p, int n_p, int op
R4D_PICK(l);
}
extern "C" int r4d_shape_ar_rmsnorm_had_quant_i8g(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t n = pi(p, n_p, "n");
const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK);
if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED;
const RadOpdDesc l[] = {
opd((uint32_t)RAD_BF16, M, n), /* inout: the message and the input */
opd((uint32_t)RAD_BF16, M, n),
opd((uint32_t)RAD_F32, n), /* f32 or bf16; the shim reads the operand's own */
opd((uint32_t)RAD_I8, M, n),
opd((uint32_t)RAD_F32, M, (n + g - 1) / g),
opd((uint32_t)RAD_BF16, M, n),
};
R4D_PICK(l);
}
/* ==========================================================================================
* GEMM, dequant and the row top-R (shims in the r4d_gemm_*.hip units, r4d_dequant_w4_bf16.hip and
* r4d_rowtopk_bf16.hip).
* ========================================================================================= */
extern "C" int r4d_shape_gemm_nt_f32(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K");
const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M, K), opd((uint32_t)RAD_F32, N, K),
opd((uint32_t)RAD_F32, M, N) };
R4D_PICK(l);
}
extern "C" int r4d_shape_gemm_nt(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
@@ -1243,6 +1500,22 @@ extern "C" int r4d_shape_moe_scatter(const RadParam* p, int n_p, int operand, Ra
R4D_PICK(l);
}
extern "C" int r4d_shape_moe_scatter_inv(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t ne = pi(p, n_p, "n_expert");
const int64_t k = pi(p, n_p, "top_k");
if (ne <= 0 || ne > 512 || k <= 0) return RAD_E_UNSUPPORTED;
const RadOpdDesc l[] = {
opd_idx(M, k, ne, -1),
opd((uint32_t)RAD_I32, M * k),
opd((uint32_t)RAD_I32, ne + 1),
opd((uint32_t)RAD_I32, ne),
opd((uint32_t)RAD_I32, M * k),
};
R4D_PICK(l);
}
extern "C" int r4d_shape_moe_gemm_q(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t N0 = pi(p, n_p, "N"), K0 = pi(p, n_p, "K");
@@ -1339,6 +1612,12 @@ extern "C" int r4d_shape_moe_gather(const RadParam* p, int n_p, int operand, Rad
R4D_PICK(l);
}
/* moe_gather's list with the slot table in place of `sorted_tok`: the same draw, since a valid
* table, like a valid sort, holds distinct rows of `y_expert` (and -1 for a dropped slot). */
extern "C" int r4d_shape_moe_gather_inv(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return r4d_shape_moe_gather(p, n_p, operand, out);
}
/* row_topk -- exact per-row top-R of a wide bf16 matrix (shim in r4d_rowtopk_bf16.hip). R is at
* most 32, stage 2's PT. */
extern "C" int r4d_shape_row_topk(const RadParam* p, int n_p, int operand,
@@ -1700,6 +1979,43 @@ extern "C" int r4d_shape_gated_quant_fp8(const RadParam* p, int n_p, int operand
R4D_PICK(l);
}
/* The `_had_quant_i8g` twins: the same operands with int8 codes (had_quant_act_i8g's). */
extern "C" int r4d_shape_rmsnorm_had_quant_i8g(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t n = pi(p, n_p, "n");
const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK);
const uint32_t D = dt_act(p, n_p, "dtype");
if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED;
const RadOpdDesc l[] = {
opd(D, M, n),
opd(D, M, n),
opd((uint32_t)RAD_F32, n),
opd((uint32_t)RAD_I8, M, n),
opd((uint32_t)RAD_F32, M, (n + g - 1) / g),
opd(D, M, n),
};
R4D_PICK(l);
}
extern "C" int r4d_shape_gated_had_quant_i8g(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t n = pi(p, n_p, "n");
const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK);
const uint32_t D = dt_act(p, n_p, "dtype");
if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED;
const RadOpdDesc l[] = {
opd(D, M, 2 * n), /* gate then up in one buffer */
opd((uint32_t)RAD_I8, M, n),
opd((uint32_t)RAD_F32, M, (n + g - 1) / g),
opd(D, M, n),
};
R4D_PICK(l);
}
extern "C" int r4d_shape_gate_quant_fp8(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
+148 -130
View File
@@ -51,14 +51,7 @@ __device__ __forceinline__ void st8(float* p, const float* f) {
*(float4*)p = make_float4(f[0], f[1], f[2], f[3]);
*(float4*)(p + 4) = make_float4(f[4], f[5], f[6], f[7]);
}
// Eight per-channel values of an f32 or bf16 vector, its dtype known only at run time.
__device__ __forceinline__ void ld8w(const void* p, bool f32, int c, float* f) {
if (f32) ld8((const float*)p + c, f);
else ld8((const uint16_t*)p + c, f);
}
// Four consecutive values, the chunk a group narrower than eight channels has (see group_norm):
// an 8-byte bf16 or 16-byte f32 access at the same alignment argument, rows pitching a multiple
// of eight and a chunk starting on a multiple of four.
// Four- and two-channel forms of the above, and a chunk of CW (8, 4 or 2) channels through them.
__device__ __forceinline__ void ld4(const uint16_t* p, float* f) {
const uint2 u = *(const uint2*)p;
f[0] = bf16w_lo(u.x); f[1] = bf16w_hi(u.x); f[2] = bf16w_lo(u.y); f[3] = bf16w_hi(u.y);
@@ -68,40 +61,40 @@ __device__ __forceinline__ void ld4(const float* p, float* f) {
f[0] = a.x; f[1] = a.y; f[2] = a.z; f[3] = a.w;
}
__device__ __forceinline__ void st4(uint16_t* p, const float* f) {
uint2 u;
u.x = bf16x2_rne(f[0], f[1]);
u.y = bf16x2_rne(f[2], f[3]);
*(uint2*)p = u;
*(uint2*)p = make_uint2(bf16x2_rne(f[0], f[1]), bf16x2_rne(f[2], f[3]));
}
__device__ __forceinline__ void st4(float* p, const float* f) {
*(float4*)p = make_float4(f[0], f[1], f[2], f[3]);
}
__device__ __forceinline__ void ld4w(const void* p, bool f32, int c, float* f) {
if (f32) ld4((const float*)p + c, f);
else ld4((const uint16_t*)p + c, f);
__device__ __forceinline__ void ld2(const uint16_t* p, float* f) {
const uint32_t u = *(const uint32_t*)p;
f[0] = bf16w_lo(u); f[1] = bf16w_hi(u);
}
// A thread's chunk load: eight channels, or four when a group is that wide.
template <int CS>
__device__ __forceinline__ void ldchunk(const uint16_t* p, float* f) {
if constexpr (CS == 8) ld8(p, f); else ld4(p, f);
__device__ __forceinline__ void ld2(const float* p, float* f) {
const float2 a = *(const float2*)p;
f[0] = a.x; f[1] = a.y;
}
template <int CS>
__device__ __forceinline__ void ldchunk(const float* p, float* f) {
if constexpr (CS == 8) ld8(p, f); else ld4(p, f);
__device__ __forceinline__ void st2(uint16_t* p, const float* f) {
*(uint32_t*)p = bf16x2_rne(f[0], f[1]);
}
template <int CS>
__device__ __forceinline__ void stchunk(uint16_t* p, const float* f) {
if constexpr (CS == 8) st8(p, f); else st4(p, f);
__device__ __forceinline__ void st2(float* p, const float* f) {
*(float2*)p = make_float2(f[0], f[1]);
}
template <int CS>
__device__ __forceinline__ void stchunk(float* p, const float* f) {
if constexpr (CS == 8) st8(p, f); else st4(p, f);
template <int CW, typename T> __device__ __forceinline__ void ldc(const T* p, float* f) {
if constexpr (CW == 8) ld8(p, f);
else if constexpr (CW == 4) ld4(p, f);
else ld2(p, f);
}
template <int CS>
__device__ __forceinline__ void ldchunkw(const void* p, bool f32, int c, float* f) {
if constexpr (CS == 8) ld8w(p, f32, c, f); else ld4w(p, f32, c, f);
template <int CW, typename T> __device__ __forceinline__ void stc(T* p, const float* f) {
if constexpr (CW == 8) st8(p, f);
else if constexpr (CW == 4) st4(p, f);
else st2(p, f);
}
// CW per-channel values of an f32 or bf16 vector, its dtype known only at run time.
template <int CW> __device__ __forceinline__ void ldcw(const void* p, bool f32, int c, float* f) {
if (f32) ldc<CW>((const float*)p + c, f);
else ldc<CW>((const uint16_t*)p + c, f);
}
// The volume a request runs at: (T, H, W) and its row count, or false for a geometry the operands
// cannot hold (`rows` rows of the input).
__device__ __forceinline__ bool volume_of(const int* geom, long long rows, int* T, int* H, int* W,
@@ -146,6 +139,11 @@ __device__ __forceinline__ bool volume_of(const int* geom, long long rows, int*
// guarded load instead, its last tile running past K), so neither operand's addresses cost vector
// arithmetic per tile.
//
// `tpad` pads the frames other than with zeros (LTX-2's VAE): 1 replicate, the frame clamped into
// the volume; 2 causal, output frame t's tap dt reading frame max(t + dt - 1 - tpre, 0), so the
// output has tpre more frames than the input. A neighbour's frame is resolved when its offset is,
// once a tap.
//
// Measured on the R9700 at 300 W, warm, against gemm_nt_bias at bf16 at the same M, N and K = 27
// cin: 512 -> 512 at 84 x 48 x 37 148 TFLOP/s (the GEMM 146), at 42 x 24 x 37 149 (145). The
// select-and-pointer form of the gather this replaces ran 136 and 134: its loop issued twice the
@@ -183,12 +181,13 @@ __device__ __forceinline__ int idiv_dev(int a, int b) {
/* `vec` (host-checked): y, res and the bias take 16-byte accesses at every eight-column boundary.
* `xrows` bounds the volume the device geometry may name, `xbytes` is x's extent (at most kOob)
* and `Mcap` bounds the rows written.
* and `Mcap` bounds the rows written; `tpad` and `tpre` as above.
*
* `GEN` (host-set: any non-default stride / causal / `down` / reflect, the 3x3x3 encoder forms)
* generalises the gather: a staged voxel is one of the (T2, H2, W2) output grid, its base source
* coordinate carries the stride and the negative pad, and a tap's neighbour is mirrored into the
* volume first when `refl` (torch's reflect, which the launcher has checked the volume against).
* `tpad` clamps the time tap the same way it does below; the launcher refuses it with `causal`.
* The classic path is untouched — same register allocation and measured bandwidth. */
template <bool C64, bool RES, bool BF32, bool GEN>
__global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
@@ -196,7 +195,7 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
const void* __restrict__ bias, const unsigned short* R, unsigned short* C,
const int* __restrict__ geom, unsigned ldx, unsigned ldr, unsigned ldc, int Mcap, int xrows,
unsigned xbytes, int cin, int N, unsigned vec, int st, int sp, int ft, int bk, int pt,
int pb, int pl, int pr, int refl) {
int pb, int pl, int pr, int refl, int tpad, int tpre) {
typedef r4d_u32x4 U4;
__shared__ __attribute__((aligned(16))) unsigned char s_a[2][kCBM * kCPB];
@@ -205,7 +204,7 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
if (!volume_of(geom, xrows, &gT, &gH, &gW, &vol)) return;
const int HW = gH * gW;
int H2 = gH, W2 = gW;
long long Mv64 = vol;
long long Mv64 = vol + (long long)tpre * HW; /* tpad 2 front-pads tpre frames */
if constexpr (GEN) {
const int T2 = idiv_dev(gT + ft + bk - 3, st) + 1;
H2 = idiv_dev(gH + pt + pb - 3, sp) + 1;
@@ -277,8 +276,9 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
const int dt = tap / 9, dy = (tap / 3) % 3, dx = tap % 3; // the pads ride in the base
#pragma unroll
for (uint32_t i = 0; i < kCSPT; ++i) {
const int tz = vm[i] + dt;
int tz = vm[i] + dt;
int sy = vt[i] + dy, sx = vy[i] + dx;
if (tpad) tz = min(max(tz, 0), gT - 1); /* tpad 2 stays <= gT - 1 */
if (refl) { // torch's mirror, no repeated edge; then the ordinary bounds
if (sy < 0) sy = -sy; else if (sy >= gH) sy = 2 * gH - 2 - sy;
if (sx < 0) sx = -sx; else if (sx >= gW) sx = 2 * gW - 2 - sx;
@@ -295,10 +295,14 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
const int delta = dt * HW + dy * gW + dx;
#pragma unroll
for (uint32_t i = 0; i < kCSPT; ++i) {
const bool ok = tap < kTaps && (unsigned)(vt[i] + dt) < (unsigned)gT &&
int ft = vt[i] + dt;
if (tpad == 1) ft = min(max(ft, 0), gT - 1);
else if (tpad == 2) ft = max(ft - 1 - tpre, 0);
const bool ok = tap < kTaps && vt[i] >= 0 && (unsigned)ft < (unsigned)gT &&
(unsigned)(vy[i] + dy) < (unsigned)gH &&
(unsigned)(vx[i] + dx) < (unsigned)gW;
off[i] = ok ? (uint32_t)(vm[i] + delta) * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob;
const int src = tpad ? (ft * gH + vy[i] + dy) * gW + vx[i] + dx : vm[i] + delta;
off[i] = ok ? (uint32_t)src * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob;
}
}
};
@@ -462,14 +466,16 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
// give the same bytes:
//
// 1. parts: block p takes rows [p rpp, (p + 1) rpp) and writes each group's (count, mean, M2)
// of them to the scratch. A thread keeps one chunk of one group (eight channels, or four
// when a group is four channels wide) over every
// `slots`-th row, summing deviations from its first value (the shift keeps the f32 sums of
// squares from cancelling against a large mean); the block merges its threads' triples per
// group in thread order (Chan's parallel update).
// of them to the scratch. A row is `tpr` threads, each owning `cpt` consecutive CW-channel
// chunks of one group, and the block holds `slots` = 256 / tpr rows at a time (the threads
// past slots * tpr idle). A thread keeps its chunks over every `slots`-th row, summing
// deviations from its first value (the shift keeps the f32 sums of squares from cancelling
// against a large mean); the block merges its threads' triples per group in thread order
// (Chan's parallel update).
// 2. final: block g merges group g's parts, 256 strided runs then a fixed tree, and writes
// stats[2g] = mean and stats[2g + 1] = rstd = 1 / sqrt(M2 / count + eps).
// 3. apply: a thread one chunk, v = (x - mean) rstd w + b, the modulation and SiLU in
// stats[2g] = mean and stats[2g + 1] = rstd = 1 / sqrt(M2 / count + eps), the count the
// group's exact M n / groups.
// 3. apply: a thread a CW-channel chunk, v = (x - mean) rstd w + b, the modulation and SiLU in
// f32, one rounding.
//
// The scratch beyond the 2 groups leading values holds part p of group g at 3 (g kGnParts + p).
@@ -487,31 +493,33 @@ __device__ __forceinline__ void chan_merge(float& n, float& mean, float& m2, flo
n = nab;
}
/* `CS` the channels a thread's chunk: 8, or 4 when the group is exactly that wide. `cpr_log`:
* log2 of the chunks a row (n / CS, a power of two dividing the block); `gs` the chunks a group. */
template <typename TX, int CS>
/* A chunk is CW channels (8, 4 or 2: the widest dividing a group). `tpr` threads a row, each over
* `cpt` chunks; `tpg` threads a group (its chunks / cpt). */
template <typename TX, int CW>
__global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
float* __restrict__ stats, int M, int groups,
int cpr_log, int gs, int ldx, int rpp) {
int tpr, int cpt, int tpg, int ldx, int rpp) {
__shared__ float sh[3][kT];
const int tid = threadIdx.x;
const int cpr = 1 << cpr_log, slots = kT >> cpr_log;
const int c = tid & (cpr - 1), slot = tid >> cpr_log;
const int slots = kT / tpr;
const int c = tid % tpr, slot = tid / tpr;
const int p = blockIdx.x;
const int r0 = p * rpp, r1 = min(M, r0 + rpp);
float cnt = 0.0f, s1 = 0.0f, s2 = 0.0f, shift = 0.0f;
for (int r = r0 + slot; r < r1; r += slots) {
float v[CS];
ldchunk<CS>(x + (size_t)r * ldx + c * CS, v);
if (cnt == 0.0f) shift = v[0];
if (slot < slots)
for (int r = r0 + slot; r < r1; r += slots)
for (int q = 0; q < cpt; ++q) {
float v[CW];
ldc<CW>(x + (size_t)r * ldx + (c * cpt + q) * CW, v);
if (cnt == 0.0f) shift = v[0];
#pragma unroll
for (int j = 0; j < CS; ++j) {
const float d = v[j] - shift;
s1 += d;
s2 += d * d;
}
cnt += (float)CS;
}
for (int j = 0; j < CW; ++j) {
const float d = v[j] - shift;
s1 += d;
s2 += d * d;
}
cnt += (float)CW;
}
float mean = 0.0f, m2 = 0.0f;
if (cnt > 0.0f) {
const float q = s1 / cnt;
@@ -525,8 +533,8 @@ __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
for (int g = tid; g < groups; g += kT) {
float N = 0.0f, Mn = 0.0f, Q = 0.0f;
for (int s = 0; s < slots; ++s)
for (int k = 0; k < gs; ++k) {
const int t = (s << cpr_log) + g * gs + k;
for (int k = 0; k < tpg; ++k) {
const int t = s * tpr + g * tpg + k;
chan_merge(N, Mn, Q, sh[0][t], sh[1][t], sh[2][t]);
}
float* o = stats + 2 * groups + ((size_t)g * kGnParts + p) * 3;
@@ -537,7 +545,7 @@ __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
}
__global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats, int groups,
int parts, float eps) {
int parts, float count, float eps) {
__shared__ float sh[3][kT];
const int g = blockIdx.x, tid = threadIdx.x;
const float* P = stats + 2 * groups + (size_t)g * kGnParts * 3;
@@ -558,44 +566,44 @@ __global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats,
__syncthreads();
}
if (tid == 0) {
const float var = sh[2][0] / sh[0][0];
const float var = sh[2][0] / count;
stats[2 * g] = sh[1][0];
stats[2 * g + 1] = 1.0f / sqrtf(var + eps);
}
}
/* `wf`, `bf`: the gain's and bias's dtype is f32; `modk` 0 no modulation, 1 a bf16 row, 2 an f32
* one. x and y may be the same memory: a thread reads its chunk before it writes it. */
template <typename TX, typename TY, int CS>
* one. A thread is chunk `i % cpr` of row `i / cpr`, `gs8` chunks a group. x and y may be the same
* memory: a thread reads its chunk before it writes it. */
template <typename TX, typename TY, int CW>
__global__ __launch_bounds__(kT) void gn_apply_kernel(
const TX* x, TY* y, const void* __restrict__ w, const void* __restrict__ b,
const void* __restrict__ mod, const float* __restrict__ stats, int M, int n, int cpr_log,
int gs, int ldx, int ldy, int wf, int bf, int modk, int silu) {
const int slots = kT >> cpr_log;
const int tid = threadIdx.x;
const int r = blockIdx.x * slots + (tid >> cpr_log);
const void* __restrict__ mod, const float* __restrict__ stats, int M, int n, int cpr,
int gs8, int ldx, int ldy, int wf, int bf, int modk, int silu) {
const long long i = (long long)blockIdx.x * kT + threadIdx.x;
const int r = (int)(i / cpr);
if (r >= M) return;
const int ck = tid & ((1 << cpr_log) - 1), c = ck * CS;
const int g = ck / gs;
const int ck = (int)(i - (long long)r * cpr), c = ck * CW;
const int g = ck / gs8;
const float mean = stats[2 * g], rstd = stats[2 * g + 1];
float v[CS], wv[CS], bv[CS];
ldchunk<CS>(x + (size_t)r * ldx + c, v);
ldchunkw<CS>(w, wf != 0, c, wv);
ldchunkw<CS>(b, bf != 0, c, bv);
float v[CW], wv[CW], bv[CW];
ldc<CW>(x + (size_t)r * ldx + c, v);
ldcw<CW>(w, wf != 0, c, wv);
ldcw<CW>(b, bf != 0, c, bv);
#pragma unroll
for (int j = 0; j < CS; ++j) v[j] = (v[j] - mean) * rstd * wv[j] + bv[j];
for (int j = 0; j < CW; ++j) v[j] = (v[j] - mean) * rstd * wv[j] + bv[j];
if (modk) {
float sc[CS], sf[CS];
ldchunkw<CS>(mod, modk == 2, c, sc);
ldchunkw<CS>(mod, modk == 2, n + c, sf);
float sc[CW], sf[CW];
ldcw<CW>(mod, modk == 2, c, sc);
ldcw<CW>(mod, modk == 2, n + c, sf);
#pragma unroll
for (int j = 0; j < CS; ++j) v[j] = v[j] * (1.0f + sc[j]) + sf[j];
for (int j = 0; j < CW; ++j) v[j] = v[j] * (1.0f + sc[j]) + sf[j];
}
if (silu) {
#pragma unroll
for (int j = 0; j < CS; ++j) v[j] = v[j] / (1.0f + expf(-v[j]));
for (int j = 0; j < CW; ++j) v[j] = v[j] / (1.0f + expf(-v[j]));
}
stchunk<CS>(y + (size_t)r * ldy + c, v);
stc<CW>(y + (size_t)r * ldy + c, v);
}
// ---------------------------------------------------------------------------- tconv_dw
@@ -792,12 +800,6 @@ int parse_f32_list(const char* s, float* out, int max) {
return n;
}
inline int log2_exact(long long v) {
int l = 0;
while ((1ll << l) < v) ++l;
return (1ll << l) == v ? l : -1;
}
} // namespace
// ============================================================== the plugin ABI entry points
@@ -829,12 +831,25 @@ extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) {
(reflect && reflect != 1))
return R4D_NO(RAD_E_SHAPE);
const bool gen = sp != 1 || st != 1 || causal || down || reflect;
const int ft = causal ? 2 : 1, bk = causal ? 0 : 1;
const int pt = down ? 0 : 1, pl = down ? 0 : 1, pb = 1, pr = 1;
const long long K = (long long)kTaps * cin;
if (r4d_numel(w) < cout * K || r4d_numel(b) < cout || r4d_numel(geom) < 3)
return R4D_NO(RAD_E_SHAPE);
if (!r4d_contig(w) || !r4d_contig(b) || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE);
const char* tp = r4d_gets(a, "tpad");
int tpad = 0;
if (tp && *tp) {
if (!std::strcmp(tp, "replicate")) tpad = 1;
else if (!std::strcmp(tp, "causal")) tpad = 2;
else if (std::strcmp(tp, "zero")) return R4D_NO(RAD_E_INVAL);
}
const long long tpre = r4d_geti_or(a, "tpre", 0);
if (tpre < 0 || tpre > 64 || (tpre && tpad != 2) || (causal && tpad))
return R4D_NO(RAD_E_INVAL);
/* The generic gather's time base and back pad: causal and `tpad` causal both front-pad only;
* `tpad` 2's `tpre` replicated frames ride in the front pad too. */
const int ft = causal ? 2 : tpad == 2 ? 2 + (int)tpre : 1;
const int bk = causal || tpad == 2 ? 0 : 1;
long long rx = 0, ldx = 0, ry = 0, rr = 0;
if (!rows8(x, cin, &rx, &ldx) || !r4d_aligned(r4d_p(w), 16)) return R4D_NO(RAD_E_STRIDE);
const long long ldy = r4d_rows_pitch(y, cout, &ry);
@@ -863,7 +878,8 @@ extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) {
return R4D_EMIT(stream, (conv3d_kernel<C6, RS, BF, G>), grid, dim3(kCThreads), 0, Xp, Wp, \
Bp, Rp, Cp, (const int*)r4d_p(geom), (unsigned)ldx, (unsigned)ldr, \
(unsigned)ldy, (int)Mcap, (int)rx, (unsigned)xbytes, (int)cin, (int)cout, \
vec, (int)st, (int)sp, ft, bk, pt, pb, pl, pr, (int)reflect)
vec, (int)st, (int)sp, ft, bk, pt, pb, pl, pr, (int)reflect, tpad, \
(int)tpre)
#define C3_RES(G, C6, BF) do { if (res) C3_L(G, C6, true, BF); C3_L(G, C6, false, BF); } while (0)
#define C3_BF(G, C6) do { if (bf32) C3_RES(G, C6, true); C3_RES(G, C6, false); } while (0)
#define C3_C6(G) do { if (c64) C3_BF(G, true); C3_BF(G, false); } while (0)
@@ -892,14 +908,18 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
if (!std::strcmp(act, "silu")) silu = 1;
else if (std::strcmp(act, "none")) return R4D_NO(RAD_E_INVAL);
}
/* A thread one chunk inside one group — 8 channels, or 4 when a group is exactly that wide
* (the video encoder's first level: 128 channels in 32 groups) — a row's chunks a power of
* two dividing the 256-thread block. */
const long long cg = (n > 0 && groups > 0 && !(n % groups)) ? n / groups : 0;
const int cs = (cg % 8 == 0) ? 8 : (cg == 4 ? 4 : 0);
const int cpr_log = (cs && n > 0 && !(n & 7)) ? log2_exact(n / cs) : -1;
if (cs == 0 || cpr_log < 0 || n / cs > kT || groups > kT)
/* A chunk is CW channels inside one group: 8, 4 or 2, the widest dividing the group (the
* FLUX.2 VAE's 128 channels in 32 groups take 4, SDXL's 320 in 32 take 2). A row's chunks are
* split over at most 256 threads, each taking `cpt` consecutive chunks of one group, `cpt`
* the smallest divisor of the group's chunks that fits the row in the block. */
if (groups <= 0 || groups > kT || n <= 0 || n % groups || (n / groups) % 2)
return R4D_NO(RAD_E_SHAPE);
const long long cg = n / groups;
const int CW = cg % 8 == 0 ? 8 : cg % 4 == 0 ? 4 : 2;
const int cpr = (int)(n / CW), gs8 = (int)(cg / CW);
int cpt = 1;
while (cpr / cpt > kT || gs8 % cpt) ++cpt;
const int tpr = cpr / cpt, tpg = gs8 / cpt;
if (r4d_numel(w) < n || r4d_numel(b) < n || (mod && r4d_numel(mod) < 2 * n) ||
r4d_numel(st) < groups * (2 + 3 * kGnParts))
return R4D_NO(RAD_E_SHAPE);
@@ -908,48 +928,45 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
return R4D_NO(RAD_E_STRIDE);
long long rx = 0, ldx = 0, ry = 0, ldy = 0;
if (!rows8(x, n, &rx, &ldx) || !rows8(y, n, &ry, &ldy)) return R4D_NO(RAD_E_STRIDE);
/* Over y's rows, as libref's (x may hold more); M is not read. Counts are f32 sums: exact
* while a group's M n / groups values stay under 2^24. */
/* Over y's rows, as libref's (x may hold more); M is not read. A part's count is exact in f32
* (rpp cg <= 2^24); the merged counts only weigh the merges, and the variance divides by the
* group's exact count. */
const long long M = ry;
if (M <= 0 || M > rx || M > ry || M * (n / groups) >= (1ll << 24)) return R4D_NO(RAD_E_SHAPE);
const int slots = kT >> cpr_log;
if (M <= 0 || M > rx || M > ry || M * cg >= (1ll << 31)) return R4D_NO(RAD_E_SHAPE);
const int slots = kT / tpr;
/* Whole passes of the block a part, as few parts as fill the scratch. */
long long rpp = (M + kGnParts - 1) / kGnParts;
rpp = (rpp + slots - 1) / slots * slots;
const int parts = (int)((M + rpp - 1) / rpp);
const int gs = (int)(cg / cs);
float* S = (float*)r4d_wp(st);
const float eps = (float)r4d_getf(a, "eps", 1e-5);
int rc;
if (is_f32(x))
rc = cs == 8 ? R4D_EMIT(stream, (gn_part_kernel<float, 8>), dim3((unsigned)parts),
dim3(kT), 0, (const float*)r4d_p(x), S, (int)M, (int)groups,
cpr_log, gs, (int)ldx, (int)rpp)
: R4D_EMIT(stream, (gn_part_kernel<float, 4>), dim3((unsigned)parts),
dim3(kT), 0, (const float*)r4d_p(x), S, (int)M, (int)groups,
cpr_log, gs, (int)ldx, (int)rpp);
else
rc = cs == 8 ? R4D_EMIT(stream, (gn_part_kernel<uint16_t, 8>), dim3((unsigned)parts),
dim3(kT), 0, (const uint16_t*)r4d_p(x), S, (int)M, (int)groups,
cpr_log, gs, (int)ldx, (int)rpp)
: R4D_EMIT(stream, (gn_part_kernel<uint16_t, 4>), dim3((unsigned)parts),
dim3(kT), 0, (const uint16_t*)r4d_p(x), S, (int)M, (int)groups,
cpr_log, gs, (int)ldx, (int)rpp);
#define GN_P(TX, C4) \
rc = R4D_EMIT(stream, (gn_part_kernel<TX, C4>), dim3((unsigned)parts), dim3(kT), 0, \
(const TX*)r4d_p(x), S, (int)M, (int)groups, tpr, cpt, tpg, (int)ldx, (int)rpp)
if (is_f32(x)) {
if (CW == 8) GN_P(float, 8);
else if (CW == 4) GN_P(float, 4);
else GN_P(float, 2);
} else {
if (CW == 8) GN_P(uint16_t, 8);
else if (CW == 4) GN_P(uint16_t, 4);
else GN_P(uint16_t, 2);
}
#undef GN_P
if (rc != RAD_OK) return R4D_NO(rc);
rc = R4D_EMIT(stream, gn_final_kernel, dim3((unsigned)groups), dim3(kT), 0, S, (int)groups,
parts, eps);
parts, (float)(M * cg), eps);
if (rc != RAD_OK) return R4D_NO(rc);
const int modk = !mod ? 0 : is_f32(mod) ? 2 : 1;
const dim3 grid((unsigned)((M + slots - 1) / slots));
const dim3 grid((unsigned)((M * cpr + kT - 1) / kT));
#define GN_A2(TX, TY, C4) \
return R4D_EMIT(stream, (gn_apply_kernel<TX, TY, C4>), grid, dim3(kT), 0, (const TX*)r4d_p(x),\
(TY*)r4d_wp(y), r4d_p(w), r4d_p(b), r4d_p(mod), (const float*)S, (int)M, \
(int)n, cpr, gs8, (int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), \
modk, silu)
#define GN_A(TX, TY) \
return cs == 8 ? R4D_EMIT(stream, (gn_apply_kernel<TX, TY, 8>), grid, dim3(kT), 0, \
(const TX*)r4d_p(x), (TY*)r4d_wp(y), r4d_p(w), r4d_p(b), \
r4d_p(mod), (const float*)S, (int)M, (int)n, cpr_log, gs, \
(int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), modk, silu) \
: R4D_EMIT(stream, (gn_apply_kernel<TX, TY, 4>), grid, dim3(kT), 0, \
(const TX*)r4d_p(x), (TY*)r4d_wp(y), r4d_p(w), r4d_p(b), \
r4d_p(mod), (const float*)S, (int)M, (int)n, cpr_log, gs, \
(int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), modk, silu)
do { if (CW == 8) GN_A2(TX, TY, 8); if (CW == 4) GN_A2(TX, TY, 4); GN_A2(TX, TY, 2); } while (0)
if (is_f32(x)) {
if (is_f32(y)) GN_A(float, float);
GN_A(float, uint16_t);
@@ -957,6 +974,7 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
if (is_f32(y)) GN_A(uint16_t, float);
GN_A(uint16_t, uint16_t);
#undef GN_A
#undef GN_A2
}
/* ------------------------------------------------------------------ tconv_dw */
+46 -11
View File
@@ -84,7 +84,8 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel(
const uint16_t* __restrict__ yd, const uint16_t* __restrict__ g, const uint16_t* __restrict__ s,
const uint16_t* __restrict__ w, const int* __restrict__ cu, uint16_t* __restrict__ x,
uint8_t* __restrict__ q, float* __restrict__ qs, uint16_t* __restrict__ z, int n, int n_seq,
float eps, int y_ld, int g_ld, int s_ld, int x_ld, int q_ld, int qs_ld, int z_ld) {
float eps, int y_ld, int g_ld, int s_ld, int x_ld, int q_ld, int qs_ld, int z_ld, float wadd,
int once, int layer, int none) {
__shared__ float sh[kT / 32];
const int r = blockIdx.x;
const int e = seq_of(cu, n_seq, r);
@@ -111,7 +112,32 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel(
for (int j = 0; j < 8; ++j) { v[k][j] = f[j]; ss += f[j] * f[j]; }
}
}
const float rs = 1.0f / sqrtf(block_sum(ss, sh) / (float)n + eps);
/* A LayerNorm centres first: the mean's block sum, then the centred squares'. */
float mu = 0.0f;
if (layer) {
float sm = 0.0f;
#pragma unroll
for (int k = 0; k < kRmChunks; ++k) {
const int i = ((int)threadIdx.x + k * kT) * 8;
if (i < n) {
#pragma unroll
for (int j = 0; j < 8; ++j) sm += v[k][j];
}
}
mu = block_sum(sm, sh) / (float)n;
__syncthreads();
ss = 0.0f;
#pragma unroll
for (int k = 0; k < kRmChunks; ++k) {
const int i = ((int)threadIdx.x + k * kT) * 8;
if (i < n) {
#pragma unroll
for (int j = 0; j < 8; ++j) { v[k][j] -= mu; ss += v[k][j] * v[k][j]; }
}
}
}
/* `none`: no norm (libref's n2 = x); the flag is the same for the whole workgroup. */
const float rs = none ? 1.0f : 1.0f / sqrtf(block_sum(ss, sh) / (float)n + eps);
const uint16_t* sr = s + (size_t)e * s_ld;
#pragma unroll
for (int k = 0; k < kRmChunks; ++k) {
@@ -120,10 +146,11 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel(
float shf[8], scf[8], wf[8], o[8];
ld8(sr + i, shf);
ld8(sr + n + i, scf);
ld8(w + i, wf);
if (w) ld8(w + i, wf);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const float n2 = bfr(bfr(v[k][j] * rs) * wf[j]);
const float n1 = once ? v[k][j] * rs : bfr(v[k][j] * rs);
const float n2 = w ? bfr(n1 * (wf[j] + wadd)) : bfr(v[k][j] * rs);
o[j] = bfr(bfr(n2 * bfr(1.0f + scf[j])) + shf[j]);
}
if (z) st8(z + (size_t)r * z_ld + i, o);
@@ -462,10 +489,10 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, int qmode) {
const RadTensor* q = qmode ? r4d_opt(a, 6) : nullptr;
const RadTensor* qs = qmode ? r4d_opt(a, 7) : nullptr;
const RadTensor* z = r4d_opt(a, qmode ? 8 : 6);
if (!sc || !w || !cu || !x || (qmode ? (!q || !qs) : !z)) return R4D_NO(RAD_E_INVAL);
if (!sc || !cu || !x || (qmode ? (!q || !qs) : !z)) return R4D_NO(RAD_E_INVAL);
const bool gated = r4d_geti_or(a, "gated", 0) != 0;
if (gated && (!y || !g)) return R4D_NO(RAD_E_INVAL);
if (!is_bf16(x) || !is_bf16(sc) || !is_bf16(w) || !is_i32(cu) ||
if (!is_bf16(x) || !is_bf16(sc) || (w && !is_bf16(w)) || !is_i32(cu) ||
(gated && (!is_bf16(y) || !is_bf16(g))) || (z && !is_bf16(z)) ||
(qmode && (q->dtype != (qmode == 2 ? RAD_I8 : RAD_F8E4M3) || qs->dtype != RAD_F32)))
return R4D_NO(RAD_E_DTYPE);
@@ -476,7 +503,7 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, int qmode) {
long long rx = 0, xl = 0, ry = 0, yl = 0, rg = 0, gl = 0, rs = 0, sl = 0, rz = 0, zl = 0;
long long rq = 0, rqs = 0, ql = 0, qsl = 0;
if (!rows8(x, n, &rx, &xl) || !rows8(sc, 2 * n, &rs, &sl) || !r4d_contig(cu) ||
!r4d_contig(w) || ((uintptr_t)w->data & 15) ||
(w && (!r4d_contig(w) || ((uintptr_t)w->data & 15))) ||
(gated && (!rows8(y, n, &ry, &yl) || !rows8(g, n, &rg, &gl))) ||
(z && !rows8(z, n, &rz, &zl)))
return R4D_NO(RAD_E_STRIDE);
@@ -486,18 +513,26 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, int qmode) {
if (ql < 0 || (ql & 7) || ((uintptr_t)q->data & 7) || qsl < 0) return R4D_NO(RAD_E_STRIDE);
}
const long long n_seq = r4d_numel(cu) - 1, rows = qmode ? rq : rz;
if (rows <= 0 || n_seq <= 0 || rx < rows || rs < n_seq || r4d_numel(w) < n ||
if (rows <= 0 || n_seq <= 0 || rx < rows || rs < n_seq || (w && r4d_numel(w) < n) ||
(qmode && rqs < rows) || (gated && (ry < rows || rg < n_seq)) || (z && rz < rows))
return R4D_NO(RAD_E_SHAPE);
const float eps = (float)r4d_getf(a, "eps", 1e-6);
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
const int once = (int)r4d_geti_or(a, "norm_once", 0);
const char* nk = r4d_gets(a, "norm");
const int layer = nk && !std::strcmp(nk, "layer");
const int none = nk && !std::strcmp(nk, "none");
if ((nk && !layer && !none && std::strcmp(nk, "rms")) || (none && w)) return R4D_NO(RAD_E_INVAL);
#define R4D_RMQ(G, Q) \
hipLaunchKernelGGL((rms_mod_kernel<G, Q>), dim3((unsigned)rows), dim3(kT), 0, \
(hipStream_t)st, G ? (const uint16_t*)y->data : nullptr, \
G ? (const uint16_t*)g->data : nullptr, (const uint16_t*)sc->data, \
(const uint16_t*)w->data, (const int*)cu->data, (uint16_t*)x->data, \
(Q) ? (uint8_t*)q->data : nullptr, (Q) ? (float*)qs->data : nullptr, \
w ? (const uint16_t*)w->data : nullptr, (const int*)cu->data, \
(uint16_t*)x->data, \
Q ? (uint8_t*)q->data : nullptr, Q ? (float*)qs->data : nullptr, \
z ? (uint16_t*)z->data : nullptr, (int)n, (int)n_seq, eps, (int)yl, \
(int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl)
(int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl, wadd, once, layer, \
none)
if (qmode == 2) {
if (gated) R4D_RMQ(true, 2);
else R4D_RMQ(false, 2);