diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 9529d9b3..b418bfe8 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -322,7 +322,7 @@ void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_fla void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long stream, long nblocks, long nthreads, - long drain, long acq, long gate, long gate_ctr, long stage = 0); + long drain, long acq, long gate, long gate_ctr, long stage = 0, long chain = 0); // The same with the MoE gather as its prologue: y is produced, not read, from the routed experts' // rows `ye` [M*top_k][ye_ld] summed to token order by weights `ew` [M][ew_ld] and `sorted` // [M*top_k], with the shared arm `sh` [M][sh_ld] and its gate `sg` folded when both are non-zero. @@ -335,7 +335,7 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, long stream, long nblocks, long nthreads, long drain, long acq, long inv, long gate, long gate_ctr, - long stage = 0); + long stage = 0, long chain = 0); // r4d_ar_hc_write and r4d_ar_gather_hc_write on the rotated 6-bit wire (r4d_ar_oneshot_2rank_wht6's // format, loc_pack and scratch split): byte-identical to all_reduce on that wire then hc_write, // with `ye` non-zero preceded by moe_gather. Gather operands as r4d_ar_gather_hc_write; its slot diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 65371cc9..d90394d0 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -18,6 +18,7 @@ * with a 60-second timeout and a named error. */ +#include "r4d_chain.h" #include "r4d_args.h" #include "r4d.h" #include "r4d_ar_shards.h" @@ -1715,7 +1716,8 @@ extern "C" int r4d_rad_ar_gather_hc_write(const RadArgs* a, RadStream s) { sh ? r4d_addr(sh) : 0L, sh ? r4d_addr(sg) : 0L, (long)ye_ld, (long)ew_ld, (long)sh_ld, (long)sg_ld, (long)top_k, (long)sig, (long)(uintptr_t)s, nblocks, cfgv.nthreads, cfgv.drain, cfgv.acq, has_inv ? (long)(uintptr_t)a->scratch : 0L, early, - early ? in->gate_ctr : 0L, in->my_stage); + early ? in->gate_ctr : 0L, in->my_stage, + r4d_geti_or(a, "chain", 0) != 0 && r4d_chain_rows_ok(M) ? 1L : 0L); if (rc != 0) return RAD_E_SHAPE; return early ? RAD_LINK_ENDED : RAD_OK; } @@ -1844,7 +1846,8 @@ extern "C" int r4d_rad_ar_hc_write(const RadArgs* a, RadStream s) { in->my_seq, in->slot16, r4d_addr(y), r4d_addr(inj), r4d_addr(h), (long)M, (long)n, (long)hc, (long)irow, (long)hrow, (long)(uintptr_t)s, nblocks, cfgv.nthreads, cfgv.drain, cfgv.acq, early, - early ? in->gate_ctr : 0L, in->my_stage)); + early ? in->gate_ctr : 0L, in->my_stage, + r4d_geti_or(a, "chain", 0) != 0 && r4d_chain_rows_ok(M) ? 1L : 0L)); return early ? RAD_LINK_ENDED : RAD_OK; } diff --git a/libr4d/r4d_ar_oneshot_2rank_exact.hip b/libr4d/r4d_ar_oneshot_2rank_exact.hip index 8a3da1b6..1181d130 100644 --- a/libr4d/r4d_ar_oneshot_2rank_exact.hip +++ b/libr4d/r4d_ar_oneshot_2rank_exact.hip @@ -18,6 +18,7 @@ // * Fine-grained memory (hipDeviceMallocFinegrained) is uncached and posted straight to the // fabric, so system-scope release/acquire skip the L2 writeback. The drain/acq fences are // selectable (default drain=1/acq=0 on fine-grained). +#include "r4d_chain.h" #include "r4d.h" #include "r4d_ar_seq.h" #include "r4d_ar_hc.h" // the gather word and the hc write word, shared with the rotated wire @@ -147,7 +148,7 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( // // n is a multiple of eight, so a word never straddles a row and the block that reduces it owns // every stream element behind it. -__global__ void r4d_ar_hc_write_kernel( +__device__ __forceinline__ void r4d_ar_hc_write_kernel_body( int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow, @@ -209,6 +210,26 @@ __global__ void r4d_ar_hc_write_kernel( } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +__global__ void r4d_ar_hc_write_kernel( + int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags, + unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj, + unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow, + int slot_stride16, int drain, int acq, unsigned int nbw, long long* gate, + unsigned int* gate_ctr, long stage) { + r4d_ar_hc_write_kernel_body(y4, peer_base, my_base, peer_flags, my_flags, seq_ctrs, inj, h, n16, n, hc, irow, hrow, slot_stride16, drain, acq, nbw, gate, gate_ctr, stage); +} +__global__ void r4dchain_ar_hc_write( + int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags, + unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj, + unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow, + int slot_stride16, int drain, int acq, unsigned int nbw, long long* gate, + unsigned int* gate_ctr, long stage) { + r4d_chain_wait(); + r4d_ar_hc_write_kernel_body(y4, peer_base, my_base, peer_flags, my_flags, seq_ctrs, inj, h, n16, n, hc, irow, hrow, slot_stride16, drain, acq, nbw, gate, gate_ctr, stage); + r4d_chain_done(); +} + // The same write with the MoE gather as its prologue. The routed experts' rows go back to token // order, y[t][i] = sum over t's slots, ascending, of w[t][j] * y_expert[slot][i] rounded to bf16, // with the shared arm folded in as moe_gather does; the word is pushed to the peer and kept as this @@ -238,7 +259,7 @@ __global__ void r4d_ar_gather_inv_kernel(int* __restrict__ inv, const int* __res } template -__global__ void r4d_ar_gather_hc_write_kernel( +__device__ __forceinline__ void r4d_ar_gather_hc_write_kernel_body( int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow, @@ -326,6 +347,28 @@ __global__ void r4d_ar_gather_hc_write_kernel( } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +template +__global__ void r4d_ar_gather_hc_write_kernel( + int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags, + unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj, + unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow, + int slot_stride16, int drain, int acq, unsigned int nbw, R4dArGather G, + const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr, long stage) { + r4d_ar_gather_hc_write_kernel_body(y4, peer_base, my_base, peer_flags, my_flags, seq_ctrs, inj, h, n16, n, hc, irow, hrow, slot_stride16, drain, acq, nbw, G, inv, gate, gate_ctr, stage); +} +template +__global__ void r4dchain_ar_gather_hc_write( + int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags, + unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj, + unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow, + int slot_stride16, int drain, int acq, unsigned int nbw, R4dArGather G, + const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr, long stage) { + r4d_chain_wait(); + r4d_ar_gather_hc_write_kernel_body(y4, peer_base, my_base, peer_flags, my_flags, seq_ctrs, inj, h, n16, n, hc, irow, hrow, slot_stride16, drain, acq, nbw, G, inv, gate, gate_ctr, stage); + r4d_chain_done(); +} + // The IPC handle goes into a caller-owned buffer of R4D_AR_HANDLE_BYTES so this stays a C ABI. static_assert(sizeof(hipIpcMemHandle_t) <= R4D_AR_HANDLE_BYTES, "ipc handle larger than the ABI buffer"); @@ -420,7 +463,7 @@ int r4d_p2p_copy2d(long dst, long src, long dpitch, long spitch, long width, lon void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long stream_i, long nblocks, long nthreads, - long drain, long acq, long gate, long gate_ctr, long stage) { + long drain, long acq, long gate, long gate_ctr, long stage, long chain) { hipStream_t st = (hipStream_t)stream_i; if (n <= 0 || M <= 0 || n % 8) throw std::runtime_error("ar_hc_write: n must be a positive multiple of 8"); if (hc < 1 || hrow % 8) throw std::runtime_error("ar_hc_write: the streams must be whole 16B words"); @@ -436,7 +479,7 @@ void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long m if (nt < 64) nt = 64; if (nt > 1024) nt = 1024; nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes - r4d_ar_hc_write_kernel<<>>( + (chain ? r4dchain_ar_hc_write : r4d_ar_hc_write_kernel)<<>>( (int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, @@ -448,7 +491,8 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long n, long hc, long irow, long hrow, long ye, long ew, long sorted, long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, long stream_i, long nblocks, long nthreads, - long drain, long acq, long inv, long gate, long gate_ctr, long stage) { + long drain, long acq, long inv, long gate, long gate_ctr, long stage, + long chain) { hipStream_t st = (hipStream_t)stream_i; if (n <= 0 || M <= 0 || n % 8 || hc < 1 || hrow % 8) return -1; if (top_k < 1 || top_k > R4D_ARG_SLOTS) return -2; @@ -488,13 +532,13 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, G.top_k = (int)top_k; G.T = (int)(M * top_k); G.sig = (int)sig; if (by_inv) { r4d_ar_gather_inv_kernel<<<1, 1024, 0, st>>>((int*)inv, (const int*)sorted, G.T); - r4d_ar_gather_hc_write_kernel<<>>( + (chain ? r4dchain_ar_gather_hc_write : r4d_ar_gather_hc_write_kernel)<<>>( (int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G, (const int*)inv, (long long*)gate, (unsigned int*)gate_ctr, stage); } else { - r4d_ar_gather_hc_write_kernel<<>>( + (chain ? r4dchain_ar_gather_hc_write : r4d_ar_gather_hc_write_kernel)<<>>( (int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G, diff --git a/libr4d/r4d_chain.h b/libr4d/r4d_chain.h index bf975352..074479c2 100644 --- a/libr4d/r4d_chain.h +++ b/libr4d/r4d_chain.h @@ -83,3 +83,18 @@ __device__ __forceinline__ void r4d_chain_done() { __hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT); } #endif /* __HIP__ */ + +/* The launchers given a chained form here take it only at steps of up to 32 token rows: above that + * the waiting blocks hold room a wide predecessor needs. Flash-Next on 2x R9700 at MTP depth 5 with + * the adaptive window, sampled: 32 against 64 rows 214/349/494/654/890 -> 218/355/494/662/893 tok/s + * at 1/2/4/8/16 streams. */ +constexpr long long kR4dChainMaxRows = 32; +inline bool r4d_chain_rows_ok(long long rows) { return rows <= kR4dChainMaxRows; } + +/* A launcher that takes no RadArgs reads its row's `chain` here; the plugin + * ABI entry sets it around the launch only, so a direct C call never chains. */ +inline thread_local bool g_r4d_chain_arg = false; +struct R4dChainArg { + explicit R4dChainArg(bool on) { g_r4d_chain_arg = on; } + ~R4dChainArg() { g_r4d_chain_arg = false; } +}; diff --git a/libr4d/r4d_fused_quant_fp8.hip b/libr4d/r4d_fused_quant_fp8.hip index f6d44f67..be11f9a5 100644 --- a/libr4d/r4d_fused_quant_fp8.hip +++ b/libr4d/r4d_fused_quant_fp8.hip @@ -36,6 +36,7 @@ #include "r4d_ar_seq.h" // the all-reduce sequence step the fused all-reduce + norm takes #include "r4d_fp8_args.h" #include "r4d_emit.h" +#include "r4d_chain.h" #include "r4d_common.h" // r4d_act_threads: the workgroup width, shared with the int8 path #include "r4d_fwht.h" // the in-register rotation the `_had_` forms put before the absmax #include "r4d_q8.h" // the 8-bit codes: E4M3, or int8 for an int8 trunk linear @@ -215,7 +216,7 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel( // The launcher sizes the workgroup to the row's groups (capped at r4d_act_threads' width) and the // kernel reads the width from blockDim, so a narrow row does not leave most waves idle. template -__global__ __launch_bounds__(1024) void gated_quant_fp8_kernel( +__device__ __forceinline__ void gated_quant_fp8_kernel_body( const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t gu_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld) { @@ -251,6 +252,24 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel( } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +template +__global__ __launch_bounds__(1024) void gated_quant_fp8_kernel( + const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q, + float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t gu_ld, uint32_t y_ld, + uint32_t q_ld, uint32_t s_ld) { + gated_quant_fp8_kernel_body(gu, y, q, s, n, nkb, gu_ld, y_ld, q_ld, s_ld); +} +template +__global__ __launch_bounds__(1024) void r4dchain_gated_quant_fp8( + const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q, + float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t gu_ld, uint32_t y_ld, + uint32_t q_ld, uint32_t s_ld) { + r4d_chain_wait(); + gated_quant_fp8_kernel_body(gu, y, q, s, n, nkb, gu_ld, y_ld, q_ld, s_ld); + r4d_chain_done(); +} + // -------------------------------------------------- gate . x -> quant, two source buffers // // The same epilogue with the gate in a separate buffer. For gated attention, `x` is the attention @@ -267,7 +286,7 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel( // and the absmax, as gated_quant_fp8_kernel's ROT, for an out projection stored rotated: the codes // are had_quant_act_i8g's over `y`. template -__global__ __launch_bounds__(1024) void gate_quant_fp8_kernel( +__device__ __forceinline__ void gate_quant_fp8_kernel_body( const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t g_ld, uint32_t x_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld) { @@ -313,6 +332,24 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel( } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +template +__global__ __launch_bounds__(1024) void gate_quant_fp8_kernel( + const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y, + uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t g_ld, + uint32_t x_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld) { + gate_quant_fp8_kernel_body(g, x, y, q, s, n, nkb, g_ld, x_ld, y_ld, q_ld, s_ld); +} +template +__global__ __launch_bounds__(1024) void r4dchain_gate_quant_fp8( + const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y, + uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t g_ld, + uint32_t x_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld) { + r4d_chain_wait(); + gate_quant_fp8_kernel_body(g, x, y, q, s, n, nkb, g_ld, x_ld, y_ld, q_ld, s_ld); + r4d_chain_done(); +} + // -------------------------------------------------------- all-reduce -> rmsnorm -> quant // // The same norm with the tensor-parallel all-reduce that always precedes it folded in (o_proj, @@ -808,7 +845,7 @@ extern "C" int r4d_rmsnorm_had_quant_i8g(long x, long res, long w, long y, long // 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) { + bool rot, bool i8 = false, bool chain = false) { int emit_rc = RAD_OK; if (!gu || !q || !s) return -1; if (M <= 0 || n <= 0) return -2; @@ -824,7 +861,8 @@ static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n, // there is no cross-row reduction and the rotation is wave-local (r4d_fwht.h). const int thr = std::min(nkb, r4d_act_threads(M, n) / (int)kWave) * (int)kWave; #define R4D_GQ_R(a, R, I) \ - emit_rc = R4D_EMIT(stream, (gated_quant_fp8_kernel), dim3((uint32_t)M), dim3(thr), \ + emit_rc = R4D_EMIT(stream, (chain ? &r4dchain_gated_quant_fp8 \ + : &gated_quant_fp8_kernel), dim3((uint32_t)M), dim3(thr), \ 0, (const uint16_t*)gu, (uint16_t*)y, (uint8_t*)q, \ (float*)s, (uint32_t)n, (uint32_t)nkb, (uint32_t)gu_ld, (uint32_t)y_ld, \ (uint32_t)q_ld, (uint32_t)s_ld) @@ -888,11 +926,15 @@ static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, in // A wave a group, capped at r4d_act_threads' width, as gated_quant_fp8 above. const int thr = std::min(nkb, r4d_act_threads(M, n) / (int)kWave) * (int)kWave; #define R4D_GTQ_I(a, I) \ - emit_rc = rot ? R4D_EMIT(stream, (gate_quant_fp8_kernel), dim3((uint32_t)M), \ - dim3(thr), 0, (const uint16_t*)g, (const uint16_t*)x, (uint16_t*)y, \ - (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)nkb, (uint32_t)g_ld, \ - (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)q_ld, (uint32_t)s_ld) \ - : R4D_EMIT(stream, (gate_quant_fp8_kernel), dim3((uint32_t)M), dim3(thr), 0, \ + emit_rc = rot ? R4D_EMIT(stream, (g_r4d_chain_arg ? &r4dchain_gate_quant_fp8 \ + : &gate_quant_fp8_kernel), \ + dim3((uint32_t)M), dim3(thr), 0, (const uint16_t*)g, \ + (const uint16_t*)x, (uint16_t*)y, (uint8_t*)q, (float*)s, \ + (uint32_t)n, (uint32_t)nkb, (uint32_t)g_ld, (uint32_t)x_ld, \ + (uint32_t)y_ld, (uint32_t)q_ld, (uint32_t)s_ld) \ + : R4D_EMIT(stream, (g_r4d_chain_arg ? &r4dchain_gate_quant_fp8 \ + : &gate_quant_fp8_kernel), dim3((uint32_t)M), \ + dim3(thr), 0, \ (const uint16_t*)g, (const uint16_t*)x, \ (uint16_t*)y, (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)nkb, \ (uint32_t)g_ld, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)q_ld, \ @@ -1124,7 +1166,9 @@ static int rad_gated_quant_fp8(const RadArgs* a, RadStream stream, bool rot, boo if (mode < 0) return R4D_NO(RAD_E_UNSUPPORTED); const int e = gated_quant_fp8_launch(r4d_addr(gu), y ? r4d_addr(y) : 0, r4d_addr(q), r4d_addr(sc), (int)M, (int)K, mode, (int)gp, (int)yp, - (int)qp, (int)sp, stream, rot, q->dtype == RAD_I8); + (int)qp, (int)sp, stream, rot, q->dtype == RAD_I8, + /* decode heights: its rows are tokens or routed slots */ + r4d_geti_or(a, "chain", 0) != 0 && M <= 1024); return e == 0 ? RAD_OK : RAD_E_SHAPE; } @@ -1190,6 +1234,7 @@ static int rad_gate_quant(const RadArgs* a, RadStream stream, bool rot) { if (gp < 0 || xp < 0 || qp < 0 || sp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE); const int mode = act_mode(a, 1); /* sigmoid: gated attention */ if (mode < 0) return R4D_NO(RAD_E_UNSUPPORTED); + const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0 && M <= 1024); const int e = gate_quant_fp8_emit(r4d_addr(g), r4d_addr(x), y ? r4d_addr(y) : 0, r4d_addr(q), r4d_addr(sc), (int)M, (int)K, mode, (int)gp, (int)xp, (int)yp, (int)qp, (int)sp, stream, diff --git a/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip b/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip index 5e1e0d9b..44e5e141 100644 --- a/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip +++ b/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip @@ -32,6 +32,7 @@ #include "r4d_gdn_wmma.h" #include "r4d_common.h" #include "r4d_gdn_conv_tap.h" +#include "r4d_chain.h" #include "r4d_q8.h" // the 8-bit codes the folded quantiser writes: E4M3 or int8 #include "r4d_fwht.h" // NORM 3: had_quant_act_i8g's rotation before the int8 codes #include @@ -218,8 +219,7 @@ __device__ __forceinline__ void ru_conv_rewrite(unsigned short* sp, const unsign template -__global__ __launch_bounds__(RU_V / VS * 2) -void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, +__device__ __forceinline__ void r4d_gdn_recurrent_update_kernel_body(const unsigned short* __restrict__ q, const unsigned short* __restrict__ k, const unsigned short* __restrict__ v, const void* __restrict__ av, @@ -239,8 +239,7 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, long zg_pitch, const float* __restrict__ nw, float neps, int nact, int H, int Hg, float scale, float sp_thr, - const RuConv cv) -{ + const RuConv cv) { using ST = typename ru_state::T; constexpr int NR = RU_V / VS; // v rows this workgroup owns constexpr int THR = NR * 2; @@ -732,6 +731,62 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +template +__global__ __launch_bounds__(RU_V / VS * 2) +void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, + const unsigned short* __restrict__ k, + const unsigned short* __restrict__ v, + const void* __restrict__ av, + const void* __restrict__ bv, long ab_stride, + const float* __restrict__ A_log, + const float* __restrict__ dt_bias, + typename ru_state::T* __restrict__ state, + long st_slot, long st_head, + unsigned short* __restrict__ o, + unsigned char* __restrict__ oq, + float* __restrict__ os, long oq_pitch, + long os_ld, + const int* __restrict__ cu, + const int* __restrict__ sidx, long sidx_stride, + const int* __restrict__ naccept, + const unsigned short* __restrict__ zg, + long zg_pitch, + const float* __restrict__ nw, float neps, int nact, + int H, int Hg, float scale, float sp_thr, + const RuConv cv) { + r4d_gdn_recurrent_update_kernel_body(q, k, v, av, bv, ab_stride, A_log, dt_bias, state, st_slot, st_head, o, oq, os, oq_pitch, os_ld, cu, sidx, sidx_stride, naccept, zg, zg_pitch, nw, neps, nact, H, Hg, scale, sp_thr, cv); +} +template +__global__ __launch_bounds__(RU_V / VS * 2) +void r4dchain_gdn_recurrent_update(const unsigned short* __restrict__ q, + const unsigned short* __restrict__ k, + const unsigned short* __restrict__ v, + const void* __restrict__ av, + const void* __restrict__ bv, long ab_stride, + const float* __restrict__ A_log, + const float* __restrict__ dt_bias, + typename ru_state::T* __restrict__ state, + long st_slot, long st_head, + unsigned short* __restrict__ o, + unsigned char* __restrict__ oq, + float* __restrict__ os, long oq_pitch, + long os_ld, + const int* __restrict__ cu, + const int* __restrict__ sidx, long sidx_stride, + const int* __restrict__ naccept, + const unsigned short* __restrict__ zg, + long zg_pitch, + const float* __restrict__ nw, float neps, int nact, + int H, int Hg, float scale, float sp_thr, + const RuConv cv) { + r4d_chain_wait(); + r4d_gdn_recurrent_update_kernel_body(q, k, v, av, bv, ab_stride, A_log, dt_bias, state, st_slot, st_head, o, oq, os, oq_pitch, os_ld, cu, sidx, sidx_stride, naccept, zg, zg_pitch, nw, neps, nact, H, Hg, scale, sp_thr, cv); + r4d_chain_done(); +} + // Non-temporal hint on the state load and store (TH_LOAD_NT / TH_STORE_NT): no result changes; // chosen per launch because its cost and saving land in different kernels. In isolation it makes // this kernel 43.8% slower (DRAM-write bound), but no state survives the 64 MB last-level cache @@ -763,6 +818,14 @@ static bool ru_anchor() { #define RU_NT_MB 16 // `oq_i8` picks the folded quantiser's codes: E4M3 (0) or int8 (1); see the kernel's epilogue. +/* The chained form (r4d_chain.h) for this thread's launch: set by the plugin ABI entries below from + * the row's `chain`, around their launch only, so the C entry point never chains. */ +static thread_local bool g_ru_chain = false; +struct RuChainScope { + explicit RuChainScope(bool on) { g_ru_chain = on; } + ~RuChainScope() { g_ru_chain = false; } +}; + static int ru_update_launch( const void* q, const void* k, const void* v, const void* a, const void* b, long ab_stride, int ab_is_bf16, const void* A_log, const void* dt_bias, void* state, @@ -788,7 +851,8 @@ static int ru_update_launch( dim3 grid(N, H, vs), blk(RU_V / vs * 2); // Every switch is a template parameter; the nested pick macros enumerate the instantiations. #define RU_LAUNCH(AB, NM, VSC, NTC, ANCC, STGC, SDTC) \ - hipLaunchKernelGGL((r4d_gdn_recurrent_update_kernel), \ + hipLaunchKernelGGL((g_ru_chain ? &r4dchain_gdn_recurrent_update \ + : &r4d_gdn_recurrent_update_kernel), \ grid, blk, 0, (hipStream_t)stream, \ (const unsigned short*)q, (const unsigned short*)k, \ (const unsigned short*)v, a, b, ab_stride, \ @@ -928,7 +992,8 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void* else if (oq_i8) RC_LAUNCH_NM(2, NTC, ANCC, SDTC, CVC); \ else RC_LAUNCH_NM(1, NTC, ANCC, SDTC, CVC); } while (0) #define RC_LAUNCH_NM(NM, NTC, ANCC, SDTC, CVC) \ - hipLaunchKernelGGL((r4d_gdn_recurrent_update_kernel<1, NM, 1, NTC, ANCC, 0, SDTC, CVC>), \ + hipLaunchKernelGGL((g_ru_chain ? &r4dchain_gdn_recurrent_update<1, NM, 1, NTC, ANCC, 0, SDTC, CVC> \ + : &r4d_gdn_recurrent_update_kernel<1, NM, 1, NTC, ANCC, 0, SDTC, CVC>), \ grid, blk, 0, (hipStream_t)stream, nullptr, nullptr, nullptr, a, b, \ ab_stride, (const float*)A_log, (const float*)dt_bias, \ (ru_state::T*)state, st_slot, st_head, (unsigned short*)o, \ @@ -1051,6 +1116,7 @@ extern "C" int r4d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s) { /* Slot and head strides come from the tensor, so a cache with padded slots is served too * (see the header); the engine's own state cache is dense ([n_states, H, V, K] per layer). */ + const RuChainScope chain_scope(r4d_geti_or(a, "chain", 0) != 0); return R4D_RAW(ru_update_launch( q->data, k->data, v->data, ta->data, tb->data, (long)ab_stride, ab_is_bf16, alog->data, dtb->data, state->data, @@ -1171,6 +1237,7 @@ static int gdn_conv_recurrent_entry(const RadArgs* a, RadStream s, bool had) { cv.ctr = ru_conv_ctr(s, o->data); if (!cv.ctr) return R4D_NO(RAD_E_NOMEM); + const RuChainScope chain_scope(r4d_geti_or(a, "chain", 0) != 0); return ru_conv_recurrent_launch( cv, ta->data, tb->data, (long)ab_stride, alog->data, dtb->data, state->data, (long)state->stride[0], (long)state->stride[1], o->data, oq ? oq->data : nullptr, diff --git a/libr4d/r4d_hc_bf16.hip b/libr4d/r4d_hc_bf16.hip index d688e0c5..3fce8351 100644 --- a/libr4d/r4d_hc_bf16.hip +++ b/libr4d/r4d_hc_bf16.hip @@ -62,6 +62,7 @@ #include #include "r4d.h" #include "r4d_emit.h" +#include "r4d_chain.h" #include "r4d_gdn_args.h" #include "r4d_common.h" #include "r4d_gdn_wmma.h" @@ -305,6 +306,49 @@ __device__ __forceinline__ void hc8_dot_up(const float* __restrict__ sd, long lr } } +/* hc8_up_dot_rows over `d` already in floats: the same fmaf sequence on the same values. */ +template +__device__ __forceinline__ void hc8_up_dot_rows_f(const float* __restrict__ sdf, long lr, const Q* o, + int q4, float (*acc)[RG]) { + const long G = lr / 4, k0 = (long)q4 * G; + const int nq = (int)(G / 16); +#pragma unroll + for (int m = 0; m < RPT; ++m) +#pragma unroll + for (int r = 0; r < RG; ++r) acc[m][r] = 0.0f; +#pragma unroll + for (int i = 0; i < 8; ++i) { + if (i >= nq) break; + float wf[RPT][16]; +#pragma unroll + for (int m = 0; m < RPT; ++m) { + e4m3x8(o[m].c[i].x, o[m].c[i].y, wf[m]); + e4m3x8(o[m].c[i].z, o[m].c[i].w, wf[m] + 8); + } +#pragma unroll + for (int r = 0; r < RG; ++r) { + const float4* dr = (const float4*)(sdf + (long)r * lr + k0 + 16 * i); + const float4 d0 = dr[0], d1 = dr[1], d2 = dr[2], d3 = dr[3]; + const float dv[16] = { d0.x, d0.y, d0.z, d0.w, d1.x, d1.y, d1.z, d1.w, + d2.x, d2.y, d2.z, d2.w, d3.x, d3.y, d3.z, d3.w }; +#pragma unroll + for (int t = 0; t < 16; ++t) { +#pragma unroll + for (int m = 0; m < RPT; ++m) acc[m][r] = fmaf(wf[m][t], dv[t], acc[m][r]); + } + } + } +#pragma unroll + for (int m = 0; m < RPT; ++m) +#pragma unroll + for (int r = 0; r < RG; ++r) { + float a = acc[m][r] * o[m].sc; + a += __shfl_xor(a, 1); + a += __shfl_xor(a, 2); + acc[m][r] = a; + } +} + /* hc8_dot_up split at its loads, so a kernel can issue them before `d` exists: a * quarter's codes and its group scale, then the same arithmetic in the same order. */ struct Hc8UpQuarter { @@ -1224,7 +1268,9 @@ __device__ __forceinline__ void hc_rot_group(float* v, int lane, unsigned char* /* The fused form's wait (hc_read_fused_kernel, below): its B blocks hold here until every A * block has published `d` and the scales. */ -constexpr unsigned kHcSyncCtr = 3; /* tickets, A blocks done, B blocks past the wait */ +/* Tickets, A blocks done, B blocks past the wait; then decode form G's tile counters. */ +constexpr unsigned kHcGTilesMax = 192; /* tiles x row groups */ +constexpr unsigned kHcSyncCtr = 3 + kHcGTilesMax; __device__ __forceinline__ void hc_role_wait(unsigned int* __restrict__ sync, unsigned na, unsigned nb_all) { @@ -1268,7 +1314,7 @@ __device__ __forceinline__ void hc_role_wait(unsigned int* __restrict__ sync, un /* RPT > 1 (E4M3 only) gives the workgroup RPT * 64 rows of W_up, RPT a thread with one * quarter each (hc8_up_dot_rows), and 1 / RPT the grid (kUpRpt). WAIT is the fused form's * (hc_read_fused_kernel): `d` and kernel A's scales are read only after hc_role_wait. */ -template +template __device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, long uld, const unsigned short* __restrict__ dbuf, const unsigned short* __restrict__ h, const float* __restrict__ w, @@ -1302,7 +1348,9 @@ __device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, lon constexpr int kDStage = 2; const bool dpre = lr <= (long)kDStage * kThreads; unsigned short dv[RG][kDStage]; /* bf16 bits; the E4M3 dot keeps them as is */ - if (dpre && !WAIT) { + /* PREW (the chained form): the constant W_up quarters first, then the chain wait, + * then everything the predecessor wrote. */ + if (!PREW && dpre && !WAIT) { #pragma unroll for (int r = 0; r < RG; ++r) { const bool live = r0 + r < rows; @@ -1325,6 +1373,47 @@ __device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, lon } } const bool one = RG * ipb <= kThreads; + /* PF: the chained E4M3 form issues everything the predecessor wrote in one batch. */ + constexpr bool PF = PREW && F8; + float NpreP[kHcMax]; + uint4 dq[2]; + if constexpr (PF) { + const bool item = one && tid < RG * ipb; + const int rl = item ? tid / ipb : 0, ii = tid - rl * ipb; + const long rP = r0 + rl < rows ? r0 + rl : rows - 1; + float wvP[kHcMax]; +#pragma unroll + for (int c = 0; c < kHcMax; ++c) wvP[c] = (item && c < hc) ? w[(long)c * n + i0 + ii] : 0.0f; + r4d_chain_wait(); + const long live = rows - r0 < RG ? rows - r0 : RG; + const int nq8 = (int)(live * lr / 8); +#pragma unroll + for (int s2 = 0; s2 < 2; ++s2) { + const int i = tid + s2 * kThreads; + dq[s2] = i < nq8 ? ((const uint4*)(dbuf + r0 * lr))[i] : make_uint4(0u, 0u, 0u, 0u); + } + float hvP[kHcMax], scP[kHcMax]; +#pragma unroll + for (int c = 0; c < kHcMax; ++c) { + hvP[c] = (item && c < hc) ? bf2f(h[rP * hrow + (long)c * n + i0 + ii]) : 0.0f; + scP[c] = (item && c < hc) ? scalein[rP * kHcMax + c] : 0.0f; + } +#pragma unroll + for (int c = 0; c < kHcMax; ++c) NpreP[c] = nbf(hvP[c] * scP[c] * (wvP[c] + wadd)); + } else if constexpr (PREW) { + r4d_chain_wait(); + if (dpre) { +#pragma unroll + for (int r = 0; r < RG; ++r) { + const bool live = r0 + r < rows; +#pragma unroll + for (int s2 = 0; s2 < kDStage; ++s2) { + const long k = tid + (long)s2 * kThreads; + dv[r][s2] = (live && k < lr) ? dbuf[(r0 + r) * lr + k] : (unsigned short)0; + } + } + } + } float Npre[kHcMax]; if constexpr (WAIT) { /* The fused form (hc_read_fused_kernel): `h` and the gain here, kernel A's half after it. */ @@ -1359,6 +1448,9 @@ __device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, lon Npre[c] = nbf(hv[c] * scalein[r * kHcMax + c] * (wv[c] + wadd)); } } + } else if constexpr (PF) { +#pragma unroll + for (int c = 0; c < kHcMax; ++c) Npre[c] = NpreP[c]; } else if (one && tid < RG * ipb) { const int rl = tid / ipb, ii = tid - rl * ipb; const long r = r0 + rl < rows ? r0 + rl : rows - 1; @@ -1371,9 +1463,22 @@ __device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, lon } } - /* `d` as bf16 for the E4M3 dot (hc8_up_dot_rows), as floats for the bf16 one. */ + /* `d` as bf16 for the E4M3 dot (hc8_up_dot_rows), as floats for the bf16 one; as floats for the + * chained E4M3 form (PF). */ unsigned short* const sdh = (unsigned short*)sd; - if (dpre) { + if constexpr (PF) { +#pragma unroll + for (int s2 = 0; s2 < 2; ++s2) { + const int i = tid + s2 * kThreads; + if (i < RG * (int)lr / 8) { + float f[8]; + bf8_f(dq[s2], f); + float4* dst = (float4*)(sd + (long)i * 8); + dst[0] = make_float4(f[0], f[1], f[2], f[3]); + dst[1] = make_float4(f[4], f[5], f[6], f[7]); + } + } + } else if (dpre) { #pragma unroll for (int r = 0; r < RG; ++r) #pragma unroll @@ -1401,7 +1506,8 @@ __device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, lon * E4M3 form takes each row four threads at a time, as in hc_up_kernel. */ if constexpr (F8) { float acc[RPT][RG]; - hc8_up_dot_rows(sdh, lr, wq, q4, acc); + if constexpr (PF) hc8_up_dot_rows_f(sd, lr, wq, q4, acc); + else hc8_up_dot_rows(sdh, lr, wq, q4, acc); #pragma unroll for (int m = 0; m < RPT; ++m) #pragma unroll @@ -1466,9 +1572,14 @@ __device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, lon __HIP_MEMORY_SCOPE_AGENT); __syncthreads(); if (s_arrived + 1u != (unsigned)nb) return; - if (tid == 0) - __hip_atomic_store(&ctr[slot], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); - __threadfence(); + /* The reset goes after this block's codes (wave 0 always quantises a row), so the + * acquire waits for no store. */ + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent"); + struct ResetAtEnd { + unsigned int* c; + bool on; + __device__ ~ResetAtEnd() { if (on) __hip_atomic_store(c, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } + } reset_at_end{ &ctr[slot], tid == 0 }; /* One wave per row (RG <= wave count); a lane takes four of the group's 128 channels, one * packed dword of codes. */ @@ -1508,6 +1619,647 @@ void hc_up_mix_kernel(const void* __restrict__ upv, long uld, hc_up_mix_body(upv, uld, dbuf, h, w, scalein, x, q, qs, rq, rqs, ctr, rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd, blockIdx.x, blockIdx.y); } +/* Its chained form (r4d_chain.h): the body waits itself, after the W_up loads (PREW). */ +template +__global__ __launch_bounds__(kThreads) +void r4dchain_hc_up_mix(const void* __restrict__ upv, long uld, + const unsigned short* __restrict__ dbuf, + const unsigned short* __restrict__ h, const float* __restrict__ w, + const float* __restrict__ scalein, + unsigned short* __restrict__ x, unsigned char* __restrict__ q, + float* __restrict__ qs, unsigned char* __restrict__ rq, + float* __restrict__ rqs, unsigned int* __restrict__ ctr, + long rows, long n, int hc, long lr, long hrow, long xrow, + long qrow, long srow, long rqrow, long rsrow, float wadd) { + hc_up_mix_body(upv, uld, dbuf, h, w, scalein, x, q, qs, rq, rqs, ctr, rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd, blockIdx.x, blockIdx.y); + r4d_chain_done(); +} + +/* ============================================================== hc_read, decode form G (A') + * + * Kernel A for one to eight decode rows at Flash-Next's shape as + * (16-column tile, sub-stream c) blocks plus one inject tile: the grouped norm of stream c needs + * only h[r, c, :], so a block holds every row of the step and reads its W_down slice once. The + * slice and the norm gain are constant and load before the chain wait; everything after it is one + * round trip for h, the norm (hc_read_a_body's arithmetic: same scales, same N), bf16 WMMA dots + * and a deterministic finisher: the last of a tile's hc blocks sums their partials in ascending c. + * + * WMMA operand order (r4d_gdn_wmma.h): lane half hh of a 32-wide K chunk takes 16 contiguous + * elements, the first eight in one step and the last eight in the next, for N and for W alike, so + * both operands map every K slot to the same element and each chunk's 32 products are summed. A + * chunk lies in one 128-wide scale group; a wave's 320-wide slice spans at most three, and the + * accumulator is scaled and folded into P at each group change. */ +constexpr long kHcGN = 2560; /* n: the form's only width */ +constexpr int kHcGTile = 16; /* W_down columns a block owns */ +constexpr int kHcGSlice = (int)kHcGN / kWaves; /* 320: K a wave covers in its stream */ +constexpr int kHcGChunks = kHcGSlice / 32; /* 10 */ +constexpr int kHcGPer = (int)kHcGN / kThreads; /* 10 values of h a thread a row */ + +__device__ __forceinline__ v8bf hcg_e4m3_v8bf(uint32_t lo, uint32_t hi) { + float f[8]; + e4m3x8(lo, hi, f); + union { unsigned u[4]; v8bf v; } r; +#pragma unroll + for (int i = 0; i < 4; ++i) /* exact: an E4M3 value has three mantissa bits */ + r.u[i] = __builtin_amdgcn_perm(__float_as_uint(f[2 * i + 1]), __float_as_uint(f[2 * i]), + 0x07060302u); + return r.v; +} +__device__ __forceinline__ v8bf hcg_v8bf(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { + union { uint4 u; v8bf v; } r; + r.u = make_uint4(a, b, c, d); + return r.v; +} + +template +__device__ __forceinline__ void hc_read_g_down_body( + const unsigned short* __restrict__ h, const float* __restrict__ w, + const unsigned char* __restrict__ downv, long dld, const unsigned short* __restrict__ injw, + unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, + float* __restrict__ scaleout, float* __restrict__ part, unsigned int* __restrict__ tctr, + long lr, long hrow, long irow, float eps, float wadd, int ntd, long rows) { + extern __shared__ __attribute__((aligned(16))) unsigned short sN[]; /* [RG][kHcGN] */ + __shared__ float s_red[kWaves][16][16]; + __shared__ float s_part[kWaves][RG]; + __shared__ float s_scale[RG]; + __shared__ unsigned s_last; + constexpr int hc = 4; + constexpr long HN = hc * kHcGN; + constexpr long NG = HN / r4d_hc8::kDownGroup; + const int tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; + const int t = (int)blockIdx.x / hc, c = (int)blockIdx.x % hc; + const bool itile = t == ntd; + /* This block's row group: rows r0 .. r0 + rr - 1 of the step (RG a group, the last may be short). */ + const long r0 = (long)blockIdx.y * RG; + const int rr = (int)(rows - r0 < RG ? rows - r0 : RG); + h += r0 * hrow; + dout += r0 * lr; + if (inj) inj += r0 * irow; + if (scaleout) scaleout += r0 * kHcMax; + part += (long)blockIdx.y * (ntd + 1) * hc * RG * kHcGTile; + tctr += (long)blockIdx.y * (ntd + 1); + const int col = lane & 15, hh = lane >> 4; + const long kslice = (long)c * kHcGN + (long)wave * kHcGSlice; /* the wave's first K */ + const long kl = kslice + 16 * hh; /* the lane half's */ + + /* ---- constant operands, before the chain wait */ + uint4 wc[kHcGChunks]; + float wsc[3] = { 0.0f, 0.0f, 0.0f }; + const long g0 = kslice / r4d_hc8::kDownGroup; + if (!itile) { + long k = (long)t * kHcGTile + col; + if (k >= lr) k = lr - 1; + const unsigned char* row = downv + k * dld; +#pragma unroll + for (int j = 0; j < kHcGChunks; ++j) wc[j] = *(const uint4*)(row + kl + 32 * j); + const float* sr = (const float*)(row + HN); +#pragma unroll + for (int i = 0; i < 3; ++i) wsc[i] = sr[g0 + i < NG ? g0 + i : NG - 1]; + } else { + /* The inject rows are bf16: the slice's first half (five chunks, two loads each) now. */ + const unsigned short* row = injw + (long)(col < hc ? col : hc - 1) * HN; +#pragma unroll + for (int j = 0; j < kHcGChunks / 2; ++j) { + wc[2 * j] = *(const uint4*)(row + kl + 32 * j); + wc[2 * j + 1] = *(const uint4*)(row + kl + 32 * j + 8); + } + } + float wv[kHcGPer]; +#pragma unroll + for (int p = 0; p < kHcGPer; ++p) wv[p] = w[(long)c * kHcGN + tid + (long)p * kThreads]; + if constexpr (CH) r4d_chain_wait(); + + /* ---- the grouped norm of stream c for every row, as hc_read_a_body's preloaded form */ + uint32_t hv[RG][kHcGPer]; +#pragma unroll + for (int r = 0; r < RG; ++r) +#pragma unroll + for (int p = 0; p < kHcGPer; ++p) + hv[r][p] = bfw(h + (long)(r < rr ? r : rr - 1) * hrow + (long)c * kHcGN + tid + (long)p * kThreads); +#pragma unroll + for (int r = 0; r < RG; ++r) { + float acc = 0.0f; +#pragma unroll + for (int p = 0; p < kHcGPer; ++p) { const float v = bfw_f(hv[r][p]); acc += v * v; } + acc = wave_sum(acc); + if (lane == 0) s_part[wave][r] = acc; + } + __syncthreads(); + if (tid < RG) { + float ss = 0.0f; + for (int k = 0; k < kWaves; ++k) ss += s_part[k][tid]; + s_scale[tid] = __frsqrt_rn(ss / (float)kHcGN + eps); + if (t == 0 && scaleout && tid < rr) scaleout[(long)tid * kHcMax + c] = s_scale[tid]; + } + __syncthreads(); +#pragma unroll + for (int r = 0; r < RG; ++r) { + const float sc = s_scale[r]; +#pragma unroll + for (int p = 0; p < kHcGPer; ++p) + sN[(long)r * kHcGN + tid + (long)p * kThreads] = f2bf(bfw_f(hv[r][p]) * sc * (wv[p] + wadd)); + } + __syncthreads(); + + /* ---- the dots: rows of N as A (rows past RG repeat the last; their D rows are dropped) */ + const unsigned short* nr = sN + (long)(col < rr ? col : rr - 1) * kHcGN + (kl - (long)c * kHcGN); + float P[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) P[e] = 0.0f; + v8f D = {}; + if (!itile) { + int gi = 0; +#pragma unroll + for (int j = 0; j < kHcGChunks; ++j) { + const int g = (int)((kslice + 32 * j) / r4d_hc8::kDownGroup - g0); + if (g != gi) { +#pragma unroll + for (int e = 0; e < 8; ++e) { P[e] = fmaf(D[e], wsc[gi], P[e]); D[e] = 0.0f; } + gi = g; + } + const uint4 a0 = *(const uint4*)(nr + 32 * j); + const uint4 a1 = *(const uint4*)(nr + 32 * j + 8); + D = mma(hcg_v8bf(a0.x, a0.y, a0.z, a0.w), hcg_e4m3_v8bf(wc[j].x, wc[j].y), D); + D = mma(hcg_v8bf(a1.x, a1.y, a1.z, a1.w), hcg_e4m3_v8bf(wc[j].z, wc[j].w), D); + } +#pragma unroll + for (int e = 0; e < 8; ++e) P[e] = fmaf(D[e], wsc[gi], P[e]); + } else { + const unsigned short* row = injw + (long)(col < hc ? col : hc - 1) * HN; +#pragma unroll + for (int half = 0; half < 2; ++half) { + if (half == 1) { +#pragma unroll + for (int j = 0; j < kHcGChunks / 2; ++j) { + const long o = kl + 32 * (j + kHcGChunks / 2); + wc[2 * j] = *(const uint4*)(row + o); + wc[2 * j + 1] = *(const uint4*)(row + o + 8); + } + } +#pragma unroll + for (int j = 0; j < kHcGChunks / 2; ++j) { + const int jj = j + half * (kHcGChunks / 2); + const uint4 a0 = *(const uint4*)(nr + 32 * jj); + const uint4 a1 = *(const uint4*)(nr + 32 * jj + 8); + D = mma(hcg_v8bf(a0.x, a0.y, a0.z, a0.w), + hcg_v8bf(wc[2 * j].x, wc[2 * j].y, wc[2 * j].z, wc[2 * j].w), D); + D = mma(hcg_v8bf(a1.x, a1.y, a1.z, a1.w), + hcg_v8bf(wc[2 * j + 1].x, wc[2 * j + 1].y, wc[2 * j + 1].z, wc[2 * j + 1].w), D); + } + } +#pragma unroll + for (int e = 0; e < 8; ++e) P[e] = D[e]; + } + + /* ---- the waves' partials, summed in ascending wave order; this block's into scratch */ +#pragma unroll + for (int e = 0; e < 8; ++e) s_red[wave][col][8 * hh + e] = P[e]; + __syncthreads(); + const long pstride = (long)RG * kHcGTile; /* one stream's partials of a tile */ + float* const pt = part + (long)t * hc * pstride; + if (tid < RG * kHcGTile) { + const int r = tid / kHcGTile, n = tid % kHcGTile; + float v = 0.0f; + for (int k = 0; k < kWaves; ++k) v += s_red[k][n][r]; + pt[(long)c * pstride + r * kHcGTile + n] = v; + } + + /* ---- the tile's last block finishes: c ascending, then silu or the doubled sigmoid */ + __threadfence(); + __syncthreads(); + if (tid == 0) + s_last = __hip_atomic_fetch_add(&tctr[t], 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT) + + 1u == (unsigned)hc; + __syncthreads(); + if (!s_last) return; + /* Every wave: a workgroup's waves may sit on both CUs of a WGP, each with its own cache. The + * reset goes after the payload, so this acquire waits for no store. */ + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent"); + struct ResetAtEnd { + unsigned int* c; + bool on; + __device__ ~ResetAtEnd() { if (on) __hip_atomic_store(c, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } + } reset_at_end{ &tctr[t], tid == 0 }; + if (tid < RG * kHcGTile) { + const int r = tid / kHcGTile, n = tid % kHcGTile; + const float* pp = pt + r * kHcGTile + n; + float acc = pp[0]; + acc += pp[pstride]; + acc += pp[2 * pstride]; + acc += pp[3 * pstride]; + const float inv_hc = 1.0f / (float)hc; + if (r >= rr) { + } else if (!itile) { + const long k = (long)t * kHcGTile + n; + if (k < lr) dout[(long)r * lr + k] = f2bf(siluf_(acc * inv_hc)); + } else if (n < hc && inj) { + inj[(long)r * irow + n] = f2bf(2.0f * sigmoidf_(acc * inv_hc)); + } + } +} + +/* ============================================================== hc_read, decode form S (A' for 9..16 rows) + * + * As form G's kernel A', but the norm's scale is applied after the dot: + * the A operand bf16(h * (w + wadd)) is formed from h in global memory per WMMA fragment, so nothing of N sits in + * LDS and one block takes every row of the step (MT m-tiles). A lane's squares of h ride along; the block sums + * them per row in a fixed order (a whole stream a block: every tile gets the same scale). P = sum over the + * stream's groups of D_g * w_scale_g is multiplied by s[r, c] after the waves' fixed-order sum. */ +template +__device__ __forceinline__ void hc_read_s_down_body( + const unsigned short* __restrict__ h, const float* __restrict__ w, + const unsigned char* __restrict__ downv, long dld, const unsigned short* __restrict__ injw, + unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, + float* __restrict__ scaleout, float* __restrict__ part, unsigned int* __restrict__ tctr, + long lr, long hrow, long irow, float eps, float wadd, int ntd, long rows) { + constexpr int RM = 16 * MT; /* rows the m-tiles hold */ + __shared__ float s_red[kWaves][16][RM]; + __shared__ __attribute__((aligned(16))) float s_w[kHcGN]; /* this stream's w + wadd */ + __shared__ float s_ss[kWaves][RM]; + __shared__ float s_sc[RM]; + __shared__ unsigned s_last; + constexpr int hc = 4; + constexpr long HN = hc * kHcGN; + constexpr long NG = HN / r4d_hc8::kDownGroup; + const int tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; + const int t = (int)blockIdx.x / hc, c = (int)blockIdx.x % hc; + const bool itile = t == ntd; + const int col = lane & 15, hh = lane >> 4; + const long kslice = (long)c * kHcGN + (long)wave * kHcGSlice; + const long kl = kslice + 16 * hh; + /* This block's row group (RM rows a group; the last may be short). */ + { + const long r0 = (long)blockIdx.y * RM; + h += r0 * hrow; + dout += r0 * lr; + if (inj) inj += r0 * irow; + if (scaleout) scaleout += r0 * kHcMax; + part += (long)blockIdx.y * (ntd + 1) * hc * RM * kHcGTile; + tctr += (long)blockIdx.y * (ntd + 1); + rows = rows - r0 < RM ? rows - r0 : RM; + } + + /* ---- constant operands, before the chain wait (form G's) */ + uint4 wc[kHcGChunks]; + float wsc[3] = { 0.0f, 0.0f, 0.0f }; + const long g0 = kslice / r4d_hc8::kDownGroup; + if (!itile) { + long k = (long)t * kHcGTile + col; + if (k >= lr) k = lr - 1; + const unsigned char* row = downv + k * dld; +#pragma unroll + for (int j = 0; j < kHcGChunks; ++j) wc[j] = *(const uint4*)(row + kl + 32 * j); + const float* sr = (const float*)(row + HN); +#pragma unroll + for (int i = 0; i < 3; ++i) wsc[i] = sr[g0 + i < NG ? g0 + i : NG - 1]; + } else { + const unsigned short* row = injw + (long)(col < hc ? col : hc - 1) * HN; +#pragma unroll + for (int j = 0; j < kHcGChunks / 2; ++j) { + wc[2 * j] = *(const uint4*)(row + kl + 32 * j); + wc[2 * j + 1] = *(const uint4*)(row + kl + 32 * j + 8); + } + } +#pragma unroll + for (int p = 0; p < kHcGPer; ++p) { + const long i = tid + (long)p * kThreads; + s_w[i] = w[(long)c * kHcGN + i] + wadd; + } + if constexpr (CH) r4d_chain_wait(); + __syncthreads(); + + /* ---- the dots, A = bf16(h * (w + wadd)) per fragment, squares alongside */ + const float* wl = s_w + (kl - (long)c * kHcGN); + const unsigned short* irow_w = injw + (long)(col < hc ? col : hc - 1) * HN; + float ss[MT]; + float P[MT][8]; +#pragma unroll 1 + for (int mt = 0; mt < MT; ++mt) { + const long r = 16 * mt + col; + const unsigned short* hrp = h + (r < rows ? r : rows - 1) * hrow + kl; + if (itile && mt > 0) { +#pragma unroll + for (int jj = 0; jj < kHcGChunks / 2; ++jj) { + wc[2 * jj] = *(const uint4*)(irow_w + kl + 32 * jj); + wc[2 * jj + 1] = *(const uint4*)(irow_w + kl + 32 * jj + 8); + } + } + float ssm = 0.0f, Pm[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) Pm[e] = 0.0f; + v8f D = {}; + int gi = 0; +#pragma unroll + for (int j = 0; j < kHcGChunks; ++j) { + if (!itile) { + const int g = (int)((kslice + 32 * j) / r4d_hc8::kDownGroup - g0); + if (g != gi) { +#pragma unroll + for (int e = 0; e < 8; ++e) { Pm[e] = fmaf(D[e], wsc[gi], Pm[e]); D[e] = 0.0f; } + gi = g; + } + } else if (j == kHcGChunks / 2) { +#pragma unroll + for (int jj = 0; jj < kHcGChunks / 2; ++jj) { + const long o = kl + 32 * (jj + kHcGChunks / 2); + wc[2 * jj] = *(const uint4*)(irow_w + o); + wc[2 * jj + 1] = *(const uint4*)(irow_w + o + 8); + } + } + v8bf bA, bB; + if (!itile) { + bA = hcg_e4m3_v8bf(wc[j].x, wc[j].y); + bB = hcg_e4m3_v8bf(wc[j].z, wc[j].w); + } else { + const int q = 2 * (j % (kHcGChunks / 2)); + bA = hcg_v8bf(wc[q].x, wc[q].y, wc[q].z, wc[q].w); + bB = hcg_v8bf(wc[q + 1].x, wc[q + 1].y, wc[q + 1].z, wc[q + 1].w); + } +#pragma unroll + for (int hf = 0; hf < 2; ++hf) { + const uint4 hv4 = *(const uint4*)(hrp + 32 * j + 8 * hf); + const float4 wa = *(const float4*)(wl + 32 * j + 8 * hf), wb = *(const float4*)(wl + 32 * j + 8 * hf + 4); + const float wf[8] = { wa.x, wa.y, wa.z, wa.w, wb.x, wb.y, wb.z, wb.w }; + float v[8]; + bf8_f(hv4, v); + float av[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) { ssm = fmaf(v[e], v[e], ssm); av[e] = v[e] * wf[e]; } + const uint4 pa = f2bf8(av); + D = mma(hcg_v8bf(pa.x, pa.y, pa.z, pa.w), hf ? bB : bA, D); + } + __builtin_amdgcn_sched_barrier(0); + } +#pragma unroll + for (int e = 0; e < 8; ++e) Pm[e] = itile ? D[e] : fmaf(D[e], wsc[gi], Pm[e]); + /* MT is 1 or 2: select into the per-m-tile arrays without a dynamic register index */ +#pragma unroll + for (int q = 0; q < MT; ++q) + if (q == mt) { + ss[q] = ssm; +#pragma unroll + for (int e = 0; e < 8; ++e) P[q][e] = Pm[e]; + } + } + + /* ---- the stream's scale for every row: lanes l and l + 16 hold the same row's two halves */ +#pragma unroll + for (int mt = 0; mt < MT; ++mt) { + const float v = ss[mt] + __shfl_xor(ss[mt], 16); + if (hh == 0) s_ss[wave][16 * mt + col] = v; +#pragma unroll + for (int e = 0; e < 8; ++e) s_red[wave][col][16 * mt + 8 * hh + e] = P[mt][e]; + } + __syncthreads(); + if (tid < RM) { + float q = 0.0f; + for (int k = 0; k < kWaves; ++k) q += s_ss[k][tid]; + s_sc[tid] = __frsqrt_rn(q / (float)kHcGN + eps); + if (t == 0 && scaleout && tid < rows) scaleout[(long)tid * kHcMax + c] = s_sc[tid]; + } + __syncthreads(); + const long pstride = (long)rows * kHcGTile; + float* const pt = part + (long)t * hc * pstride; + for (int i = tid; i < rows * kHcGTile; i += kThreads) { + const int r = i / kHcGTile, n = i % kHcGTile; + float v = 0.0f; + for (int k = 0; k < kWaves; ++k) v += s_red[k][n][r]; + pt[(long)c * pstride + i] = v * s_sc[r]; + } + + /* ---- the tile's last block finishes, as form G's */ + __threadfence(); + __syncthreads(); + if (tid == 0) + s_last = __hip_atomic_fetch_add(&tctr[t], 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT) + + 1u == (unsigned)hc; + __syncthreads(); + if (!s_last) return; + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent"); + struct ResetAtEnd { + unsigned int* c; + bool on; + __device__ ~ResetAtEnd() { if (on) __hip_atomic_store(c, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } + } reset_at_end{ &tctr[t], tid == 0 }; + const float inv_hc = 1.0f / (float)hc; + for (int i = tid; i < rows * kHcGTile; i += kThreads) { + const int r = i / kHcGTile, n = i % kHcGTile; + const float* pp = pt + i; + float acc = pp[0]; + acc += pp[pstride]; + acc += pp[2 * pstride]; + acc += pp[3 * pstride]; + if (!itile) { + const long k = (long)t * kHcGTile + n; + if (k < lr) dout[(long)r * lr + k] = f2bf(siluf_(acc * inv_hc)); + } else if (n < hc && inj) { + inj[(long)r * irow + n] = f2bf(2.0f * sigmoidf_(acc * inv_hc)); + } + } +} + +/* ============================================================== hc_read, kernel B3 (forms G and S) + * Kernel B for forms G and S at lr 320: the up product as WMMA over d with W_up's exact quarter + * scales, then the mix in each lane. Block b: channels 32b .. 32b + 31 of all streams; wave w: + * channels 32b + 4w .. + 3 (16 W_up rows). RG: the step's rows (1..16). W_up and its scales load + * before the chain wait. */ +constexpr int kHcBCh = 32; /* channels a block */ +template +__device__ __forceinline__ void hc_up_w_body( + const unsigned char* __restrict__ upv, long uld, const unsigned short* __restrict__ dbuf, + const unsigned short* __restrict__ h, const float* __restrict__ w, const float* __restrict__ scalein, + unsigned short* __restrict__ x, unsigned char* __restrict__ q, float* __restrict__ qs, + unsigned char* __restrict__ rq, float* __restrict__ rqs, unsigned int* __restrict__ ctr, + long rows, long n, long lr, long hrow, long xrow, long qrow, long srow, long rqrow, long rsrow, + float wadd) { + constexpr int hc = 4; + constexpr int kLr = 320, kQ = kLr / 4, kStepsQ = kQ / 16; /* 80 codes, 5 steps a quarter */ + __shared__ __attribute__((aligned(16))) unsigned short sd[RG * kLr]; /* d [RG][lr] */ + __shared__ float s_usc[kWaves][16][4]; + __shared__ unsigned s_arrived; + const int tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; + const int col = lane & 15, hh = lane >> 4; + const long i0 = (long)blockIdx.x * kHcBCh; + const long iw = i0 + 4 * wave; + + /* ---- constant operands before the chain wait: this lane's W_up row (m = col), its half of every quarter */ + const unsigned char* wr = upv + ((long)(col & 3) * n + iw + (col >> 2)) * uld; + uint2 wc[4][kStepsQ]; +#pragma unroll + for (int qq = 0; qq < 4; ++qq) +#pragma unroll + for (int st = 0; st < kStepsQ; ++st) wc[qq][st] = *(const uint2*)(wr + qq * kQ + 40 * hh + 8 * st); + if (hh == 0) { +#pragma unroll + for (int qq = 0; qq < 4; ++qq) s_usc[wave][col][qq] = ((const float*)(wr + kLr))[qq]; + } + float wv[2][4]; +#pragma unroll + for (int a = 0; a < 2; ++a) +#pragma unroll + for (int c = 0; c < hc; ++c) wv[a][c] = w[(long)c * n + iw + 2 * hh + a] + wadd; + if constexpr (CH) r4d_chain_wait(); + + /* ---- one batch: d (uint4, contiguous rows), the mix items' h and scales */ + constexpr int kD8 = RG * kLr / 8; + uint4 dq[(kD8 + kThreads - 1) / kThreads]; +#pragma unroll + for (int i = 0; i < (kD8 + kThreads - 1) / kThreads; ++i) { + const int k = tid + i * kThreads; + dq[i] = k < kD8 ? ((const uint4*)dbuf)[k] : make_uint4(0u, 0u, 0u, 0u); + } + const int rr = col < RG ? col : RG - 1; + float sc[4]; + uint32_t hv2[4]; +#pragma unroll + for (int c = 0; c < hc; ++c) { + sc[c] = scalein[(long)rr * kHcMax + c]; + hv2[c] = *(const uint32_t*)(h + (long)rr * hrow + (long)c * n + iw + 2 * hh); + } +#pragma unroll + for (int i = 0; i < (kD8 + kThreads - 1) / kThreads; ++i) { + const int k = tid + i * kThreads; + if (k < kD8) ((uint4*)sd)[k] = dq[i]; + } + float Npre[2][4]; +#pragma unroll + for (int c = 0; c < hc; ++c) +#pragma unroll + for (int a = 0; a < 2; ++a) + Npre[a][c] = nbf(bfw_f(a ? (hv2[c] >> 16) : (hv2[c] & 0xffffu)) * sc[c] * wv[a][c]); + __syncthreads(); + + /* ---- the up product: per quarter five WMMA steps, folded with the quarter's scale */ + float U[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) U[e] = 0.0f; + const unsigned short* dr = sd + (long)rr * kLr + 40 * hh; +#pragma unroll + for (int qq = 0; qq < 4; ++qq) { + v8f D = {}; +#pragma unroll + for (int st = 0; st < kStepsQ; ++st) { + const uint4 b = *(const uint4*)(dr + qq * kQ + 8 * st); + D = mma(hcg_e4m3_v8bf(wc[qq][st].x, wc[qq][st].y), hcg_v8bf(b.x, b.y, b.z, b.w), D); + } +#pragma unroll + for (int e = 0; e < 8; ++e) U[e] = fmaf(D[e], s_usc[wave][8 * hh + e][qq], U[e]); + } + + /* ---- sigmoid, narrowed; the mix in the lane (D row 8hh + e = channel 2hh + e/4, stream e%4) */ + const float inv_hc = 1.0f / (float)hc; + if (col < RG && col < rows) { + float acc[2]; +#pragma unroll + for (int a = 0; a < 2; ++a) { + acc[a] = 0.0f; +#pragma unroll + for (int c = 0; c < hc; ++c) acc[a] += nbf(sigmoidf_(U[4 * a + c])) * Npre[a][c]; + acc[a] *= inv_hc; + } + *(uint32_t*)(x + (long)col * xrow + iw + 2 * hh) = f2bf2(acc[0], acc[1]); + } + if (!q || !ctr) return; + + /* ---- the 128-channel group's last block quantises it */ + const int nb = kUpTB / kHcBCh; + __threadfence(); + __syncthreads(); + const unsigned slot = (unsigned)(i0 / kUpTB); + if (tid == 0) + s_arrived = __hip_atomic_fetch_add(&ctr[slot], 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT); + __syncthreads(); + if (s_arrived + 1u != (unsigned)nb) return; + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent"); + const long base = (i0 / kUpTB) * kUpTB; + for (int r = wave; r < RG && r < rows; r += kWaves) { + const unsigned short* const xr = x + (long)r * xrow + base; + float v[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = bf2f(xr[lane * 4 + j]); + float m = fmaxf(fmaxf(fabsf(v[0]), fabsf(v[1])), fmaxf(fabsf(v[2]), fabsf(v[3]))); + m = r4d_wave_max(m); + const float scq = m > 0.0f ? m * (1.0f / q8_top()) : 1.0f; + const float inv = 1.0f / scq; + if (lane == 0) qs[(long)r * srow + base / kUpTB] = scq; + const uint32_t pk = q8_pack4(v[0], v[1], v[2], v[3], inv); + *(unsigned*)(q + (long)r * qrow + base + lane * 4) = (unsigned)pk; + if (rq) hc_rot_group(v, lane, rq + (long)r * rqrow + base, rqs + (long)r * rsrow + base / kUpTB); + } + if (tid == 0) __hip_atomic_store(&ctr[slot], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); +} + +#define R4D_HCW_PARAMS \ + const unsigned char* __restrict__ upv, long uld, const unsigned short* __restrict__ dbuf, \ + const unsigned short* __restrict__ h, const float* __restrict__ w, \ + const float* __restrict__ scalein, unsigned short* __restrict__ x, unsigned char* __restrict__ q, \ + float* __restrict__ qs, unsigned char* __restrict__ rq, float* __restrict__ rqs, \ + unsigned int* __restrict__ ctr, long rows, long n, long lr, long hrow, long xrow, long qrow, \ + long srow, long rqrow, long rsrow, float wadd +#define R4D_HCW_ARGS upv, uld, dbuf, h, w, scalein, x, q, qs, rq, rqs, ctr, rows, n, lr, hrow, xrow, \ + qrow, srow, rqrow, rsrow, wadd +template +__global__ __launch_bounds__(kThreads) void hc_up_w_kernel(R4D_HCW_PARAMS) { + hc_up_w_body(R4D_HCW_ARGS); +} +template +__global__ __launch_bounds__(kThreads) void r4dchain_hc_up_w(R4D_HCW_PARAMS) { + hc_up_w_body(R4D_HCW_ARGS); + r4d_chain_done(); +} +template +__global__ __launch_bounds__(kThreads) +void hc_read_s_down_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, + const unsigned char* __restrict__ downv, long dld, + const unsigned short* __restrict__ injw, + unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, + float* __restrict__ scaleout, float* __restrict__ part, + unsigned int* __restrict__ tctr, long lr, long hrow, long irow, + float eps, float wadd, int ntd, long rows) { + hc_read_s_down_body(h, w, downv, dld, injw, dout, inj, scaleout, part, tctr, lr, + hrow, irow, eps, wadd, ntd, rows); +} +template +__global__ __launch_bounds__(kThreads) +void r4dchain_hc_read_s_down(const unsigned short* __restrict__ h, const float* __restrict__ w, + const unsigned char* __restrict__ downv, long dld, + const unsigned short* __restrict__ injw, + unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, + float* __restrict__ scaleout, float* __restrict__ part, + unsigned int* __restrict__ tctr, long lr, long hrow, long irow, + float eps, float wadd, int ntd, long rows) { + hc_read_s_down_body(h, w, downv, dld, injw, dout, inj, scaleout, part, tctr, lr, + hrow, irow, eps, wadd, ntd, rows); + r4d_chain_done(); +} + +template +__global__ __launch_bounds__(kThreads) +void hc_read_g_down_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, + const unsigned char* __restrict__ downv, long dld, + const unsigned short* __restrict__ injw, + unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, + float* __restrict__ scaleout, float* __restrict__ part, + unsigned int* __restrict__ tctr, long lr, long hrow, long irow, + float eps, float wadd, int ntd, long rows) { + hc_read_g_down_body(h, w, downv, dld, injw, dout, inj, scaleout, part, tctr, lr, + hrow, irow, eps, wadd, ntd, rows); +} +/* The chained form: the body waits itself, after the constant loads. */ +template +__global__ __launch_bounds__(kThreads) +void r4dchain_hc_read_g_down(const unsigned short* __restrict__ h, const float* __restrict__ w, + const unsigned char* __restrict__ downv, long dld, + const unsigned short* __restrict__ injw, + unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, + float* __restrict__ scaleout, float* __restrict__ part, + unsigned int* __restrict__ tctr, long lr, long hrow, long irow, + float eps, float wadd, int ntd, long rows) { + hc_read_g_down_body(h, w, downv, dld, injw, dout, inj, scaleout, part, tctr, lr, + hrow, irow, eps, wadd, ntd, rows); + r4d_chain_done(); +} + /* ============================================================== hc_read, A and B in one grid * * At decode, kernel A is mostly latency (its norm prologue and the L2 round trips around @@ -1525,9 +2277,7 @@ void hc_up_mix_kernel(const void* __restrict__ upv, long uld, * * Bit-identical to the two launches: the same bodies, the same per-block work. */ template -__global__ __launch_bounds__(kThreads) -__attribute__((amdgpu_waves_per_eu(9, 9))) -void hc_read_fused_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, +__device__ __forceinline__ void hc_read_fused_kernel_body(const unsigned short* __restrict__ h, const float* __restrict__ w, const void* __restrict__ downv, long dld, const unsigned short* __restrict__ injw, unsigned short* __restrict__ dbuf, unsigned short* __restrict__ inj, @@ -1560,6 +2310,46 @@ void hc_read_fused_kernel(const unsigned short* __restrict__ h, const float* __r wadd, b % gxb, b / gxb, sync, na, nb_all); } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +template +__global__ __launch_bounds__(kThreads) +__attribute__((amdgpu_waves_per_eu(9, 9))) +void hc_read_fused_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, + const void* __restrict__ downv, long dld, + const unsigned short* __restrict__ injw, + unsigned short* __restrict__ dbuf, unsigned short* __restrict__ inj, + float* __restrict__ scale, long ta, long irow, float eps, + const void* __restrict__ upv, long uld, + unsigned short* __restrict__ x, unsigned char* __restrict__ q, + float* __restrict__ qs, unsigned char* __restrict__ rq, + float* __restrict__ rqs, unsigned int* __restrict__ ctr, + long rows, long n, int hc, long lr, long hrow, long xrow, + long qrow, long srow, long rqrow, long rsrow, float wadd, + unsigned int* __restrict__ sync, + unsigned na, unsigned gxa, unsigned gxb, unsigned nb_all) { + hc_read_fused_kernel_body(h, w, downv, dld, injw, dbuf, inj, scale, ta, irow, eps, upv, uld, x, q, qs, rq, rqs, ctr, rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd, sync, na, gxa, gxb, nb_all); +} +template +__global__ __launch_bounds__(kThreads) +__attribute__((amdgpu_waves_per_eu(9, 9))) +void r4dchain_hc_read_fused(const unsigned short* __restrict__ h, const float* __restrict__ w, + const void* __restrict__ downv, long dld, + const unsigned short* __restrict__ injw, + unsigned short* __restrict__ dbuf, unsigned short* __restrict__ inj, + float* __restrict__ scale, long ta, long irow, float eps, + const void* __restrict__ upv, long uld, + unsigned short* __restrict__ x, unsigned char* __restrict__ q, + float* __restrict__ qs, unsigned char* __restrict__ rq, + float* __restrict__ rqs, unsigned int* __restrict__ ctr, + long rows, long n, int hc, long lr, long hrow, long xrow, + long qrow, long srow, long rqrow, long rsrow, float wadd, + unsigned int* __restrict__ sync, + unsigned na, unsigned gxa, unsigned gxb, unsigned nb_all) { + r4d_chain_wait(); + hc_read_fused_kernel_body(h, w, downv, dld, injw, dbuf, inj, scale, ta, irow, eps, upv, uld, x, q, qs, rq, rqs, ctr, rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd, sync, na, gxa, gxb, nb_all); + r4d_chain_done(); +} + /* Row group size: the row count, up to eight. RG is a template parameter so `acc[RG]` stays in * registers. Every size from 1 to 8 is instantiated, so up to eight rows read the weight once * (a five-row verify split 4 + 1 would read W_up twice). Output bytes do not depend on RG. @@ -1845,9 +2635,14 @@ void hc_up_mix_2grid_kernel(const void* __restrict__ upv, long uld, __HIP_MEMORY_SCOPE_AGENT); __syncthreads(); if (s_arrived + 1u != (unsigned)nb) return; - if (tid == 0) - __hip_atomic_store(&ctr[slot], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); - __threadfence(); + /* The reset goes after this block's codes (wave 0 always quantises a row), so the + * acquire waits for no store. */ + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent"); + struct ResetAtEnd { + unsigned int* c; + bool on; + __device__ ~ResetAtEnd() { if (on) __hip_atomic_store(c, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } + } reset_at_end{ &ctr[slot], tid == 0 }; /* One wave per row (RG <= wave count); a lane takes four of the group's 128 channels, one * packed dword of codes. */ @@ -1923,7 +2718,7 @@ static inline int hc_up_mix_launch(const RadTensor* up, long uld, bool f8, bool unsigned int* ctr, long long rows, long long n, int hc, long long lr, long long hrow, long long xrow, long long qrow, long long srow, long long rqrow, long long rsrow, float wadd, - RadStream stream) { + RadStream stream, bool ch = false) { if (g_hc_decode_form == 1) return hc_up_mix_2grid_launch(up, uld, f8, i8, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd, @@ -1935,7 +2730,8 @@ static inline int hc_up_mix_launch(const RadTensor* up, long uld, bool f8, bool const unsigned lds = (unsigned)(rg * lr * sizeof(float)); const void* upp = up->data; #define HC_UPMIX_K(RG_, F8_, I8_, RPT_) \ - emit_rc = R4D_EMIT(stream, (hc_up_mix_kernel), grid, dim3(kThreads), lds, \ + emit_rc = R4D_EMIT(stream, (ch ? &r4dchain_hc_up_mix \ + : &hc_up_mix_kernel), grid, dim3(kThreads), lds, \ upp, uld, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, (long)rows, (long)n, \ hc, \ (long)lr, (long)hrow, (long)xrow, (long)qrow, (long)srow, (long)rqrow, \ @@ -2077,8 +2873,7 @@ constexpr long kDecMinRows = 8; // below this the per-row kernels win; the t * N. Bit-identical to the fused form: same thread stride, wave_sum and ascending sum over the wave * partials. Removing the launch itself would need `h`'s producer (hc_write, another op with its * own arena) to compute the scales. */ -__global__ __launch_bounds__(kThreads) -void hc_norm_scale_kernel(const unsigned short* __restrict__ h, float* __restrict__ scaleout, +__device__ __forceinline__ void hc_norm_scale_kernel_body(const unsigned short* __restrict__ h, float* __restrict__ scaleout, long rows, long n, long hrow, float eps) { __shared__ float s_part[kWaves]; const long r = blockIdx.y, c = blockIdx.x; @@ -2097,6 +2892,20 @@ void hc_norm_scale_kernel(const unsigned short* __restrict__ h, float* __restric } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +__global__ __launch_bounds__(kThreads) +void hc_norm_scale_kernel(const unsigned short* __restrict__ h, float* __restrict__ scaleout, + long rows, long n, long hrow, float eps) { + hc_norm_scale_kernel_body(h, scaleout, rows, n, hrow, eps); +} +__global__ __launch_bounds__(kThreads) +void r4dchain_hc_norm_scale(const unsigned short* __restrict__ h, float* __restrict__ scaleout, + long rows, long n, long hrow, float eps) { + r4d_chain_wait(); + hc_norm_scale_kernel_body(h, scaleout, rows, n, hrow, eps); + r4d_chain_done(); +} + /* ==================================================== tile shape follows the row count * * RT varies with rows: 128 suits thousands of rows, but at 32 it would stage 128 rows to use 32 @@ -2128,8 +2937,7 @@ constexpr int kTKSPLIT_WANT = 128; // workgroups the down product aims to cove * at eight sequences). `ncol` is lr + hc with gains, lr without; columns at or past lr read injw * and take the sigmoid epilogue. */ template -__global__ __launch_bounds__(kThreads) -void hc_down_tiled_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, +__device__ __forceinline__ void hc_down_tiled_kernel_body(const unsigned short* __restrict__ h, const float* __restrict__ w, const void* __restrict__ downv, long dld, const float* __restrict__ scalein, const unsigned short* __restrict__ injw, @@ -2225,10 +3033,37 @@ void hc_down_tiled_kernel(const unsigned short* __restrict__ h, const float* __r } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +template +__global__ __launch_bounds__(kThreads) +void hc_down_tiled_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, + const void* __restrict__ downv, long dld, + const float* __restrict__ scalein, + const unsigned short* __restrict__ injw, + unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, + float* __restrict__ part, + long rows, long n, int hc, long lr, long ncol, long hrow, long irow, + long kc, float wadd) { + hc_down_tiled_kernel_body(h, w, downv, dld, scalein, injw, dout, inj, part, rows, n, hc, lr, ncol, hrow, irow, kc, wadd); +} +template +__global__ __launch_bounds__(kThreads) +void r4dchain_hc_down_tiled(const unsigned short* __restrict__ h, const float* __restrict__ w, + const void* __restrict__ downv, long dld, + const float* __restrict__ scalein, + const unsigned short* __restrict__ injw, + unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, + float* __restrict__ part, + long rows, long n, int hc, long lr, long ncol, long hrow, long irow, + long kc, float wadd) { + r4d_chain_wait(); + hc_down_tiled_kernel_body(h, w, downv, dld, scalein, injw, dout, inj, part, rows, n, hc, lr, ncol, hrow, irow, kc, wadd); + r4d_chain_done(); +} + /* The split-K reduce: partials summed in ascending z (reproducible), then the epilogue: silu for a * W_down column, doubled sigmoid for an inject column. */ -__global__ __launch_bounds__(kThreads) -void hc_down_reduce_kernel(const float* __restrict__ part, unsigned short* __restrict__ dout, +__device__ __forceinline__ void hc_down_reduce_kernel_body(const float* __restrict__ part, unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, long rows, long lr, long ncol, long irow, int ksplit, float inv_hc) { const long i = (long)blockIdx.x * kThreads + threadIdx.x; @@ -2251,6 +3086,22 @@ void hc_down_reduce_kernel(const float* __restrict__ part, unsigned short* __res else inj[r * irow + (col - lr)] = f2bf(2.0f * sigmoidf_(s * inv_hc)); } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +__global__ __launch_bounds__(kThreads) +void hc_down_reduce_kernel(const float* __restrict__ part, unsigned short* __restrict__ dout, + unsigned short* __restrict__ inj, long rows, long lr, long ncol, + long irow, int ksplit, float inv_hc) { + hc_down_reduce_kernel_body(part, dout, inj, rows, lr, ncol, irow, ksplit, inv_hc); +} +__global__ __launch_bounds__(kThreads) +void r4dchain_hc_down_reduce(const float* __restrict__ part, unsigned short* __restrict__ dout, + unsigned short* __restrict__ inj, long rows, long lr, long ncol, + long irow, int ksplit, float inv_hc) { + r4d_chain_wait(); + hc_down_reduce_kernel_body(part, dout, inj, rows, lr, ncol, irow, ksplit, inv_hc); + r4d_chain_done(); +} + /* The prefill tile: rows, down-product columns per workgroup and up-product channels per * workgroup. 112 columns is three tiles over 320 + 4, the fewest that fit the 128-row A tile and * the B tile in LDS twice per CU; faster than 64 and 128 at 129 to 4096 rows. */ @@ -2546,8 +3397,7 @@ void hc_up_tiled_kernel(const void* __restrict__ upv, long uld, * Bit-identical to the unfused pair: `u` and `N` are narrowed to bf16 where hc_mix would read them * back, both pass through LDS as bf16, and the sum over c ascends. */ template -__global__ __launch_bounds__(kThreads) -void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, +__device__ __forceinline__ void hc_up_mix_tiled_kernel_body(const void* __restrict__ upv, long uld, const unsigned short* __restrict__ dbuf, const unsigned short* __restrict__ h, const float* __restrict__ w, const float* __restrict__ scalein, @@ -2819,6 +3669,36 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +template +__global__ __launch_bounds__(kThreads) +void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, + const unsigned short* __restrict__ dbuf, + const unsigned short* __restrict__ h, const float* __restrict__ w, + const float* __restrict__ scalein, + unsigned short* __restrict__ x, unsigned char* __restrict__ q, + float* __restrict__ qs, unsigned char* __restrict__ rq, + float* __restrict__ rqs, unsigned int* __restrict__ ctr, + long rows, long n, int hc, long lr, long hrow, long xrow, + long qrow, long srow, long rqrow, long rsrow, float wadd) { + hc_up_mix_tiled_kernel_body(upv, uld, dbuf, h, w, scalein, x, q, qs, rq, rqs, ctr, rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd); +} +template +__global__ __launch_bounds__(kThreads) +void r4dchain_hc_up_mix_tiled(const void* __restrict__ upv, long uld, + const unsigned short* __restrict__ dbuf, + const unsigned short* __restrict__ h, const float* __restrict__ w, + const float* __restrict__ scalein, + unsigned short* __restrict__ x, unsigned char* __restrict__ q, + float* __restrict__ qs, unsigned char* __restrict__ rq, + float* __restrict__ rqs, unsigned int* __restrict__ ctr, + long rows, long n, int hc, long lr, long hrow, long xrow, + long qrow, long srow, long rqrow, long rsrow, float wadd) { + r4d_chain_wait(); + hc_up_mix_tiled_kernel_body(upv, uld, dbuf, h, w, scalein, x, q, qs, rq, rqs, ctr, rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd); + r4d_chain_done(); +} + /* The tiled up-mix with its K passes unpipelined, for r4d_hc_read_pin_decode(1) (see the * two-grid decode kernels above). */ template @@ -3250,7 +4130,8 @@ static inline void hc_up_mix_tiled_launch(int rt, bool f8, bool i8, const void* #define HC_UM_CASE3(RT_, F8_, I8_) \ do { \ if (g_hc_decode_form == 1) HC_UM_K((hc_up_mix_tiled_2grid_kernel)); \ - else HC_UM_K((hc_up_mix_tiled_kernel)); \ + else HC_UM_K((g_r4d_chain_arg ? &r4dchain_hc_up_mix_tiled \ + : &hc_up_mix_tiled_kernel)); \ } while (0) #define HC_UM_CASE(RT_, F8_) \ do { if (i8) HC_UM_CASE3(RT_, F8_, true); else HC_UM_CASE3(RT_, F8_, false); } while (0) @@ -4140,7 +5021,8 @@ static inline void hc_down_tiled_launch(int rt, bool f8, const unsigned short* h const dim3 gd((unsigned)((ncol + kTNT - 1) / kTNT), (unsigned)((rows + rt - 1) / rt), (unsigned)((HN + kc - 1) / kc)); #define HC_DOWN_CASE(RT_, F8_) \ - hipLaunchKernelGGL((hc_down_tiled_kernel), gd, dim3(kThreads), 0, \ + hipLaunchKernelGGL((g_r4d_chain_arg ? &r4dchain_hc_down_tiled \ + : &hc_down_tiled_kernel), gd, dim3(kThreads), 0, \ (hipStream_t)s, h, w, down, dld, scale, injw, dbuf, inj, part, rows, n, \ hc, lr, ncol, hrow, irow, kc, wadd) switch (rt) { @@ -4638,8 +5520,39 @@ extern "C" int r4d_rad_hc_read(const RadArgs* a, RadStream s) { * (prefill), else 32 or 64 with a K-split down product. Below kDecMinRows the per-row kernels * win. */ bool fused = false; - const bool tiled = can_tile && rows >= kDecMinRows; + /* Decode forms G (one to eight rows) and S (9..16) at Flash-Next's shape with the inject gains: + * kernel A' as (tile, stream) blocks, its partials after `fixed` and its tile counters behind the + * fused form's, then kernel B3. From 17 rows the tiled path (chained) measured faster (x8 +2.9 % + * against two 16-row groups of form S). */ + constexpr long hcg_max = 16; + const long hcg_nt = (lr + kHcGTile - 1) / kHcGTile; + unsigned int* hcg_ctr = nullptr; + float* hcg_part = nullptr; + /* Form S: one block a (tile, stream) holds every row. */ + const bool hcs = rows > 8 && rows <= 16 && (hrow % 8) == 0 + && (((uintptr_t)h->data & 15u) == 0u) && (((uintptr_t)w->data & 15u) == 0u); + const long hcg_rg = hcs ? 16 : rows <= 8 ? rows : 8; /* rows a group of kernel A' */ + const long hcg_gy = (rows + hcg_rg - 1) / hcg_rg; + if (f8 && hc == 4 && n == kHcGN && lr % kHcGTile == 0 && lr <= 2L * kThreads + && (hcg_nt + 1) * hcg_gy <= (long)kHcGTilesMax + && rows >= 1 && rows <= hcg_max && injw && inj && g_hc_decode_form == 0 + && a->scratch_bytes >= fixed + hcg_gy * (hcg_nt + 1) * hc * hcg_rg * kHcGTile * 4) { + unsigned int* mc = hc_mix_ctr(s); + if (mc) { + hcg_ctr = mc + kMaxMixCtr + 3; + hcg_part = (float*)((unsigned char*)a->scratch + fixed); + } + } + const bool hcg = hcg_ctr != nullptr; + const bool hcg_ch = hcg && r4d_geti_or(a, "chain", 0) != 0; + /* Kernel B3 for forms G and S at lr 320, a single row group; else the chained up-mix. */ + const bool hcw = hcg && lr == 320 && rows <= 16 && (rows <= 8 || hcs) && (n % 128) == 0 + && (hrow % 2) == 0 && (xrow % 2) == 0; + const bool tiled = can_tile && rows >= kDecMinRows && !hcg; if (tiled) { + /* The chained forms of the tiled kernels (r4d_chain.h) at decode heights, where the row + * resolved with `chain`. */ + const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0 && rows <= 64); const int rt = hc_down_rt(rows); /* The inject gains, if any, are hc more columns of the same GEMM. */ const bool fold = injw != nullptr && inj != nullptr; @@ -4678,7 +5591,7 @@ extern "C" int r4d_rad_hc_read(const RadArgs* a, RadStream s) { } /* The per-s norm scales: one workgroup per (row, s). */ - hipLaunchKernelGGL(hc_norm_scale_kernel, + hipLaunchKernelGGL((g_r4d_chain_arg ? &r4dchain_hc_norm_scale : &hc_norm_scale_kernel), dim3((unsigned)hc, (unsigned)rows), dim3(kThreads), 0, (hipStream_t)s, (const unsigned short*)h->data, scale, (long)rows, (long)n, (long)hrow, eps); @@ -4702,7 +5615,7 @@ extern "C" int r4d_rad_hc_read(const RadArgs* a, RadStream s) { if (ks > 1) { const long tot = (long)rows * ncol; - hipLaunchKernelGGL(hc_down_reduce_kernel, + hipLaunchKernelGGL((g_r4d_chain_arg ? &r4dchain_hc_down_reduce : &hc_down_reduce_kernel), dim3((unsigned)((tot + kThreads - 1) / kThreads)), dim3(kThreads), 0, (hipStream_t)s, part, dbuf, fold ? (unsigned short*)inj->data : nullptr, @@ -4761,7 +5674,7 @@ extern "C" int r4d_rad_hc_read(const RadArgs* a, RadStream s) { * there kernels A and B as one grid (hc_read_fused_kernel) when the row group is the whole * step, the up-mix fuses (q's counters or none) and the per-stream counters exist. */ const bool pre = f8 && hc == 4 && n == 10LL * kThreads && g_hc_decode_form != 1; - if (pre) { + if (pre && !hcg) { const long rgf = hc_up_rg(rows, lr); const int rpt = hc_up_rpt(true, (int)hc, n); const long ipf = (long)kUpRows * rpt / hc; @@ -4774,8 +5687,11 @@ extern "C" int r4d_rad_hc_read(const RadArgs* a, RadStream s) { const unsigned na = gxa * (unsigned)rows; const unsigned gxb = (unsigned)(n / ipf); const unsigned nbf_ = gxb; /* one row group */ + /* The chained form (r4d_chain.h) where the row resolved with `chain`. */ + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && r4d_chain_rows_ok(rows); #define HC_FUSED_K(RG_, I8_, RPT_) \ - emit_rc = R4D_EMIT(s, (hc_read_fused_kernel), \ + emit_rc = R4D_EMIT(s, (ch ? &r4dchain_hc_read_fused \ + : &hc_read_fused_kernel), \ dim3(na + nbf_), dim3(kThreads), (unsigned)lds, \ (const unsigned short*)h->data, (const float*)w->data, (const void*)down->data, \ (long)dld, injw ? (const unsigned short*)injw->data : nullptr, dbuf, \ @@ -4814,7 +5730,39 @@ extern "C" int r4d_rad_hc_read(const RadArgs* a, RadStream s) { (long)dld, injw ? (const unsigned short*)injw->data : nullptr, dbuf, \ inj ? (unsigned short*)inj->data : nullptr, scale, (long)rows, (long)n, (int)hc, \ (long)lr, (long)ta, (long)hrow, (long)irow, eps, wadd) - if (g_hc_decode_form == 1) + if (hcg && hcs) { +#define HC_S_K(MT_) \ + emit_rc = R4D_EMIT(s, (hcg_ch ? &r4dchain_hc_read_s_down : &hc_read_s_down_kernel), \ + dim3((unsigned)((hcg_nt + 1) * hc), (unsigned)hcg_gy), dim3(kThreads), 0, \ + (const unsigned short*)h->data, (const float*)w->data, \ + (const unsigned char*)down->data, (long)dld, \ + (const unsigned short*)injw->data, dbuf, (unsigned short*)inj->data, \ + scale, hcg_part, hcg_ctr, (long)lr, (long)hrow, (long)irow, eps, wadd, \ + (int)hcg_nt, (long)rows) + HC_S_K(1); +#undef HC_S_K + } else if (hcg) { +#define HC_G_K(RG_) \ + emit_rc = R4D_EMIT(s, (hcg_ch ? &r4dchain_hc_read_g_down : &hc_read_g_down_kernel), \ + dim3((unsigned)((hcg_nt + 1) * hc), (unsigned)hcg_gy), dim3(kThreads), \ + (unsigned)(RG_ * kHcGN * sizeof(unsigned short)), \ + (const unsigned short*)h->data, (const float*)w->data, \ + (const unsigned char*)down->data, (long)dld, \ + (const unsigned short*)injw->data, dbuf, (unsigned short*)inj->data, \ + scale, hcg_part, hcg_ctr, (long)lr, (long)hrow, (long)irow, eps, wadd, \ + (int)hcg_nt, (long)rows) + switch (hcg_rg) { + case 8: HC_G_K(8); break; + case 7: HC_G_K(7); break; + case 6: HC_G_K(6); break; + case 5: HC_G_K(5); break; + case 4: HC_G_K(4); break; + case 3: HC_G_K(3); break; + case 2: HC_G_K(2); break; + default: HC_G_K(1); break; + } +#undef HC_G_K + } else if (g_hc_decode_form == 1) emit_rc = f8 ? HC_READ_A(hc_read_a_2grid_kernel) : HC_READ_A(hc_read_a_2grid_kernel); else if (pre) emit_rc = HC_READ_A((hc_read_a_kernel)); else emit_rc = f8 ? HC_READ_A(hc_read_a_kernel) : HC_READ_A(hc_read_a_kernel); @@ -4832,7 +5780,31 @@ extern "C" int r4d_rad_hc_read(const RadArgs* a, RadStream s) { mctr = hc_mix_ctr(s); fused = (mctr != nullptr); } - if (fused) + if (hcw) { + unsigned int* const qctr = q ? mctr : nullptr; +#define HC_UPW_K(RG_, I8_) \ + emit_rc = R4D_EMIT(s, (hcg_ch ? &r4dchain_hc_up_w : &hc_up_w_kernel), \ + dim3((unsigned)(n / kHcBCh)), dim3(kThreads), 0, \ + (const unsigned char*)up->data, (long)uld, (const unsigned short*)dbuf, \ + (const unsigned short*)h->data, (const float*)w->data, \ + (const float*)scale, (unsigned short*)x->data, \ + q ? (unsigned char*)q->data : nullptr, q ? (float*)qs->data : nullptr, \ + rq ? (unsigned char*)rq->data : nullptr, \ + rq ? (float*)rqs->data : nullptr, qctr, (long)rows, (long)n, (long)lr, \ + (long)hrow, (long)xrow, (long)qrow, (long)srow, (long)rqrow, \ + (long)rsrow, wadd) +#define HC_UPW_R(RG_) do { if (i8) HC_UPW_K(RG_, true); else HC_UPW_K(RG_, false); } while (0) + switch (rows) { + case 16: HC_UPW_R(16); break; case 15: HC_UPW_R(15); break; case 14: HC_UPW_R(14); break; + case 13: HC_UPW_R(13); break; case 12: HC_UPW_R(12); break; case 11: HC_UPW_R(11); break; + case 10: HC_UPW_R(10); break; case 9: HC_UPW_R(9); break; case 8: HC_UPW_R(8); break; + case 7: HC_UPW_R(7); break; case 6: HC_UPW_R(6); break; case 5: HC_UPW_R(5); break; + case 4: HC_UPW_R(4); break; case 3: HC_UPW_R(3); break; case 2: HC_UPW_R(2); break; + default: HC_UPW_R(1); break; + } +#undef HC_UPW_R +#undef HC_UPW_K + } else if (fused) emit_rc = hc_up_mix_launch(up, (long)uld, f8, i8, dbuf, (const unsigned short*)h->data, (const float*)w->data, scale, (unsigned short*)x->data, @@ -4840,7 +5812,7 @@ extern "C" int r4d_rad_hc_read(const RadArgs* a, RadStream s) { q ? (float*)qs->data : nullptr, rq ? (unsigned char*)rq->data : nullptr, rq ? (float*)rqs->data : nullptr, mctr, rows, n, (int)hc, lr, - hrow, xrow, qrow, srow, rqrow, rsrow, wadd, s); + hrow, xrow, qrow, srow, rqrow, rsrow, wadd, s, hcg_ch); else emit_rc = hc_up_launch(up, (long)uld, f8, dbuf, ubuf, rows, HN, lr, s); if (emit_rc != RAD_OK) return R4D_NO(RAD_E_DEVICE); diff --git a/libr4d/r4d_moe.hip b/libr4d/r4d_moe.hip index 8ed82a09..db7a0661 100644 --- a/libr4d/r4d_moe.hip +++ b/libr4d/r4d_moe.hip @@ -42,6 +42,7 @@ #include "r4d_fp8_wmma.h" #include "r4d_plugin.h" #include "r4d_emit.h" +#include "r4d_chain.h" #include "r4d_gemm_args.h" #include "r4d_moe_sort.h" #include "r4d_moe_gather.h" @@ -677,8 +678,7 @@ constexpr uint32_t moe_waves(uint32_t ntl, int w4, bool es, bool al, uint32_t fk template -__global__ __launch_bounds__(WGM * WGN * kWave) R4D_WAVES(moe_waves(NTL, W4, ES, AL, FK, RS)) -void moe_gemm_q_kernel( +__device__ __forceinline__ void moe_gemm_q_kernel_body( const uint8_t* __restrict__ Aq, const float* __restrict__ As, const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3, const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, @@ -1431,6 +1431,36 @@ void moe_gemm_q_kernel( } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +template +__global__ __launch_bounds__(WGM * WGN * kWave) R4D_WAVES(moe_waves(NTL, W4, ES, AL, FK, RS)) +void moe_gemm_q_kernel( + const uint8_t* __restrict__ Aq, const float* __restrict__ As, + const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3, + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, + uint16_t* __restrict__ Y, const uint32_t* __restrict__ map, + uint32_t T, uint32_t N, uint32_t n_expert, uint32_t top_k, + uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) { + moe_gemm_q_kernel_body(Aq, As, c_even, c_odd, c_2, c_3, sorted, off, Y, map, T, N, n_expert, top_k, a_ld, as_ld, y_ld, mode, tab); +} +template +__global__ __launch_bounds__(WGM * WGN * kWave) R4D_WAVES(moe_waves(NTL, W4, ES, AL, FK, RS)) +void r4dchain_moe_gemm_q( + const uint8_t* __restrict__ Aq, const float* __restrict__ As, + const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3, + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, + uint16_t* __restrict__ Y, const uint32_t* __restrict__ map, + uint32_t T, uint32_t N, uint32_t n_expert, uint32_t top_k, + uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) { + r4d_chain_wait(); + moe_gemm_q_kernel_body(Aq, As, c_even, c_odd, c_2, c_3, sorted, off, Y, map, T, N, n_expert, top_k, a_ld, as_ld, y_ld, mode, tab); + r4d_chain_done(); +} + /* ================================================================== moe_gemm_q, the down decode form * * The sorted-operand projection at decode: one block per run tile, G column tiles per block. @@ -1463,7 +1493,7 @@ void moe_gemm_q_kernel( * Sorted operand only: a run's activation rows are [rs, re) of `Aq` with no gather. Every row in a * run is a placed slot (the scatter fills exactly [0, off[n_expert])), so `sorted` is not read. */ template -__global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( +__device__ __forceinline__ void moe_down_dec_kernel_body( const uint8_t* __restrict__ Aq, const float* __restrict__ As, const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3, const int32_t* __restrict__ off, uint16_t* __restrict__ Y, @@ -1769,6 +1799,28 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +template +__global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( + const uint8_t* __restrict__ Aq, const float* __restrict__ As, + const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3, + const int32_t* __restrict__ off, uint16_t* __restrict__ Y, + uint32_t T, uint32_t N, uint32_t n_expert, uint32_t G, + uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) { + moe_down_dec_kernel_body(Aq, As, c_even, c_odd, c_2, c_3, off, Y, T, N, n_expert, G, a_ld, as_ld, y_ld, mode, tab); +} +template +__global__ __launch_bounds__(4 * kWave) void r4dchain_moe_down_dec( + const uint8_t* __restrict__ Aq, const float* __restrict__ As, + const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3, + const int32_t* __restrict__ off, uint16_t* __restrict__ Y, + uint32_t T, uint32_t N, uint32_t n_expert, uint32_t G, + uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) { + r4d_chain_wait(); + moe_down_dec_kernel_body(Aq, As, c_even, c_odd, c_2, c_3, off, Y, T, N, n_expert, G, a_ld, as_ld, y_ld, mode, tab); + r4d_chain_done(); +} + /* One or a few routed rows at I4 with BF16 scales per 128 K (signed or a 16-entry codebook). * A block owns one sorted row and 64 columns; * the two halves of each wave read the same activation row and their own eight K bytes directly @@ -2848,6 +2900,9 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) { * rows take the aligned 32-row form; r4d_moe_decode_band has the crossover. */ const uint32_t ny = (uint32_t)(N / 64); const int form = g_moe_prefill_form; + /* The chained forms (r4d_chain.h) where the row resolved with `chain`, at decode heights. */ + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && + r4d_chain_rows_ok(a_sorted ? (T + top_k - 1) / top_k : M); if ((form == 0 && r4d_moe_decode_band(T, n_expert)) || form == 2) { /* The decode grid is (tile, run) wide (the kernel's ES note); decode has one tile of rows, * which alone would give only N/64 workgroups. */ @@ -2861,7 +2916,7 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) { if (dn_dec && g2 > 0) { const unsigned slots = (unsigned)(std::min(T, n_expert) + (T + 15) / 16); const unsigned groups = (unsigned)((N + 64 * g2 - 1) / (64 * g2)); - emit_rc = R4D_EMIT(stream, (moe_down_dec_kernel), + emit_rc = R4D_EMIT(stream, (ch ? &r4dchain_moe_down_dec : &moe_down_dec_kernel), dim3(slots + 1u, groups), dim3(4 * kWave), 0, (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, (const int32_t*)off->data, (uint16_t*)Y->data, @@ -2878,6 +2933,9 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) { const bool rs = n_expert <= (long long)kMaxExpert; auto pick = [&](auto fk) { constexpr uint32_t F = decltype(fk)::value; + if (ch) + return rs ? &r4dchain_moe_gemm_q<1, 4, 1, 4, W4, true, false, false, F, true, true> + : &r4dchain_moe_gemm_q<1, 4, 1, 4, W4, true, false, false, F, true, false>; return rs ? &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true, true> : &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true, false>; }; @@ -3404,7 +3462,7 @@ struct RgGeom { /* `lg` is neither const nor __restrict__: every block writes it and the last one reads it back. */ template -__global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel( +__device__ __forceinline__ void router_gemm_topk_scatter_kernel_body( const uint16_t* __restrict__ A, const uint16_t* __restrict__ W, const uint16_t* __restrict__ Wg, uint16_t* lg, uint16_t* __restrict__ gate, int32_t* __restrict__ ids, uint16_t* __restrict__ w, int32_t* __restrict__ sorted, @@ -3472,6 +3530,28 @@ __global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel( scatter_small_place(sorted, off, cnt, g.M * g.top_k, g.n_local, sl); } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +template +__global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel( + const uint16_t* __restrict__ A, const uint16_t* __restrict__ W, + const uint16_t* __restrict__ Wg, uint16_t* lg, uint16_t* __restrict__ gate, + int32_t* __restrict__ ids, uint16_t* __restrict__ w, int32_t* __restrict__ sorted, + int32_t* __restrict__ off, int32_t* __restrict__ cnt, unsigned int* __restrict__ ctr, + RgGeom g, Protect prot) { + router_gemm_topk_scatter_kernel_body(A, W, Wg, lg, gate, ids, w, sorted, off, cnt, ctr, g, prot); +} +template +__global__ __launch_bounds__(NW * kWave) void r4dchain_router_gemm_topk_scatter( + const uint16_t* __restrict__ A, const uint16_t* __restrict__ W, + const uint16_t* __restrict__ Wg, uint16_t* lg, uint16_t* __restrict__ gate, + int32_t* __restrict__ ids, uint16_t* __restrict__ w, int32_t* __restrict__ sorted, + int32_t* __restrict__ off, int32_t* __restrict__ cnt, unsigned int* __restrict__ ctr, + RgGeom g, Protect prot) { + r4d_chain_wait(); + router_gemm_topk_scatter_kernel_body(A, W, Wg, lg, gate, ids, w, sorted, off, cnt, ctr, g, prot); + r4d_chain_done(); +} + /* The arrival counter belongs to the op instance and is taken at init, not on the launch path. * * It must persist between launches, zeroed (the last block resets it; a non-zero start would rank @@ -3645,9 +3725,12 @@ extern "C" int r4d_rad_router_gemm_topk_scatter(const RadArgs* a, RadStream stre g.sk = (uint32_t)cr.sk; g.tpb = (uint32_t)tpb; g.nrb = (uint32_t)nrb; g.skg = wg ? (uint32_t)cg.sk : 0u; const dim3 grid((unsigned)(nrb + (wg ? 1 : 0)), (unsigned)((M + 15) / 16)); + /* The chained form (r4d_chain.h) where the row resolved with `chain`. */ + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && r4d_chain_rows_ok(M); #define R4D_RG_L(OWN, NWV) \ - emit_rc = R4D_EMIT(stream, (router_gemm_topk_scatter_kernel), grid, \ + emit_rc = R4D_EMIT(stream, (ch ? &r4dchain_router_gemm_topk_scatter \ + : &router_gemm_topk_scatter_kernel), grid, \ dim3((NWV) * kWave), lds, \ (const uint16_t*)x->data, (const uint16_t*)wr->data, \ wg ? (const uint16_t*)wg->data : (const uint16_t*)nullptr, \ diff --git a/libr4d/r4d_qk_norm_rope_gate.hip b/libr4d/r4d_qk_norm_rope_gate.hip index a2b27c3c..38ec74db 100644 --- a/libr4d/r4d_qk_norm_rope_gate.hip +++ b/libr4d/r4d_qk_norm_rope_gate.hip @@ -19,6 +19,7 @@ #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" +#include "r4d_chain.h" #include "r4d_common.h" #include "rad_yarn.h" #include @@ -67,7 +68,7 @@ enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2, QK_KV_F8V4 = 3, QK_KV_K6V4 * writes that element and the head's v element into the cache at the token's slot, as E4M3 with * kv_store_fp8's arithmetic or as bf16 like kv_store_bf16 (see the store at the end). */ template -__global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( +__device__ __forceinline__ void r4d_qk_norm_rope_gate_kernel_body( const __hip_bfloat16* __restrict__ QG, const __hip_bfloat16* __restrict__ K, __hip_bfloat16* __restrict__ QO, __hip_bfloat16* __restrict__ KO, __hip_bfloat16* __restrict__ GO, @@ -274,6 +275,32 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +template +__global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( + const __hip_bfloat16* __restrict__ QG, const __hip_bfloat16* __restrict__ K, + __hip_bfloat16* __restrict__ QO, __hip_bfloat16* __restrict__ KO, + __hip_bfloat16* __restrict__ GO, + const void* __restrict__ WQ, const void* __restrict__ WK, + const void* __restrict__ CS, const void* __restrict__ POS, long cs_rows, + int nq, int nkv, int rot, float eps, float wadd, + int qg_pitch, int k_pitch, int cs_f32, int pos_i64, int w_f32, QkKvStore kvs) { + r4d_qk_norm_rope_gate_kernel_body(QG, K, QO, KO, GO, WQ, WK, CS, POS, cs_rows, nq, nkv, rot, eps, wadd, qg_pitch, k_pitch, cs_f32, pos_i64, w_f32, kvs); +} +template +__global__ __launch_bounds__(256) void r4dchain_qk_norm_rope_gate( + const __hip_bfloat16* __restrict__ QG, const __hip_bfloat16* __restrict__ K, + __hip_bfloat16* __restrict__ QO, __hip_bfloat16* __restrict__ KO, + __hip_bfloat16* __restrict__ GO, + const void* __restrict__ WQ, const void* __restrict__ WK, + const void* __restrict__ CS, const void* __restrict__ POS, long cs_rows, + int nq, int nkv, int rot, float eps, float wadd, + int qg_pitch, int k_pitch, int cs_f32, int pos_i64, int w_f32, QkKvStore kvs) { + r4d_chain_wait(); + r4d_qk_norm_rope_gate_kernel_body(QG, K, QO, KO, GO, WQ, WK, CS, POS, cs_rows, nq, nkv, rot, eps, wadd, qg_pitch, k_pitch, cs_f32, pos_i64, w_f32, kvs); + r4d_chain_done(); +} + // ============================================================ the cos/sin table // // The fused kernel reads a precomputed table instead of theta, and this fills it: one launch per @@ -376,7 +403,10 @@ static int qk_body(const RadArgs* args, RadStream stream, const QkKvStore& kvs) const int nh = (int)(nq + nkv); // One block per (token, head), 256 threads, one element per lane. The width is fixed at 256, not // fitted to the head count, so the sum of squares matches r4d_rmsnorm_bf16 (see the kernel). -#define R4D_QKG_L(H) emit_rc = R4D_EMIT(stream, (r4d_qk_norm_rope_gate_kernel), \ + /* The chained form (r4d_chain.h) where the row resolved with `chain`. */ + const bool ch = r4d_geti_or(args, "chain", 0) != 0 && r4d_chain_rows_ok(M); +#define R4D_QKG_L(H) emit_rc = R4D_EMIT(stream, (ch ? &r4dchain_qk_norm_rope_gate \ + : &r4d_qk_norm_rope_gate_kernel), \ dim3((int)M, nh), dim3(256), 0, (const __hip_bfloat16*)r4d_p(qg), \ (const __hip_bfloat16*)r4d_p(k), (__hip_bfloat16*)r4d_wp(qo), (__hip_bfloat16*)r4d_wp(ko), \ (__hip_bfloat16*)r4d_wp(go), r4d_p(wq), r4d_p(wk), r4d_p(cs), r4d_p(po), (long)cs_rows, \ diff --git a/libr4d/r4d_qsa_block_key_bf16.hip b/libr4d/r4d_qsa_block_key_bf16.hip index b7e6743a..5f1bcd57 100644 --- a/libr4d/r4d_qsa_block_key_bf16.hip +++ b/libr4d/r4d_qsa_block_key_bf16.hip @@ -30,6 +30,7 @@ #include "r4d_args.h" #include "rad_yarn.h" #include "r4d_emit.h" +#include "r4d_chain.h" #include "r4d_common.h" // r4d_wave_sum #include @@ -54,7 +55,7 @@ __device__ __forceinline__ int qbk_comp(int mode, int i, int s0, int s1, int s2) return i < s0 ? 0 : (i < s0 + s1 ? 1 : 2); } -__global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel( +__device__ __forceinline__ void qsa_block_key_kernel_body( const uint16_t* __restrict__ k, const float* __restrict__ w, const int32_t* __restrict__ page, const int32_t* __restrict__ bpos, uint16_t* __restrict__ out, @@ -124,6 +125,26 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel( ((__hip_bfloat16*)out)[(size_t)orow * o_ld + t] = __float2bfloat16(res); } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +__global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel( + const uint16_t* __restrict__ k, const float* __restrict__ w, + const int32_t* __restrict__ page, const int32_t* __restrict__ bpos, + uint16_t* __restrict__ out, + int n, int ratio, int rot, float eps, float wadd, float theta, float rscale, + long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc, RadYarn yarn) { + qsa_block_key_kernel_body(k, w, page, bpos, out, n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld, o_ld, mode, s0, s1, s2, bstep, mc, yarn); +} +__global__ __launch_bounds__(kMaxN) void r4dchain_qsa_block_key( + const uint16_t* __restrict__ k, const float* __restrict__ w, + const int32_t* __restrict__ page, const int32_t* __restrict__ bpos, + uint16_t* __restrict__ out, + int n, int ratio, int rot, float eps, float wadd, float theta, float rscale, + long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc, RadYarn yarn) { + r4d_chain_wait(); + qsa_block_key_kernel_body(k, w, page, bpos, out, n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld, o_ld, mode, s0, s1, s2, bstep, mc, yarn); + r4d_chain_done(); +} + } // namespace // k [M*ratio][n] bf16, `k_ld` elements a row (0 = n) @@ -144,7 +165,7 @@ static int r4d_qsa_block_key_bf16_emit(long k, long w, long page, long bpos, lon if (!o_ld) o_ld = n; /* n threads rounded up to whole waves for the block reduction (extra threads contribute 0). */ const int thr = ((n + 31) / 32) * 32; - return R4D_EMIT(stream, qsa_block_key_kernel, dim3((unsigned)M), dim3((unsigned)thr), 0, + return R4D_EMIT(stream, g_r4d_chain_arg ? &r4dchain_qsa_block_key : &qsa_block_key_kernel, dim3((unsigned)M), dim3((unsigned)thr), 0, (const uint16_t*)k, (const float*)w, (const int32_t*)page, (const int32_t*)bpos, (uint16_t*)out, n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld, o_ld, mode, s0, s1, s2, bstep, mc, yarn); @@ -217,6 +238,7 @@ extern "C" int r4d_rad_qsa_block_key(const RadArgs* a, RadStream stream) { if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || r4d_getf(a, "scale", 1.0) != 1.0))) return R4D_NO(RAD_E_INVAL); + const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0); return r4d_qsa_block_key_bf16_emit( r4d_addr(k), r4d_addr(w), r4d_addr(pg), r4d_addr(bp), r4d_addr(o), (int)M, (int)n, (int)ratio, (int)rot, diff --git a/libr4d/r4d_qsa_score_bf16.hip b/libr4d/r4d_qsa_score_bf16.hip index 3c4c5c29..b13a479e 100644 --- a/libr4d/r4d_qsa_score_bf16.hip +++ b/libr4d/r4d_qsa_score_bf16.hip @@ -20,6 +20,7 @@ #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" +#include "r4d_chain.h" #include "r4d_common.h" #include "r4d_gdn_wmma.h" @@ -242,7 +243,7 @@ constexpr long long kMxWavesTarget = 4096; constexpr long long kMxMinTiles = 4; template -__global__ __launch_bounds__(kMxWaves * kWave) void qsa_score_mx_kernel( +__device__ __forceinline__ void qsa_score_mx_kernel_body( const unsigned short* __restrict__ q, const unsigned short* __restrict__ bk, const int32_t* __restrict__ bt, const int32_t* __restrict__ cu, const int32_t* __restrict__ nc, float* __restrict__ out, @@ -334,6 +335,26 @@ __global__ __launch_bounds__(kMxWaves * kWave) void qsa_score_mx_kernel( } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +template +__global__ __launch_bounds__(kMxWaves * kWave) void qsa_score_mx_kernel( + const unsigned short* __restrict__ q, const unsigned short* __restrict__ bk, + const int32_t* __restrict__ bt, const int32_t* __restrict__ cu, + const int32_t* __restrict__ nc, float* __restrict__ out, + int M, int nb, int nseq, int tpw, int q_ld, int bk_ld, int bt_ld, int out_ld, int vec) { + qsa_score_mx_kernel_body(q, bk, bt, cu, nc, out, M, nb, nseq, tpw, q_ld, bk_ld, bt_ld, out_ld, vec); +} +template +__global__ __launch_bounds__(kMxWaves * kWave) void r4dchain_qsa_score_mx( + const unsigned short* __restrict__ q, const unsigned short* __restrict__ bk, + const int32_t* __restrict__ bt, const int32_t* __restrict__ cu, + const int32_t* __restrict__ nc, float* __restrict__ out, + int M, int nb, int nseq, int tpw, int q_ld, int bk_ld, int bt_ld, int out_ld, int vec) { + r4d_chain_wait(); + qsa_score_mx_kernel_body(q, bk, bt, cu, nc, out, M, nb, nseq, tpw, q_ld, bk_ld, bt_ld, out_ld, vec); + r4d_chain_done(); +} + /* Form override for tests (r4d_selftest compares the two): 0 = automatic, 1 = scalar, * 2 = matrix. Like r4d_gemm_fp8a8_pin_mw. */ int g_qsa_form = 0; @@ -374,7 +395,7 @@ static int r4d_qsa_score_bf16_emit(long q, long bk, long bt, long cu, long nc, l const unsigned gx = (unsigned)((tiles + tpw * kMxWaves - 1) / (tpw * kMxWaves)); const int vec = (out_ld % 4 == 0) && ((out & 15) == 0); #define RAD_QSA_MX(H) \ - emit_rc = R4D_EMIT(stream, (qsa_score_mx_kernel), dim3(gx, (unsigned)qt), \ + emit_rc = R4D_EMIT(stream, (g_r4d_chain_arg ? &r4dchain_qsa_score_mx : &qsa_score_mx_kernel), dim3(gx, (unsigned)qt), \ dim3(kMxWaves * kWave), 0, (const unsigned short*)q, \ (const unsigned short*)bk, \ (const int32_t*)bt, (const int32_t*)cu, (const int32_t*)nc, \ @@ -461,6 +482,7 @@ extern "C" int r4d_rad_qsa_score(const RadArgs* a, RadStream stream) { const long long qp = r4d_row_pitch(q), kp = r4d_row_pitch(bk); const long long tp = r4d_row_pitch(bt), op = r4d_row_pitch(o); if (qp < 0 || kp < 0 || tp < 0 || op < 0) return R4D_NO(RAD_E_STRIDE); + const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0); return r4d_qsa_score_bf16_emit(r4d_addr(q), r4d_addr(bk), r4d_addr(bt), r4d_addr(cu), r4d_addr(nc), r4d_addr(o), (int)M, (int)n, (int)heads, (int)nb, (int)nseq, diff --git a/libr4d/r4d_qsa_select_bf16.hip b/libr4d/r4d_qsa_select_bf16.hip index aeb3c285..91614ff9 100644 --- a/libr4d/r4d_qsa_select_bf16.hip +++ b/libr4d/r4d_qsa_select_bf16.hip @@ -20,6 +20,7 @@ #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" +#include "r4d_chain.h" #include "r4d_launch.h" // R4D_DYN_LDS #include "r4d_common.h" // the DPP wave scans @@ -129,7 +130,7 @@ __device__ __forceinline__ void counts_before(const uint32_t* wsum, int lane, in * entirely in the query's past when b * ratio + ratio - 1 <= pos. At decode this equals the * sequence's complete count. */ template -__global__ __launch_bounds__(kThreads) void qsa_select_kernel( +__device__ __forceinline__ void qsa_select_kernel_body( const float* __restrict__ score, const int32_t* __restrict__ bt, const int32_t* __restrict__ nc, const int32_t* __restrict__ pos, const int32_t* __restrict__ cu, @@ -294,6 +295,28 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +template +__global__ __launch_bounds__(kThreads) void qsa_select_kernel( + const float* __restrict__ score, const int32_t* __restrict__ bt, + const int32_t* __restrict__ nc, const int32_t* __restrict__ pos, + const int32_t* __restrict__ cu, + int32_t* __restrict__ sel, int32_t* __restrict__ nsel, int32_t* __restrict__ seqused, + int nb, int topk, int ratio, int nseq, int s_ld, int t_ld, int o_ld, int cap) { + qsa_select_kernel_body(score, bt, nc, pos, cu, sel, nsel, seqused, nb, topk, ratio, nseq, s_ld, t_ld, o_ld, cap); +} +template +__global__ __launch_bounds__(kThreads) void r4dchain_qsa_select( + const float* __restrict__ score, const int32_t* __restrict__ bt, + const int32_t* __restrict__ nc, const int32_t* __restrict__ pos, + const int32_t* __restrict__ cu, + int32_t* __restrict__ sel, int32_t* __restrict__ nsel, int32_t* __restrict__ seqused, + int nb, int topk, int ratio, int nseq, int s_ld, int t_ld, int o_ld, int cap) { + r4d_chain_wait(); + qsa_select_kernel_body(score, bt, nc, pos, cu, sel, nsel, seqused, nb, topk, ratio, nseq, s_ld, t_ld, o_ld, cap); + r4d_chain_done(); +} + /* ===================================================== the wide-launch path, for a prefill chunk * * Without the key cache the kernel above reads every key from global memory five times, and its @@ -1148,7 +1171,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, g_r4d_chain_arg ? &r4dchain_qsa_select : &qsa_select_kernel, 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, @@ -1168,6 +1191,7 @@ enum { QL_SCORE = 0, QL_BT = 1, QL_NC = 2, QL_POS = 3, QL_CU = 4, QL_SEL = 5, QL QL_SEQ = 7 }; extern "C" int r4d_rad_qsa_select(const RadArgs* a, RadStream stream) { + const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0); const RadTensor* sc = r4d_opt(a, QL_SCORE); const RadTensor* bt = r4d_opt(a, QL_BT); const RadTensor* nc = r4d_opt(a, QL_NC); diff --git a/libr4d/r4d_qsa_tail_store_bf16.hip b/libr4d/r4d_qsa_tail_store_bf16.hip index ceb83fed..7640fe3d 100644 --- a/libr4d/r4d_qsa_tail_store_bf16.hip +++ b/libr4d/r4d_qsa_tail_store_bf16.hip @@ -22,6 +22,7 @@ #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" +#include "r4d_chain.h" #include #include @@ -30,7 +31,7 @@ namespace { constexpr int kThreads = 256; -__global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel( +__device__ __forceinline__ void qsa_tail_store_kernel_body( const uint16_t* __restrict__ k, const int32_t* __restrict__ pos, const int32_t* __restrict__ cu, const int32_t* __restrict__ sidx, uint16_t* __restrict__ state, @@ -59,6 +60,24 @@ __global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel( for (int d = (int)threadIdx.x; d < n; d += kThreads) state[dst + d] = k[src + d]; } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +__global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel( + const uint16_t* __restrict__ k, const int32_t* __restrict__ pos, + const int32_t* __restrict__ cu, const int32_t* __restrict__ sidx, + uint16_t* __restrict__ state, + int T, int n, int ring, int seqs, int slots, int k_ld, int s_slot, int s_row, int sidx_ld) { + qsa_tail_store_kernel_body(k, pos, cu, sidx, state, T, n, ring, seqs, slots, k_ld, s_slot, s_row, sidx_ld); +} +__global__ __launch_bounds__(kThreads) void r4dchain_qsa_tail_store( + const uint16_t* __restrict__ k, const int32_t* __restrict__ pos, + const int32_t* __restrict__ cu, const int32_t* __restrict__ sidx, + uint16_t* __restrict__ state, + int T, int n, int ring, int seqs, int slots, int k_ld, int s_slot, int s_row, int sidx_ld) { + r4d_chain_wait(); + qsa_tail_store_kernel_body(k, pos, cu, sidx, state, T, n, ring, seqs, slots, k_ld, s_slot, s_row, sidx_ld); + r4d_chain_done(); +} + } // namespace // k [T][n] bf16, `k_ld` elements a row (0 = n) @@ -75,7 +94,7 @@ static int r4d_qsa_tail_store_bf16_emit(long k, long pos, long cu, long sidx, lo if (!k_ld) k_ld = n; if (!s_row) s_row = n; if (!sidx_ld) sidx_ld = 1; - return R4D_EMIT(stream, qsa_tail_store_kernel, dim3((unsigned)T), dim3(kThreads), 0, + return R4D_EMIT(stream, g_r4d_chain_arg ? &r4dchain_qsa_tail_store : &qsa_tail_store_kernel, dim3((unsigned)T), dim3(kThreads), 0, (const uint16_t*)k, (const int32_t*)pos, (const int32_t*)cu, (const int32_t*)sidx, (uint16_t*)state, T, n, ring, seqs, slots, k_ld, s_slot, s_row, sidx_ld); @@ -113,6 +132,7 @@ extern "C" int r4d_rad_qsa_tail_store(const RadArgs* a, RadStream stream) { const long long kp = r4d_row_pitch(k); if (kp < 0) return R4D_NO(RAD_E_STRIDE); if (k->dtype != RAD_BF16 || st->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0); return r4d_qsa_tail_store_bf16_emit(r4d_addr(k), r4d_addr(po), r4d_addr(cu), r4d_addr(sx), r4d_addr(st), (int)T, (int)n, (int)ring, (int)seqs, (int)st->shape[0], (int)kp, (int)st->stride[0], diff --git a/libr4d/r4d_qsa_work_bf16.hip b/libr4d/r4d_qsa_work_bf16.hip index 5a052ff2..6cedb868 100644 --- a/libr4d/r4d_qsa_work_bf16.hip +++ b/libr4d/r4d_qsa_work_bf16.hip @@ -21,6 +21,7 @@ #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" +#include "r4d_chain.h" #include #include @@ -32,7 +33,7 @@ constexpr int kThreads = 128; * row constraint on the declared seqs (rad-convert declares 256, which must still resolve). */ constexpr int kMaxSeq = 256; -__global__ __launch_bounds__(kThreads) void qsa_work_kernel( +__device__ __forceinline__ void qsa_work_kernel_body( const uint16_t* __restrict__ k, const int32_t* __restrict__ pos, const int32_t* __restrict__ cu, const uint16_t* __restrict__ state, const int32_t* __restrict__ sidx, const int32_t* __restrict__ bt, @@ -113,6 +114,32 @@ __global__ __launch_bounds__(kThreads) void qsa_work_kernel( } } +/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */ +__global__ __launch_bounds__(kThreads) void qsa_work_kernel( + const uint16_t* __restrict__ k, const int32_t* __restrict__ pos, + const int32_t* __restrict__ cu, const uint16_t* __restrict__ state, + const int32_t* __restrict__ sidx, const int32_t* __restrict__ bt, + uint16_t* __restrict__ stage, int32_t* __restrict__ page, int32_t* __restrict__ bpos, + int32_t* __restrict__ nc, + int n, int ratio, int ring, int seqs, int max_work, int k_ld, int s_slot, int s_row, + int sidx_ld, int bt_ld, int g_ld, const int32_t* __restrict__ rope, int rplane, + int bstep) { + qsa_work_kernel_body(k, pos, cu, state, sidx, bt, stage, page, bpos, nc, n, ratio, ring, seqs, max_work, k_ld, s_slot, s_row, sidx_ld, bt_ld, g_ld, rope, rplane, bstep); +} +__global__ __launch_bounds__(kThreads) void r4dchain_qsa_work( + const uint16_t* __restrict__ k, const int32_t* __restrict__ pos, + const int32_t* __restrict__ cu, const uint16_t* __restrict__ state, + const int32_t* __restrict__ sidx, const int32_t* __restrict__ bt, + uint16_t* __restrict__ stage, int32_t* __restrict__ page, int32_t* __restrict__ bpos, + int32_t* __restrict__ nc, + int n, int ratio, int ring, int seqs, int max_work, int k_ld, int s_slot, int s_row, + int sidx_ld, int bt_ld, int g_ld, const int32_t* __restrict__ rope, int rplane, + int bstep) { + r4d_chain_wait(); + qsa_work_kernel_body(k, pos, cu, state, sidx, bt, stage, page, bpos, nc, n, ratio, ring, seqs, max_work, k_ld, s_slot, s_row, sidx_ld, bt_ld, g_ld, rope, rplane, bstep); + r4d_chain_done(); +} + } // namespace // k [T][n] bf16, this step's raw index keys @@ -140,7 +167,7 @@ static int r4d_qsa_work_bf16_emit(long k, long pos, long cu, long state, long si if (!s_row) s_row = n; if (!g_ld) g_ld = n; if (!sidx_ld) sidx_ld = 1; - return R4D_EMIT(stream, qsa_work_kernel, dim3((unsigned)max_work), dim3(kThreads), 0, + return R4D_EMIT(stream, g_r4d_chain_arg ? &r4dchain_qsa_work : &qsa_work_kernel, dim3((unsigned)max_work), dim3(kThreads), 0, (const uint16_t*)k, (const int32_t*)pos, (const int32_t*)cu, (const uint16_t*)state, (const int32_t*)sidx, (const int32_t*)bt, (uint16_t*)stage, (int32_t*)page, (int32_t*)bpos, (int32_t*)nc, n, ratio, @@ -211,6 +238,7 @@ extern "C" int r4d_rad_qsa_work(const RadArgs* a, RadStream stream) { const long long bp2 = r4d_row_pitch(bt), sp = r4d_row_pitch(st); if (kp < 0 || bp2 < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE); if (k->dtype != RAD_BF16 || tl->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0); return r4d_qsa_work_bf16_emit(r4d_addr(k), r4d_addr(po), r4d_addr(cu), r4d_addr(tl), r4d_addr(sx), r4d_addr(bt), r4d_addr(st), r4d_addr(pg), r4d_addr(bp), r4d_addr(nc), (int)n, (int)ratio, (int)ring, diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 8a2d0a99..a6373f78 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -11154,6 +11154,21 @@ extern "C" int rad_kernel_chain(int i) { "dflash_select_bf16", "dflash_tree_bf16", /* the weight read beside a collective (its blocks add before reading, r4d_prefetch.hip) */ "prefetch", + /* Flash-Next at decode heights: the MoE block */ + "router_gemm_topk_scatter_bf16", "moe_gemm_fp8a8", "moe_gemm_fp8a8_mod4", "gated_quant_fp8", + /* ...and the rest of a delta-net layer */ + "hc_read_bf16", "hc_read_e4m3", "gdn_recurrent_update_k128_v128_bf16_fp32state", + "gdn_conv_recurrent_update_k128_v128_bf16", "ar_hc_write", "ar_gather_hc_write", + /* the four-bit routed experts and their rotated quantiser */ + "moe_gemm_w4a8", "moe_gemm_w4a8_mod4", "gated_had_quant_fp8", "gated_had_quant_i8g", + /* ...and an attention layer: the indexer, the norm/rope/gate, the quantiser before o_proj + * and the gqa6 decode rows (their split-KV decode and merge already have chained forms) */ + "qk_norm_rope_gate", "qsa_work_bf16", "qsa_block_key_bf16", "qsa_tail_store_bf16", + "qsa_score_bf16", "qsa_select_i32", "gate_quant_fp8", + "attn_decode_h256_gqa6_fp8kv", "attn_decode_h256_gqa6_fp8v4", "attn_decode_h256_gqa6_k6v4", + "attn_decode_h256_gqa6_bf16kv", "attn_decode_h256_gqa6_bs4_fp8kv", + "attn_decode_h256_gqa6_bs4_bf16kv", "attn_decode_gq_h256_gqa6_bs4_fp8kv", + "attn_decode_gq_h256_gqa6_bs4_bf16kv", }; for (const char* p : kChained) if (std::strcmp(k->name, p) == 0) return 1; diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 3f05a2c3..c51a3ea7 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -20276,15 +20276,21 @@ static void hc_read_i8(const Plugin& pl, int64_t M, bool real_stream, int form) : "the int8 run changed" + bad); } -/* The gated residual's read at its decode kernels, byte for byte: the launcher's rule (kernels A and - * B as one grid at one to seven rows, the tiled up-mix pipelined from eight) against the two-grid - * form, pinned through r4d_hc_read_pin_decode(1). E4M3 or int8 codes, on a real stream (the - * one-grid form keys its counters on it). The two forms must dispatch different kernels, so a pin - * that is ignored cannot pass by comparing a form with itself. */ +/* The gated residual's read at its decode kernels: the launcher's rule against the two-grid form, + * pinned through r4d_hc_read_pin_decode(1). E4M3 or int8 codes, on a real stream (the one-grid + * form keys its counters on it). The two forms must dispatch different kernels, so a pin that is + * ignored cannot pass by comparing a form with itself. + * + * Up to sixteen rows at this shape the rule serves decode forms G (1..8) and S (9..16) with kernel + * B3: bf16 WMMA dots, S scaling after the dot. Byte for byte they match neither the per-row kernels + * nor the tiled ones, so there d is held to an fp64 host reference - no further from it than the + * two-grid form's d - the inject gains must match byte for byte, and x must stay within rounding of + * the two-grid form's. Above sixteen rows both forms are the tiled path's and match byte for byte. */ static void hc_decode_forms(const Plugin& pl, int64_t M, bool i8) { - const std::string nm = fmt("hc_read_e4m3 decode kernels at M=%lld, %s codes: the rule " - "byte-identical to the two-grid form", (long long)M, - i8 ? "int8" : "E4M3"); + const bool level = M <= 16; + const std::string nm = fmt("hc_read_e4m3 decode kernels at M=%lld, %s codes: the rule %s the " + "two-grid form", (long long)M, i8 ? "int8" : "E4M3", + level ? "as exact as" : "byte-identical to"); const RadKernelInfo* r = find(pl, "hc_read_e4m3"); if (!r) { skip(nm.c_str(), "row absent"); return; } if (!pl.pin_hc_dec || !pl.record) { skip(nm.c_str(), "no r4d_hc_read_pin_decode"); return; } @@ -20359,6 +20365,7 @@ static void hc_decode_forms(const Plugin& pl, int64_t M, bool i8) { } struct Out { std::vector x, inj, q, qs, rq, rs; std::vector fns; }; Out out[2]; + std::vector dsv[2]; /* d: the scratch's first M x lr bf16 values */ for (int form = 0; form < 2; ++form) { pl.pin_hc_dec(form); st_memset(d_x, 0, xb); st_memset(d_q, 0, qb); st_memset(d_qs, 0, sb); @@ -20379,19 +20386,87 @@ static void hc_decode_forms(const Plugin& pl, int64_t M, bool i8) { }; get(out[form].x, d_x, xb); get(out[form].inj, d_inj, ib); get(out[form].q, d_q, qb); get(out[form].qs, d_qs, sb); get(out[form].rq, d_rq, qb); get(out[form].rs, d_rs, sb); + if (a.scratch) { + dsv[form].resize((size_t)(M * lr * 2)); + st_memcpy(dsv[form].data(), a.scratch, dsv[form].size(), hipMemcpyDeviceToHost); + } } pl.pin_hc_dec(0); (void)hipStreamDestroy(hs); - std::string bad; - if (out[0].x != out[1].x) bad += " x"; - if (out[0].inj != out[1].inj) bad += " inj"; - if (out[0].q != out[1].q) bad += " q"; - if (out[0].qs != out[1].qs) bad += " qs"; - if (out[0].rq != out[1].rq) bad += " rq"; - if (out[0].rs != out[1].rs) bad += " rs"; int64_t nz = 0; for (uint8_t v : out[0].q) nz += v != 0; const bool distinct = out[0].fns != out[1].fns; + std::string bad; + if (!level) { + if (out[0].x != out[1].x) bad += " x"; + if (out[0].inj != out[1].inj) bad += " inj"; + if (out[0].q != out[1].q) bad += " q"; + if (out[0].qs != out[1].qs) bad += " qs"; + if (out[0].rq != out[1].rq) bad += " rq"; + if (out[0].rs != out[1].rs) bad += " rs"; + } else { + if (out[0].inj != out[1].inj) bad += " inj"; + if (dsv[0].empty()) bad += " (no scratch for d)"; + /* d against fp64: N unrounded, the dot over the decoded codes and their group scales. The + * error of each form as a fraction of the row's RMS of d, max and mean over every row. */ + const int64_t G = r4d_hc8::down_group(HN); + double emax[2] = { 0, 0 }, esum[2] = { 0, 0 }; + for (int64_t r0 = 0; r0 < M && !dsv[0].empty(); ++r0) { + std::vector N((size_t)HN); + for (int64_t c = 0; c < hc; ++c) { + double ss = 0; + for (int64_t j = 0; j < n; ++j) { + const double v = h_bf16(hh[(size_t)(r0 * HN + c * n + j)]); + ss += v * v; + } + const double sc = 1.0 / std::sqrt(ss / (double)n + 1e-6); + for (int64_t j = 0; j < n; ++j) + N[(size_t)(c * n + j)] = h_bf16(hh[(size_t)(r0 * HN + c * n + j)]) * sc + * ((double)wg[(size_t)(c * n + j)] + 1.0); + } + std::vector dref((size_t)lr); + double ssd = 0; + for (int64_t j = 0; j < lr; ++j) { + const uint8_t* row = down.data() + j * dld; + const float* gsc = (const float*)(row + HN); + double dot = 0; + for (int64_t kk = 0; kk < HN; ++kk) + dot += (double)h_e4m3(row[kk]) * (double)gsc[kk / G] * N[(size_t)kk]; + const double z = dot / (double)hc; + dref[(size_t)j] = z / (1.0 + std::exp(-z)); + ssd += dref[(size_t)j] * dref[(size_t)j]; + } + const double rms = std::sqrt(ssd / (double)lr) + 1e-30; + for (int f = 0; f < 2; ++f) { + const uint16_t* df = (const uint16_t*)dsv[f].data(); + for (int64_t j = 0; j < lr; ++j) { + const double e = std::fabs(h_bf16(df[r0 * lr + j]) - dref[(size_t)j]) / rms; + emax[f] = std::max(emax[f], e); + esum[f] += e; + } + } + } + const double cnt = (double)(M * lr); + if (esum[0] > esum[1] * 1.05 + 1e-6 * cnt || emax[0] > emax[1] * 1.10 + 1e-4) + bad += fmt(" d (rule %.5f / %.4f, two-grid %.5f / %.4f of RMS, mean / max)", + esum[0] / cnt, emax[0], esum[1] / cnt, emax[1]); + /* x: within rounding of the two-grid form's, as a fraction of the row's RMS. */ + const uint16_t* x0 = (const uint16_t*)out[0].x.data(); + const uint16_t* x1 = (const uint16_t*)out[1].x.data(); + double xmax = 0, xsum = 0; + for (int64_t r0 = 0; r0 < M; ++r0) { + double ss = 0; + for (int64_t j = 0; j < n; ++j) { const double v = h_bf16(x1[r0 * n + j]); ss += v * v; } + const double rms = std::sqrt(ss / (double)n) + 1e-30; + for (int64_t j = 0; j < n; ++j) { + const double e = std::fabs(h_bf16(x0[r0 * n + j]) - h_bf16(x1[r0 * n + j])) / rms; + xmax = std::max(xmax, e); + xsum += e; + } + } + if (xsum / (double)(M * n) > 0.005 || xmax > 0.15) + bad += fmt(" x (%.5f mean, %.4f max of RMS)", xsum / (double)(M * n), xmax); + } ok(nm.c_str(), bad.empty() && nz > (int64_t)qb / 2 && distinct, !bad.empty() ? "differs in" + bad : !distinct ? std::string("both forms dispatched the same kernels") @@ -33602,9 +33677,9 @@ static void device_phase(const Plugin& pl) { for (int form : { 1, 2 }) hc_read_i8(pl, m, true, form); for (int64_t m : { 700, 2048 }) hc_read_i8(pl, m, true, 3); } - /* The served decode kernels against the two-grid form: each one-grid instantiation (1 to - * 7 rows) and the tiled up-mix at both of its row tiles. */ - for (int64_t m : { 1, 2, 3, 4, 5, 6, 7, 8, 16, 32, 33, 64 }) + /* The served decode kernels against the two-grid form: each row count of form G (1 to 8), + * form S at 12 and 16 rows, and the tiled up-mix at both of its row tiles. */ + for (int64_t m : { 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 32, 33, 64 }) for (bool i8 : { false, true }) hc_decode_forms(pl, m, i8); } if (sel("hc_read_bf16")) {