okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7c5e84612
main
1// tools/hip/tune_rocblas.cpp - a rocBLAS tuning table for the prompt path's FP16-out GEMMs (gfx103x, prompt_f16()). 2// 3// On RDNA2 the prompt path's dense products run as rocBLAS FP16 in -> FP16 out (docs/AMD_HIP.md, "RDNA2"). rocBLAS 4// picks its kernel from a table by shape, and for some shapes that pick is far from the best kernel the library has: 5// on an RX 6900 XT, N=10240 K=2560 (the GDN input projection) below T=1152 tokens runs at 5 TFLOPS where the best of 6// rocBLAS's own 237 solutions for the same shape runs at 32 (E270, 2026-10-05). This tool enumerates the library's 7// solutions for each shape (rocblas_gemm_ex_get_solutions), times them, checks each against the default kernel's 8// output, and writes the rows where a solution beats the default by at least --min-gain (1.05 = 5%) as a table the 9// engine reads through STRATA_ROCBLAS_TUNING (src/prefill/rocblas_tuning.hpp; Gemm::f16_inplace). 10// 11// Solution indices are valid only for one GPU architecture and one rocBLAS build (its version string, tweak hash 12// included), so a table is calibrated on the card with the ROCm the engine runs with: 13// 14// cmake --build build-hip --target tune_rocblas 15// ./build-hip/tune_rocblas --tuning-out tools/hip/<arch>-rocblas-<version>.txt 16// 17// Defaults: the engine's 14 FP16 dense shapes at T = 256 ... 8192 (--tokens); --case T,N,K,ldy adds one shape. 18#define ROCBLAS_BETA_FEATURES_API 19#include <hip/hip_runtime.h> 20#include <hip/hip_fp16.h> 21#include <rocblas/rocblas.h> 22 23#include <algorithm> 24#include <cmath> 25#include <cstdint> 26#include <cstdio> 27#include <cstdlib> 28#include <cstring> 29#include <fstream> 30#include <functional> 31#include <limits> 32#include <random> 33#include <string> 34#include <vector> 35 36namespace { 37#define HIP_CHECK (call ) do { const hipError_t e = (call); if (e != hipSuccess) { \ 38 std::fprintf(stderr, "HIP %s:%d: %s: %s\n", __FILE__, __LINE__, #call, hipGetErrorString(e)); std::exit(2); } } while (0) 39#define RB_CHECK (call ) do { const rocblas_status e = (call); if (e != rocblas_status_success) { \ 40 std::fprintf(stderr, "rocBLAS %s:%d: %s: status=%d\n", __FILE__, __LINE__, #call, (int) e); std::exit(2); } } while (0) 41 42struct Buffer { 43void * p = nullptr ; 44explicit Buffer (size_t bytes ) {if (bytes )HIP_CHECK (hipMalloc (& p ,bytes )); } 45 ~Buffer () {if (p ) (void )hipFree (p ); } 46Buffer (const Buffer & )= delete ; 47Buffer & operator= (const Buffer & )= delete ; 48}; 49 50struct Shape {int t ,n ,k ,ldy ; }; 51struct Options { 52 std::vector < Shape > shapes ; 53 std::vector < int > tokens {256 ,512 ,768 ,1024 ,1536 ,2048 ,4096 ,8192 }; 54 std::string tuning_out ; 55double min_gain = 1.05 ; 56bool explicit_shapes = false; 57}; 58struct Err {double rel_l2 = 0 ,max_abs = 0 ;bool finite = true,ok = true;size_t padding_writes = 0 ; }; 59struct Row {Shape s ;bool tuned ;int solution ;float default_ms ,best_ms ; }; 60 61constexpr int WARMUPS = 2 ,REPS = 3 ,TOP = 8 ; 62constexpr uint16_t CANARY = 0x7BFF ;// the largest finite FP16 (65504): never a product of (-1, 1) inputs 63 64uint16_t f16_bits (float x ) {const __half h = __float2half_rn (x );uint16_t b ; std::memcpy (& b ,& h ,2 );return b ; } 65float f16_value (uint16_t b ) {__half h ; std::memcpy (& h ,& b ,2 );return __half2float (h ); } 66 67std::vector < std::string > csv (const std::string & s ) { 68 std::vector < std::string > out ;size_t b = 0 ; 69for (;;) { 70const size_t p = s .find (',' ,b ); 71out .push_back (s .substr (b ,p == std::string::npos ?p :p - b )); 72if (p == std::string::npos )return out ; 73b = p + 1 ; 74 } 75} 76int positive (const std::string & s ,const char * label ) { 77char * e = nullptr ;const long v = std::strtol (s .c_str (),& e ,10 ); 78if (s .empty ()|| !e || * e || v < 1 || v > std::numeric_limits < int > ::max ()) { 79 std::fprintf (stderr ,"invalid %s: %s\n" ,label ,s .c_str ()); std::exit (2 ); 80 } 81return (int )v ; 82} 83void usage (const char * p ) { 84 std::printf ("Usage: %s [--case T,N,K,ldy]... [--tokens T1,T2,...] [--min-gain 1.05] [--tuning-out PATH]\n" ,p ); 85 std::printf ("Defaults: the engine's 14 FP16 dense shapes (ldy = N) at T = 256,512,768,1024,1536,2048,4096,8192.\n" ); 86} 87Options options (int argc ,char ** argv ) { 88Options o ; 89for (int i = 1 ;i < argc ;++ i ) { 90const std::string a = argv [i ]; 91auto next = [& ]()-> std::string { 92if (i + 1 >=argc ) { std::fprintf (stderr ,"missing option value\n" ); std::exit (2 ); } 93return argv [++ i ]; 94 }; 95if (a == "-h" || a == "--help" ) {usage (argv [0 ]); std::exit (0 ); } 96else if (a == "--case" ) { 97const auto f = csv (next ()); 98if (f .size ()!= 4 ) { std::fprintf (stderr ,"--case expects T,N,K,ldy\n" ); std::exit (2 ); } 99const Shape s {positive (f [0 ],"T" ),positive (f [1 ],"N" ),positive (f [2 ],"K" ),positive (f [3 ],"ldy" )}; 100if (s .ldy < s .n ) { std::fprintf (stderr ,"ldy must be >= N\n" ); std::exit (2 ); } 101o .shapes .push_back (s );o .explicit_shapes = true; 102 }else if (a == "--tokens" ) { 103o .tokens .clear (); 104for (const auto & x :csv (next ()))o .tokens .push_back (positive (x ,"token bucket" )); 105 }else if (a == "--min-gain" ) {o .min_gain = std::atof (next ().c_str ());if (o .min_gain < 1.0 )o .min_gain = 1.0 ; } 106else if (a == "--tuning-out" )o .tuning_out = next (); 107else { std::fprintf (stderr ,"unknown option: %s\n" ,a .c_str ());usage (argv [0 ]); std::exit (2 ); } 108 } 109if (!o .explicit_shapes ) { 110// Qwen3.8-Flash-Next's dense FP16 products, prompt_f16() on (the hc read, GDN and QSA projections, the router 111// and the shared expert), ldy = N for every one of them. N K as the engine calls Gemm (ROCBLAS_LAYER=2). 112const int nk [][2 ]= {{10240 ,2560 }, {12288 ,2560 }, {6144 ,2560 }, {2560 ,6144 }, {2560 ,640 }, {2560 ,2560 }, 113 {640 ,2560 }, {512 ,2560 }, {128 ,2560 }, {48 ,2560 }, {320 ,10240 }, {10240 ,320 }, 114 {4 ,10240 }, {1 ,2560 }}; 115for (const auto & p :nk )for (int t :o .tokens )o .shapes .push_back ({t ,p [0 ],p [1 ],p [0 ]}); 116 } 117return o ; 118} 119 120float time_ms (hipStream_t stream ,hipEvent_t a ,hipEvent_t b ,const std::function < rocblas_status ()>& f ,int reps , 121bool & ok ) { 122HIP_CHECK (hipEventRecord (a ,stream )); 123for (int i = 0 ;i < reps ;++ i )if (f ()!= rocblas_status_success ) {ok = false;return 0 ; } 124HIP_CHECK (hipEventRecord (b ,stream )); 125HIP_CHECK (hipEventSynchronize (b )); 126float ms = 0 ;HIP_CHECK (hipEventElapsedTime (& ms ,a ,b )); 127ok = true; 128return ms /reps ; 129} 130 131// The candidate's FP16 output against the default kernel's, over the N x T results; the rest of each 2*ldy-half column 132// (what the engine's widen_rows_f16 does not cover) must still hold the canary. 133Err compare (const std::vector < uint16_t >& ref ,const std::vector < uint16_t >& got ,const Shape & s ) { 134Err e ;long double d2 = 0 ,r2 = 0 ;float max_ref = 0 ; 135const size_t ldc = (size_t )s .ldy * 2 ; 136for (int col = 0 ;col < s .t ;++ col ) { 137for (int row = 0 ;row < s .n ;++ row ) { 138const float r = f16_value (ref [col * ldc + row ]),g = f16_value (got [col * ldc + row ]); 139if (!std::isfinite (r )|| !std::isfinite (g )) {e .finite = false;continue ; } 140const double d = (double )g - r ; 141d2 += (long double )d * d ;r2 += (long double )r * r ; 142e .max_abs = std::max (e .max_abs , std::abs (d ));max_ref = std::max (max_ref , std::abs (r )); 143 } 144for (size_t row = s .n ;row < ldc ;++ row )if (got [col * ldc + row ]!= CANARY )++ e .padding_writes ; 145 } 146e .rel_l2 = std::sqrt ((double ) (d2 / std::max (r2 ,1e-300L ))); 147// the two kernels sum K products in different orders, then both round to FP16: a few last-bit differences 148const float ulp = std::ldexp (1.0f , (int ) std::floor (std::log2 (std::max (max_ref ,1e-30f )))- 10 ); 149e .ok = e .finite && e .padding_writes == 0 && e .rel_l2 <=2e-3 && e .max_abs <=4.0 * ulp ; 150return e ; 151} 152}// namespace 153 154int main (int argc ,char ** argv ) { 155const Options o = options (argc ,argv ); 156rocblas_handle h ;RB_CHECK (rocblas_create_handle (& h )); 157hipStream_t stream ;HIP_CHECK (hipStreamCreateWithFlags (& stream ,hipStreamNonBlocking )); 158RB_CHECK (rocblas_set_stream (h ,stream )); 159char ver [128 ]= {0 };RB_CHECK (rocblas_get_version_string (ver ,sizeof ver )); 160int device = 0 ;hipDeviceProp_t prop {}; 161HIP_CHECK (hipGetDevice (& device ));HIP_CHECK (hipGetDeviceProperties (& prop ,device )); 162 std::string arch (prop .gcnArchName );if (const auto c = arch .find (':' );c != std::string::npos )arch .resize (c ); 163 std::printf ("meta device_arch=%s rocblas_version=%s shapes=%zu min_gain=%.3f\n" ,arch .c_str (),ver ,o .shapes .size (),o .min_gain ); 164hipEvent_t ea ,eb ;HIP_CHECK (hipEventCreate (& ea ));HIP_CHECK (hipEventCreate (& eb )); 165 166 std::vector < Row > rows ; 167for (size_t ci = 0 ;ci < o .shapes .size ();++ ci ) { 168const Shape & s = o .shapes [ci ]; 169const size_t na = (size_t )s .n * s .k ,nb = (size_t )s .t * s .k ,ldc = (size_t )s .ldy * 2 ,nc = ldc * s .t ; 170 std::vector < uint16_t > ha (na ),hb (nb ),canary (nc ,CANARY ); 171 std::mt19937 rng (0x5A17C3u + (uint32_t )ci * 0x10001u ); 172 std::uniform_real_distribution < float > dist (-1.0f ,1.0f ); 173for (auto & x :ha )x = f16_bits (dist (rng )); 174for (auto & x :hb )x = f16_bits (dist (rng )); 175Buffer da (na * 2 ),db (nb * 2 ),dc (nc * 2 ); 176HIP_CHECK (hipMemcpy (da .p ,ha .data (),na * 2 ,hipMemcpyHostToDevice )); 177HIP_CHECK (hipMemcpy (db .p ,hb .data (),nb * 2 ,hipMemcpyHostToDevice )); 178const float alpha = 1.0f ,beta = 0.0f ; 179// the engine's call (Gemm::f16_inplace): C[N x T] = W^T . X, FP16 out, ldc = 2 * ldy halves 180auto gemm = [& ](rocblas_gemm_algo algo ,int32_t sol ) { 181return rocblas_gemm_ex (h ,rocblas_operation_transpose ,rocblas_operation_none ,s .n ,s .t ,s .k ,& alpha , 182da .p ,rocblas_datatype_f16_r ,s .k ,db .p ,rocblas_datatype_f16_r ,s .k ,& beta ,dc .p , 183rocblas_datatype_f16_r , (int )ldc ,dc .p ,rocblas_datatype_f16_r , (int )ldc , 184rocblas_datatype_f32_r ,algo ,sol ,0 ); 185 }; 186bool ok = true; 187HIP_CHECK (hipMemcpy (dc .p ,canary .data (),nc * 2 ,hipMemcpyHostToDevice )); 188for (int i = 0 ;i < WARMUPS ;++ i )RB_CHECK (gemm (rocblas_gemm_algo_standard ,0 )); 189const float default_ms = time_ms (stream ,ea ,eb , [& ] {return gemm (rocblas_gemm_algo_standard ,0 ); },REPS ,ok ); 190HIP_CHECK (hipDeviceSynchronize ()); 191 std::vector < uint16_t > ref (nc ); 192HIP_CHECK (hipMemcpy (ref .data (),dc .p ,nc * 2 ,hipMemcpyDeviceToHost )); 193const Err self = compare (ref ,ref ,s ); 194 std::printf ("case T=%d N=%d K=%d ldy=%d default_ms=%.4f default_padding_writes=%zu\n" ,s .t ,s .n ,s .k ,s .ldy , 195default_ms ,self .padding_writes ); 196 197rocblas_int count = 0 ; 198auto solutions = [& ](rocblas_int * list ,rocblas_int * n ) { 199return rocblas_gemm_ex_get_solutions (h ,rocblas_operation_transpose ,rocblas_operation_none ,s .n ,s .t ,s .k , 200& alpha ,da .p ,rocblas_datatype_f16_r ,s .k ,db .p ,rocblas_datatype_f16_r , 201s .k ,& beta ,dc .p ,rocblas_datatype_f16_r , (int )ldc ,dc .p , 202rocblas_datatype_f16_r , (int )ldc ,rocblas_datatype_f32_r , 203rocblas_gemm_algo_solution_index ,0 ,list ,n ); 204 }; 205if (solutions (nullptr ,& count )!= rocblas_status_success || count <=0 ) { 206 std::printf ("no_solutions T=%d N=%d K=%d ldy=%d\n" ,s .t ,s .n ,s .k ,s .ldy ); 207continue ; 208 } 209 std::vector < rocblas_int > ids (count ); 210RB_CHECK (solutions (ids .data (),& count )); 211// pass 1: one timed call each; pass 2: the TOP fastest get the full measurement and the output check 212 std::vector < std::pair < float ,rocblas_int >> quick ; 213for (rocblas_int id :ids ) { 214if (gemm (rocblas_gemm_algo_solution_index ,id )!= rocblas_status_success )continue ; 215const float ms = time_ms (stream ,ea ,eb , [& ] {return gemm (rocblas_gemm_algo_solution_index ,id ); },1 ,ok ); 216if (ok )quick .push_back ({ms ,id }); 217 } 218 std::sort (quick .begin (),quick .end ()); 219rocblas_int best = 0 ;float best_ms = std::numeric_limits < float > ::infinity (); 220for (size_t i = 0 ;i < quick .size ()&& i < (size_t )TOP ;++ i ) { 221const rocblas_int id = quick [i ].second ; 222HIP_CHECK (hipMemcpy (dc .p ,canary .data (),nc * 2 ,hipMemcpyHostToDevice )); 223for (int w = 0 ;w < WARMUPS ;++ w )if (gemm (rocblas_gemm_algo_solution_index ,id )!= rocblas_status_success ) {ok = false;break ; } 224if (!ok )continue ; 225const float ms = time_ms (stream ,ea ,eb , [& ] {return gemm (rocblas_gemm_algo_solution_index ,id ); },REPS ,ok ); 226if (!ok )continue ; 227HIP_CHECK (hipDeviceSynchronize ()); 228 std::vector < uint16_t > got (nc ); 229HIP_CHECK (hipMemcpy (got .data (),dc .p ,nc * 2 ,hipMemcpyDeviceToHost )); 230Err e = compare (ref ,got ,s ); 231// the engine applies a row to every T nearest its bucket, and a kernel can refuse a T it was not 232// measured at (a tile or grid predicate): the solution must also run at odd, smaller token counts 233bool accepts_neighbors = true; 234for (int tn : {s .t - 1 ,s .t - 37 ,s .t - 63 ,s .t /2 + 1 }) { 235if (tn < 1 )continue ; 236const rocblas_status st = rocblas_gemm_ex ( 237h ,rocblas_operation_transpose ,rocblas_operation_none ,s .n ,tn ,s .k ,& alpha ,da .p , 238rocblas_datatype_f16_r ,s .k ,db .p ,rocblas_datatype_f16_r ,s .k ,& beta ,dc .p ,rocblas_datatype_f16_r , 239 (int )ldc ,dc .p ,rocblas_datatype_f16_r , (int )ldc ,rocblas_datatype_f32_r , 240rocblas_gemm_algo_solution_index ,id ,0 ); 241if (st != rocblas_status_success ) {accepts_neighbors = false;break ; } 242 } 243HIP_CHECK (hipDeviceSynchronize ()); 244e .ok = e .ok && accepts_neighbors ; 245 std::printf (" solution=%d ms=%.4f gain=%.2f relative_l2=%.3g max_abs=%.3g padding_writes=%zu %s%s\n" , (int )id , 246ms ,default_ms /ms ,e .rel_l2 ,e .max_abs ,e .padding_writes ,e .ok ?"ok" :"REJECT" , 247accepts_neighbors ?"" :" (refuses a smaller T)" ); 248if (e .ok && ms < best_ms ) {best = id ;best_ms = ms ; } 249 } 250if (std::isfinite (best_ms )&& default_ms /best_ms >=o .min_gain ) { 251 std::printf ("best T=%d N=%d K=%d ldy=%d solution=%d ms=%.4f default_ms=%.4f gain=%.2f\n" ,s .t ,s .n ,s .k ,s .ldy , 252 (int )best ,best_ms ,default_ms ,default_ms /best_ms ); 253rows .push_back ({s , true, (int )best ,default_ms ,best_ms }); 254 }else { 255// written too: the engine applies a row to the token counts nearest its bucket, and a `default` row keeps 256// a neighbouring bucket's solution from reaching token counts where the default kernel measured best 257 std::printf ("keep_default T=%d N=%d K=%d ldy=%d (%zu solutions; best %.4f ms vs default %.4f)\n" ,s .t ,s .n ,s .k , 258s .ldy ,quick .size (),best_ms ,default_ms ); 259rows .push_back ({s , false,0 ,default_ms ,best_ms }); 260 } 261 } 262 263if (!o .tuning_out .empty ()) { 264 std::ofstream f (o .tuning_out ); 265if (!f ) { std::fprintf (stderr ,"cannot write tuning output: %s\n" ,o .tuning_out .c_str ());return 2 ; } 266f <<"# rocBLAS solution indices for the prompt path's FP16-out GEMMs; valid for this architecture and rocBLAS build only\n" ; 267f <<"# rows: type N K ldy T solution (type f16o: FP16 in, FP16 out, FP32 compute; Gemm::f16_inplace)\n" ; 268f <<"# solution: rocBLAS's solution index, or `default` where its own choice measured best at that bucket\n" ; 269f <<"STRATA_ROCBLAS_TUNING_V1 " <<arch <<" " <<ver <<"\n" ; 270size_t tuned = 0 ; 271for (const auto & r :rows ) { 272f <<"f16o " <<r .s .n <<" " <<r .s .k <<" " <<r .s .ldy <<" " <<r .s .t <<" " ; 273if (r .tuned ) {f <<r .solution <<" # " <<r .default_ms <<" ms -> " <<r .best_ms <<" ms\n" ;++ tuned ; } 274else f <<"default # " <<r .default_ms <<" ms\n" ; 275 } 276 std::printf ("wrote %zu rows (%zu with a solution) to %s\n" ,rows .size (),tuned ,o .tuning_out .c_str ()); 277 } 278HIP_CHECK (hipEventDestroy (ea ));HIP_CHECK (hipEventDestroy (eb )); 279HIP_CHECK (hipStreamDestroy (stream ));RB_CHECK (rocblas_destroy_handle (h )); 280return 0 ; 281}