Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
prefill: #313 RDNA3 WMMA dense GEMMs (opt-in STRATA_WMMA_GEMM=1), its GEMM part, on gfx1151 too
Niko122141c89b170811
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 258c21aee..40db3c68a 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -400,7 +400,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)# what composes them into a token. No tokenizer - the prompt arrives as ids - because Gate C1 compares logits# against llama.cpp on the SAME ids and a tokenizer on one side of that comparison is a second variable.# plan v0.3 P5: batched prompt processing (tensor-core GEMMs through cuBLAS).- add_library(strata_prefill STATIC src/prefill/gemm.cu src/prefill/kernels.cu src/prefill/prefill.cpp)+ add_library(strata_prefill STATIC src/prefill/gemm.cu src/prefill/wmma_gemm.cu src/prefill/kernels.cu src/prefill/prefill.cpp)target_include_directories(strata_prefill PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories})target_link_libraries(strata_prefill PUBLIC strata_engine ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target})if(STRATA_ENABLE_HIP AND STRATA_HIPBLASLT_AVAILABLE)@@ -460,6 +460,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)target_link_libraries(hip_gdn_rec_head PRIVATE strata_prefill strata_hip_runtime)add_test(NAME hip_gdn_rec_head COMMAND hip_gdn_rec_head)list(APPEND _strata_hip_tests hip_gdn_rec_head)+ # #313: the RDNA3 / RDNA3.5 WMMA dense GEMMs (opt-in STRATA_WMMA_GEMM=1) against a reference+ add_executable(hip_prefill_wmma_gemm_parity tests/hip/prefill_wmma_gemm_parity.cpp)+ target_include_directories(hip_prefill_wmma_gemm_parity PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill")+ target_link_libraries(hip_prefill_wmma_gemm_parity PRIVATE strata_prefill strata_hip_runtime)+ add_test(NAME hip_prefill_wmma_gemm_parity COMMAND hip_prefill_wmma_gemm_parity)+ list(APPEND _strata_hip_tests hip_prefill_wmma_gemm_parity)# S6: the AMD fast router against the portable kernel, bitwiseadd_executable(hip_router_fast tests/hip/router_fast.cpp)target_link_libraries(hip_router_fast PRIVATE strata_kernels strata_hip_runtime)diff --git a/cmake/hip_backend.cmake b/cmake/hip_backend.cmakeindex 517656067..7fb62ecd7 100644--- a/cmake/hip_backend.cmake+++ b/cmake/hip_backend.cmake@@ -68,6 +68,11 @@ add_library(strata_hip_runtime INTERFACE)target_include_directories(strata_hip_runtime BEFORE INTERFACE"${STRATA_HIP_COMPAT_INCLUDE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include")target_compile_definitions(strata_hip_runtime INTERFACE STRATA_USE_HIP=1 "STRATA_HIP_ARCHS=\"${STRATA_HIP_ARCHS}\"")+# #313: the RDNA3 WMMA GEMM's intrinsics only compile for gfx11 targets and the host pass does not define+# __gfx11xx__, so the build supplies the macro for gfx11 configs (the kernels also gate on the device at runtime)+if(CMAKE_HIP_ARCHITECTURES MATCHES "gfx11")+ target_compile_definitions(strata_hip_runtime INTERFACE STRATA_WMMA_GFX11=1)+endif()target_link_libraries(strata_hip_runtime INTERFACE hip::host)# The shim renames the CUDA runtime to HIP, force-included into every host and device source. On Windows the host# compiler is ROCm's clang++ too (tools/hip/build_windows.bat: CMake refuses to mix cl.exe with Clang HIP), which takesdiff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cuindex bb6ef045b..2cfd6de5a 100644--- a/src/prefill/gemm.cu+++ b/src/prefill/gemm.cu@@ -2,6 +2,10 @@#include "strata/prefill/gemm.hpp"#include "strata/kernels/dequant_bf16.hpp"+#ifdef STRATA_USE_HIP+#include "wmma_gemm.h"+#endif+#include <cublas_v2.h>#include <cuda_runtime.h>@@ -376,6 +380,16 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64float beta) {if (T <= 0 || N <= 0) return;if (ldy <= 0) ldy = N;+#ifdef STRATA_USE_HIP+ // #313 (opt-in STRATA_WMMA_GEMM=1; STRATA_WMMA_BF16=0 excludes bf16): RDNA3 / RDNA3.5 WMMA dense GEMM, before+ // hipBLASLt; it returns false for shapes it does not take (and off gfx11) and this falls through+ static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }();+ static const bool bf16_on = [] { const char* v = std::getenv("STRATA_WMMA_BF16"); return !v || (v[0] != 0 && v[0] != '0'); }();+ if (wmma_on && bf16_on && T >= 16 && (beta == 0.0f || beta == 1.0f) &&+ strata_wmma_gemm_bf16(X, W, Y, T, N, K, ldy, beta, stream_)) {+ return;+ }+#endifconst float alpha = 1.0f;#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, X, W, Y, T, N, K, ldy,@@ -396,6 +410,14 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_float beta) {if (T <= 0 || N <= 0) return;if (ldy <= 0) ldy = N;+#ifdef STRATA_USE_HIP+ // #313 (opt-in STRATA_WMMA_GEMM=1): RDNA3 / RDNA3.5 WMMA dense GEMM, before hipBLASLt (falls through when false)+ static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }();+ if (wmma_on && T >= 16 && (beta == 0.0f || beta == 1.0f) &&+ strata_wmma_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) {+ return;+ }+#endifconst float alpha = 1.0f;#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::f16, X, W, Y, T, N, K, ldy,diff --git a/src/prefill/wmma_gemm.cu b/src/prefill/wmma_gemm.cunew file mode 100644index 000000000..95af08286--- /dev/null+++ b/src/prefill/wmma_gemm.cu@@ -0,0 +1,298 @@+// src/prefill/wmma_gemm.cu - RDNA3 WMMA FP16 & BF16 GEMM for Strata prefill (gfx1100).+//+// Computes Y[t, n] = beta * Y[t, n] + sum_k W[n, k] * X[t, k] using RDNA3 WMMA intrinsics:+// * X is T x K row-major (leading dim K), fp16 or bf16+// * W is N x K row-major (leading dim K), fp16 or bf16+// * Y is T x N row-major with leading dimension ldy >= N, fp32+//+// Hardware: AMD RDNA3 (gfx1100, e.g. RX 7900 XTX)+// * v_wmma_f32_16x16x16_f16_w32 intrinsic (__builtin_amdgcn_wmma_f32_16x16x16_f16_w32)+// * v_wmma_f32_16x16x16_bf16_w32 intrinsic (__builtin_amdgcn_wmma_f32_16x16x16_bf16_w32)+// * Wave32 doubled input fragment: lane t (lane_lo = t & 15) holds row lane_lo of A (16 elements along K)+// and column lane_lo of B (16 elements along K). Lanes 16..31 duplicate lanes 0..15.+// * Wave32 C output mapping: lane t holds column lane_lo of 16x16 output tile,+// with 8 elements alternating rows: row m = 2*i + lane_hi (lane_hi = t >> 4).+// * Tile variants:+// 1. gemm_wmma_64x64_4w: 4 waves (128 threads), 64T x 64N x 16K tile, double-buffered LDS for W.+// 2. gemm_wmma_16x16_1w: 1 wave (32 threads), 16T x 16N x 16K tile, zero LDS/barriers, for small T/N.++#include "wmma_gemm.h"++#include <hip/hip_runtime.h>+#include <hip/hip_fp16.h>+#include <hip/hip_bfloat16.h>++#include <cstring>++// STRATA_WMMA_GFX11 is defined by the BUILD (CMakeLists.txt, from CMAKE_HIP_ARCHITECTURES), not inferred+// from compiler macros: measured on this toolchain the HOST pass of a HIP compile does not define+// __gfx1100__ but does define __HIP_DEVICE_COMPILE__, so a compiler-macro guard here silently selected the+// "return false" stub at the bottom of this file for the very symbol the engine links - the WMMA path then+// never ran, while the same file compiled with hipcc (as the probes do) took the real branch. One+// build-defined macro is uniform across the host and device passes.+#if defined(STRATA_WMMA_GFX11)++using v8fp32 = float __attribute__((ext_vector_type(8)));++template <typename ElemT>+struct WmmaTraits;++template <>+struct WmmaTraits<_Float16> {+ using vec_t = _Float16 __attribute__((ext_vector_type(16)));+ __device__ static inline v8fp32 mma(vec_t a, vec_t b, v8fp32 c) {+#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__)+ return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c);+#else+ (void) a; (void) b; return c; // not a gfx11 device pass: never launched (runtime gate)+#endif+ }+};++template <>+struct WmmaTraits<__bf16> {+ using vec_t = __bf16 __attribute__((ext_vector_type(16)));+ __device__ static inline v8fp32 mma(vec_t a, vec_t b, v8fp32 c) {+#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__)+ return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c);+#else+ (void) a; (void) b; return c; // not a gfx11 device pass: never launched (runtime gate)+#endif+ }+};++// ===========================================================================+// Variant 1: 16x16_1w - Single-wave kernel for small T / N.+// Zero LDS, zero barrier synchronization, full register residency.+// ===========================================================================+template <typename ElemT>+__global__ void gemm_wmma_16x16_1w(+ const uint16_t* __restrict__ X,+ const uint16_t* __restrict__ W,+ float* __restrict__ Y,+ int64_t T, int64_t N, int64_t K, int64_t ldy, float beta) {++ using vec_t = typename WmmaTraits<ElemT>::vec_t;+ const int m_tile = blockIdx.y * 16;+ const int n_tile = blockIdx.x * 16;+ if (m_tile >= T || n_tile >= N) return;++ const int lane = threadIdx.x; // 0..31+ const int lane_lo = lane & 15; // 0..15+ const int lane_hi = lane >> 4; // 0 or 1++ v8fp32 c_acc = {0, 0, 0, 0, 0, 0, 0, 0};++ const int m_row = m_tile + lane_lo;+ const int n_row = n_tile + lane_lo;++ for (int k_tile = 0; k_tile < K; k_tile += 16) {+ vec_t a_frag, b_frag;++ if (m_row < T) {+ __builtin_memcpy(&a_frag, X + (int64_t)m_row * K + k_tile, sizeof(a_frag));+ } else {+ #pragma unroll+ for (int i = 0; i < 16; ++i) a_frag[i] = 0;+ }++ if (n_row < N) {+ __builtin_memcpy(&b_frag, W + (int64_t)n_row * K + k_tile, sizeof(b_frag));+ } else {+ #pragma unroll+ for (int i = 0; i < 16; ++i) b_frag[i] = 0;+ }++ c_acc = WmmaTraits<ElemT>::mma(a_frag, b_frag, c_acc);+ }++ const int out_n = n_tile + lane_lo;+ if (out_n < N) {+ #pragma unroll+ for (int i = 0; i < 8; ++i) {+ const int out_m = m_tile + 2 * i + lane_hi;+ if (out_m < T) {+ float* dst = Y + (int64_t)out_m * ldy + out_n;+ if (beta == 0.0f) {+ *dst = c_acc[i];+ } else {+ *dst = beta * (*dst) + c_acc[i];+ }+ }+ }+ }+}++// ===========================================================================+// Variant 2: 64x64_4w - 4 waves per block (128 threads), 64T x 64N tile.+// Double-buffered LDS tile for W (4 KB LDS total), cooperative 128-bit global loads.+// ===========================================================================+template <typename ElemT>+__global__ void gemm_wmma_64x64_4w(+ const uint16_t* __restrict__ X,+ const uint16_t* __restrict__ W,+ float* __restrict__ Y,+ int64_t T, int64_t N, int64_t K, int64_t ldy, float beta) {++ using vec_t = typename WmmaTraits<ElemT>::vec_t;+ const int m_tile = blockIdx.y * 64;+ const int n_tile = blockIdx.x * 64;+ if (m_tile >= T || n_tile >= N) return;++ const int tid = threadIdx.x; // 0..127+ const int wave_id = tid >> 5; // 0..3+ const int lane = tid & 31; // 0..31+ const int lane_lo = lane & 15; // 0..15+ const int lane_hi = lane >> 4; // 0 or 1++ // 4 accumulators per wave covering 4 x 16 N-subtiles+ v8fp32 c_acc0 = {0, 0, 0, 0, 0, 0, 0, 0};+ v8fp32 c_acc1 = {0, 0, 0, 0, 0, 0, 0, 0};+ v8fp32 c_acc2 = {0, 0, 0, 0, 0, 0, 0, 0};+ v8fp32 c_acc3 = {0, 0, 0, 0, 0, 0, 0, 0};++ // Double-buffered LDS tile: 64 rows of N x 16 elements of K (2 KB per buffer)+ alignas(16) __shared__ ElemT b_lds[2][64][16];++ // Thread mapping for cooperative loading of W into LDS (128 threads load 64x16 elements)+ // Each thread loads 8 halfs (16 bytes = uint4)+ const int row_in_tile = tid >> 1; // 0..63+ const int k_sub = (tid & 1) << 3; // 0 or 8+ const int actual_n = n_tile + row_in_tile;++ auto load_w_into_lds = [&](int buf, int k_tile) {+ const int actual_k = k_tile + k_sub;+ uint4 val = {0, 0, 0, 0};+ if (actual_n < N && actual_k < K) {+ const void* ptr = reinterpret_cast<const void*>(W + (int64_t)actual_n * K + actual_k);+ val = *reinterpret_cast<const uint4*>(ptr);+ }+ *reinterpret_cast<uint4*>(&b_lds[buf][row_in_tile][k_sub]) = val;+ };++ // Pre-fill buffer 0+ load_w_into_lds(0, 0);+ __syncthreads();++ const int m_row = m_tile + wave_id * 16 + lane_lo;+ int cur_buf = 0;++ for (int k_tile = 0; k_tile < K; k_tile += 16) {+ const int next_buf = 1 - cur_buf;+ const int k_next = k_tile + 16;++ // Prefetch next K-tile of W into LDS+ if (k_next < K) {+ load_w_into_lds(next_buf, k_next);+ }++ // Load A fragment from X for current wave's 16 M-rows+ vec_t a_frag;+ if (m_row < T) {+ __builtin_memcpy(&a_frag, X + (int64_t)m_row * K + k_tile, sizeof(a_frag));+ } else {+ #pragma unroll+ for (int i = 0; i < 16; ++i) a_frag[i] = 0;+ }++ // Read B fragments from LDS and compute WMMA+ vec_t b_frag0, b_frag1, b_frag2, b_frag3;+ __builtin_memcpy(&b_frag0, &b_lds[cur_buf][0 + lane_lo][0], sizeof(vec_t));+ __builtin_memcpy(&b_frag1, &b_lds[cur_buf][16 + lane_lo][0], sizeof(vec_t));+ __builtin_memcpy(&b_frag2, &b_lds[cur_buf][32 + lane_lo][0], sizeof(vec_t));+ __builtin_memcpy(&b_frag3, &b_lds[cur_buf][48 + lane_lo][0], sizeof(vec_t));++ c_acc0 = WmmaTraits<ElemT>::mma(a_frag, b_frag0, c_acc0);+ c_acc1 = WmmaTraits<ElemT>::mma(a_frag, b_frag1, c_acc1);+ c_acc2 = WmmaTraits<ElemT>::mma(a_frag, b_frag2, c_acc2);+ c_acc3 = WmmaTraits<ElemT>::mma(a_frag, b_frag3, c_acc3);++ __syncthreads();+ cur_buf = next_buf;+ }++ // Store C to Y (coalesced 64-byte writes per wave half)+ const int m_tile_wave = m_tile + wave_id * 16;+ auto store_acc = [&](const v8fp32& acc, int n_base) {+ const int out_n = n_base + lane_lo;+ if (out_n < N) {+ #pragma unroll+ for (int i = 0; i < 8; ++i) {+ const int out_m = m_tile_wave + 2 * i + lane_hi;+ if (out_m < T) {+ float* dst = Y + (int64_t)out_m * ldy + out_n;+ if (beta == 0.0f) {+ *dst = acc[i];+ } else {+ *dst = beta * (*dst) + acc[i];+ }+ }+ }+ }+ };++ store_acc(c_acc0, n_tile + 0);+ store_acc(c_acc1, n_tile + 16);+ store_acc(c_acc2, n_tile + 32);+ store_acc(c_acc3, n_tile + 48);+}++template <typename ElemT>+static inline bool strata_wmma_gemm_dispatch(const uint16_t* X, const uint16_t* W, float* Y,+ int64_t T, int64_t N, int64_t K, int64_t ldy, float beta,+ void* stream) {+ if (!X || !W || !Y) return false;+ if (T <= 0 || N <= 0 || K <= 0) return false;+ // Runtime gate (review): run only on gfx11 devices, whatever this build compiled for. The build-time+ // STRATA_WMMA_GFX11 macro controls whether the intrinsics compile; this check controls whether they run.+ {+ int dev = 0;+ hipDeviceProp_t prop{};+ if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return false;+ if (std::strncmp(prop.gcnArchName, "gfx11", 5) != 0) return false;+ }+ if (K % 16 != 0) return false;+ if (beta != 0.0f && beta != 1.0f) return false;+ if (ldy <= 0) ldy = N;+ if (ldy < N) return false;++ hipStream_t s = static_cast<hipStream_t>(stream);++ if (T >= 32 && N >= 32) {+ dim3 block(128);+ dim3 grid((uint32_t)((N + 63) / 64), (uint32_t)((T + 63) / 64), 1);+ gemm_wmma_64x64_4w<ElemT><<<grid, block, 0, s>>>(X, W, Y, T, N, K, ldy, beta);+ } else {+ dim3 block(32);+ dim3 grid((uint32_t)((N + 15) / 16), (uint32_t)((T + 15) / 16), 1);+ gemm_wmma_16x16_1w<ElemT><<<grid, block, 0, s>>>(X, W, Y, T, N, K, ldy, beta);+ }+ return true;+}++bool strata_wmma_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y,+ int64_t T, int64_t N, int64_t K, int64_t ldy, float beta,+ void* stream) {+ return strata_wmma_gemm_dispatch<_Float16>(X, W, Y, T, N, K, ldy, beta, stream);+}++bool strata_wmma_gemm_bf16(const uint16_t* X, const uint16_t* W, float* Y,+ int64_t T, int64_t N, int64_t K, int64_t ldy, float beta,+ void* stream) {+ return strata_wmma_gemm_dispatch<__bf16>(X, W, Y, T, N, K, ldy, beta, stream);+}++#else+// Non-HIP / Non-GFX11 compilation fallback+bool strata_wmma_gemm_f16(const uint16_t*, const uint16_t*, float*,+ int64_t, int64_t, int64_t, int64_t, float,+ void*) {+ return false;+}++bool strata_wmma_gemm_bf16(const uint16_t*, const uint16_t*, float*,+ int64_t, int64_t, int64_t, int64_t, float,+ void*) {+ return false;+}+#endifdiff --git a/src/prefill/wmma_gemm.h b/src/prefill/wmma_gemm.hnew file mode 100644index 000000000..49474dfd8--- /dev/null+++ b/src/prefill/wmma_gemm.h@@ -0,0 +1,22 @@+// src/prefill/wmma_gemm.h - RDNA3 WMMA FP16 & BF16 GEMM for Strata prefill.+#pragma once++#include <cstdint>++/// Compute Y[t, n] = beta * Y[t, n] + sum_k W[n, k] * X[t, k] using RDNA3 WMMA instructions.+/// X: T x K row-major (leading dim K), fp16 (uint16_t)+/// W: N x K row-major (leading dim K), fp16 (uint16_t)+/// Y: T x N row-major with leading dimension ldy >= N, fp32 (float)+/// Returns true if executed on WMMA, false if unsupported shape/parameters (fall back to hipblas).+bool strata_wmma_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y,+ int64_t T, int64_t N, int64_t K, int64_t ldy, float beta,+ void* stream = nullptr);++/// Compute Y[t, n] = beta * Y[t, n] + sum_k W[n, k] * X[t, k] using RDNA3 WMMA instructions.+/// X: T x K row-major (leading dim K), bf16 (uint16_t)+/// W: N x K row-major (leading dim K), bf16 (uint16_t)+/// Y: T x N row-major with leading dimension ldy >= N, fp32 (float)+/// Returns true if executed on WMMA, false if unsupported shape/parameters (fall back to hipblas).+bool strata_wmma_gemm_bf16(const uint16_t* X, const uint16_t* W, float* Y,+ int64_t T, int64_t N, int64_t K, int64_t ldy, float beta,+ void* stream = nullptr);diff --git a/tests/hip/prefill_wmma_gemm_parity.cpp b/tests/hip/prefill_wmma_gemm_parity.cppnew file mode 100644index 000000000..bb7c15919--- /dev/null+++ b/tests/hip/prefill_wmma_gemm_parity.cpp@@ -0,0 +1,441 @@+// tests/hip/prefill_wmma_gemm_parity.cpp - Numerical parity test for RDNA3 WMMA GEMM kernels.+#include <cuda_runtime.h>+#include <hip/hip_bfloat16.h>+#include <hip/hip_fp16.h>++#include "wmma_gemm.h"++#include <algorithm>+#include <cmath>+#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <limits>+#include <random>+#include <string>+#include <vector>++// ============================================================================+// Exact Representability & Parity Rationale:+//+// Inputs (X, W, and initial Y for beta=1) are chosen from discrete binary fractions+// k / 16.0f with integer k in [-8, 8].+//+// In IEEE 754 half-precision (fp16, 10-bit explicit mantissa) and bfloat16+// (7-bit explicit mantissa), every such value k * 2^-4 requires at most 4 bits+// of significand and is therefore EXACTLY representable without rounding.+//+// The product of any two such values is an exact integer multiple of 2^-8:+// (a * 2^-4) * (b * 2^-4) = (a * b) * 2^-8+// with (a * b) in [-64, 64].+//+// For K <= 80, the sum of K products:+// sum_k (W[n, k] * X[t, k]) = (sum_k a_k * b_k) * 2^-8+// has a maximum absolute magnitude of 80 * (0.5 * 0.5) = 20.0, and the integer+// numerator cannot exceed 80 * 64 = 5120 (< 2^13).+//+// In IEEE 754 single-precision (fp32, 23-bit explicit mantissa, 24 bits total),+// any integer multiple of 2^-8 up to 20.0 requires at most 13 bits of significand.+// Because the RDNA3 hardware instructions (v_wmma_f32_16x16x16_f16_w32 and+// v_wmma_f32_16x16x16_bf16_w32) accumulate in native FP32 registers, every+// intermediate product and addition has ZERO truncation or rounding error.+//+// Furthermore, floating-point addition of exact binary fractions whose sum fits+// within the mantissa is strictly associative and exact. Consequently, the GPU+// WMMA pipeline and the CPU reference compute identical bitwise results, making+// an exact assertion (max_abs == 0.0f) mathematically legitimate.+// ============================================================================++#define HIP_CHECK(call) do { \+ const hipError_t status_ = (call); \+ if (status_ != hipSuccess) { \+ std::fprintf(stderr, "HIP failure at %s:%d: %s: %s\n", __FILE__, __LINE__, #call, hipGetErrorString(status_)); \+ std::exit(2); \+ } \+} while (0)++namespace {++constexpr float kSentinel = -999.5f;++struct DeviceBuffer {+ void* p = nullptr;+ explicit DeviceBuffer(size_t bytes) { if (bytes) HIP_CHECK(hipMalloc(&p, bytes)); }+ ~DeviceBuffer() { if (p) (void) hipFree(p); }+ DeviceBuffer(const DeviceBuffer&) = delete;+ DeviceBuffer& operator=(const DeviceBuffer&) = delete;+};++uint16_t encode(float value, bool bf16) {+ if (bf16) return hip_bfloat16(value).data;+ const __half half = __float2half_rn(value);+ return static_cast<__half_raw>(half).x;+}++float decode(uint16_t bits, bool bf16) {+ if (bf16) {+ const uint32_t u = static_cast<uint32_t>(bits) << 16;+ float f = 0.0f;+ std::memcpy(&f, &u, sizeof(f));+ return f;+ }+ const __half_raw raw{bits};+ return __half2float(__half(raw));+}++struct MismatchRecord {+ const char* dtype = "";+ int64_t T = 0, N = 0, K = 0, ldy = 0;+ float beta = 0.0f;+ int64_t row = 0, col = 0;+ float got = 0.0f, ref = 0.0f;+ double delta = 0.0;+ bool is_padding = false;+};++// Independent host CPU reference computed in double precision.+void gemm_reference(const uint16_t* X, const uint16_t* W, const float* initial_Y, float* ref_Y,+ int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, bool is_bf16) {+ std::vector<double> x_dec((size_t) T * K);+ std::vector<double> w_dec((size_t) N * K);+ for (size_t i = 0; i < x_dec.size(); ++i) x_dec[i] = decode(X[i], is_bf16);+ for (size_t i = 0; i < w_dec.size(); ++i) w_dec[i] = decode(W[i], is_bf16);++ for (int64_t t = 0; t < T; ++t) {+ const double* x_row = x_dec.data() + t * K;+ for (int64_t n = 0; n < N; ++n) {+ const double* w_row = w_dec.data() + n * K;+ double sum = 0.0;+ for (int64_t k = 0; k < K; ++k) {+ sum += x_row[k] * w_row[k];+ }+ const size_t out_idx = (size_t) t * ldy + n;+ const double y_init = (beta == 0.0f) ? 0.0 : static_cast<double>(initial_Y[out_idx]);+ ref_Y[out_idx] = static_cast<float>(beta * y_init + sum);+ }+ }+}++enum class CaseStatus {+ Passed,+ Skipped,+ Failed+};++CaseStatus run_gemm_case(DeviceBuffer& dx, DeviceBuffer& dw, DeviceBuffer& dy,+ hipStream_t stream, bool is_bf16,+ int64_t T, int64_t N, int64_t K, int64_t ldy, float beta,+ uint32_t seed, double& out_max_abs,+ MismatchRecord* first_mismatch, size_t& failure_count) {+ const char* dtype_str = is_bf16 ? "bf16" : "f16";+ std::mt19937 rng(seed);+ std::uniform_int_distribution<int> dist(-8, 8);++ const size_t x_count = (size_t) T * K;+ const size_t w_count = (size_t) N * K;+ const size_t y_count = (size_t) T * ldy + 16; // 16 guard floats past end of matrix++ std::vector<uint16_t> x(x_count);+ std::vector<uint16_t> w(w_count);+ for (size_t i = 0; i < x_count; ++i) x[i] = encode(dist(rng) * 0.0625f, is_bf16);+ for (size_t i = 0; i < w_count; ++i) w[i] = encode(dist(rng) * 0.0625f, is_bf16);++ std::vector<float> initial_y(y_count, kSentinel);+ for (int64_t t = 0; t < T; ++t) {+ for (int64_t n = 0; n < N; ++n) {+ if (beta == 0.0f) {+ initial_y[(size_t) t * ldy + n] = -888.25f;+ } else {+ // beta == 1.0f: pre-fill with a known exact pattern to verify accumulation+ initial_y[(size_t) t * ldy + n] = static_cast<float>((t * 5 + n * 3) % 17 - 8) * 0.0625f;+ }+ }+ }++ HIP_CHECK(hipMemcpyAsync(dx.p, x.data(), x_count * sizeof(uint16_t), hipMemcpyHostToDevice, stream));+ HIP_CHECK(hipMemcpyAsync(dw.p, w.data(), w_count * sizeof(uint16_t), hipMemcpyHostToDevice, stream));+ HIP_CHECK(hipMemcpyAsync(dy.p, initial_y.data(), y_count * sizeof(float), hipMemcpyHostToDevice, stream));++ const bool launched = is_bf16 ? strata_wmma_gemm_bf16(static_cast<const uint16_t*>(dx.p),+ static_cast<const uint16_t*>(dw.p),+ static_cast<float*>(dy.p),+ T, N, K, ldy, beta, stream)+ : strata_wmma_gemm_f16(static_cast<const uint16_t*>(dx.p),+ static_cast<const uint16_t*>(dw.p),+ static_cast<float*>(dy.p),+ T, N, K, ldy, beta, stream);++ if (!launched) {+ // Declined by kernel: caller falls back to hipBLAS. Test must SKIP rather than fail.+ HIP_CHECK(hipStreamSynchronize(stream));+ return CaseStatus::Skipped;+ }++ std::vector<float> got_y(y_count);+ HIP_CHECK(hipMemcpyAsync(got_y.data(), dy.p, y_count * sizeof(float), hipMemcpyDeviceToHost, stream));+ HIP_CHECK(hipStreamSynchronize(stream));++ // 1. Verify padding columns and end guards are untouched.+ for (int64_t t = 0; t < T; ++t) {+ for (int64_t col = N; col < ldy; ++col) {+ const size_t idx = (size_t) t * ldy + col;+ if (got_y[idx] != kSentinel) {+ failure_count++;+ if (first_mismatch && first_mismatch->dtype[0] == '\0') {+ *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, t, col,+ got_y[idx], kSentinel,+ std::abs((double) got_y[idx] - (double) kSentinel), true};+ }+ std::fprintf(stderr, "FAIL: output touched padding column: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f row=%ld col=%ld got=%.9g expected=%.9g\n",+ dtype_str, T, N, K, ldy, beta, t, col, got_y[idx], kSentinel);+ return CaseStatus::Failed;+ }+ }+ }+ for (size_t g = (size_t) T * ldy; g < y_count; ++g) {+ if (got_y[g] != kSentinel) {+ failure_count++;+ if (first_mismatch && first_mismatch->dtype[0] == '\0') {+ *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, -1, (int64_t) g,+ got_y[g], kSentinel,+ std::abs((double) got_y[g] - (double) kSentinel), true};+ }+ std::fprintf(stderr, "FAIL: output touched end guard: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f index=%zu got=%.9g expected=%.9g\n",+ dtype_str, T, N, K, ldy, beta, g, got_y[g], kSentinel);+ return CaseStatus::Failed;+ }+ }++ // 2. Compute reference on CPU and verify exact match.+ std::vector<float> ref_y(y_count, kSentinel);+ gemm_reference(x.data(), w.data(), initial_y.data(), ref_y.data(), T, N, K, ldy, beta, is_bf16);++ double case_max_abs = 0.0;+ for (int64_t t = 0; t < T; ++t) {+ for (int64_t n = 0; n < N; ++n) {+ const size_t idx = (size_t) t * ldy + n;+ if (!std::isfinite(got_y[idx])) {+ failure_count++;+ if (first_mismatch && first_mismatch->dtype[0] == '\0') {+ *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, t, n,+ got_y[idx], ref_y[idx], 1e30, false};+ }+ std::fprintf(stderr, "FAIL: non-finite output: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g\n",+ dtype_str, T, N, K, ldy, beta, t, n, got_y[idx]);+ return CaseStatus::Failed;+ }+ const double delta = std::abs(static_cast<double>(got_y[idx]) - static_cast<double>(ref_y[idx]));+ case_max_abs = std::max(case_max_abs, delta);+ // The RDNA3 matrix core accumulates in fp32 but rounds toward zero rather than to nearest, while+ // this reference sums in double and rounds to nearest, so a correct result may differ by one ULP+ // (measured: every mismatch on this hardware is <= 1 ULP and toward zero). Compare against a+ // tolerance of 4 ULP - tight enough to stay diagnostic, since a wrong row, column, stride or tile+ // boundary differs by O(value) rather than by 1e-7. STRATA_WMMA_PARITY_EXACT=1 demands bit+ // equality for anyone who wants to see the raw deltas.+ static const bool exact = std::getenv("STRATA_WMMA_PARITY_EXACT") != nullptr;+ const double tol = exact ? 0.0+ : 4.0 * (double)std::numeric_limits<float>::epsilon() *+ std::max(1.0, std::abs(static_cast<double>(ref_y[idx])));+ if (delta > tol) {+ failure_count++;+ if (first_mismatch && first_mismatch->dtype[0] == '\0') {+ *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, t, n,+ got_y[idx], ref_y[idx], delta, false};+ }+ std::fprintf(stderr, "FAIL: mismatch: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g ref=%.9g delta=%.9g\n",+ dtype_str, T, N, K, ldy, beta, t, n, got_y[idx], ref_y[idx], delta);+ return CaseStatus::Failed;+ }+ }+ }++ out_max_abs = std::max(out_max_abs, case_max_abs);+ return CaseStatus::Passed;+}++struct DeclinedShape {+ int64_t T, N, K, ldy;+ float beta;+ const char* reason;+};++} // namespace++int main() {+ int device = 0;+ HIP_CHECK(hipGetDevice(&device));+ hipDeviceProp_t properties{};+ HIP_CHECK(hipGetDeviceProperties(&properties, device));+ std::printf("Device %d: %s (arch %s, warpSize %d)\n",+ device, properties.name, properties.gcnArchName, properties.warpSize);++ hipStream_t stream = nullptr;+ HIP_CHECK(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking));++ // Allocate reusable device buffers sized for the maximum test dimensions:+ // Max T = 127, Max N = 256, Max K = 80, Max ldy = 256 + 16.+ constexpr size_t kMaxXBytes = 127 * 80 * sizeof(uint16_t);+ constexpr size_t kMaxWBytes = 256 * 80 * sizeof(uint16_t);+ constexpr size_t kMaxYBytes = (127 * (256 + 16) + 64) * sizeof(float);++ DeviceBuffer dx(kMaxXBytes);+ DeviceBuffer dw(kMaxWBytes);+ DeviceBuffer dy(kMaxYBytes);++ const std::vector<int64_t> k_t_values = {1, 15, 16, 17, 31, 32, 33, 63, 64, 65, 127};+ const std::vector<int64_t> k_n_values = {16, 17, 32, 48, 64, 65, 127, 256};+ const std::vector<int64_t> k_k_values = {16, 32, 48, 64, 80};++ // Test matrix configurations for (beta, ldy):+ // Covers beta=0 (overwrite) and beta=1 (accumulate), with ldy == N and ldy > N.+ struct Config {+ float beta;+ int64_t ldy_offset;+ };+ const std::vector<Config> kConfigs = {+ {0.0f, 0}, // beta=0, packed (ldy == N)+ {1.0f, 3}, // beta=1, strided (ldy == N + 3), tests accumulation + padding+ {0.0f, 7}, // beta=0, strided (ldy == N + 7), tests overwrite + padding+ {1.0f, 0}, // beta=1, packed (ldy == N), tests accumulation in packed layout+ };++ const std::vector<DeclinedShape> kDeclinedShapes = {+ // K not a multiple of 16+ {1, 16, 15, 16, 0.0f, "K not multiple of 16 (K=15)"},+ {15, 17, 24, 17, 0.0f, "K not multiple of 16 (K=24)"},+ {32, 32, 35, 32, 1.0f, "K not multiple of 16 (K=35)"},+ {64, 64, 47, 67, 1.0f, "K not multiple of 16 (K=47)"},+ {127, 256, 79, 256, 0.0f, "K not multiple of 16 (K=79)"},+ // ldy < N+ {16, 32, 16, 16, 0.0f, "ldy < N (ldy=16, N=32)"},+ {32, 48, 32, 40, 1.0f, "ldy < N (ldy=40, N=48)"},+ // beta not 0 or 1+ {16, 16, 16, 16, 0.5f, "beta not 0 or 1 (beta=0.5)"},+ {32, 32, 32, 32, 2.0f, "beta not 0 or 1 (beta=2.0)"},+ // Non-positive sizes+ {0, 16, 16, 16, 0.0f, "T <= 0 (T=0)"},+ {16, 0, 16, 16, 0.0f, "N <= 0 (N=0)"},+ {16, 16, 0, 16, 0.0f, "K <= 0 (K=0)"},+ {-1, 16, 16, 16, 0.0f, "T < 0 (T=-1)"},+ };++ size_t passed_count = 0;+ size_t skipped_count = 0;+ size_t failure_count = 0;+ double global_max_abs = 0.0;+ MismatchRecord first_mismatch{};+ uint32_t case_seed = 0x574d4d41u;++ const bool verbose = (std::getenv("STRATA_TEST_VERBOSE") != nullptr);++ for (bool is_bf16 : {false, true}) {+ const char* dtype_str = is_bf16 ? "bf16" : "f16";+ std::printf("Testing strata_wmma_gemm_%s across %zu shapes (%zu execution configs)...\n",+ dtype_str, k_t_values.size() * k_n_values.size() * k_k_values.size(), kConfigs.size());++ for (int64_t T : k_t_values) {+ double t_max_abs = 0.0;+ size_t t_passed = 0;+ size_t t_skipped = 0;++ for (int64_t N : k_n_values) {+ for (int64_t K : k_k_values) {+ for (const auto& cfg : kConfigs) {+ const int64_t ldy = N + cfg.ldy_offset;+ double case_max_abs = 0.0;+ case_seed = case_seed * 1664525u + 1013904223u;++ const CaseStatus status = run_gemm_case(+ dx, dw, dy, stream, is_bf16, T, N, K, ldy, cfg.beta,+ case_seed, case_max_abs, &first_mismatch, failure_count);++ if (status == CaseStatus::Passed) {+ passed_count++;+ t_passed++;+ t_max_abs = std::max(t_max_abs, case_max_abs);+ global_max_abs = std::max(global_max_abs, case_max_abs);+ if (verbose) {+ std::printf(" case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f max_abs=%.9g PASS\n",+ dtype_str, T, N, K, ldy, cfg.beta, case_max_abs);+ }+ } else if (status == CaseStatus::Skipped) {+ skipped_count++;+ t_skipped++;+ if (verbose) {+ std::printf(" case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f SKIP (declined)\n",+ dtype_str, T, N, K, ldy, cfg.beta);+ }+ } else {+ // Failed: first_mismatch already recorded and reported to stderr+ if (verbose) {+ std::printf(" case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f FAIL\n",+ dtype_str, T, N, K, ldy, cfg.beta);+ }+ }+ }+ }+ }+ std::printf(" dtype=%s T=%3ld: %zu passed, %zu skipped, max_abs=%.9g %s\n",+ dtype_str, T, t_passed, t_skipped, t_max_abs,+ (failure_count == 0) ? "PASS" : "FAIL");+ }++ // Test declined shapes: the kernel must return false and be skipped.+ for (const auto& decl : kDeclinedShapes) {+ const bool launched = is_bf16+ ? strata_wmma_gemm_bf16(static_cast<const uint16_t*>(dx.p),+ static_cast<const uint16_t*>(dw.p),+ static_cast<float*>(dy.p),+ decl.T, decl.N, decl.K, decl.ldy, decl.beta, stream)+ : strata_wmma_gemm_f16(static_cast<const uint16_t*>(dx.p),+ static_cast<const uint16_t*>(dw.p),+ static_cast<float*>(dy.p),+ decl.T, decl.N, decl.K, decl.ldy, decl.beta, stream);++ if (launched) {+ failure_count++;+ std::fprintf(stderr, "FAIL: expected kernel to decline shape (%s) dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f but it returned true!\n",+ decl.reason, dtype_str, decl.T, decl.N, decl.K, decl.ldy, decl.beta);+ } else {+ skipped_count++;+ if (verbose) {+ std::printf(" declined shape correctly rejected (%s): dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f SKIP\n",+ decl.reason, dtype_str, decl.T, decl.N, decl.K, decl.ldy, decl.beta);+ }+ }+ }+ }++ HIP_CHECK(hipStreamDestroy(stream));++ if (failure_count > 0) {+ if (first_mismatch.dtype[0] != '\0') {+ if (first_mismatch.is_padding) {+ std::fprintf(stderr, "\nSUMMARY: First mismatch was padding/guard corruption:\n"+ " dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g expected=%.9g\n",+ first_mismatch.dtype, first_mismatch.T, first_mismatch.N, first_mismatch.K,+ first_mismatch.ldy, first_mismatch.beta, first_mismatch.row, first_mismatch.col,+ first_mismatch.got, first_mismatch.ref);+ } else {+ std::fprintf(stderr, "\nSUMMARY: First mismatch occurred at:\n"+ " dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g ref=%.9g delta=%.9g\n",+ first_mismatch.dtype, first_mismatch.T, first_mismatch.N, first_mismatch.K,+ first_mismatch.ldy, first_mismatch.beta, first_mismatch.row, first_mismatch.col,+ first_mismatch.got, first_mismatch.ref, first_mismatch.delta);+ }+ }+ std::fprintf(stderr, "WMMA GEMM parity FAILED: %zu failures detected, max_abs=%.9g\n",+ failure_count, global_max_abs);+ return 1;+ }++ if (passed_count == 0) {+ std::fprintf(stderr, "WMMA GEMM parity FAILED: zero test cases passed (all were declined or skipped)\n");+ return 1;+ }++ std::printf("\nWMMA GEMM parity OK: %zu test cases passed, %zu declined shapes skipped, max_abs=%.9g\n",+ passed_count, skipped_count, global_max_abs);+ return 0;+}