okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
53623e56f
main
1// tests/hip/prefill_wmma_gemm_parity.cpp - Numerical parity test for RDNA3 WMMA GEMM kernels. 2#include <cuda_runtime.h> 3#include <hip/hip_bfloat16.h> 4#include <hip/hip_fp16.h> 5 6#include "wmma_gemm.h" 7#include "strata/kernels/gfx_arch.hpp" 8 9#include <algorithm> 10#include <cmath> 11#include <cstdint> 12#include <cstdio> 13#include <cstdlib> 14#include <cstring> 15#include <limits> 16#include <random> 17#include <string> 18#include <vector> 19 20// ============================================================================ 21// Exact Representability & Parity Rationale: 22// 23// Inputs (X, W, and initial Y for beta=1) are chosen from discrete binary fractions 24// k / 16.0f with integer k in [-8, 8]. 25// 26// In IEEE 754 half-precision (fp16, 10-bit explicit mantissa) and bfloat16 27// (7-bit explicit mantissa), every such value k * 2^-4 requires at most 4 bits 28// of significand and is therefore EXACTLY representable without rounding. 29// 30// The product of any two such values is an exact integer multiple of 2^-8: 31// (a * 2^-4) * (b * 2^-4) = (a * b) * 2^-8 32// with (a * b) in [-64, 64]. 33// 34// For K <= 80, the sum of K products: 35// sum_k (W[n, k] * X[t, k]) = (sum_k a_k * b_k) * 2^-8 36// has a maximum absolute magnitude of 80 * (0.5 * 0.5) = 20.0, and the integer 37// numerator cannot exceed 80 * 64 = 5120 (< 2^13). 38// 39// In IEEE 754 single-precision (fp32, 23-bit explicit mantissa, 24 bits total), 40// any integer multiple of 2^-8 up to 20.0 requires at most 13 bits of significand. 41// Because the RDNA3 hardware instructions (v_wmma_f32_16x16x16_f16_w32 and 42// v_wmma_f32_16x16x16_bf16_w32) accumulate in native FP32 registers, every 43// intermediate product and addition has ZERO truncation or rounding error. 44// 45// Furthermore, floating-point addition of exact binary fractions whose sum fits 46// within the mantissa is strictly associative and exact. Consequently, the GPU 47// WMMA pipeline and the CPU reference compute identical bitwise results, making 48// an exact assertion (max_abs == 0.0f) mathematically legitimate. 49// ============================================================================ 50 51#define HIP_CHECK (call ) do { \ 52 const hipError_t status_ = (call); \ 53 if (status_ != hipSuccess) { \ 54 std::fprintf(stderr, "HIP failure at %s:%d: %s: %s\n", __FILE__, __LINE__, #call, hipGetErrorString(status_)); \ 55 std::exit(2); \ 56 } \ 57} while (0) 58 59namespace { 60 61constexpr float kSentinel = -999.5f ; 62 63struct DeviceBuffer { 64void * p = nullptr ; 65explicit DeviceBuffer (size_t bytes ) {if (bytes )HIP_CHECK (hipMalloc (& p ,bytes )); } 66 ~DeviceBuffer () {if (p ) (void )hipFree (p ); } 67DeviceBuffer (const DeviceBuffer & )= delete ; 68DeviceBuffer & operator= (const DeviceBuffer & )= delete ; 69}; 70 71uint16_t encode (float value ,bool bf16 ) { 72if (bf16 )return hip_bfloat16 (value ).data ; 73const __half half = __float2half_rn (value ); 74return static_cast < __half_raw > (half ).x ; 75} 76 77float decode (uint16_t bits ,bool bf16 ) { 78if (bf16 ) { 79const uint32_t u = static_cast < uint32_t > (bits ) <<16 ; 80float f = 0.0f ; 81 std::memcpy (& f ,& u ,sizeof (f )); 82return f ; 83 } 84const __half_raw raw {bits }; 85return __half2float (__half (raw )); 86} 87 88struct MismatchRecord { 89const char * dtype = "" ; 90int64_t T = 0 ,N = 0 ,K = 0 ,ldy = 0 ; 91float beta = 0.0f ; 92int64_t row = 0 ,col = 0 ; 93float got = 0.0f ,ref = 0.0f ; 94double delta = 0.0 ; 95bool is_padding = false; 96}; 97 98// Independent host CPU reference computed in double precision. 99void gemm_reference (const uint16_t * X ,const uint16_t * W ,const float * initial_Y ,float * ref_Y , 100int64_t T ,int64_t N ,int64_t K ,int64_t ldy ,float beta ,bool is_bf16 ) { 101 std::vector < double > x_dec ((size_t )T * K ); 102 std::vector < double > w_dec ((size_t )N * K ); 103for (size_t i = 0 ;i < x_dec .size ();++ i )x_dec [i ]= decode (X [i ],is_bf16 ); 104for (size_t i = 0 ;i < w_dec .size ();++ i )w_dec [i ]= decode (W [i ],is_bf16 ); 105 106for (int64_t t = 0 ;t < T ;++ t ) { 107const double * x_row = x_dec .data ()+ t * K ; 108for (int64_t n = 0 ;n < N ;++ n ) { 109const double * w_row = w_dec .data ()+ n * K ; 110double sum = 0.0 ; 111for (int64_t k = 0 ;k < K ;++ k ) { 112sum += x_row [k ]* w_row [k ]; 113 } 114const size_t out_idx = (size_t )t * ldy + n ; 115const double y_init = (beta == 0.0f ) ?0.0 :static_cast < double > (initial_Y [out_idx ]); 116ref_Y [out_idx ]= static_cast < float > (beta * y_init + sum ); 117 } 118 } 119} 120 121enum class CaseStatus { 122Passed , 123Skipped , 124Failed 125}; 126 127CaseStatus run_gemm_case (DeviceBuffer & dx ,DeviceBuffer & dw ,DeviceBuffer & dy , 128hipStream_t stream ,bool is_bf16 , 129int64_t T ,int64_t N ,int64_t K ,int64_t ldy ,float beta , 130uint32_t seed ,double & out_max_abs , 131MismatchRecord * first_mismatch ,size_t & failure_count ) { 132const char * dtype_str = is_bf16 ?"bf16" :"f16" ; 133 std::mt19937 rng (seed ); 134 std::uniform_int_distribution < int > dist (-8 ,8 ); 135 136const size_t x_count = (size_t )T * K ; 137const size_t w_count = (size_t )N * K ; 138const size_t y_count = (size_t )T * ldy + 16 ;// 16 guard floats past end of matrix 139 140 std::vector < uint16_t > x (x_count ); 141 std::vector < uint16_t > w (w_count ); 142for (size_t i = 0 ;i < x_count ;++ i )x [i ]= encode (dist (rng )* 0.0625f ,is_bf16 ); 143for (size_t i = 0 ;i < w_count ;++ i )w [i ]= encode (dist (rng )* 0.0625f ,is_bf16 ); 144 145 std::vector < float > initial_y (y_count ,kSentinel ); 146for (int64_t t = 0 ;t < T ;++ t ) { 147for (int64_t n = 0 ;n < N ;++ n ) { 148if (beta == 0.0f ) { 149initial_y [(size_t )t * ldy + n ]= -888.25f ; 150 }else { 151// beta == 1.0f: pre-fill with a known exact pattern to verify accumulation 152initial_y [(size_t )t * ldy + n ]= static_cast < float > ((t * 5 + n * 3 ) %17 - 8 )* 0.0625f ; 153 } 154 } 155 } 156 157HIP_CHECK (hipMemcpyAsync (dx .p ,x .data (),x_count * sizeof (uint16_t ),hipMemcpyHostToDevice ,stream )); 158HIP_CHECK (hipMemcpyAsync (dw .p ,w .data (),w_count * sizeof (uint16_t ),hipMemcpyHostToDevice ,stream )); 159HIP_CHECK (hipMemcpyAsync (dy .p ,initial_y .data (),y_count * sizeof (float ),hipMemcpyHostToDevice ,stream )); 160 161const bool launched = is_bf16 ?strata_wmma_gemm_bf16 (static_cast < const uint16_t *> (dx .p ), 162static_cast < const uint16_t *> (dw .p ), 163static_cast < float *> (dy .p ), 164T ,N ,K ,ldy ,beta ,stream ) 165 :strata_wmma_gemm_f16 (static_cast < const uint16_t *> (dx .p ), 166static_cast < const uint16_t *> (dw .p ), 167static_cast < float *> (dy .p ), 168T ,N ,K ,ldy ,beta ,stream ); 169 170if (!launched ) { 171// Declined by kernel: caller falls back to hipBLAS. Test must SKIP rather than fail. 172HIP_CHECK (hipStreamSynchronize (stream )); 173return CaseStatus ::Skipped ; 174 } 175 176 std::vector < float > got_y (y_count ); 177HIP_CHECK (hipMemcpyAsync (got_y .data (),dy .p ,y_count * sizeof (float ),hipMemcpyDeviceToHost ,stream )); 178HIP_CHECK (hipStreamSynchronize (stream )); 179 180// 1. Verify padding columns and end guards are untouched. 181for (int64_t t = 0 ;t < T ;++ t ) { 182for (int64_t col = N ;col < ldy ;++ col ) { 183const size_t idx = (size_t )t * ldy + col ; 184if (got_y [idx ]!= kSentinel ) { 185failure_count ++ ; 186if (first_mismatch && first_mismatch -> dtype [0 ]== '\0' ) { 187* first_mismatch = MismatchRecord {dtype_str ,T ,N ,K ,ldy ,beta ,t ,col , 188got_y [idx ],kSentinel , 189 std::abs ((double )got_y [idx ]- (double )kSentinel ), true}; 190 } 191 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" , 192dtype_str ,T ,N ,K ,ldy ,beta ,t ,col ,got_y [idx ],kSentinel ); 193return CaseStatus ::Failed ; 194 } 195 } 196 } 197for (size_t g = (size_t )T * ldy ;g < y_count ;++ g ) { 198if (got_y [g ]!= kSentinel ) { 199failure_count ++ ; 200if (first_mismatch && first_mismatch -> dtype [0 ]== '\0' ) { 201* first_mismatch = MismatchRecord {dtype_str ,T ,N ,K ,ldy ,beta ,-1 , (int64_t )g , 202got_y [g ],kSentinel , 203 std::abs ((double )got_y [g ]- (double )kSentinel ), true}; 204 } 205 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" , 206dtype_str ,T ,N ,K ,ldy ,beta ,g ,got_y [g ],kSentinel ); 207return CaseStatus ::Failed ; 208 } 209 } 210 211// 2. Compute reference on CPU and verify exact match. 212 std::vector < float > ref_y (y_count ,kSentinel ); 213gemm_reference (x .data (),w .data (),initial_y .data (),ref_y .data (),T ,N ,K ,ldy ,beta ,is_bf16 ); 214 215double case_max_abs = 0.0 ; 216for (int64_t t = 0 ;t < T ;++ t ) { 217for (int64_t n = 0 ;n < N ;++ n ) { 218const size_t idx = (size_t )t * ldy + n ; 219if (!std::isfinite (got_y [idx ])) { 220failure_count ++ ; 221if (first_mismatch && first_mismatch -> dtype [0 ]== '\0' ) { 222* first_mismatch = MismatchRecord {dtype_str ,T ,N ,K ,ldy ,beta ,t ,n , 223got_y [idx ],ref_y [idx ],1e30 , false}; 224 } 225 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" , 226dtype_str ,T ,N ,K ,ldy ,beta ,t ,n ,got_y [idx ]); 227return CaseStatus ::Failed ; 228 } 229const double delta = std::abs (static_cast < double > (got_y [idx ])- static_cast < double > (ref_y [idx ])); 230case_max_abs = std::max (case_max_abs ,delta ); 231// The RDNA3 matrix core accumulates in fp32 but rounds toward zero rather than to nearest, while 232// this reference sums in double and rounds to nearest, so a correct result may differ by one ULP 233// (measured: every mismatch on this hardware is <= 1 ULP and toward zero). Compare against a 234// tolerance of 4 ULP - tight enough to stay diagnostic, since a wrong row, column, stride or tile 235// boundary differs by O(value) rather than by 1e-7. STRATA_WMMA_PARITY_EXACT=1 demands bit 236// equality for anyone who wants to see the raw deltas. 237static const bool exact = std::getenv ("STRATA_WMMA_PARITY_EXACT" )!= nullptr ; 238const double tol = exact ?0.0 239 :4.0 * (double )std::numeric_limits < float > ::epsilon ()* 240 std::max (1.0 , std::abs (static_cast < double > (ref_y [idx ]))); 241if (delta > tol ) { 242failure_count ++ ; 243if (first_mismatch && first_mismatch -> dtype [0 ]== '\0' ) { 244* first_mismatch = MismatchRecord {dtype_str ,T ,N ,K ,ldy ,beta ,t ,n , 245got_y [idx ],ref_y [idx ],delta , false}; 246 } 247 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" , 248dtype_str ,T ,N ,K ,ldy ,beta ,t ,n ,got_y [idx ],ref_y [idx ],delta ); 249return CaseStatus ::Failed ; 250 } 251 } 252 } 253 254out_max_abs = std::max (out_max_abs ,case_max_abs ); 255return CaseStatus ::Passed ; 256} 257 258struct DeclinedShape { 259int64_t T ,N ,K ,ldy ; 260float beta ; 261const char * reason ; 262}; 263 264}// namespace 265 266int main () { 267int device = 0 ; 268HIP_CHECK (hipGetDevice (& device )); 269hipDeviceProp_t properties {}; 270HIP_CHECK (hipGetDeviceProperties (& properties ,device )); 271 std::printf ("Device %d: %s (arch %s, warpSize %d)\n" , 272device ,properties .name ,properties .gcnArchName ,properties .warpSize ); 273// No matrix cores (RDNA2 and older, gfx906): the kernel declines every shape, so the suite has nothing to compare 274// and reports that as a skip (exit 77, SKIP_RETURN_CODE in CMake), as hip_prompt_attn_wmma does, not a failure. 275if (!strata::kernels::gfx_arch_is_gfx11_wmma (properties .gcnArchName )) { 276 std::printf ("WMMA GEMM parity SKIPPED: %s has no WMMA matrix cores (the kernel declines every shape here)\n" , 277properties .gcnArchName ); 278return 77 ; 279 } 280 281hipStream_t stream = nullptr ; 282HIP_CHECK (hipStreamCreateWithFlags (& stream ,hipStreamNonBlocking )); 283 284// Allocate reusable device buffers sized for the maximum test dimensions: 285// Max T = 127, Max N = 256, Max K = 80, Max ldy = 256 + 16. 286constexpr size_t kMaxXBytes = 127 * 80 * sizeof (uint16_t ); 287constexpr size_t kMaxWBytes = 256 * 80 * sizeof (uint16_t ); 288constexpr size_t kMaxYBytes = (127 * (256 + 16 )+ 64 )* sizeof (float ); 289 290DeviceBuffer dx (kMaxXBytes ); 291DeviceBuffer dw (kMaxWBytes ); 292DeviceBuffer dy (kMaxYBytes ); 293 294const std::vector < int64_t > k_t_values = {1 ,15 ,16 ,17 ,31 ,32 ,33 ,63 ,64 ,65 ,127 }; 295const std::vector < int64_t > k_n_values = {16 ,17 ,32 ,48 ,64 ,65 ,127 ,256 }; 296const std::vector < int64_t > k_k_values = {16 ,32 ,48 ,64 ,80 }; 297 298// Test matrix configurations for (beta, ldy): 299// Covers beta=0 (overwrite) and beta=1 (accumulate), with ldy == N and ldy > N. 300struct Config { 301float beta ; 302int64_t ldy_offset ; 303 }; 304const std::vector < Config > kConfigs = { 305 {0.0f ,0 },// beta=0, packed (ldy == N) 306 {1.0f ,3 },// beta=1, strided (ldy == N + 3), tests accumulation + padding 307 {0.0f ,7 },// beta=0, strided (ldy == N + 7), tests overwrite + padding 308 {1.0f ,0 },// beta=1, packed (ldy == N), tests accumulation in packed layout 309 }; 310 311const std::vector < DeclinedShape > kDeclinedShapes = { 312// K not a multiple of 16 313 {1 ,16 ,15 ,16 ,0.0f ,"K not multiple of 16 (K=15)" }, 314 {15 ,17 ,24 ,17 ,0.0f ,"K not multiple of 16 (K=24)" }, 315 {32 ,32 ,35 ,32 ,1.0f ,"K not multiple of 16 (K=35)" }, 316 {64 ,64 ,47 ,67 ,1.0f ,"K not multiple of 16 (K=47)" }, 317 {127 ,256 ,79 ,256 ,0.0f ,"K not multiple of 16 (K=79)" }, 318// ldy < N 319 {16 ,32 ,16 ,16 ,0.0f ,"ldy < N (ldy=16, N=32)" }, 320 {32 ,48 ,32 ,40 ,1.0f ,"ldy < N (ldy=40, N=48)" }, 321// beta not 0 or 1 322 {16 ,16 ,16 ,16 ,0.5f ,"beta not 0 or 1 (beta=0.5)" }, 323 {32 ,32 ,32 ,32 ,2.0f ,"beta not 0 or 1 (beta=2.0)" }, 324// Non-positive sizes 325 {0 ,16 ,16 ,16 ,0.0f ,"T <= 0 (T=0)" }, 326 {16 ,0 ,16 ,16 ,0.0f ,"N <= 0 (N=0)" }, 327 {16 ,16 ,0 ,16 ,0.0f ,"K <= 0 (K=0)" }, 328 {-1 ,16 ,16 ,16 ,0.0f ,"T < 0 (T=-1)" }, 329 }; 330 331size_t passed_count = 0 ; 332size_t skipped_count = 0 ; 333size_t failure_count = 0 ; 334double global_max_abs = 0.0 ; 335MismatchRecord first_mismatch {}; 336uint32_t case_seed = 0x574d4d41u ; 337 338const bool verbose = (std::getenv ("STRATA_TEST_VERBOSE" )!= nullptr ); 339 340for (bool is_bf16 : {false, true}) { 341const char * dtype_str = is_bf16 ?"bf16" :"f16" ; 342 std::printf ("Testing strata_wmma_gemm_%s across %zu shapes (%zu execution configs)...\n" , 343dtype_str ,k_t_values .size ()* k_n_values .size ()* k_k_values .size (),kConfigs .size ()); 344 345for (int64_t T :k_t_values ) { 346double t_max_abs = 0.0 ; 347size_t t_passed = 0 ; 348size_t t_skipped = 0 ; 349 350for (int64_t N :k_n_values ) { 351for (int64_t K :k_k_values ) { 352for (const auto & cfg :kConfigs ) { 353const int64_t ldy = N + cfg .ldy_offset ; 354double case_max_abs = 0.0 ; 355case_seed = case_seed * 1664525u + 1013904223u ; 356 357const CaseStatus status = run_gemm_case ( 358dx ,dw ,dy ,stream ,is_bf16 ,T ,N ,K ,ldy ,cfg .beta , 359case_seed ,case_max_abs ,& first_mismatch ,failure_count ); 360 361if (status == CaseStatus ::Passed ) { 362passed_count ++ ; 363t_passed ++ ; 364t_max_abs = std::max (t_max_abs ,case_max_abs ); 365global_max_abs = std::max (global_max_abs ,case_max_abs ); 366if (verbose ) { 367 std::printf (" case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f max_abs=%.9g PASS\n" , 368dtype_str ,T ,N ,K ,ldy ,cfg .beta ,case_max_abs ); 369 } 370 }else if (status == CaseStatus ::Skipped ) { 371skipped_count ++ ; 372t_skipped ++ ; 373if (verbose ) { 374 std::printf (" case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f SKIP (declined)\n" , 375dtype_str ,T ,N ,K ,ldy ,cfg .beta ); 376 } 377 }else { 378// Failed: first_mismatch already recorded and reported to stderr 379if (verbose ) { 380 std::printf (" case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f FAIL\n" , 381dtype_str ,T ,N ,K ,ldy ,cfg .beta ); 382 } 383 } 384 } 385 } 386 } 387 std::printf (" dtype=%s T=%3ld: %zu passed, %zu skipped, max_abs=%.9g %s\n" , 388dtype_str ,T ,t_passed ,t_skipped ,t_max_abs , 389 (failure_count == 0 ) ?"PASS" :"FAIL" ); 390 } 391 392// Test declined shapes: the kernel must return false and be skipped. 393for (const auto & decl :kDeclinedShapes ) { 394const bool launched = is_bf16 395 ?strata_wmma_gemm_bf16 (static_cast < const uint16_t *> (dx .p ), 396static_cast < const uint16_t *> (dw .p ), 397static_cast < float *> (dy .p ), 398decl .T ,decl .N ,decl .K ,decl .ldy ,decl .beta ,stream ) 399 :strata_wmma_gemm_f16 (static_cast < const uint16_t *> (dx .p ), 400static_cast < const uint16_t *> (dw .p ), 401static_cast < float *> (dy .p ), 402decl .T ,decl .N ,decl .K ,decl .ldy ,decl .beta ,stream ); 403 404if (launched ) { 405failure_count ++ ; 406 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" , 407decl .reason ,dtype_str ,decl .T ,decl .N ,decl .K ,decl .ldy ,decl .beta ); 408 }else { 409skipped_count ++ ; 410if (verbose ) { 411 std::printf (" declined shape correctly rejected (%s): dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f SKIP\n" , 412decl .reason ,dtype_str ,decl .T ,decl .N ,decl .K ,decl .ldy ,decl .beta ); 413 } 414 } 415 } 416 } 417 418HIP_CHECK (hipStreamDestroy (stream )); 419 420if (failure_count > 0 ) { 421if (first_mismatch .dtype [0 ]!= '\0' ) { 422if (first_mismatch .is_padding ) { 423 std::fprintf (stderr ,"\nSUMMARY: First mismatch was padding/guard corruption:\n" 424" dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g expected=%.9g\n" , 425first_mismatch .dtype ,first_mismatch .T ,first_mismatch .N ,first_mismatch .K , 426first_mismatch .ldy ,first_mismatch .beta ,first_mismatch .row ,first_mismatch .col , 427first_mismatch .got ,first_mismatch .ref ); 428 }else { 429 std::fprintf (stderr ,"\nSUMMARY: First mismatch occurred at:\n" 430" dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g ref=%.9g delta=%.9g\n" , 431first_mismatch .dtype ,first_mismatch .T ,first_mismatch .N ,first_mismatch .K , 432first_mismatch .ldy ,first_mismatch .beta ,first_mismatch .row ,first_mismatch .col , 433first_mismatch .got ,first_mismatch .ref ,first_mismatch .delta ); 434 } 435 } 436 std::fprintf (stderr ,"WMMA GEMM parity FAILED: %zu failures detected, max_abs=%.9g\n" , 437failure_count ,global_max_abs ); 438return 1 ; 439 } 440 441if (passed_count == 0 ) { 442 std::fprintf (stderr ,"WMMA GEMM parity FAILED: zero test cases passed (all were declined or skipped)\n" ); 443return 1 ; 444 } 445 446 std::printf ("\nWMMA GEMM parity OK: %zu test cases passed, %zu declined shapes skipped, max_abs=%.9g\n" , 447passed_count ,skipped_count ,global_max_abs ); 448return 0 ; 449}