diff --git a/libr4d/r4d_ar_twoshot_Nrank_exact.hip b/libr4d/r4d_ar_twoshot_Nrank_exact.hip index b384cf38..559d6e3b 100644 --- a/libr4d/r4d_ar_twoshot_Nrank_exact.hip +++ b/libr4d/r4d_ar_twoshot_Nrank_exact.hip @@ -357,7 +357,7 @@ __device__ __forceinline__ void r4d_ar_twoshot_coded_body( int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, int n16, int slot_stride16, int rank, int drain, int acq, int pub, long long* gate, unsigned int* gate_ctr) { - if (CHAIN) r4d_chain_wait(); + if (CHAIN) r4d_chain_wait_vec(); constexpr int NPEERS = WS - 1; const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; diff --git a/libr4d/r4d_attn_decode_h256_gqa6.hip b/libr4d/r4d_attn_decode_h256_gqa6.hip index ea9cd174..fdc82089 100644 --- a/libr4d/r4d_attn_decode_h256_gqa6.hip +++ b/libr4d/r4d_attn_decode_h256_gqa6.hip @@ -732,7 +732,7 @@ template(a, splits); r4d_chain_done(); } @@ -918,7 +918,7 @@ template __global__ __launch_bounds__(32 * JPB) void r4dchain_attn_splitkv_combine_vec(const R4DArgs a, int splits, int tile) { - r4d_chain_wait(); + r4d_chain_wait_vec(); splitkv_combine_vec_body(a, splits, tile, R4DGateQuant{}); r4d_chain_done(); @@ -1077,7 +1077,7 @@ template __global__ __launch_bounds__(HEAD_DIM) void r4dchain_attn_splitkv_combine(const R4DArgs a, int splits, int tile) { - r4d_chain_wait(); + r4d_chain_wait_vec(); splitkv_combine_body(a, splits, tile, R4DGateQuant{}); r4d_chain_done(); } diff --git a/libr4d/r4d_attn_paged_window.hip b/libr4d/r4d_attn_paged_window.hip index e0d71108..91c922d5 100644 --- a/libr4d/r4d_attn_paged_window.hip +++ b/libr4d/r4d_attn_paged_window.hip @@ -1131,7 +1131,7 @@ __global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) { } template __global__ __launch_bounds__(kThreads) void r4dchain_attn_window(AttnArgs A) { - r4d_chain_wait(); + r4d_chain_wait_vec(); attn_body(A); r4d_chain_done(); } @@ -1139,7 +1139,7 @@ template __global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { merge_body(A); } template __global__ __launch_bounds__(kThreads) void r4dchain_merge_window(AttnArgs A) { - r4d_chain_wait(); + r4d_chain_wait_vec(); merge_body(A); r4d_chain_done(); } diff --git a/libr4d/r4d_chain.h b/libr4d/r4d_chain.h index c22ad6ac..fc15c96c 100644 --- a/libr4d/r4d_chain.h +++ b/libr4d/r4d_chain.h @@ -34,6 +34,7 @@ struct R4dUnchained { static constexpr bool on = false; }; /* The host SIMT emulator (tests/r4d_emu) compiles some of these sources as C++: no engine record * ever reaches a launch there, so a chained form is its plain form. */ __device__ __forceinline__ void r4d_chain_wait() {} +__device__ __forceinline__ void r4d_chain_wait_vec() {} __device__ __forceinline__ void r4d_chain_done() {} #else @@ -80,9 +81,9 @@ __device__ __forceinline__ const R4dChainRec* r4d_chain_rec() { // The acquire behind a chained wait: the vector caches by the fence, the scalar data cache by // hand, which the fence leaves (see the head of this file). Every wave, for the compute unit it // runs on. -__device__ __forceinline__ void r4d_chain_acquire() { +__device__ __forceinline__ void r4d_chain_acquire(bool scalar = true) { __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent"); - asm volatile("s_dcache_inv" ::: "memory"); + if (scalar) asm volatile("s_dcache_inv" ::: "memory"); } #ifndef R4D_CHAIN_TINY @@ -94,7 +95,9 @@ __device__ __forceinline__ void r4d_chain_acquire() { #ifndef R4D_CHAIN_MID #define R4D_CHAIN_MID 4 #endif -__device__ __forceinline__ void r4d_chain_wait() { +// The wait itself; `Scalar` false leaves the scalar data cache alone (see r4d_chain_wait_vec). +template +__device__ __forceinline__ void r4d_chain_wait_impl() { const R4dChainRec* r = r4d_chain_rec(); if (!r) return; if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0) { @@ -116,9 +119,31 @@ __device__ __forceinline__ void r4d_chain_wait() { } } __syncthreads(); - r4d_chain_acquire(); + r4d_chain_acquire(Scalar); } +// The wait every kernel uses unless it has been shown not to need the scalar half of the acquire. +#ifdef R4D_CHAIN_SURVEY_NO_SCALAR +// Audit builds only (tests/chain_scalar_audit.py): every wait skips the instruction, so the audit +// lists the kernels that do scalar loads behind it. +__device__ __forceinline__ void r4d_chain_wait() { r4d_chain_wait_impl(); } +#else +__device__ __forceinline__ void r4d_chain_wait() { r4d_chain_wait_impl(); } +#endif + +// The wait of a kernel that reads nothing a launch in front wrote through a scalar load: no +// operand or scale of it is a value all lanes share and the compiler loads through the scalar +// data cache. Then the fence's vector-cache acquire is all the wait needs and `s_dcache_inv` +// (a scalar-cache flush and the refetch of every kernel argument after it) is left out. The +// kernel's instantiations all have to be free of such loads: tests/chain_scalar_audit.py +// compiles every unit and fails on a kernel that skips the instruction and has one, and +// R4D_CHAIN_SCINV_ALWAYS builds the library with the instruction behind every wait again. +#ifdef R4D_CHAIN_SCINV_ALWAYS +__device__ __forceinline__ void r4d_chain_wait_vec() { r4d_chain_wait_impl(); } +#else +__device__ __forceinline__ void r4d_chain_wait_vec() { r4d_chain_wait_impl(); } +#endif + // After the block's last write: release, then one add a block. __device__ __forceinline__ void r4d_chain_done() { const R4dChainRec* r = r4d_chain_rec(); diff --git a/libr4d/r4d_dflash_conv_t2_g16_bf16.hip b/libr4d/r4d_dflash_conv_t2_g16_bf16.hip index 60d874f9..614aff42 100644 --- a/libr4d/r4d_dflash_conv_t2_g16_bf16.hip +++ b/libr4d/r4d_dflash_conv_t2_g16_bf16.hip @@ -27,7 +27,7 @@ __global__ __launch_bounds__(DFC_THREADS) void r4dchain_dflash_conv( const r4d_u16* __restrict__ base, r4d_u16* __restrict__ out, int H, int dpitch, int NG, int vpr, int blockmask) { - r4d_chain_wait(); + r4d_chain_wait_vec(); const int hv = blockIdx.x * DFC_THREADS + threadIdx.x; r4d_dflash_conv_body(x, delta, base, out, H, dpitch, NG, vpr, blockmask, blockIdx.y, hv); diff --git a/libr4d/r4d_fused_quant_fp8.hip b/libr4d/r4d_fused_quant_fp8.hip index f1e81600..801afc79 100644 --- a/libr4d/r4d_fused_quant_fp8.hip +++ b/libr4d/r4d_fused_quant_fp8.hip @@ -250,7 +250,7 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(R4D_RQ_PARAMS) { } template __global__ __launch_bounds__(THR) void r4dchain_rmsnorm_quant(R4D_RQ_PARAMS) { - r4d_chain_wait(); + r4d_chain_wait_vec(); rmsnorm_quant_fp8_body(R4D_RQ_ARGS); r4d_chain_done(); } @@ -319,7 +319,7 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel(R4D_GQ_PARAMS) { } template __global__ __launch_bounds__(1024) void r4dchain_gated_quant(R4D_GQ_PARAMS) { - r4d_chain_wait(); + r4d_chain_wait_vec(); gated_quant_fp8_body(gu, y, q, s, n, nkb, gu_ld, y_ld, q_ld, s_ld); r4d_chain_done(); } @@ -403,7 +403,7 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(R4D_GTQ_PARAMS) { } template __global__ __launch_bounds__(1024) void r4dchain_gate_quant(R4D_GTQ_PARAMS) { - r4d_chain_wait(); + r4d_chain_wait_vec(); gate_quant_fp8_body(g, x, y, q, s, n, nkb, g_ld, x_ld, y_ld, q_ld, s_ld); r4d_chain_done(); } diff --git a/libr4d/r4d_gelu_mul_quant_i8.hip b/libr4d/r4d_gelu_mul_quant_i8.hip index 62f105a1..98e2d6fe 100644 --- a/libr4d/r4d_gelu_mul_quant_i8.hip +++ b/libr4d/r4d_gelu_mul_quant_i8.hip @@ -26,7 +26,7 @@ template __device__ __forceinline__ void gelu_mul_quant_i8_body( const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) { - if (CHAIN) r4d_chain_wait(); + if (CHAIN) r4d_chain_wait_vec(); extern __shared__ uint16_t ybuf[]; __shared__ float lm[THR / 32]; const uint32_t row = blockIdx.x; diff --git a/libr4d/r4d_gemm_bf16_nt_m64.hip b/libr4d/r4d_gemm_bf16_nt_m64.hip index fe824080..469ec804 100644 --- a/libr4d/r4d_gemm_bf16_nt_m64.hip +++ b/libr4d/r4d_gemm_bf16_nt_m64.hip @@ -55,7 +55,7 @@ template __device__ __forceinline__ void r4d_gemm_bf16_nt_m64_body( const unsigned short* __restrict__ A, const unsigned short* __restrict__ W, __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) { - if (CHAIN) r4d_chain_wait(); + if (CHAIN) r4d_chain_wait_vec(); extern __shared__ float red[]; // WV*SK*256 floats: one 16x16 tile per (column, split) const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32; const int col_local = wave / SK, ksplit = wave % SK; diff --git a/libr4d/r4d_gemm_fp8a8.hip b/libr4d/r4d_gemm_fp8a8.hip index 8b0003f9..13ef579e 100644 --- a/libr4d/r4d_gemm_fp8a8.hip +++ b/libr4d/r4d_gemm_fp8a8.hip @@ -865,7 +865,7 @@ __device__ __forceinline__ void gemm_i8_kpar_body(R4D_I8KPAR_PARAMS) { template __global__ __launch_bounds__(KW * kWave) R4D_WAVES(6) void gemm_i8_kpar_kernel(R4D_I8KPAR_PARAMS) { - if (CH::on) r4d_chain_wait(); + if (CH::on) r4d_chain_wait_vec(); gemm_i8_kpar_body(Ap, Sa, Bp, Sb, C, rows, cols, M, b_ld, sb_ld); if (CH::on) r4d_chain_done(); } diff --git a/libr4d/r4d_gemm_iqr.hip b/libr4d/r4d_gemm_iqr.hip index e367a432..a5213fce 100644 --- a/libr4d/r4d_gemm_iqr.hip +++ b/libr4d/r4d_gemm_iqr.hip @@ -364,7 +364,7 @@ __global__ __launch_bounds__((GATED ? 2u : 1u) * KW * kWave) R4D_WAVES(6) void iqr_m16_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restrict__ XS, uint16_t* __restrict__ Y, uint32_t N, uint32_t M, uint32_t x_ld, uint32_t xs_ld, GatedOut go) { - if (CH::on) r4d_chain_wait(); + if (CH::on) r4d_chain_wait_vec(); using D = Dec; static_assert(!GATED || NT == 1u, "the gated form serves one token tile"); constexpr bool BIAS = F::SC == kRowF32; @@ -754,7 +754,7 @@ __device__ __forceinline__ void iqr_m64_body(R4D_IQR_M64_PARAMS) { template __global__ __launch_bounds__(MW * kWave) R4D_WAVES(MW >= 8u ? 4u : 6u) void iqr_m64_kernel(R4D_IQR_M64_PARAMS) { - if (CH::on) r4d_chain_wait(); + if (CH::on) r4d_chain_wait_vec(); iqr_m64_body(c0, Bp, Sb, Y, C, Ctr, rows, cols, nb, b_ld, sb_ld, ck); if (CH::on) r4d_chain_done(); } diff --git a/libr4d/r4d_gemm_w2a8_nt.hip b/libr4d/r4d_gemm_w2a8_nt.hip index db07cb15..8bac249a 100644 --- a/libr4d/r4d_gemm_w2a8_nt.hip +++ b/libr4d/r4d_gemm_w2a8_nt.hip @@ -230,7 +230,7 @@ __device__ __forceinline__ void r4d_gemm_w2a8_nt_body(R4D_GEMM_W2A8_NT_PARAMS) { template __global__ __launch_bounds__(R4D_W2A8_BOUNDS(MT, NPW)) void r4d_gemm_w2a8_nt_kernel(R4D_GEMM_W2A8_NT_PARAMS) { - if (CH::on) r4d_chain_wait(); + if (CH::on) r4d_chain_wait_vec(); r4d_gemm_w2a8_nt_body(A, Ascale, Wq, Ws, Asum, C, M, K, N, WV, SK); if (CH::on) r4d_chain_done(); } diff --git a/libr4d/r4d_gemm_w4a8_nt_m64.hip b/libr4d/r4d_gemm_w4a8_nt_m64.hip index 594bf80f..d8f4f93d 100644 --- a/libr4d/r4d_gemm_w4a8_nt_m64.hip +++ b/libr4d/r4d_gemm_w4a8_nt_m64.hip @@ -104,7 +104,7 @@ __device__ __forceinline__ void r4d_gemm_w4a8_nt_m64_body( const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws, const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) { - if (CHAIN) r4d_chain_wait(); + if (CHAIN) r4d_chain_wait_vec(); extern __shared__ float red[]; const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32; const int col_local = wave / SK, ksplit = wave % SK; diff --git a/libr4d/r4d_gemm_w8a8_nt_m64.hip b/libr4d/r4d_gemm_w8a8_nt_m64.hip index f72a98ed..05800f24 100644 --- a/libr4d/r4d_gemm_w8a8_nt_m64.hip +++ b/libr4d/r4d_gemm_w8a8_nt_m64.hip @@ -234,7 +234,7 @@ __global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4dchain_gemm_w8a8_n const signed char* __restrict__ A, const float* __restrict__ Ascale, const unsigned* __restrict__ Wq, const unsigned short* __restrict__ Ws, __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) { - r4d_chain_wait(); + r4d_chain_wait_vec(); r4d_gemm_w8a8_nt_m64_body(A, Ascale, Wq, Ws, C, M, K, N, WV, SK); r4d_chain_done(); } diff --git a/libr4d/r4d_hc_bf16.hip b/libr4d/r4d_hc_bf16.hip index be482b0f..4e3e98e5 100644 --- a/libr4d/r4d_hc_bf16.hip +++ b/libr4d/r4d_hc_bf16.hip @@ -407,7 +407,7 @@ __device__ __forceinline__ void hc_enter_body(HC_ENTER_PARAMS) { template __global__ __launch_bounds__(kThreads) void hc_enter_kernel(HC_ENTER_PARAMS) { - if (CH::on) r4d_chain_wait(); + if (CH::on) r4d_chain_wait_vec(); hc_enter_body(x, h, rows, n, hc, xrow, hrow); if (CH::on) r4d_chain_done(); } @@ -2170,7 +2170,7 @@ void hc_read_fused_kernel(const unsigned short* __restrict__ h, const float* __r long qrow, long srow, long rqrow, long rsrow, float wadd, unsigned int* __restrict__ sync, unsigned na, unsigned gxa, unsigned gxb, unsigned nb_all) { - if (CH::on) r4d_chain_wait(); + if (CH::on) r4d_chain_wait_vec(); __shared__ unsigned s_ticket; if (threadIdx.x == 0) s_ticket = __hip_atomic_fetch_add(&sync[0], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); @@ -3076,7 +3076,7 @@ void hc_norm_down_tiled_kernel(const unsigned short* __restrict__ h, const float long kc, float wadd, unsigned int* __restrict__ ctr, unsigned int* __restrict__ sync, float eps, unsigned nn, unsigned gdx, unsigned gdy, unsigned gdz) { - if (CH::on) r4d_chain_wait(); + if (CH::on) r4d_chain_wait_vec(); __shared__ unsigned s_ticket; if (threadIdx.x == 0) s_ticket = __hip_atomic_fetch_add(&sync[0], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); @@ -3696,7 +3696,7 @@ __device__ __forceinline__ void hc_up_mix_tiled_body(HC_UMT_PARAMS) { template __global__ __launch_bounds__(kThreads) void hc_up_mix_tiled_kernel(HC_UMT_PARAMS) { - if (CH::on) r4d_chain_wait(); + if (CH::on) r4d_chain_wait_vec(); hc_up_mix_tiled_body(upv, uld, dbuf, h, w, scalein, x, q, qs, rq, rqs, ctr, rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd); @@ -4761,7 +4761,7 @@ __device__ __forceinline__ void mtp_enter_tiled_body(MTP_ENTER_TILED_PARAMS) { template __global__ __launch_bounds__(kThreads) void mtp_enter_tiled_kernel(MTP_ENTER_TILED_PARAMS) { - if (CH::on) r4d_chain_wait(); + if (CH::on) r4d_chain_wait_vec(); mtp_enter_tiled_body(h, e, wh, we, fchv, fcev, fld, x, rows, n, hc, flat, eps, wadd, hrow, erow, xrow); if (CH::on) r4d_chain_done(); } diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index 72a26f63..908c3ad7 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -267,7 +267,7 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel(R4D_RN_PARAMS) { } template __global__ __launch_bounds__(THR) void r4dchain_rmsnorm(R4D_RN_PARAMS) { - r4d_chain_wait(); + r4d_chain_wait_vec(); rmsnorm_body(x, w, y, n, eps, wadd, mult, x_ld, y_ld, M); r4d_chain_done(); } @@ -322,7 +322,7 @@ __global__ __launch_bounds__(THR) void add_rmsnorm_kernel(R4D_ARN_PARAMS) { } template __global__ __launch_bounds__(THR) void r4dchain_add_rmsnorm(R4D_ARN_PARAMS) { - r4d_chain_wait(); + r4d_chain_wait_vec(); add_rmsnorm_body(x, a, w, y, n, eps, wadd, mult, x_ld, a_ld, y_ld, M); r4d_chain_done(); } @@ -375,7 +375,7 @@ __global__ __launch_bounds__(kThreads) void binary_kernel(R4D_BIN_PARAMS) { binary_body(a, b, y, n, a_ld, b_ld, y_ld, mul, b_step, div); } __global__ __launch_bounds__(kThreads) void r4dchain_binary(R4D_BIN_PARAMS) { - r4d_chain_wait(); + r4d_chain_wait_vec(); binary_body(a, b, y, n, a_ld, b_ld, y_ld, mul, b_step, div); r4d_chain_done(); } @@ -447,7 +447,7 @@ __global__ __launch_bounds__(kThreads) void sigmoid_kernel(R4D_SIG_PARAMS) { sigmoid_body(x, y, n, x_ld, y_ld); } __global__ __launch_bounds__(kThreads) void r4dchain_sigmoid(R4D_SIG_PARAMS) { - r4d_chain_wait(); + r4d_chain_wait_vec(); sigmoid_body(x, y, n, x_ld, y_ld); r4d_chain_done(); } @@ -485,7 +485,7 @@ __global__ __launch_bounds__(kThreads) void logit_softcap_kernel_f32( __global__ __launch_bounds__(kThreads) void r4dchain_logit_softcap( const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) { - r4d_chain_wait(); + r4d_chain_wait_vec(); const uint32_t m = blockIdx.x; const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; @@ -496,7 +496,7 @@ __global__ __launch_bounds__(kThreads) void r4dchain_logit_softcap( __global__ __launch_bounds__(kThreads) void r4dchain_logit_softcap_f32( const float* __restrict__ x, float* __restrict__ y, uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) { - r4d_chain_wait(); + r4d_chain_wait_vec(); const uint32_t m = blockIdx.x; const float* __restrict__ xr = x + (size_t)m * x_ld; float* __restrict__ yr = y + (size_t)m * y_ld; @@ -562,7 +562,7 @@ __global__ __launch_bounds__(kThreads) void silu_mul_kernel(R4D_SM_PARAMS) { silu_mul_body(gu, y, n, gu_ld, y_ld); } __global__ __launch_bounds__(kThreads) void r4dchain_silu_mul(R4D_SM_PARAMS) { - r4d_chain_wait(); + r4d_chain_wait_vec(); silu_mul_body(gu, y, n, gu_ld, y_ld); r4d_chain_done(); } @@ -591,7 +591,7 @@ __global__ __launch_bounds__(kThreads) void gelu_mul_kernel(R4D_GM_PARAMS) { gelu_mul_body(gu, y, n, gu_ld, y_ld); } __global__ __launch_bounds__(kThreads) void r4dchain_gelu_mul(R4D_GM_PARAMS) { - r4d_chain_wait(); + r4d_chain_wait_vec(); gelu_mul_body(gu, y, n, gu_ld, y_ld); r4d_chain_done(); } diff --git a/libr4d/r4d_ple_gate_bf16.hip b/libr4d/r4d_ple_gate_bf16.hip index a3ebae01..a28513dd 100644 --- a/libr4d/r4d_ple_gate_bf16.hip +++ b/libr4d/r4d_ple_gate_bf16.hip @@ -133,7 +133,7 @@ __device__ __forceinline__ void ple_gate_body(PLE_GATE_PARAMS) { template __global__ __launch_bounds__(kPgThreads) void ple_gate_kernel(PLE_GATE_PARAMS) { - if (CH::on) r4d_chain_wait(); + if (CH::on) r4d_chain_wait_vec(); ple_gate_body(k, q, v, wk, wq, wc, gv, gvn, n, hc, k_ld, q_ld, v_ld, g_ld, gn_ld, eps, wadd, geps, per_thread); if (CH::on) r4d_chain_done(); } diff --git a/libr4d/r4d_prefetch.hip b/libr4d/r4d_prefetch.hip index 5c86a17a..5c3bbfb4 100644 --- a/libr4d/r4d_prefetch.hip +++ b/libr4d/r4d_prefetch.hip @@ -38,7 +38,7 @@ __global__ __launch_bounds__(256) void prefetch_kernel(const int4* __restrict__ * between a GEMM and the collective after it (where launches chain), it starts reading as the * GEMM's last block ends, with no event between the queues and no barrier bit on the GEMM. */ __global__ __launch_bounds__(256) void r4dchain_prefetch(const int4* __restrict__ p, size_t n16) { - r4d_chain_wait(); + r4d_chain_wait_vec(); r4d_chain_done(); const size_t tid = (size_t)blockIdx.x * blockDim.x + threadIdx.x; const size_t nt = (size_t)gridDim.x * blockDim.x; diff --git a/libr4d/r4d_quant_act_fp8.hip b/libr4d/r4d_quant_act_fp8.hip index 4aa8507d..385dce53 100644 --- a/libr4d/r4d_quant_act_fp8.hip +++ b/libr4d/r4d_quant_act_fp8.hip @@ -56,7 +56,7 @@ __device__ __forceinline__ void quant_act_fp8_body( const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t K, uint32_t nkb, uint32_t x_ld, uint32_t q_ld, uint32_t s_ld) { static_assert(SUB == 1 || (SUB == 2 && I8), "a 256 group is the int8 quantiser's"); - if (CHAIN) r4d_chain_wait(); + if (CHAIN) r4d_chain_wait_vec(); const uint32_t row = blockIdx.x; const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; const size_t xrow = (size_t)row * x_ld; diff --git a/libr4d/r4d_quant_act_i8.hip b/libr4d/r4d_quant_act_i8.hip index b6920eff..98077737 100644 --- a/libr4d/r4d_quant_act_i8.hip +++ b/libr4d/r4d_quant_act_i8.hip @@ -21,7 +21,7 @@ template __device__ __forceinline__ void r4d_quant_act_i8_body( const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S, int K) { - if (CHAIN) r4d_chain_wait(); + if (CHAIN) r4d_chain_wait_vec(); const int row = blockIdx.x; const __hip_bfloat16* a = A + (size_t)row * K; signed char* q = Q + (size_t)row * K; @@ -125,7 +125,7 @@ __device__ __forceinline__ void r4d_quant_act_i8_asum_body(R4D_QUANT_ACT_I8_ASUM template __global__ __launch_bounds__(THR) void r4d_quant_act_i8_asum_kernel(R4D_QUANT_ACT_I8_ASUM_PARAMS) { - if (CH::on) r4d_chain_wait(); + if (CH::on) r4d_chain_wait_vec(); r4d_quant_act_i8_asum_body(A, Q, S, Asum, K, group, Mpad); if (CH::on) r4d_chain_done(); } diff --git a/libr4d/r4d_rmsnorm_quant_i8.hip b/libr4d/r4d_rmsnorm_quant_i8.hip index a3955978..ccf0bb03 100644 --- a/libr4d/r4d_rmsnorm_quant_i8.hip +++ b/libr4d/r4d_rmsnorm_quant_i8.hip @@ -885,7 +885,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_sp_kernel(R4D_ARQ8S_P } template __global__ __launch_bounds__(THR) void r4dchain_ar_rmsnorm_quant_i8_sp(R4D_ARQ8S_PARAMS) { - r4d_chain_wait(); + r4d_chain_wait_vec(); ar_rmsnorm_quant_i8_sp_body(R4D_ARQ8S_ARGS); r4d_chain_done(); } diff --git a/libr4d/r4d_rowtopk_bf16.hip b/libr4d/r4d_rowtopk_bf16.hip index 3fbf63e3..77dd1541 100644 --- a/libr4d/r4d_rowtopk_bf16.hip +++ b/libr4d/r4d_rowtopk_bf16.hip @@ -193,7 +193,7 @@ template __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4dchain_rowtopk_stage1( const unsigned short* __restrict__ Y, unsigned long long* __restrict__ P, int N, int RC, int NCH, int CH) { - r4d_chain_wait(); + r4d_chain_wait_vec(); r4d_rowtopk_stage1_body(Y, P, N, RC, NCH, CH); r4d_chain_done(); } @@ -263,7 +263,7 @@ template __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4dchain_rowtopk_stage2( const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI, float* __restrict__ OP, int off, int R, int n) { - r4d_chain_wait(); + r4d_chain_wait_vec(); r4d_rowtopk_stage2_body(P, OV, OI, OP, off, R, n); r4d_chain_done(); } @@ -369,7 +369,7 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_merge_kernel( } __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4dchain_rowtopk_merge( const float* __restrict__ G, float* __restrict__ OV, int* __restrict__ OI, int R, int n) { - r4d_chain_wait(); + r4d_chain_wait_vec(); r4d_rowtopk_merge_body(G, OV, OI, R, n); r4d_chain_done(); } @@ -542,7 +542,7 @@ __device__ __forceinline__ void r4d_logit_rerank_body(R4D_LOGIT_RERANK_PARAMS) { template __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_RERANK_WPB) void r4d_logit_rerank_kernel(R4D_LOGIT_RERANK_PARAMS) { - if (CH::on) r4d_chain_wait(); + if (CH::on) r4d_chain_wait_vec(); r4d_logit_rerank_body(X, IN, W, OI, OV, OP, R, K, voff, nv, w_ld); if (CH::on) r4d_chain_done(); } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 550cb494..c24b9322 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -455,6 +455,20 @@ if(RAD_HIP_FOUND AND TARGET r4d_selftest) ENVIRONMENT "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home") endif() +# ================================================================== the chained waits' scalar-cache flush +# +# A chained kernel whose wait is r4d_chain_wait_vec skips `s_dcache_inv` (libr4d/r4d_chain.h). This +# compiles every unit with a chained kernel to gfx1201 assembly with the build's own flags and fails +# on a kernel that skips it and has a scalar load, from anything but its argument segment, behind +# its acquire. No card needed; it recompiles the kernels (minutes), hence `slow`. +find_package(Python3 QUIET COMPONENTS Interpreter) +if(RAD_HIP_FOUND AND Python3_FOUND AND CMAKE_EXPORT_COMPILE_COMMANDS) + add_test(NAME chain_scalar_audit + COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/chain_scalar_audit.py + ${CMAKE_BINARY_DIR} ${CMAKE_BINARY_DIR}/chain_scalar_audit --check) + set_tests_properties(chain_scalar_audit PROPERTIES LABELS "slow" TIMEOUT 1800) +endif() + # ================================================================== libhalo's interface parity # # libhalo serves gfx1151 behind libr4d's exact interface (libhalo/halo_parity.cpp): the same op diff --git a/tests/chain_scalar_audit.py b/tests/chain_scalar_audit.py new file mode 100644 index 00000000..0842b742 --- /dev/null +++ b/tests/chain_scalar_audit.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""chain_scalar_audit.py BUILD_DIR OUT_DIR [--check] + +A chained wait ends with an acquire: the agent-scope fence for the vector caches and, unless the kernel's wait is the +variant that leaves it out, `s_dcache_inv` for the scalar data cache (libr4d/r4d_chain.h). A kernel may use that +variant only when nothing it reads behind the wait goes through a scalar load. This audit compiles every HIP unit that +holds a chained kernel to gfx1201 assembly with the build's own flags (compile_commands.json) and checks each chained +(`r4dchain`) kernel: one that has no `s_dcache_inv` must have no scalar load, from a base other than the kernel +argument segment (s[0:1]), behind its in-kernel acquire (`global_inv` at device or system scope). + +--list also lists the kernels that keep it, with their scalar-load counts. +--check exits 1 when a kernel breaks that rule. Without it the kernels that skip the instruction are listed.""" +import json, sys, os, re, shlex, subprocess, concurrent.futures as cf + +args = [a for a in sys.argv[1:] if not a.startswith("--")] +bd, out = os.path.abspath(args[0]), os.path.abspath(args[1]) +check = "--check" in sys.argv +os.makedirs(out, exist_ok=True) +cc = json.load(open(bd + "/compile_commands.json")) +units = [e for e in cc if e["file"].endswith(".hip") and + ("/libr4d/" in e["file"] or "/core/device/" in e["file"] or "/core/sched/" in e["file"])] + + +def sregs(t): + """The scalar registers an operand names, [] for anything else (v, exec, vcc, an immediate).""" + m = re.fullmatch(r"s\[(\d+):(\d+)\]", t) + if m: + return list(range(int(m.group(1)), int(m.group(2)) + 1)) + m = re.fullmatch(r"s(\d+)", t) + return [int(m.group(1))] if m else [] + + +def run(e): + a = shlex.split(e["command"]) + o = [] + i = 0 + while i < len(a): + if a[i] == "-o": + i += 2; continue + if a[i] == "-c": + i += 1; continue + if a[i].startswith("--offload-arch=") and a[i] != "--offload-arch=gfx1201": + i += 1; continue + if a[i] == "--no-offload-compress": + i += 1; continue + o.append(a[i]); i += 1 + s = out + "/" + os.path.basename(e["file"]) + ".s" + o += shlex.split(os.environ.get("AUDIT_FLAGS", "")) + if "--reuse" in sys.argv and os.path.exists(s): + return s + o = [x for x in o if x != e["file"]] + ["--offload-device-only", "-S", "-o", s, e["file"]] + r = subprocess.run(o, cwd=e["directory"], capture_output=True, text=True) + if r.returncode: + print("FAIL", e["file"], r.stderr[-400:]) + return None + return s + + +with cf.ThreadPoolExecutor(int(os.environ.get("J", "24"))) as ex: + sfs = [s for s in ex.map(run, units) if s] +bad = nk = skip = keep = 0 +for fn in sorted(sfs): + cur = None + rows = [] + for line in open(fn, errors="replace"): + m = re.match(r"^(_Z\S+):\s*; @", line) + if m: + cur = {"name": m.group(1), "inv": 0, "dc": 0, "after": 0, "ex": [], "k": {0, 1}} + rows.append(cur) + continue + if cur is None: + continue + s = line.strip() + if not s or s.startswith((".", ";")): + continue + if s.startswith("global_inv") and ("SCOPE_DEV" in s or "SCOPE_SYS" in s): + cur["inv"] += 1 + if s.startswith("s_dcache_inv"): + cur["dc"] += 1 + ops = [o.strip() for o in s.split(None, 1)[1].split(",")] if " " in s else [] + op = s.split()[0] + if op.startswith(("s_load_", "s_buffer_load_")) and len(ops) >= 2: + if op.startswith("s_buffer"): + base = None + else: + base = sregs(ops[1]) + if cur["inv"] > 0 and not (base and all(r in cur["k"] for r in base)): + cur["after"] += 1 + if len(cur["ex"]) < 2: + cur["ex"].append(s) + for r in sregs(ops[0]): + cur["k"].discard(r) + elif ops and sregs(ops[0]) and not op.startswith(("s_cmp", "s_bitcmp", "s_wait", "s_cbranch")): + d = sregs(ops[0]) + srcs = [sregs(o) for o in ops[1:]] + src0 = srcs[0] if srcs else [] + derived = False + if op in ("s_mov_b64", "s_mov_b32") and src0: + derived = all(r in cur["k"] for r in src0) + elif op in ("s_add_nc_u64", "s_add_u32", "s_add_co_u32", "s_add_nc_u32", "s_add_co_ci_u32", "s_addc_u32") and src0: + derived = all(r in cur["k"] for r in src0) + elif op == "s_cselect_b32" and src0: + derived = all(r in cur["k"] for r in src0) + if derived: + cur["k"].update(d) + elif op not in ("s_cselect_b32",) or True: + for r in d: + cur["k"].discard(r) + for r in rows: + if "r4dchain" not in r["name"]: + continue + nk += 1 + if r["dc"]: + keep += 1 + if "--list" in sys.argv: + print("keeps s_dcache_inv: %-90s scalar loads behind the acquire: %d" % (r["name"][:90], r["after"])) + continue + skip += 1 + if r["after"]: + bad += 1 + print("%s skips s_dcache_inv: %-90s scalar loads behind the acquire: %d %s" % + ("BAD" if r["after"] else "ok ", r["name"][:90], r["after"], r["ex"])) +print("chained kernels %d: keep s_dcache_inv %d, skip it %d, of those with a scalar load behind the acquire %d" % + (nk, keep, skip, bad)) +sys.exit(1 if (check and bad) else 0)