okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
025602c2b
main
1#include <hip/hip_runtime.h> 2#include <hip/hip_fp16.h> 3#include <hip/hip_bfloat16.h> 4#include "../../include/strata/kernels/bf16_bits.hpp" 5#include <hip/hip_version.h> 6#include <hipblas/hipblas.h> 7#include <hipblaslt/hipblaslt.h> 8#include <hipblaslt/hipblaslt-ext.hpp> 9 10#include <algorithm> 11#include <cmath> 12#include <cstdint> 13#include <cstdio> 14#include <cstdlib> 15#include <cstring> 16#include <fstream> 17#include <functional> 18#include <iomanip> 19#include <iostream> 20#include <iterator> 21#include <limits> 22#include <random> 23#include <regex> 24#include <sstream> 25#include <string> 26#include <vector> 27 28namespace { 29#define HIP_CHECK (call ) do { const hipError_t e = (call); if (e != hipSuccess) { \ 30 std::fprintf(stderr, "HIP %s:%d: %s: %s\n", __FILE__, __LINE__, #call, hipGetErrorString(e)); std::exit(2); } } while (0) 31#define BLAS_CHECK (call ) do { const hipblasStatus_t e = (call); if (e != HIPBLAS_STATUS_SUCCESS) { \ 32 std::fprintf(stderr, "hipBLAS %s:%d: %s: status=%d\n", __FILE__, __LINE__, #call, (int)e); std::exit(2); } } while (0) 33#define LT_CHECK (call ) do { const hipblasStatus_t e = (call); if (e != HIPBLAS_STATUS_SUCCESS) { \ 34 std::fprintf(stderr, "hipBLASLt %s:%d: %s: status=%d\n", __FILE__, __LINE__, #call, (int)e); std::exit(2); } } while (0) 35 36struct Buffer { 37void * p = nullptr ; 38explicit Buffer (size_t bytes ) {if (bytes )HIP_CHECK (hipMalloc (& p ,bytes )); } 39 ~Buffer () {if (p ) (void )hipFree (p ); } 40Buffer (const Buffer & )= delete ; 41Buffer & operator= (const Buffer & )= delete ; 42}; 43struct Events { 44hipEvent_t a = nullptr ,b = nullptr ; 45Events () {HIP_CHECK (hipEventCreate (& a ));HIP_CHECK (hipEventCreate (& b )); } 46 ~Events () {if (a ) (void )hipEventDestroy (a );if (b ) (void )hipEventDestroy (b ); } 47}; 48 49struct Shape {int t ,n ,k ,ldy ;bool bf16 ; }; 50struct Options { 51size_t workspace = 32U * 1024U * 1024U ; 52 std::vector < Shape > shapes ; 53 std::vector < int > tokens {4096 ,8192 }; 54 std::string shapes_file ,tuning_out ; 55bool explicit_shapes = false; 56}; 57struct Err {double rel_l2 ,max_abs ;bool finite ;size_t padding_writes ; }; 58struct Best { 59Shape s ; 60int heuristic_index ,solution_id ; 61size_t required_workspace ,algo_workspace ; 62float mean_ms ; 63Err error ; 64 std::string solution ,kernel ,config ; 65}; 66 67constexpr int WARMUPS = 2 ; 68constexpr int REPS = 3 ; 69constexpr int MAX_ALGOS = 16 ; 70constexpr double REL_L2_TOL = 1e-4 ; 71constexpr double MAX_ABS_TOL = 1e-2 ; 72constexpr float PADDING_CANARY = 123456.25f ; 73 74const char * dtype (bool bf16 ) {return bf16 ?"bf16" :"f16" ; } 75const char * status_name (hipblasStatus_t s ) { 76switch (s ) { 77case HIPBLAS_STATUS_SUCCESS :return "success" ; 78case HIPBLAS_STATUS_NOT_SUPPORTED :return "not_supported" ; 79case HIPBLAS_STATUS_INVALID_VALUE :return "invalid_value" ; 80case HIPBLAS_STATUS_ARCH_MISMATCH :return "arch_mismatch" ; 81default :return "other" ; 82 } 83} 84std::string json (const std::string & s ) { 85 std::ostringstream o ;o <<'"' ; 86for (unsigned char c :s ) { 87if (c == '"' )o <<"\\\"" ; 88else if (c == '\\' )o <<"\\\\" ; 89else if (c == '\n' )o <<"\\n" ; 90else if (c == '\r' )o <<"\\r" ; 91else if (c == '\t' )o <<"\\t" ; 92else if (c < 0x20 )o <<"\\u" << std::hex << std::setw (4 ) << std::setfill ('0' ) << (unsigned )c << std::dec ; 93else o << (char )c ; 94 } 95o <<'"' ;return o .str (); 96} 97std::string config_hex (const hipblasLtMatmulAlgo_t & algo ) { 98 std::ostringstream o ;o << std::hex << std::setfill ('0' ); 99for (uint8_t b :algo .data )o << std::setw (2 ) << (unsigned )b ; 100return o .str (); 101} 102uint16_t input_bits (float x ,bool bf16 ) { 103if (bf16 )return strata::kernels::bf16_from_f32 (x ); 104const __half half = __float2half_rn (x ); 105uint16_t bits = 0 ; 106 std::memcpy (& bits ,& half ,sizeof (bits )); 107return bits ; 108} 109void fill (std::vector < uint16_t > & v ,uint32_t seed ,bool bf16 ) { 110 std::mt19937 rng (seed ); 111 std::uniform_real_distribution < float > dist (-1.0f ,1.0f ); 112for (auto & x :v )x = input_bits (dist (rng ),bf16 ); 113} 114float time_call (hipStream_t stream ,const std::function < void ()> & f ) { 115Events ev ; 116HIP_CHECK (hipEventRecord (ev .a ,stream )); 117f (); 118HIP_CHECK (hipEventRecord (ev .b ,stream )); 119HIP_CHECK (hipEventSynchronize (ev .b )); 120HIP_CHECK (hipDeviceSynchronize ()); 121float ms = 0 ; 122HIP_CHECK (hipEventElapsedTime (& ms ,ev .a ,ev .b )); 123return ms ; 124} 125Err compare (const std::vector < float > & ref ,const std::vector < float > & got ,int n ,int t ,int ld ) { 126long double d2 = 0 ,r2 = 0 ;double max_abs = 0 ;bool finite = true; 127for (int col = 0 ;col < t ;++ col )for (int row = 0 ;row < n ;++ row ) { 128const size_t i = (size_t )col * ld + row ; 129const double r = ref [i ],g = got [i ]; 130if (!std::isfinite (r )|| !std::isfinite (g )) {finite = false;continue ; } 131const double d = g - r ; 132if (!std::isfinite (d )) {finite = false;continue ; } 133d2 += (long double )d * d ;r2 += (long double )r * r ; 134max_abs = std::max (max_abs , std::abs (d )); 135 } 136if (!finite )return {std::numeric_limits < double > ::infinity (), 137 std::numeric_limits < double > ::infinity (), false,0 }; 138return {std::sqrt ((double )(d2 / std::max (r2 ,1e-300L ))),max_abs , true,0 }; 139} 140size_t padding_writes (const std::vector < float > & got ,int n ,int t ,int ld ) { 141size_t writes = 0 ; 142for (int col = 0 ;col < t ;++ col )for (int row = n ;row < ld ;++ row ) 143if (got [(size_t )col * ld + row ]!= PADDING_CANARY )++ writes ; 144return writes ; 145} 146bool accuracy_ok (const Err & e ) { 147return e .finite && e .padding_writes == 0 && 148e .rel_l2 <=REL_L2_TOL && e .max_abs <=MAX_ABS_TOL ; 149} 150std::vector < std::string > csv (const std::string & s ) { 151 std::vector < std::string > out ;size_t b = 0 ; 152for (;;) { 153const size_t p = s .find (',' ,b ); 154out .push_back (s .substr (b ,p == std::string::npos ?p :p - b )); 155if (p == std::string::npos )return out ; 156b = p + 1 ; 157 } 158} 159int positive (const std::string & s ,const char * label ) { 160char * e = nullptr ;const long v = std::strtol (s .c_str (),& e ,10 ); 161if (s .empty ()|| !e || * e || v < 1 || v > std::numeric_limits < int > ::max ()) { 162 std::fprintf (stderr ,"invalid %s: %s\n" ,label ,s .c_str ()); std::exit (2 ); 163 } 164return (int )v ; 165} 166void add (Options & o ,bool bf16 ,int t ,int n ,int k ,int ldy ) { 167if (ldy < n ) { std::fprintf (stderr ,"ldy must be >= N\n" ); std::exit (2 ); } 168o .shapes .push_back ({t ,n ,k ,ldy ,bf16 }); 169} 170void add_shape (Options & o ,const std::string & v ) { 171const auto f = csv (v ); 172if (f .size ()!= 3 ) { std::fprintf (stderr ,"--shape expects T,N,K\n" ); std::exit (2 ); } 173int t = positive (f [0 ],"T" ),n = positive (f [1 ],"N" ),k = positive (f [2 ],"K" ); 174add (o ,false,t ,n ,k ,n );add (o ,true,t ,n ,k ,n );o .explicit_shapes = true; 175} 176void add_case (Options & o ,const std::string & v ) { 177const auto f = csv (v ); 178if (f .size ()!= 5 || (f [0 ]!= "f16" && f [0 ]!= "bf16" )) { 179 std::fprintf (stderr ,"--case expects dtype,T,N,K,ldy\n" ); std::exit (2 ); 180 } 181add (o ,f [0 ]== "bf16" ,positive (f [1 ],"T" ),positive (f [2 ],"N" ),positive (f [3 ],"K" ),positive (f [4 ],"ldy" )); 182o .explicit_shapes = true; 183} 184std::vector < int > parse_tokens (const std::string & s ) { 185 std::vector < int > out ; 186for (const auto & x :csv (s ))out .push_back (positive (x ,"token bucket" )); 187return out ; 188} 189void load_shapes (Options & o ) { 190 std::ifstream f (o .shapes_file ); 191if (!f ) { std::fprintf (stderr ,"cannot open shapes file: %s\n" ,o .shapes_file .c_str ()); std::exit (2 ); } 192const std::string text ((std::istreambuf_iterator < char > (f )),{}); 193const std::regex obj (R"(\{[^{}]*\})" ),dtype_re (R"re("dtype"\s*:\s*"(f16|bf16)")re" ), 194n_re (R"("N"\s*:\s*([0-9]+))" ),k_re (R"("K"\s*:\s*([0-9]+))" ), 195ld_re (R"("ldy"\s*:\s*([0-9]+))" ); 196int count = 0 ; 197for (auto i = std::sregex_iterator (text .begin (),text .end (),obj );i != std::sregex_iterator ();++ i ) { 198const std::string item = i -> str (); std::smatch d ,n ,k ,ld ; 199if (!std::regex_search (item ,d ,dtype_re )|| !std::regex_search (item ,n ,n_re )|| 200 !std::regex_search (item ,k ,k_re )|| !std::regex_search (item ,ld ,ld_re ))continue ; 201for (int t :o .tokens )add (o ,d [1 ]== "bf16" ,t ,positive (n [1 ],"N" ),positive (k [1 ],"K" ),positive (ld [1 ],"ldy" )); 202++ count ; 203 } 204if (!count ) { std::fprintf (stderr ,"no dtype,N,K,ldy entries in %s\n" ,o .shapes_file .c_str ()); std::exit (2 ); } 205o .explicit_shapes = true; 206} 207void usage (const char * p ) { 208 std::printf ("Usage: %s [--workspace-mib N] [--shape T,N,K]... [--case dtype,T,N,K,ldy]...\n" ,p ); 209 std::printf (" [--shapes-file PATH [--tokens T1,T2,...]] [--tuning-out PATH]\n" ); 210 std::printf ("Defaults: original three shapes, f16+bf16, T=8192, workspace=32 MiB.\n" ); 211} 212Options options (int argc ,char ** argv ) { 213Options o ; 214for (int i = 1 ;i < argc ;++ i ) { 215 std::string a = argv [i ]; 216auto next = [& ]()-> std::string {if (i + 1 >=argc ){std::fprintf (stderr ,"missing option value\n" );std::exit (2 );}return argv [++ i ]; }; 217if (a == "-h" || a == "--help" ){usage (argv [0 ]);std::exit (0 );} 218else if (a == "--workspace-mib" ){ 219 std::string v = next ();char * e = nullptr ;unsigned long long x = std::strtoull (v .c_str (),& e ,10 ); 220if (v .empty ()|| !e ||* e || x > std::numeric_limits < size_t > ::max ()/(1024ULL * 1024ULL )){std::fprintf (stderr ,"bad workspace MiB\n" );std::exit (2 );} 221o .workspace = (size_t )x * 1024U * 1024U ; 222 }else if (a == "--shape" )add_shape (o ,next ()); 223else if (a == "--case" )add_case (o ,next ()); 224else if (a == "--shapes-file" ){o .shapes_file = next ();o .explicit_shapes = true;} 225else if (a == "--tokens" )o .tokens = parse_tokens (next ()); 226else if (a == "--tuning-out" )o .tuning_out = next (); 227else {std::fprintf (stderr ,"unknown option: %s\n" ,a .c_str ());usage (argv [0 ]);std::exit (2 );} 228 } 229if (!o .shapes_file .empty ())load_shapes (o ); 230if (!o .explicit_shapes ) { 231struct DefaultShape {int n ,k ,ldy ;bool bf16 ; }; 232const DefaultShape defs []= {{10240 ,2560 ,10240 ,false},{320 ,10240 ,320 ,false},{2560 ,320 ,2560 ,false}, 233 {10240 ,2560 ,10240 ,true},{320 ,10240 ,320 ,true},{2560 ,320 ,2560 ,true}}; 234for (const auto & s :defs )add (o ,s .bf16 ,8192 ,s .n ,s .k ,s .ldy ); 235 } 236if (o .shapes .empty ()){std::fprintf (stderr ,"no shapes requested\n" );std::exit (2 );} 237return o ; 238} 239std::string arch_name (const char * s ) { 240 std::string a = s ?s :"unknown" ;size_t p = a .find (':' );if (p != std::string::npos )a .resize (p );return a ; 241} 242void emit_candidate (const Shape & s ,size_t workspace ,int h ,int id ,size_t req ,size_t algows ,float ms ,const Err & error , 243const std::string & arch ,int version ,const std::string & sol ,const std::string & kernel ,const std::string & config ) { 244 std::cout <<"candidate_json={\"device_arch\":" <<json (arch )<<",\"hipblaslt_version\":" <<version 245 <<",\"dtype\":" <<json (dtype (s .bf16 ))<<",\"T\":" <<s .t <<",\"N\":" <<s .n <<",\"K\":" <<s .k <<",\"ldy\":" <<s .ldy 246 <<",\"workspace_limit_bytes\":" <<workspace <<",\"heuristic_index\":" <<h <<",\"solution_id\":" <<id 247 <<",\"required_workspace_bytes\":" <<req <<",\"algo_max_workspace_bytes\":" <<algows 248 <<",\"finite\":" <<(error .finite ?"true" :"false" )<<",\"padding_writes\":" <<error .padding_writes 249 <<",\"relative_l2\":" <<std::setprecision (12 )<<error .rel_l2 <<",\"max_abs\":" <<error .max_abs 250 <<",\"relative_l2_tolerance\":" <<REL_L2_TOL <<",\"max_abs_tolerance\":" <<MAX_ABS_TOL 251 <<",\"mean_ms\":" <<std::setprecision (9 )<<ms <<",\"solution_name\":" <<json (sol ) 252 <<",\"kernel_name\":" <<json (kernel )<<",\"algo_config_hex\":" <<json (config )<<"}\n" ; 253} 254void emit_best (const Best & b ,size_t workspace ,const std::string & arch ,int version ,int hipver ) { 255const auto & s = b .s ; 256 std::cout <<"best_json={\"device_arch\":" <<json (arch )<<",\"hipblaslt_version\":" <<version 257 <<",\"hip_runtime_version\":" <<hipver <<",\"dtype\":" <<json (dtype (s .bf16 )) 258 <<",\"T\":" <<s .t <<",\"N\":" <<s .n <<",\"K\":" <<s .k <<",\"ldy\":" <<s .ldy 259 <<",\"workspace_limit_bytes\":" <<workspace <<",\"heuristic_index\":" <<b .heuristic_index 260 <<",\"solution_id\":" <<b .solution_id <<",\"required_workspace_bytes\":" <<b .required_workspace 261 <<",\"algo_max_workspace_bytes\":" <<b .algo_workspace <<",\"mean_ms\":" <<std::setprecision (9 )<<b .mean_ms 262 <<",\"finite\":" <<(b .error .finite ?"true" :"false" )<<",\"padding_writes\":" <<b .error .padding_writes 263 <<",\"relative_l2\":" <<std::setprecision (12 )<<b .error .rel_l2 <<",\"max_abs\":" <<b .error .max_abs 264 <<",\"relative_l2_tolerance\":" <<REL_L2_TOL <<",\"max_abs_tolerance\":" <<MAX_ABS_TOL 265 <<",\"solution_name\":" <<json (b .solution )<<",\"kernel_name\":" <<json (b .kernel ) 266 <<",\"algo_config_hex\":" <<json (b .config )<<"}\n" ; 267} 268 269void run_case (hipblasHandle_t blas ,hipblasLtHandle_t lt ,const Shape & s ,int case_id ,size_t ws ,hipStream_t stream , 270const std::string & arch ,int version ,int hipver ,std::vector < Best >& bests ) { 271const size_t na = (size_t )s .k * s .n ,nb = (size_t )s .k * s .t ,out_elems = (size_t )s .ldy * s .t ; 272const hipDataType it = s .bf16 ?HIP_R_16BF :HIP_R_16F ; 273const hipblasOperation_t ta = HIPBLAS_OP_T ,tb = HIPBLAS_OP_N ; 274const int m = s .n ,n = s .t ,k = s .k ,lda = s .k ,ldb = s .k ,ldc = s .ldy ; 275const float alpha = 1.f ,beta = 0.f ; 276 std::vector < uint16_t > ha (na ),hb (nb ); 277uint32_t seed = 0x5A17C3U + (uint32_t )case_id * 0x10001U + (s .bf16 ?0xB16U :0xF16U ); 278fill (ha ,seed ,s .bf16 );fill (hb ,seed ^0x9E3779B9U ,s .bf16 ); 279Buffer da (na * sizeof (uint16_t )),db (nb * sizeof (uint16_t )),dc (out_elems * sizeof (float )),dy (out_elems * sizeof (float )),dws (ws ); 280const std::vector < float > canary (out_elems ,PADDING_CANARY ); 281HIP_CHECK (hipMemcpyAsync (dc .p ,canary .data (),out_elems * sizeof (float ),hipMemcpyHostToDevice ,stream )); 282HIP_CHECK (hipMemcpyAsync (da .p ,ha .data (),na * sizeof (uint16_t ),hipMemcpyHostToDevice ,stream )); 283HIP_CHECK (hipMemcpyAsync (db .p ,hb .data (),nb * sizeof (uint16_t ),hipMemcpyHostToDevice ,stream )); 284HIP_CHECK (hipStreamSynchronize (stream )); 285 286hipblasLtMatmulDesc_t op = nullptr ; 287hipblasLtMatrixLayout_t ad = nullptr ,bd = nullptr ,cd = nullptr ; 288hipblasLtMatmulPreference_t pref = nullptr ; 289LT_CHECK (hipblasLtMatmulDescCreate (& op ,HIPBLAS_COMPUTE_32F ,HIP_R_32F )); 290LT_CHECK (hipblasLtMatmulDescSetAttribute (op ,HIPBLASLT_MATMUL_DESC_TRANSA ,& ta ,sizeof (ta ))); 291LT_CHECK (hipblasLtMatmulDescSetAttribute (op ,HIPBLASLT_MATMUL_DESC_TRANSB ,& tb ,sizeof (tb ))); 292LT_CHECK (hipblasLtMatrixLayoutCreate (& ad ,it ,s .k ,s .n ,lda )); 293LT_CHECK (hipblasLtMatrixLayoutCreate (& bd ,it ,s .k ,s .t ,ldb )); 294LT_CHECK (hipblasLtMatrixLayoutCreate (& cd ,HIP_R_32F ,s .n ,s .t ,ldc )); 295LT_CHECK (hipblasLtMatmulPreferenceCreate (& pref )); 296const uint64_t limit = ws ; 297LT_CHECK (hipblasLtMatmulPreferenceSetAttribute (pref ,HIPBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES ,& limit ,sizeof (limit ))); 298 299BLAS_CHECK (hipblasSetStream (blas ,stream )); 300auto base = [& ]{BLAS_CHECK (hipblasGemmEx (blas ,ta ,tb ,m ,n ,k ,& alpha ,da .p ,it ,lda ,db .p ,it ,ldb ,& beta ,dc .p ,HIP_R_32F ,ldc ,HIPBLAS_COMPUTE_32F ,HIPBLAS_GEMM_DEFAULT ));}; 301for (int i = 0 ;i < WARMUPS ;++ i ){base ();HIP_CHECK (hipDeviceSynchronize ());} 302float base_ms [REPS ]{}; 303for (int i = 0 ;i < REPS ;++ i )base_ms [i ]= time_call (stream ,base ); 304 std::vector < float > ref (out_elems ); 305HIP_CHECK (hipMemcpyAsync (ref .data (),dc .p ,out_elems * sizeof (float ),hipMemcpyDeviceToHost ,stream )); 306HIP_CHECK (hipStreamSynchronize (stream )); 307const size_t baseline_padding = padding_writes (ref ,s .n ,s .t ,s .ldy ); 308 std::printf ("baseline dtype=%s T=%d N=%d K=%d ldy=%d padding_writes=%zu\n" ,dtype (s .bf16 ),s .t ,s .n ,s .k ,s .ldy ,baseline_padding ); 309float base_mean = (base_ms [0 ]+ base_ms [1 ]+ base_ms [2 ])/REPS ; 310 311hipblasLtMatmulHeuristicResult_t hs [MAX_ALGOS ]{}; 312int count = 0 ; 313const hipblasStatus_t query = hipblasLtMatmulAlgoGetHeuristic (lt ,op ,ad ,bd ,cd ,cd ,pref ,MAX_ALGOS ,hs ,& count ); 314 std::printf ("case dtype=%s T=%d N=%d K=%d ldy=%d workspace_limit_bytes=%zu baseline=hipblasGemmEx rep1_ms=%.4f rep2_ms=%.4f rep3_ms=%.4f mean_ms=%.4f\n" , 315dtype (s .bf16 ),s .t ,s .n ,s .k ,s .ldy ,ws ,base_ms [0 ],base_ms [1 ],base_ms [2 ],base_mean ); 316if (query != HIPBLAS_STATUS_SUCCESS || count == 0 ){ 317 std::printf ("lt_unsupported dtype=%s T=%d N=%d K=%d ldy=%d status=%s(%d) heuristic_count=%d\n" , 318dtype (s .bf16 ),s .t ,s .n ,s .k ,s .ldy ,status_name (query ),(int )query ,count ); 319 }else { 320int best_h = -1 ,best_id = -1 ;float best_ms = std::numeric_limits < float > ::infinity (); 321size_t best_req = 0 ,best_maxws = 0 ; std::string best_sol ,best_kernel ,best_config ; 322Err best_error {std::numeric_limits < double > ::infinity (),std::numeric_limits < double > ::infinity (),false,0 }; 323for (int h = 0 ;h < count ;++ h ){ 324if (hs [h ].state != HIPBLAS_STATUS_SUCCESS || hs [h ].workspaceSize > ws ){ 325 std::printf ("lt_skip dtype=%s T=%d N=%d K=%d ldy=%d heuristic_index=%d status=%s(%d) required_workspace_bytes=%zu\n" , 326dtype (s .bf16 ),s .t ,s .n ,s .k ,s .ldy ,h ,status_name (hs [h ].state ),(int )hs [h ].state ,hs [h ].workspaceSize ); 327continue ; 328 } 329auto algo = hs [h ].algo ; 330const int id = hipblaslt_ext::getIndexFromAlgo (algo ); 331const std::string sol = hipblaslt_ext::getSolutionNameFromAlgo (lt ,algo ); 332const std::string kernel = hipblaslt_ext::getKernelNameFromAlgo (lt ,algo ); 333const std::string config = config_hex (algo ); 334auto run = [& ]{LT_CHECK (hipblasLtMatmul (lt ,op ,& alpha ,da .p ,ad ,db .p ,bd ,& beta ,dy .p ,cd ,dy .p ,cd ,& algo ,dws .p ,ws ,stream ));}; 335 336HIP_CHECK (hipMemcpyAsync (dy .p ,canary .data (),out_elems * sizeof (float ),hipMemcpyHostToDevice ,stream )); 337HIP_CHECK (hipStreamSynchronize (stream )); 338const hipblasStatus_t check_status = hipblasLtMatmul (lt ,op ,& alpha ,da .p ,ad ,db .p ,bd ,& beta ,dy .p ,cd ,dy .p ,cd ,& algo ,dws .p ,ws ,stream ); 339if (check_status != HIPBLAS_STATUS_SUCCESS ){ 340 std::printf ("lt_unsupported dtype=%s T=%d N=%d K=%d ldy=%d heuristic_index=%d solution_id=%d status=%s(%d) phase=accuracy_check\n" , 341dtype (s .bf16 ),s .t ,s .n ,s .k ,s .ldy ,h ,id ,status_name (check_status ),(int )check_status );continue ; 342 } 343HIP_CHECK (hipStreamSynchronize (stream )); 344 std::vector < float > checked_y (out_elems ); 345HIP_CHECK (hipMemcpyAsync (checked_y .data (),dy .p ,out_elems * sizeof (float ),hipMemcpyDeviceToHost ,stream )); 346HIP_CHECK (hipStreamSynchronize (stream )); 347Err error = compare (ref ,checked_y ,s .n ,s .t ,s .ldy ); 348error .padding_writes = padding_writes (checked_y ,s .n ,s .t ,s .ldy ); 349if (!accuracy_ok (error )){ 350 std::printf ("lt_reject dtype=%s T=%d N=%d K=%d ldy=%d heuristic_index=%d solution_id=%d finite=%s relative_l2=%.12g relative_l2_tolerance=%.3g max_abs=%.12g max_abs_tolerance=%.3g padding_writes=%zu reason=accuracy_gate\n" , 351dtype (s .bf16 ),s .t ,s .n ,s .k ,s .ldy ,h ,id ,error .finite ?"true" :"false" , 352error .rel_l2 ,REL_L2_TOL ,error .max_abs ,MAX_ABS_TOL ,error .padding_writes );continue ; 353 } 354 355bool failed = false; 356for (int i = 0 ;i < WARMUPS ;++ i ){ 357const hipblasStatus_t st = hipblasLtMatmul (lt ,op ,& alpha ,da .p ,ad ,db .p ,bd ,& beta ,dy .p ,cd ,dy .p ,cd ,& algo ,dws .p ,ws ,stream ); 358if (st != HIPBLAS_STATUS_SUCCESS ){ 359 std::printf ("lt_unsupported dtype=%s T=%d N=%d K=%d ldy=%d heuristic_index=%d solution_id=%d status=%s(%d)\n" , 360dtype (s .bf16 ),s .t ,s .n ,s .k ,s .ldy ,h ,id ,status_name (st ),(int )st );failed = true;break ; 361 } 362HIP_CHECK (hipDeviceSynchronize ()); 363 } 364if (failed )continue ; 365float ms [REPS ]{}; 366for (int i = 0 ;i < REPS ;++ i )ms [i ]= time_call (stream ,run ); 367const float mean = (ms [0 ]+ ms [1 ]+ ms [2 ])/REPS ; 368 std::printf ("lt dtype=%s T=%d N=%d K=%d ldy=%d heuristic_index=%d solution_id=%d solution=%s kernel=%s algo_config_hex=%s required_workspace_bytes=%zu algo_max_workspace_bytes=%zu finite=%s relative_l2=%.12g max_abs=%.12g padding_writes=%zu rep1_ms=%.4f rep2_ms=%.4f rep3_ms=%.4f mean_ms=%.4f\n" , 369dtype (s .bf16 ),s .t ,s .n ,s .k ,s .ldy ,h ,id ,sol .c_str (),kernel .c_str (),config .c_str (),hs [h ].workspaceSize ,algo .max_workspace_bytes , 370error .finite ?"true" :"false" ,error .rel_l2 ,error .max_abs ,error .padding_writes ,ms [0 ],ms [1 ],ms [2 ],mean ); 371emit_candidate (s ,ws ,h ,id ,hs [h ].workspaceSize ,algo .max_workspace_bytes ,mean ,error ,arch ,version ,sol ,kernel ,config ); 372if (mean < best_ms ){ 373best_h = h ;best_id = id ;best_ms = mean ;best_req = hs [h ].workspaceSize ;best_maxws = algo .max_workspace_bytes ; 374best_sol = sol ;best_kernel = kernel ;best_config = config ;best_error = error ; 375 } 376 } 377if (best_h < 0 )std::printf ("lt_unsupported dtype=%s T=%d N=%d K=%d ldy=%d status=no_valid_heuristics heuristic_count=%d\n" , 378dtype (s .bf16 ),s .t ,s .n ,s .k ,s .ldy ,count ); 379else { 380Best b {s ,best_h ,best_id ,best_req ,best_maxws ,best_ms ,best_error ,best_sol ,best_kernel ,best_config }; 381bests .push_back (b ); 382 std::printf ("lt_best dtype=%s T=%d N=%d K=%d ldy=%d heuristic_index=%d solution_id=%d solution=%s kernel=%s algo_config_hex=%s required_workspace_bytes=%zu algo_max_workspace_bytes=%zu mean_ms=%.4f speedup_vs_blas=%.4fx finite=%s relative_l2=%.9g max_abs=%.9g padding_writes=%zu\n" , 383dtype (s .bf16 ),s .t ,s .n ,s .k ,s .ldy ,best_h ,best_id ,best_sol .c_str (),best_kernel .c_str (),best_config .c_str (),best_req ,best_maxws ,best_ms ,base_mean /best_ms , 384best_error .finite ?"true" :"false" ,best_error .rel_l2 ,best_error .max_abs ,best_error .padding_writes ); 385emit_best (b ,ws ,arch ,version ,hipver ); 386 } 387 } 388 (void )hipblasLtMatmulPreferenceDestroy (pref ); 389 (void )hipblasLtMatrixLayoutDestroy (cd );(void )hipblasLtMatrixLayoutDestroy (bd );(void )hipblasLtMatrixLayoutDestroy (ad ); 390 (void )hipblasLtMatmulDescDestroy (op ); 391} 392void tuning_file (const std::string & path ,const std::string & arch ,int version ,const std::vector < Best >& rows ){ 393if (path .empty ())return ; 394 std::ofstream f (path ); 395if (!f ){std::fprintf (stderr ,"cannot write tuning output: %s\n" ,path .c_str ());std::exit (2 );} 396f <<"# solution IDs are scoped to this hipBLASLt version and device architecture\n" ; 397f <<"STRATA_HIPBLASLT_TUNING_V1 " <<arch <<" " <<version <<"\n" ; 398for (const auto & b :rows )f <<dtype (b .s .bf16 )<<" " <<b .s .n <<" " <<b .s .k <<" " <<b .s .ldy <<" " <<b .s .t <<" " <<b .solution_id <<"\n" ; 399} 400}// namespace 401 402int main (int argc ,char ** argv ){ 403Options o = options (argc ,argv ); 404hipblasHandle_t blas = nullptr ;hipblasLtHandle_t lt = nullptr ; 405BLAS_CHECK (hipblasCreate (& blas ));LT_CHECK (hipblasLtCreate (& lt )); 406int device = 0 ,hipver = 0 ,version = 0 ;hipDeviceProp_t prop {}; 407HIP_CHECK (hipGetDevice (& device ));HIP_CHECK (hipGetDeviceProperties (& prop ,device ));HIP_CHECK (hipRuntimeGetVersion (& hipver )); 408const hipblasStatus_t vs = hipblasLtGetVersion (lt ,& version ); 409if (vs != HIPBLAS_STATUS_SUCCESS ){std::fprintf (stderr ,"hipblasLtGetVersion failed: %d\n" ,(int )vs );return 2 ;} 410const std::string arch = arch_name (prop .gcnArchName ); 411 std::printf ("meta device_arch=%s hipblaslt_version=%d hipblaslt_header_version=%d.%d.%d hip_runtime_version=%d\n" , 412arch .c_str (),version ,HIPBLASLT_VERSION_MAJOR ,HIPBLASLT_VERSION_MINOR ,HIPBLASLT_VERSION_PATCH ,hipver ); 413hipStream_t stream = nullptr ;HIP_CHECK (hipStreamCreateWithFlags (& stream ,hipStreamNonBlocking )); 414 std::vector < Best > bests ; 415for (size_t i = 0 ;i < o .shapes .size ();++ i )run_case (blas ,lt ,o .shapes [i ],(int )i ,o .workspace ,stream ,arch ,version ,hipver ,bests ); 416tuning_file (o .tuning_out ,arch ,version ,bests ); 417HIP_CHECK (hipStreamSynchronize (stream ));HIP_CHECK (hipStreamDestroy (stream )); 418LT_CHECK (hipblasLtDestroy (lt ));BLAS_CHECK (hipblasDestroy (blas )); 419return 0 ; 420}