okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5af104b51
main
1// src/prefill/gemm_bf16_parity.cu - Gemm::bf16 against cuBLAS's own BF16 product (GPU, synthetic, no model). 2// 3// Below sm_80 (no BF16 tensor cores) Gemm::bf16 converts the weight and the activations to FP16 and runs the FP16 4// tensor-core GEMM (Volta by default, Turing with STRATA_BF16_TC=1) or widens them to fp32 (Pascal); everywhere else 5// it is the cuBLAS BF16 call itself. (On Pascal the cuBLAS BF16 reference itself may be refused: the test then fails 6// at the reference, which says so.) This 7// checks the result against cublasGemmEx on the same BF16 inputs, within fp32-accumulation rounding, over the prompt 8// path's shapes: the hyper-connection down / up projections, the router and indexer rows, the PLE value matrix, a T 9// large enough to slice the activations, beta = 1 accumulation (the bf16x2 low parts) and an output row stride wider 10// than N. --bench adds the time of each against the cuBLAS BF16 product. 11#define DPCT_PROFILING_ENABLED 12#include <sycl/sycl.hpp> 13#include <dpct/dpct.hpp> 14#include "strata/prefill/gemm.hpp" 15#include <dpct/blas_utils.hpp> 16 17#include <algorithm> 18#include <chrono> 19#include <cmath> 20#include <cstdint> 21#include <cstdio> 22#include <cstring> 23#include <random> 24#include <string> 25#include <vector> 26#include <dpct/lib_common_utils.hpp> 27 28namespace { 29 30uint16_t to_bf16 (float f ) {// round to nearest even 31uint32_t u ; 32 std::memcpy (& u ,& f ,4 ); 33u += 0x7fffu + ((u >>16 )& 1u ); 34return (uint16_t ) (u >>16 ); 35} 36 37bool ok_or (dpct::err0 e ,const char * what ) { 38/* 39DPCT1009: SYCL reports errors using exceptions and does not use error 40codes. Please replace the "get_error_string_dummy(...)" with a real 41error-handling function. 42*/ 43 44return e == 0 ; 45} 46 47struct Shape { 48int64_t T ,N ,K ,ldy ; 49const char * what ; 50}; 51 52}// namespace 53 54int main (int argc ,char ** argv )try { 55const bool bench = argc > 1 && std::string (argv [1 ])== "--bench" ; 56int dev = 0 ,maj = 0 ,min = 0 ; 57dev = dpct::get_current_device_id (); 58maj = dpct::get_device (dev ).get_major_version (); 59min = dpct::get_device (dev ).get_minor_version (); 60 std::printf ("gemm_bf16_parity: compute capability %d.%d\n" ,maj ,min ); 61 62 dpct::queue_ptr st = & dpct::get_in_order_queue (); 63if (!ok_or (DPCT_CHECK_ERROR ( 64st = dpct::get_current_device ().create_queue (true)), 65"stream" ))return 1 ; 66 strata::prefill::Gemm gemm ; 67 std::string err ; 68if (!gemm .init (st ,0 ,err )) { std::printf ("FAIL: %s\n" ,err .c_str ());return 1 ; } 69 dpct::blas::descriptor_ptr h = nullptr ; 70if (DPCT_CHECK_ERROR (h = new dpct::blas::descriptor ())!= 0 ) { 71 std::printf ("FAIL: cublasCreate\n" );return 1 ; 72 } 73h -> set_queue (st ); 74 75const Shape shapes []= { 76 {4096 ,320 ,10240 ,0 ,"hc down (activations sliced)" }, 77 {4096 ,10240 ,320 ,0 ,"hc up" }, 78 {777 ,2560 ,2560 ,0 ,"PLE value" }, 79 {512 ,512 ,2560 ,0 ,"router / indexer q" }, 80 {300 ,4 ,10240 ,0 ,"hc inject" }, 81 {2048 ,1 ,2560 ,0 ,"single row" }, 82 {333 ,128 ,2560 ,136 ,"row stride wider than N" }, 83 }; 84 std::mt19937 rng (1234 ); 85 std::normal_distribution < float > nd (0.0f ,1.0f ); 86int failures = 0 ; 87for (const Shape & s :shapes ) { 88const int64_t ldy = s .ldy > 0 ?s .ldy :s .N ; 89 std::vector < uint16_t > x ((size_t ) (s .T * s .K )),xlo (x .size ()),w ((size_t ) (s .N * s .K )); 90for (size_t i = 0 ;i < x .size ();++ i ) { 91const float v = 3.0f * nd (rng );// activations: normalized, a few units 92x [i ]= to_bf16 (v ); 93xlo [i ]= to_bf16 (1e-3f * nd (rng ));// a bf16x2 low part 94 } 95for (auto & v :w )v = to_bf16 (0.02f * nd (rng )); 96uint16_t * dx = nullptr ,* dxlo = nullptr ,* dw = nullptr ; 97float * dy = nullptr ,* dr = nullptr ; 98const size_t ybytes = (size_t ) (s .T * ldy )* 4 ; 99bool ok = 100ok_or ( 101DPCT_CHECK_ERROR (dx = (uint16_t * )sycl::malloc_device ( 102x .size ()* 2 , dpct::get_in_order_queue ())), 103"x" )&& 104ok_or ( 105DPCT_CHECK_ERROR (dxlo = (uint16_t * )sycl::malloc_device ( 106x .size ()* 2 , dpct::get_in_order_queue ())), 107"xlo" )&& 108ok_or ( 109DPCT_CHECK_ERROR (dw = (uint16_t * )sycl::malloc_device ( 110w .size ()* 2 , dpct::get_in_order_queue ())), 111"w" )&& 112ok_or (DPCT_CHECK_ERROR (dy = (float * )sycl::malloc_device ( 113ybytes , dpct::get_in_order_queue ())), 114"y" )&& 115ok_or (DPCT_CHECK_ERROR (dr = (float * )sycl::malloc_device ( 116ybytes , dpct::get_in_order_queue ())), 117"ref" ); 118if (!ok )return 1 ; 119/* 120DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 121assuming in the original code the source host memory is pageable memory. 122If the memory is not pageable, call wait() on event return by memcpy API 123to ensure synchronization behavior. 124*/ 125 dpct::get_in_order_queue ().memcpy (dx ,x .data (),x .size ()* 2 ).wait (); 126/* 127DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 128assuming in the original code the source host memory is pageable memory. 129If the memory is not pageable, call wait() on event return by memcpy API 130to ensure synchronization behavior. 131*/ 132 dpct::get_in_order_queue ().memcpy (dxlo ,xlo .data (),xlo .size ()* 2 ).wait (); 133/* 134DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 135assuming in the original code the source host memory is pageable memory. 136If the memory is not pageable, call wait() on event return by memcpy API 137to ensure synchronization behavior. 138*/ 139 dpct::get_in_order_queue ().memcpy (dw ,w .data (),w .size ()* 2 ).wait (); 140 dpct::get_in_order_queue ().memset (dy ,0 ,ybytes ).wait (); 141 dpct::get_in_order_queue ().memset (dr ,0 ,ybytes ).wait (); 142 143// the product under test: X . W^T, then the low part added with beta = 1 144gemm .bf16 (dx ,dw ,dy ,s .T ,s .N ,s .K ,ldy ); 145gemm .bf16 (dxlo ,dw ,dy ,s .T ,s .N ,s .K ,ldy ,1.0f ); 146// the reference: cuBLAS on the BF16 inputs, the same two calls 147const float one = 1.0f ,zero = 0.0f ; 148auto ref = [& ](const uint16_t * X ,float beta ) { 149/* 150DPCT1020: Migration of cublasGemmEx, if it is called from 151__global__ or __device__ function, is not supported. You may need to 152redesign the code to use the host-side dpct::blas::gemm instead, 153which submits this call to the SYCL queue automatically. 154*/ 155return cublasGemmEx ( 156h , oneapi::mkl::transpose::trans , 157 oneapi::mkl::transpose::nontrans , (int )s .N , (int )s .T , (int )s .K , 158& one ,dw , dpct::library_data_t::real_bfloat16 , (int )s .K ,X , 159 dpct::library_data_t::real_bfloat16 , (int )s .K ,& beta ,dr , 160 dpct::library_data_t::real_float , (int )ldy , 161 dpct::compute_type::f32 ,-1 ); 162 }; 163if (ref (dx ,zero )!= 0 || ref (dxlo ,one )!= 0 ) { 164 std::printf ("FAIL: reference cublasGemmEx\n" ); 165return 1 ; 166 } 167if (!ok_or (DPCT_CHECK_ERROR (st -> wait ()),"sync" ))return 1 ; 168 std::vector < float > y ((size_t ) (s .T * ldy )),r (y .size ()); 169 dpct::get_in_order_queue ().memcpy (y .data (),dy ,ybytes ).wait (); 170 dpct::get_in_order_queue ().memcpy (r .data (),dr ,ybytes ).wait (); 171double worst = 0.0 ,mag = 1e-30 ; 172int bad = 0 ; 173for (int64_t t = 0 ;t < s .T ;++ t ) 174for (int64_t c = 0 ;c < s .N ;++ c ) { 175const float a = y [(size_t ) (t * ldy + c )],b = r [(size_t ) (t * ldy + c )]; 176if (!std::isfinite (a ))++ bad ; 177worst = std::max (worst , (double ) std::fabs (a - b )); 178mag = std::max (mag , (double ) std::fabs (b )); 179 } 180// the untouched columns of a wider row stride stay as they were 181for (int64_t t = 0 ;t < s .T && ldy > s .N ;++ t ) 182for (int64_t c = s .N ;c < ldy ;++ c ) 183if (y [(size_t ) (t * ldy + c )]!= 0.0f )++ bad ; 184const bool pass = bad == 0 && worst <=1e-4 * mag ; 185if (!pass )++ failures ; 186 std::printf (" %-32s T %5lld N %5lld K %5lld ldy %5lld: worst |diff| %.3e of max |ref| %.3e (rel %.2e) %s\n" , 187s .what , (long long )s .T , (long long )s .N , (long long )s .K , (long long )ldy ,worst ,mag ,worst /mag , 188pass ?"pass" :"FAIL" ); 189 190if (bench ) { 191auto time = [& ](auto && f ) { 192#pragma unroll 193for (int i = 0 ;i < 3 ;++ i )f (); 194st -> wait (); 195const auto t0 = std::chrono::steady_clock::now (); 196#pragma unroll 197for (int i = 0 ;i < 20 ;++ i )f (); 198st -> wait (); 199return std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count () /20 ; 200 }; 201const double us_gemm = time ([& ] {gemm .bf16 (dx ,dw ,dy ,s .T ,s .N ,s .K ,ldy ); }); 202const double us_ref = time ([& ] {ref (dx ,zero ); }); 203 std::printf (" bench: Gemm::bf16 %9.1f us cuBLAS BF16 %9.1f us (%.2fx)\n" ,us_gemm ,us_ref , 204us_ref /us_gemm ); 205 } 206 sycl::free (dx , dpct::get_in_order_queue ()); 207 sycl::free (dxlo , dpct::get_in_order_queue ()); 208 sycl::free (dw , dpct::get_in_order_queue ()); 209 sycl::free (dy , dpct::get_in_order_queue ()); 210 sycl::free (dr , dpct::get_in_order_queue ()); 211 } 212delete (h ); 213 dpct::get_current_device ().destroy_queue (st ); 214 std::printf ("gemm_bf16_parity: %d failures\n" ,failures ); 215return failures == 0 ?0 :1 ; 216} 217catch (sycl::exception const & exc ) { 218 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 219 <<", line:" <<__LINE__ << std::endl ; 220 std::exit (1 ); 221}