okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a8a51b280
main
1// src/prefill/gemm.cu - see include/strata/prefill/gemm.hpp. 2#define DPCT_PROFILING_ENABLED 3#include <sycl/sycl.hpp> 4#include "strata/kprof.hpp" 5#include <dpct/dpct.hpp> 6#include "strata/sycl_queue.hpp" 7#include "strata/prefill/gemm.hpp" 8#include "strata/workload_trace.hpp" 9#include "strata/kernels/dequant_bf16.hpp" 10#include <dpct/blas_utils.hpp> 11 12#if defined(STRATA_PREFILL_MMQ )&& defined(__HIPCC__ ) 13#include "strata/prefill/moe_mmq.hpp" 14#endif 15 16#ifdef STRATA_USE_HIP 17#include "wmma_gemm.h" 18#endif 19 20#include <algorithm> 21#include <atomic> 22 23#if defined(__HIPCC__ )&& defined(STRATA_HIPBLASLT_AVAILABLE ) 24// The HIP compatibility shim maps CUDA shuffle spellings to Strata helpers. 25// hipBLASLt's public headers declare native HIP shuffle functions, so keep 26// those declarations from being macro-expanded in this translation unit. 27#undef __shfl_xor_sync 28#undef __shfl_down_sync 29#undef __shfl_up_sync 30#undef __shfl_sync 31#undef __ballot_sync 32#endif 33 34#include <algorithm> 35#include <climits> 36#include <cstdio> 37#include <cstdlib> 38#include <cstring> 39#include <memory> 40#include <cmath> 41 42#include <dpct/lib_common_utils.hpp> 43 44#if defined(__HIPCC__ )&& defined(STRATA_HIPBLASLT_AVAILABLE ) 45#include "hipblaslt_tuning.hpp" 46#include <hip/hip_runtime_api.h> 47#include <hipblaslt/hipblaslt.h> 48#include <hipblaslt/hipblaslt-ext.hpp> 49#include <map> 50#include <set> 51#include <tuple> 52#endif 53 54#if defined(__HIPCC__ ) 55#include <hip/hip_fp16.h> 56#endif 57 58namespace strata::prefill { 59namespace { 60#if defined(__HIPCC__ ) 61// Y's rows, written by an FP16-out GEMM as FP16 at the start of each FP32 row (ldc = 2 ldy halves), widened in place. 62// Float c overwrites halves 2c and 2c+1, so a row is walked from its end in blocks: a block's halves are read into 63// registers, the block syncs, then writes its floats - which only cover halves of blocks already read. 64// STRATA_DBG_NAN: the FP16 outputs that are not finite (an FP32-accumulated sum past 65504 becomes inf in FP16). 65__device__ unsigned long long g_f16_nonfinite = 0 ; 66__global__ void widen_rows_f16 (float * __restrict__Y ,int64_t n ,int64_t ldy ,int count_nonfinite ) { 67float * y = Y + (int64_t )blockIdx .x * ldy ; 68const __half * h = reinterpret_cast < const __half *> (y ); 69const int64_t nb = (n + blockDim .x - 1 ) /blockDim .x ; 70for (int64_t b = nb - 1 ;b >=0 ;-- b ) { 71const int64_t c = b * blockDim .x + threadIdx .x ; 72const float v = c < n ?__half2float (h [c ]) :0.0f ; 73if (count_nonfinite && c < n && !isfinite (v ))atomicAdd (& g_f16_nonfinite ,1ull ); 74__syncthreads (); 75if (c < n )y [c ]= v ; 76__syncthreads (); 77 } 78} 79// BF16 weight rows -> FP16, saturated (bench/results/2026-10-04-rdna2-fp16-prompt: none leaves FP16's range) 80__global__ void bf16_to_f16_rows (const uint16_t * __restrict__s ,__half * __restrict__d ,int64_t n ) { 81for (int64_t i = blockIdx .x * (int64_t )blockDim .x + threadIdx .x ;i < n ;i += (int64_t )gridDim .x * blockDim .x ) { 82const float f = __uint_as_float ((uint32_t )s [i ] <<16 ); 83d [i ]= __float2half (isnan (f ) ?f :fminf (fmaxf (f ,-65504.0f ),65504.0f ));// as hf_sat: a NaN stays NaN 84 } 85} 86#endif 87 88void ck (int s ,const char * what ) { 89if (s != 0 ) { 90 std::fprintf (stderr ,"prefill gemm: %s: cuBLAS status %d\n" ,what , (int )s ); 91 std::exit (1 ); 92 } 93} 94 95// #247/#325: on Windows (seen on gfx1201), hipBLAS can return success with the correct BF16/FP16 product for some 96// shapes (hc up once T >= 96, the router) and still leave hipErrorInvalidValue set, which the next kernel's error 97// check turns into an exit. The multiply has finished, so that one stale error is cleared after a GEMM that succeeded; 98// any other error still stops the engine. Windows only: on Linux a stale hipErrorInvalidValue is a real error from 99// an earlier call and keeps being reported. A no-op everywhere else (CUDA compiles none of it). 100#if defined(__HIPCC__ )&& defined(_WIN32 ) 101void absorb_hipblas_sticky (const char * what ) { 102const hipError_t sticky = hipGetLastError (); 103if (sticky == hipSuccess || sticky == hipErrorInvalidValue )return ; 104 std::fprintf (stderr ,"prefill gemm: %s left %s\n" ,what ,hipGetErrorString (sticky )); 105 std::exit (1 ); 106} 107#define STRATA_ABSORB_HIPBLAS_STICKY (what ) absorb_hipblas_sticky(what) 108#else 109#define STRATA_ABSORB_HIPBLAS_STICKY (what ) ((void) 0) 110#endif 111 112// A setup call whose failure the engine survives (the handle keeps its defaults), as before #240 - but said. 113void note (int s ,const char * what ) { 114if (s != 0 ) std::fprintf ( 115stderr ,"prefill gemm: %s: cuBLAS status %d (continuing)\n" ,what , 116 (int )s ); 117} 118 119#if defined(__HIPCC__ )&& defined(STRATA_HIPBLASLT_AVAILABLE ) 120struct HipLtCallKey { 121 strata::prefill::hipblaslt::InputType type ; 122int t ; 123int n ; 124int k ; 125int ldy ; 126uint32_t beta_bits ; 127 128bool operator< (const HipLtCallKey & other )const { 129return std::tie (type ,n ,k ,ldy ,t ,beta_bits )< 130 std::tie (other .type ,other .n ,other .k ,other .ldy ,other .t ,other .beta_bits ); 131 } 132}; 133 134struct HipLtCachedAlgo { 135bool supported = false; 136hipblasLtMatmulAlgo_t algo {}; 137size_t workspace_bytes = 0 ; 138}; 139 140struct HipLtState { 141hipblasLtHandle_t handle = nullptr ; 142void * workspace = nullptr ; 143size_t workspace_bytes = 0 ; 144 strata::prefill::hipblaslt::TuningTable table ; 145 std::map < HipLtCallKey ,HipLtCachedAlgo > cache ; 146uint64_t lt_launches = 0 ; 147uint64_t fallbacks = 0 ; 148 std::set < std::tuple < strata::prefill::hipblaslt::InputType ,int ,int ,int ,int >> fallback_shapes ; 149 150 ~HipLtState () { 151if (std::getenv ("STRATA_HIPBLASLT_VERBOSE" )) { 152 std::fprintf (stderr ,"prefill gemm: hipBLASLt summary launches=%llu fallbacks=%llu unique_fallback_shapes=%zu\n" , 153 (unsigned long long )lt_launches , (unsigned long long )fallbacks ,fallback_shapes .size ()); 154for (const auto & shape :fallback_shapes ) { 155const auto type = std::get < 0 > (shape ); 156 std::fprintf (stderr ,"prefill gemm: fallback shape dtype=%s T=%d N=%d K=%d ldy=%d\n" , 157type == strata::prefill::hipblaslt::InputType ::bf16 ?"bf16" :"f16" , 158 std::get < 1 > (shape ), std::get < 2 > (shape ), std::get < 3 > (shape ), std::get < 4 > (shape )); 159 } 160 } 161if (handle )hipblasLtDestroy (handle ); 162 } 163}; 164 165struct HipLtDescriptors { 166hipblasLtMatmulDesc_t op = nullptr ; 167hipblasLtMatrixLayout_t a = nullptr ; 168hipblasLtMatrixLayout_t b = nullptr ; 169hipblasLtMatrixLayout_t c = nullptr ; 170 171 ~HipLtDescriptors () { 172if (op )hipblasLtMatmulDescDestroy (op ); 173if (a )hipblasLtMatrixLayoutDestroy (a ); 174if (b )hipblasLtMatrixLayoutDestroy (b ); 175if (c )hipblasLtMatrixLayoutDestroy (c ); 176 } 177 178bool init (hipDataType type ,int t ,int n ,int k ,int ldy ,int ldb = 0 ) { 179const hipblasOperation_t trans_a = HIPBLAS_OP_T ; 180const hipblasOperation_t trans_b = HIPBLAS_OP_N ; 181if (hipblasLtMatmulDescCreate (& op ,HIPBLAS_COMPUTE_32F ,HIP_R_32F )!= HIPBLAS_STATUS_SUCCESS || 182hipblasLtMatmulDescSetAttribute (op ,HIPBLASLT_MATMUL_DESC_TRANSA ,& trans_a ,sizeof (trans_a ))!= 183HIPBLAS_STATUS_SUCCESS || 184hipblasLtMatmulDescSetAttribute (op ,HIPBLASLT_MATMUL_DESC_TRANSB ,& trans_b ,sizeof (trans_b ))!= 185HIPBLAS_STATUS_SUCCESS || 186hipblasLtMatrixLayoutCreate (& a ,type ,k ,n ,k )!= HIPBLAS_STATUS_SUCCESS || 187hipblasLtMatrixLayoutCreate (& b ,type ,k ,t ,ldb > k ?ldb :k )!= HIPBLAS_STATUS_SUCCESS || 188hipblasLtMatrixLayoutCreate (& c ,HIP_R_32F ,n ,t ,ldy )!= HIPBLAS_STATUS_SUCCESS ) { 189return false; 190 } 191return true; 192 } 193}; 194 195std::unique_ptr < HipLtState > create_hipblaslt_state (void * workspace ,size_t workspace_bytes ) { 196const char * path = std::getenv ("STRATA_HIPBLASLT_TUNING" ); 197if (!path || !* path )return nullptr ; 198 199auto state = std::make_unique < HipLtState > (); 200state -> workspace = workspace ; 201state -> workspace_bytes = workspace_bytes ; 202if (hipblasLtCreate (& state -> handle )!= HIPBLAS_STATUS_SUCCESS ) { 203 std::fprintf (stderr ,"prefill gemm: hipBLASLt handle creation failed; using hipBLASEx\n" ); 204return nullptr ; 205 } 206 207int version = 0 ; 208if (hipblasLtGetVersion (state -> handle ,& version )!= HIPBLAS_STATUS_SUCCESS ) { 209 std::fprintf (stderr ,"prefill gemm: hipBLASLt version query failed; using hipBLASEx\n" ); 210return nullptr ; 211 } 212int device = 0 ; 213hipDeviceProp_t properties {}; 214if (hipGetDevice (& device )!= hipSuccess || hipGetDeviceProperties (& properties ,device )!= hipSuccess ) { 215 std::fprintf (stderr ,"prefill gemm: HIP device query failed; using hipBLASEx\n" ); 216return nullptr ; 217 } 218 std::string arch (properties .gcnArchName ); 219const auto suffix = arch .find (':' ); 220if (suffix != std::string::npos )arch .resize (suffix ); 221 222 std::string error ; 223if (!state -> table .load (path ,arch ,version ,error )) { 224 std::fprintf (stderr ,"prefill gemm: %s; using hipBLASEx\n" ,error .c_str ()); 225return nullptr ; 226 } 227 std::fprintf (stderr ,"prefill gemm: hipBLASLt tuning enabled (%zu rows, %s, version %d)\n" , 228state -> table .rows ().size (),arch .c_str (),version ); 229return state ; 230} 231 232HipLtCachedAlgo resolve_hipblaslt_algo (HipLtState & state , strata::prefill::hipblaslt::InputType type ,int t , 233int n ,int k ,int ldy ,float beta ) { 234uint32_t beta_bits = 0 ; 235 static_assert(sizeof (beta_bits )== sizeof (beta )); 236 std::memcpy (& beta_bits ,& beta ,sizeof (beta )); 237const HipLtCallKey key {type ,t ,n ,k ,ldy ,beta_bits }; 238const auto cached = state .cache .find (key ); 239if (cached != state .cache .end ())return cached -> second ; 240 241HipLtCachedAlgo resolved ; 242const bool verbose = std::getenv ("STRATA_HIPBLASLT_VERBOSE" )!= nullptr ; 243const auto * row = state .table .closest (type ,n ,k ,ldy ,t ); 244if (!row ) { 245if (verbose ) { 246 std::fprintf (stderr ,"prefill gemm: Lt fallback; no calibration for dtype=%s T=%d N=%d K=%d ldy=%d\n" , 247type == strata::prefill::hipblaslt::InputType ::bf16 ?"bf16" :"f16" ,t ,n ,k ,ldy ); 248 } 249return state .cache .emplace (key ,resolved ).first -> second ; 250 } 251 252HipLtDescriptors desc ; 253const hipDataType input_type = type == strata::prefill::hipblaslt::InputType ::bf16 ?HIP_R_16BF :HIP_R_16F ; 254if (!desc .init (input_type ,t ,n ,k ,ldy )) { 255return state .cache .emplace (key ,resolved ).first -> second ; 256 } 257 258 std::vector < int > solution_ids {row -> solution_id }; 259 std::vector < hipblasLtMatmulHeuristicResult_t > candidates ; 260if (hipblaslt_ext::getAlgosFromIndex (state .handle ,solution_ids ,candidates )!= HIPBLAS_STATUS_SUCCESS || 261candidates .empty ()|| candidates .front ().state != HIPBLAS_STATUS_SUCCESS || 262 hipblaslt_ext::getIndexFromAlgo (candidates .front ().algo )!= row -> solution_id ) { 263if (verbose ) { 264 std::fprintf (stderr ,"prefill gemm: Lt fallback; solution %d unavailable for T=%d N=%d K=%d ldy=%d\n" , 265row -> solution_id ,t ,n ,k ,ldy ); 266 } 267return state .cache .emplace (key ,resolved ).first -> second ; 268 } 269 270const float alpha = 1.0f ; 271size_t required_workspace = 0 ; 272auto algo = candidates .front ().algo ; 273if (hipblaslt_ext::matmulIsAlgoSupported (state .handle ,desc .op ,& alpha ,desc .a ,desc .b ,& beta ,desc .c ,desc .c , 274algo ,required_workspace )!= HIPBLAS_STATUS_SUCCESS ) { 275if (verbose ) { 276 std::fprintf (stderr ,"prefill gemm: Lt fallback; solution %d rejects actual T=%d N=%d K=%d ldy=%d beta=%.9g\n" , 277row -> solution_id ,t ,n ,k ,ldy ,beta ); 278 } 279return state .cache .emplace (key ,resolved ).first -> second ; 280 } 281 282resolved .supported = true; 283resolved .algo = algo ; 284resolved .workspace_bytes = required_workspace ; 285if (verbose ) { 286 std::fprintf (stderr , 287"prefill gemm: Lt solution=%d dtype=%s T=%d N=%d K=%d ldy=%d beta=%.9g workspace=%zu\n" , 288row -> solution_id ,type == strata::prefill::hipblaslt::InputType ::bf16 ?"bf16" :"f16" ,t ,n , 289k ,ldy ,beta ,required_workspace ); 290 } 291return state .cache .emplace (key ,resolved ).first -> second ; 292} 293 294// the hipBLASLt solution index the tuning table gives this call (-1: none / unsupported) 295int hipblaslt_solution_for (void * opaque_state , strata::prefill::hipblaslt::InputType type ,int64_t t ,int64_t n ,int64_t k , 296int64_t ldy ,float beta ) { 297auto * state = static_cast < HipLtState *> (opaque_state ); 298if (!state || t <=0 || n <=0 || k <=0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX || ldy < n )return -1 ; 299const auto resolved = resolve_hipblaslt_algo (* state ,type , (int )t , (int )n , (int )k , (int )ldy ,beta ); 300if (!resolved .supported || resolved .workspace_bytes > state -> workspace_bytes )return -1 ; 301auto algo = resolved .algo ; 302return hipblaslt_ext::getIndexFromAlgo (algo ); 303} 304 305bool try_hipblaslt (void * opaque_state , strata::prefill::hipblaslt::InputType type ,const uint16_t * x , 306const uint16_t * w ,float * y ,int64_t t ,int64_t n ,int64_t k ,int64_t ldy ,float beta , 307void * stream ,int64_t ldx = 0 ) { 308auto * state = static_cast < HipLtState *> (opaque_state ); 309if (!state || t <=0 || n <=0 || k <=0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX || 310ldy < n ) { 311return false; 312 } 313const auto resolved = resolve_hipblaslt_algo (* state ,type , (int )t , (int )n , (int )k , (int )ldy ,beta ); 314if (!resolved .supported ) { 315++ state -> fallbacks ; 316state -> fallback_shapes .emplace (type , (int )t , (int )n , (int )k , (int )ldy ); 317return false; 318 } 319if (resolved .workspace_bytes > state -> workspace_bytes ) { 320++ state -> fallbacks ; 321state -> fallback_shapes .emplace (type , (int )t , (int )n , (int )k , (int )ldy ); 322if (std::getenv ("STRATA_HIPBLASLT_VERBOSE" )) { 323 std::fprintf (stderr ,"prefill gemm: Lt fallback; solution needs %zu workspace bytes, have %zu\n" , 324resolved .workspace_bytes ,state -> workspace_bytes ); 325 } 326return false; 327 } 328 329HipLtDescriptors desc ; 330const hipDataType input_type = type == strata::prefill::hipblaslt::InputType ::bf16 ?HIP_R_16BF :HIP_R_16F ; 331if (!desc .init (input_type , (int )t , (int )n , (int )k , (int )ldy , (int )ldx ))return false; 332const float alpha = 1.0f ; 333const hipblasStatus_t status = hipblasLtMatmul (state -> handle ,desc .op ,& alpha ,w ,desc .a ,x ,desc .b ,& beta ,y , 334desc .c ,y ,desc .c ,& resolved .algo ,state -> workspace , 335state -> workspace_bytes , (hipStream_t )stream ); 336if (status == HIPBLAS_STATUS_SUCCESS ) { 337++ state -> lt_launches ; 338return true; 339 } 340 341 std::fprintf (stderr ,"prefill gemm: hipBLASLt launch failed with status %d\n" , (int )status ); 342if (beta != 0.0f ) { 343 std::fprintf (stderr ,"prefill gemm: refusing a fallback after hipBLASLt failed with nonzero beta\n" ); 344 std::exit (1 ); 345 } 346auto * mutable_state = static_cast < HipLtState *> (opaque_state ); 347uint32_t beta_bits = 0 ; 348 std::memcpy (& beta_bits ,& beta ,sizeof (beta_bits )); 349auto cached = mutable_state -> cache .find (HipLtCallKey {type , (int )t , (int )n , (int )k , (int )ldy ,beta_bits }); 350if (cached != mutable_state -> cache .end ())cached -> second .supported = false; 351++ mutable_state -> fallbacks ; 352mutable_state -> fallback_shapes .emplace (type , (int )t , (int )n , (int )k , (int )ldy ); 353return false; 354} 355#endif 356 357}// namespace 358 359bool prompt_f16 () { 360#if defined(__HIPCC__ ) 361constexpr int kMaxDev = 64 ; 362static std::atomic < int8_t > cached [kMaxDev ]= {};// 0 unknown, 1 off, 2 on 363int dev = 0 ; 364if (hipGetDevice (& dev )!= hipSuccess || dev < 0 || dev >=kMaxDev ) { (void )hipGetLastError ();return false; } 365if (const int8_t c = cached [dev ].load (std::memory_order_relaxed ))return c == 2 ; 366// Opt-in (#835): only STRATA_HIP_PROMPT_F16=1 turns it on. It changes the prompt path's numbers (an FP16 rounding of 367// each 16-bit GEMM's output), so no card gets it unasked. On gfx103x it is ~2x faster, so we say so once. 368const char * e = std::getenv ("STRATA_HIP_PROMPT_F16" ); 369const bool on = e != nullptr && e [0 ]== '1' ; 370hipDeviceProp_t p {}; 371if (hipGetDeviceProperties (& p ,dev )!= hipSuccess ) { (void )hipGetLastError ();p .gcnArchName [0 ]= 0 ; } 372if (on ) std::fprintf (stderr ,"strata prefill: HIP device %d%s%s - STRATA_HIP_PROMPT_F16=1: the prompt's 16-bit GEMMs run FP16 in and out " 373"(rocBLAS is tuned only for that on gfx103x; not bit-identical to the default)%s" , 374dev ,p .gcnArchName [0 ] ?" " :"" ,p .gcnArchName ,"\n" ); 375else if (e == nullptr && std::strncmp (p .gcnArchName ,"gfx103" ,6 )== 0 ) 376 std::fprintf (stderr ,"strata prefill: HIP device %d %s - tip: STRATA_HIP_PROMPT_F16=1 reads long prompts about 2x faster here " 377"(FP16 prompt GEMMs, rocBLAS is tuned only for FP16 on gfx103x; the numbers differ slightly, see docs/AMD_HIP.md)%s" , 378dev ,p .gcnArchName ,"\n" ); 379cached [dev ].store (on ?2 :1 , std::memory_order_relaxed ); 380return on ; 381#else 382return false; 383#endif 384} 385 386Gemm ::~Gemm () { 387#if defined(STRATA_PREFILL_MMQ )&& defined(__HIPCC__ ) 388delete static_cast < strata::prefill::mmq::Context *> (mmq_ctx_ ); 389if (mmq_buf_ )cudaFree (mmq_buf_ ); 390#endif 391#if defined(__HIPCC__ )&& defined(STRATA_HIPBLASLT_AVAILABLE ) 392delete static_cast < HipLtState *> (hipblaslt_state_ ); 393#endif 394if (handle_ )delete ((dpct::blas::descriptor_ptr )handle_ ); 395if (tc_w_ ) sycl::free (tc_w_ , dpct::get_in_order_queue ()); 396if (tc_x_ ) sycl::free (tc_x_ , dpct::get_in_order_queue ()); 397if (!external_ ) { 398if (scratch_ ) sycl::free (scratch_ , dpct::get_in_order_queue ()); 399if (workspace_ ) sycl::free (workspace_ , dpct::get_in_order_queue ()); 400 } 401} 402 403bool Gemm ::init_external (void * stream ,uint16_t * scratch ,int64_t scratch_elems , 404void * workspace ,size_t ws_bytes , 405 std::string & err )try { 406 dpct::blas::descriptor_ptr h = nullptr ; 407if (const int s = DPCT_CHECK_ERROR (h = new dpct::blas::descriptor ()); 408s != 0 ) { 409err = "prefill gemm: cublasCreate: cuBLAS status " + std::to_string ((int )s ); 410return false; 411 } 412handle_ = h ; 413stream_ = stream ; 414external_ = true; 415note (DPCT_CHECK_ERROR (h -> set_queue (strata::q_of (stream ))), 416"cublasSetStream" ); 417workspace_ = workspace ; 418/* 419DPCT1027: The call to cublasSetWorkspace was replaced with 0 because 420this functionality is redundant in SYCL. 421*/ 422note (0 ,"cublasSetWorkspace" ); 423note (DPCT_CHECK_ERROR (h -> set_math_mode (dpct::blas::math_mode::mm_default )), 424"cublasSetMathMode" ); 425scratch_ = scratch ; 426scratch_elems_ = scratch_elems ; 427#if defined(__HIPCC__ )&& defined(STRATA_HIPBLASLT_AVAILABLE ) 428hipblaslt_state_ = create_hipblaslt_state (workspace_ ,ws_bytes ).release (); 429#endif 430return true; 431} 432catch (sycl::exception const & exc ) { 433 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 434 <<", line:" <<__LINE__ << std::endl ; 435 std::exit (1 ); 436} 437 438void Gemm ::rebind (uint16_t * scratch ,int64_t scratch_elems ,void * workspace ,size_t ws_bytes ) { 439scratch_ = scratch ; 440scratch_elems_ = scratch_elems ; 441workspace_ = workspace ; 442/* 443DPCT1026: The call to cublasSetWorkspace was removed because this 444functionality is redundant in SYCL. 445*/ 446#if defined(__HIPCC__ )&& defined(STRATA_HIPBLASLT_AVAILABLE ) 447if (hipblaslt_state_ ) { 448auto * state = static_cast < HipLtState *> (hipblaslt_state_ ); 449state -> workspace = workspace_ ; 450state -> workspace_bytes = ws_bytes ; 451 } 452#endif 453} 454 455bool Gemm ::init (void * stream ,int64_t scratch_elems , std::string & err )try { 456// #240: every failure names the call and the real status, so "no VRAM" can be told from a broken install 457 dpct::blas::descriptor_ptr h = nullptr ; 458if (const int s = DPCT_CHECK_ERROR (h = new dpct::blas::descriptor ()); 459s != 0 ) { 460err = "prefill gemm: cublasCreate: cuBLAS status " + std::to_string ((int )s ); 461return false; 462 } 463handle_ = h ; 464stream_ = stream ; 465note (DPCT_CHECK_ERROR (h -> set_queue (strata::q_of (stream ))), 466"cublasSetStream" ); 467// A fixed workspace so the handle never allocates on the way (and graphs could capture it later). 468const size_t ws = 32u <<20 ; 469/* 470DPCT1000: Error handling if-stmt was detected but could not be 471rewritten. 472*/ 473if (const dpct::err0 e = 474DPCT_CHECK_ERROR (workspace_ = (void * )sycl::malloc_device ( 475ws , dpct::get_in_order_queue ())); 476e != 0 ) { 477/* 478DPCT1009: SYCL reports errors using exceptions and does not use 479error codes. Please replace the "get_error_string_dummy(...)" with a 480real error-handling function. 481*/ 482/* 483DPCT1001: The statement could not be removed. 484*/ 485err = std::string ("prefill gemm: workspace of 32 MiB: " )+ 486 dpct::get_error_string_dummy (e ); 487return false; 488 } 489/* 490DPCT1027: The call to cublasSetWorkspace was replaced with 0 because 491this functionality is redundant in SYCL. 492*/ 493note (0 ,"cublasSetWorkspace" ); 494note (DPCT_CHECK_ERROR (h -> set_math_mode (dpct::blas::math_mode::mm_default )), 495"cublasSetMathMode" ); 496#if defined(__HIPCC__ )&& defined(STRATA_HIPBLASLT_AVAILABLE ) 497hipblaslt_state_ = create_hipblaslt_state (workspace_ ,ws ).release (); 498#endif 499if (scratch_elems > 0 ) { 500/* 501DPCT1000: Error handling if-stmt was detected but could not be 502rewritten. 503*/ 504if (const dpct::err0 e = DPCT_CHECK_ERROR ( 505scratch_ = (uint16_t * )sycl::malloc_device ( 506 (size_t )scratch_elems * 2 , dpct::get_in_order_queue ())); 507e != 0 ) { 508/* 509DPCT1001: The statement could not be removed. 510*/ 511err = "prefill gemm: dequant scratch of " + 512 std::to_string (scratch_elems * 2 >>20 )+ " MiB: " + 513/* 514DPCT1009: SYCL reports errors using exceptions and does 515not use error codes. Please replace the 516"get_error_string_dummy(...)" with a real error-handling 517function. 518*/ 519 dpct::get_error_string_dummy (e ); 520return false; 521 } 522 } 523scratch_elems_ = scratch_elems ; 524return true; 525} 526catch (sycl::exception const & exc ) { 527 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 528 <<", line:" <<__LINE__ << std::endl ; 529 std::exit (1 ); 530} 531 532#if !defined(__HIPCC__ ) 533// ---- below sm_80: BF16 GEMMs without BF16 tensor cores (PR #655, #540, #395) ---------------------------------------- 534// Turing and Volta have no BF16 tensor cores: cublasGemmEx on CUDA_R_16BF inputs falls back to a SIMT fp32 kernel 535// (magma_sgemmEx), a fifth of a 4K prompt on an RTX 2080 Ti (#655) and ~10% of a V100's prompt (#540). BF16 -> FP16 536// is exact for every value inside FP16's normal range (the 7-bit mantissa fits in 10 bits); weights and normalized 537// activations sit there. With the FP16 path, the weight is converted once per call and the activations in row 538// slices, into the instance's own buffers, and the product runs as the FP16 GEMM (fp32 accumulate) on the tensor 539// cores. Finite values beyond FP16's range are clamped to +-65504 (#540) instead of becoming Inf. A beta = 1 540// product (STRATA_PREFILL_BF16X2's remainder, ~2^-9 of the original, deep in FP16's subnormal band) keeps cuBLAS. 541// Default: on for compute capability 7.0 - 7.4 (Volta: only the experimental STRATA_EXPERIMENTAL_SM60 build runs 542// there), OFF for 7.5 (RTX 20 in the ready-made engine: the sums round differently, so it is opt-in until it has 543// been gated). STRATA_BF16_TC=1 / =0 turns it on / off on any 7.x card (=2, a test mode: on any card). 544// Pascal (6.x) has no tensor cores and cuBLAS has no BF16 GEMM for it (#395, measured NOT_SUPPORTED on a P40): both 545// operands are widened to fp32 by an exact shift and the product is cublasSgemm with the same fp32 accumulator. 546namespace { 547__dpct_inline__ void bf16_to_f16_kernel (const uint16_t * __restrict__in , 548 sycl::half * __restrict__out , 549int64_t n ) { 550auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 551const int64_t i = 552 (int64_t )item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 553item_ct1 .get_local_id (2 ); 554if (i < n ) { 555float f = sycl::bit_cast < float > ((uint32_t )in [i ] <<16 ); 556if (f > 65504.0f && !sycl::isinf (f ))f = 65504.0f ; 557else if (f < -65504.0f && !sycl::isinf (f ))f = -65504.0f ; 558out [i ]= sycl::vec < float ,1 > (f ) 559 .convert < sycl::half , sycl::rounding_mode::rte > ()[0 ]; 560 } 561} 562void bf16_to_f16 (const uint16_t * in ,uint16_t * out ,int64_t n , 563 dpct::queue_ptr st ) { 564if (n <=0 )return ; 565 { 566auto exp_props = sycl::ext::oneapi::experimental::properties { 567 sycl::ext::oneapi::experimental::use_root_sync }; 568 dpct::has_capability_or_fail (st -> get_device (), {sycl::aspect::fp16 }); 569 570 strata::kprof::kp (st ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < dpct_kernel_name < class bf16_to_f16_kernel_a0031a >> ( 571 sycl::nd_range < 3 > (sycl::range (1 ,1 , (unsigned )((n + 255 ) /256 ))* 572 sycl::range (1 ,1 ,256 ), 573 sycl::range (1 ,1 ,256 )), 574exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 575bf16_to_f16_kernel (in ,reinterpret_cast < sycl::half *> (out ),n ); 576 }); 577 } 578} 579#if defined(STRATA_EXPERIMENTAL_SM60 )// Pascal runs only the experimental build 580__global__ void bf16_to_f32_kernel (const uint16_t * __restrict__in ,float * __restrict__out ,int64_t n ) { 581const int64_t i = (int64_t )blockIdx .x * blockDim .x + threadIdx .x ; 582if (i < n )out [i ]= __uint_as_float ((uint32_t )in [i ] <<16 ); 583} 584void bf16_to_f32 (const uint16_t * in ,float * out ,int64_t n ,cudaStream_t st ) { 585if (n <=0 )return ; 586bf16_to_f32_kernel <<<( unsigned ) (( n + 255 ) / 256 ), 256 , 0 , st > >>( in , out , n ); 587} 588#endif 589// The current device's compute capability as 10 * major + minor, per device (a layer split can mix cards); 0: not 590// known, read as "not an old card" so a failed query keeps the cuBLAS BF16 call. 591int current_cc() try { 592static std:: atomic < int > cc [ 64 ] = {}; 593int dev = 0 ; 594/* 595DPCT1026: The call to cudaGetLastError was removed because this 596functionality is redundant in SYCL. 597*/ 598if (DPCT_CHECK_ERROR( dev = dpct::get_current_device_id()) != 0 || dev < 0 || 599dev >= 64 ) { 600; return 0 ; 601} 602int v = cc [ dev ].load(std:: memory_order_relaxed ); 603if ( v == 0 ) { 604int major = 0 , minor = 0 ; 605if (DPCT_CHECK_ERROR( 606major = dpct::get_device( dev ).get_major_version()) != 0 || 607DPCT_CHECK_ERROR( 608minor = dpct::get_device( dev ).get_minor_version()) != 0 ) { 609/* 610DPCT1026: The call to cudaGetLastError was removed because this 611functionality is redundant in SYCL. 612*/ 613return 0 ; 614} 615v = 10 * major + minor ; 616cc [ dev ].store( v , std:: memory_order_relaxed ); 617} 618return v ; 619} 620catch (sycl:: exception const & exc ) { 621std:: cerr << exc .what() << "Exception caught at file:" << __FILE__ 622<< ", line:" << __LINE__ << std:: endl ; 623std::exit( 1 ); 624} 625// 0: cuBLAS's BF16 GEMM, 1: through FP16 (tensor cores), 2: through FP32 (Pascal) 626int bf16_path() { 627static const int forced = [] { 628const char * v = std::getenv( "STRATA_BF16_TC" ); 629return v != nullptr && v [ 0 ] != '\0' ? std::atoi( v ) : -1 ; 630}(); 631const int cc = current_cc(); 632if ( forced == 2 && cc > 0 ) return 1 ; // a test mode: the FP16 path on any card (gemm_bf16_parity on sm_80+) 633if ( cc <= 0 || cc >= 80 ) return 0 ; 634if ( cc < 70 ) return 2 ; 635if ( forced >= 0 ) return forced != 0 ? 1 : 0 ; 636return cc < 75 ? 1 : 0 ; 637} 638bool grow( uint16_t *& p , int64_t & have , 639int64_t want ) try { // `have`, `want`: 2-byte elements 640if ( have >= want ) return true; 641if ( p ) sycl::free( p , dpct::get_in_order_queue()); 642p = nullptr ; 643have = 0 ; 644/* 645DPCT1026: The call to cudaGetLastError was removed because this 646functionality is redundant in SYCL. 647*/ 648if (DPCT_CHECK_ERROR( p = ( uint16_t * )sycl::malloc_device( 649( size_t ) want * 2 , dpct::get_in_order_queue())) != 6500 ) { 651; p = nullptr ; return false; 652} 653have = want ; 654return true; 655} 656catch (sycl:: exception const & exc ) { 657std:: cerr << exc .what() << "Exception caught at file:" << __FILE__ 658<< ", line:" << __LINE__ << std:: endl ; 659std::exit( 1 ); 660} 661constexpr int64_t kXSliceElems = 16ll << 20 ; // 32 MiB of FP16 activations per slice (64 MiB as fp32) 662} // namespace 663#endif 664bool Gemm ::bf16_hcd_exact( const uint16_t * X , int64_t ldx , const uint16_t * W , float * Y , int64_t T , int64_t N , int64_t K ) { 665#if defined( __HIPCC__ ) && defined( STRATA_HIPBLASLT_AVAILABLE ) 666static std:: atomic < bool > told {false}; 667if (! hipblaslt_state_ || N != 320 || K != 10240 || T < 1 ) { 668if ( N == 320 && K == 10240 && ! told .exchange(true)) 669std::fprintf( stderr , "strata: STRATA_HCD_EXACT: no hipBLASLt tuning table is loaded, so the exact kernel has nothing to match: " 670"the hyper-connection down projection stays on hipBLAS\n" ); 671return false; 672} 673// The kernel copies hipBLASLt solution 1176 / 1177's summation order, which is only true of the library build the 674// table was calibrated with: take it only when the table makes hipBLASLt pick one of those two for this T. 675const int id = hipblaslt_solution_for( hipblaslt_state_ , strata::prefill::hipblaslt:: InputType :: bf16 , T , N , K , N , 0.0f ); 676if ( id != 1176 && id != 1177 ) { 677if ( T >= 4096 && ! told .exchange(true)) // (a short chunk may legitimately get another solution: not worth a line) 678std::fprintf( stderr , "strata: STRATA_HCD_EXACT: the tuning table gives the hyper-connection down projection (N 320, K 10240) " 679"solution %d at T %lld, not 1176 / 1177: hipBLASLt runs it (a changed table or library; " 680"tools/hip/gfx1151-hipblaslt-100401.txt is the one measured)\n" , 681id , ( long long ) T ); 682return false; 683} 684return strata_pf_hcdown_exact_bf16( X , ldx , W , Y , T , N , K , stream_ ); 685#else 686( void ) X ; ( void ) ldx ; ( void ) W ; ( void ) Y ; ( void ) T ; ( void ) N ; ( void ) K ; 687return false; 688#endif 689} 690 691 692// --------------------------------------------------------------------------------------------------------------- 693// CLEAN-6.0: oneMKL's bf16 GEMM is not repeatable on the Arc A750 for skinny shapes (measured: M=48,T=86,K=2560 and 694// M=4,T=86,K=10240 give a different result on every launch; T below ~128-160 at those M and K; M<=64 at T=1..8). The 695// prompt path's ssm_alpha / ssm_beta (48 outputs) and hyper-connection inject (4 outputs) projections hit it in every 696// GDN layer, so the GDN state, and with it every token after a small near-tie, changed from run to run. Gemm::bf16 697// runs outputs <= 64 on the fixed-order kernel below instead (repeatable, and 3-36x faster than oneMKL on the shapes tried, standalone). 698// STRATA_SYCL_BF16_DET=0 gives the oneMKL call back (A/B and diagnosis). 699// Deterministic bf16 x bf16 -> f32 skinny GEMM (CLEAN-6.0). Y[t*ldy + n] (+)= sum_k W[n*K + k] * X[t*ldx + k] 700// Fixed accumulation order: lane l of a 16-lane sub-group takes the k pairs 2l, 2l+32, 2l+64, ... in order (two fp32 701// fused multiply-adds per pair), the 16 lane sums are then combined by the sub-group reduction (a fixed shuffle tree). 702// No atomics, no split-K, no dependence on scheduling: the same bits on every run. oneMKL's GEMM for these shapes is 703// not repeatable on the Arc A750 (it accumulates the K split in an order that varies from launch to launch). 704// K must be even; W rows 4-byte aligned (any bf16 tensor from the pack is). 705namespace strata_bf16_det { 706constexpr int kLanes = 16 , kSgPerWg = 4 , kOut = 4 ; 707inline float bf16lo( uint32_t u ) { return sycl::bit_cast < float > ( u << 16 ); } 708inline float bf16hi( uint32_t u ) { return sycl::bit_cast < float > ( u & 0xFFFF0000u ); } 709inline void gemm(sycl:: queue & q , const uint16_t * X , int64_t ldx , const uint16_t * W , float * Y , int64_t T , int64_t N , int64_t K , 710int64_t ldy , float beta ) { 711const int64_t nblk = ( N + kOut - 1 ) / kOut ; 712const int64_t total_sg = T * nblk ; 713const int64_t wgs = ( total_sg + kSgPerWg - 1 ) / kSgPerWg ; 714q .parallel_for(sycl::nd_range < 1 > (sycl::range < 1 > (( size_t )( wgs * kSgPerWg * kLanes )), sycl::range < 1 > ( kSgPerWg * kLanes )), 715[ = ](sycl:: nd_item < 1 > it ) [[ sycl :: reqd_sub_group_size ( 16 )]] { 716const sycl:: sub_group sg = it .get_sub_group(); 717const int64_t id = ( int64_t ) it .get_group( 0 ) * kSgPerWg + ( int64_t ) sg .get_group_linear_id(); 718if ( id >= total_sg ) return ; // (whole sub-group: uniform) 719const int64_t t = id / nblk , n0 = ( id % nblk ) * kOut ; 720const uint32_t * xr = reinterpret_cast < const uint32_t *> ( X + t * ldx ); 721const uint32_t * wr [ kOut ]; 722float acc [ kOut ]; 723for ( int o = 0 ; o < kOut ; ++ o ) { wr [ o ] = reinterpret_cast < const uint32_t *> ( W + ( n0 + ( o < N - n0 ? o : 0 )) * K ); acc [ o ] = 0.0f ; } 724const int lane = ( int ) sg .get_local_linear_id(); 725for ( int64_t k2 = lane ; k2 < K / 2 ; k2 += kLanes ) { 726const uint32_t xv = xr [ k2 ]; 727const float x0 = bf16lo( xv ), x1 = bf16hi( xv ); 728for ( int o = 0 ; o < kOut ; ++ o ) { 729const uint32_t wv = wr [ o ][ k2 ]; 730acc [ o ] = sycl::fma(bf16lo( wv ), x0 , acc [ o ]); 731acc [ o ] = sycl::fma(bf16hi( wv ), x1 , acc [ o ]); 732} 733} 734for ( int o = 0 ; o < kOut ; ++ o ) { 735const float s = sycl::reduce_over_group( sg , acc [ o ], sycl::plus < float > ()); 736if ( lane == 0 && n0 + o < N ) { 737float * y = Y + t * ldy + n0 + o ; 738* y = beta == 0.0f ? s : sycl::fma( beta , * y , s ); 739} 740} 741}); 742} 743} // namespace strata_bf16_det 744 745namespace { 746// oneMKL's GEMM reads the last, partial tile of an operand from the wrong place when it lies more than 4 GiB into its 747// allocation (Arc A770, oneMKL 2026.1: a BF16 B placed past 4 GiB of a 10.5 GiB allocation gave its last 21 columns 748// wrong, and none below 4 GiB). The prompt path borrows the top of the ~10 GiB expert cache for its buffers, so its 749// GEMMs met this and the prompt came out non-finite / garbage. An operand past 4 GiB is copied into a scratch buffer 750// of the queue's own - a fresh allocation, so at offset 0 - and the GEMM runs on that. Returns false, so the caller 751// runs the direct GEMM, when neither operand needs staging (the common, correct case). 752uint8_t * gemm_stage( size_t need , sycl:: queue & q ) { 753static thread_local uint8_t * p = nullptr ; 754static thread_local size_t cap = 0 ; 755if ( need > cap ) { 756if ( p != nullptr ) { 757q .wait(); // the queue is in-order but asynchronous: a previous staged GEMM may still read p 758sycl::free( p , q ); 759} 760p = ( uint8_t * ) sycl::malloc_device( need , q ); 761cap = p != nullptr ? need : 0 ; 762} 763return p ; 764} 765inline bool staged_gemm(sycl:: queue & q , void * handle , const uint16_t * W , int lda , const uint16_t * X , int ldb , 766dpct:: library_data_t dt , int64_t N , int64_t T , int64_t K , float alpha , float beta , 767float * Y , int64_t ldy ) { 768// STRATA_SYCL_GEMM_NO_STAGE: the tests' negative control. 0.1.43: not on Battlemage either (the A770 oneMKL bug above did not 769// show on a B70: 4K and 49K prompts, operands at 18 GiB into the cache arena, first-token logits byte-identical with and 770// without staging; the 10 MB copy per expert was ~10% of a prompt). STRATA_SYCL_GEMM_STAGE=1 stages there as before. 771static const bool no_stage = std::getenv( "STRATA_SYCL_GEMM_NO_STAGE" ) != nullptr || 772(strata::intel_gpu_gen( q .get_device()) == strata:: IntelGpuGen :: Battlemage && !(std::getenv( "STRATA_SYCL_GEMM_STAGE" ) && std::getenv( "STRATA_SYCL_GEMM_STAGE" )[ 0 ] == '1' )); 773constexpr size_t k4G = 4ull << 30 ; 774const size_t es = 2 ; 775const size_t w_bytes = ( size_t ) lda * ( size_t ) N * es ; // W stored K x N, col-major (lda = K) 776const size_t x_bytes = ( size_t ) ldb * ( size_t ) T * es ; // X stored ldb x T 777const bool far_w = strata::device_offset_end( W , w_bytes ) > k4G ; 778const bool far_x = strata::device_offset_end( X , x_bytes ) > k4G ; 779if ( no_stage || (! far_w && ! far_x )) return false; 780uint8_t * s = gemm_stage( w_bytes + x_bytes , q ); 781if ( s == nullptr ) { 782std::fprintf( stderr , "strata: WARNING: a GEMM operand lies past 4 GiB and the %zu MiB staging buffer could not be " 783"allocated; the GEMM runs directly and may be wrong on this card\n" , 784( w_bytes + x_bytes ) >> 20 ); 785return false; 786} 787uint8_t * sw = s ; 788uint8_t * sx = s + w_bytes ; 789if ( far_w ) q .memcpy( sw , W , w_bytes ); 790if ( far_x ) q .memcpy( sx , X , x_bytes ); 791const uint16_t * Wu = far_w ? ( const uint16_t * ) sw : W ; 792const uint16_t * Xu = far_x ? ( const uint16_t * ) sx : X ; 793ck(DPCT_CHECK_ERROR(dpct::blas:: gemm ( 794(dpct::blas:: descriptor_ptr ) handle , oneapi::mkl::transpose:: trans , oneapi::mkl::transpose:: nontrans , 795( int ) N , ( int ) T , ( int ) K , & alpha , Wu , dt , lda , Xu , dt , ldb , & beta , Y , 796dpct::library_data_t:: real_float , ( int ) ldy , dpct::compute_type:: f32 )), 797"cublasGemmEx (staged)" ); 798return true; 799} 800} // namespace 801 802// (#2091, CUDA Turing only) no FP16 activation image on this backend 803bool Gemm ::bf16_converts_x() const { return false; } 804 805void Gemm ::bf16( const uint16_t * X , const uint16_t * W , float * Y , int64_t T , int64_t N , int64_t K , int64_t ldy , 806float beta , int64_t ldx , bool /*x_f16*/ ) { 807if ( T <= 0 || N <= 0 ) return ; 808strata::kprof:: Section kp_sec (strata::q_of( stream_ ), strata::kprof:: enabled () ? "gemm bf16 N=" + std::to_string(( long long ) N ) + " K=" + std::to_string(( long long ) K ) : std::string()); 809if ( ldy <= 0 ) ldy = N ; 810if ( ldx <= K ) ldx = 0 ; 811#ifdef STRATA_USE_HIP 812// #313 (opt-in STRATA_WMMA_GEMM=1; STRATA_WMMA_BF16=0 excludes bf16): RDNA3 / RDNA3.5 WMMA dense GEMM, before 813// hipBLASLt; it returns false for shapes it does not take (and off gfx11) and this falls through 814static const bool wmma_on = [] { const char * v = std::getenv( "STRATA_WMMA_GEMM" ); return v && v [ 0 ] != 0 && v [ 0 ] != '0' ; }(); 815static const bool bf16_on = [] { const char * v = std::getenv( "STRATA_WMMA_BF16" ); return ! v || ( v [ 0 ] != 0 && v [ 0 ] != '0' ); }(); 816if ( wmma_on && bf16_on && ldx == 0 && T >= 16 && ( beta == 0.0f || beta == 1.0f ) && 817strata_wmma_gemm_bf16( X , W , Y , T , N , K , ldy , beta , stream_ )) { 818return ; 819} 820#endif 821#if defined( __HIPCC__ ) 822if ( f16_io_ ) { // X is the FP16 image (set_act_f16); W goes through the dequantization scratch as FP16 823// the only accumulating BF16 product is the BF16X2 low part, which bf16x2_mode() turns off with this path 824if ( beta != 0.0f ) { std::fprintf( stderr , "prefill gemm: an accumulating BF16 GEMM on the FP16 prompt path\n" ); std::exit( 1 ); } 825const int64_t rows = std::min < int64_t > ( N , scratch_elems_ / K ); 826if ( rows <= 0 ) { std::fprintf( stderr , "prefill gemm: scratch too small for K=%lld\n" , ( long long ) K ); std::exit( 1 ); } 827for ( int64_t r0 = 0 ; r0 < N ; r0 += rows ) { 828const int64_t n = std::min( rows , N - r0 ); 829bf16_to_f16_rows <<< 1024 , 256 , 0 , ( cudaStream_t ) stream_ > >>( W + r0 * K , ( __half * ) scratch_ , n * K ); 830f16_inplace( X , scratch_ , Y + r0 , T , n , K , ldy ); 831} 832return ; 833} 834#endif 835workload_trace:: Scope trace ( "gemm.bf16_to_f32" , stream_ , T , N , K , ldx ? ldx : K , ldy ); 836const float alpha = 1.0f ; 837{ // CLEAN-6.0: the repeatable path for skinny outputs (see strata_bf16_det) 838static const int det_mode = [] { const char * v = std::getenv( "STRATA_SYCL_BF16_DET" ); return v == nullptr || v [ 0 ] == 0 ? 1 : std::atoi( v ); }(); 839const int64_t xs = ldx ? ldx : K ; 840if ( det_mode != 0 && ( K & 1 ) == 0 && ( xs & 1 ) == 0 && N <= ( det_mode == 2 ? ( int64_t ) 1 << 30 : ( int64_t ) 64 ) && 841(reinterpret_cast < uintptr_t > ( X ) & 3u ) == 0 && (reinterpret_cast < uintptr_t > ( W ) & 3u ) == 0 ) { 842strata_bf16_det::gemm( * strata::q_of( stream_ ), X , xs , W , Y , T , N , K , ldy , beta ); 843return ; 844} 845} 846#if defined( __HIPCC__ ) && defined( STRATA_HIPBLASLT_AVAILABLE ) 847if (try_hipblaslt( hipblaslt_state_ , strata::prefill::hipblaslt:: InputType :: bf16 , X , W , Y , T , N , K , ldy , 848beta , stream_ , ldx )) { 849STRATA_ABSORB_HIPBLAS_STICKY( "hipBLASLt bf16" ); 850return ; 851} 852#endif 853#if !defined( __HIPCC__ ) 854if ( const int path = K > 0 ? bf16_path() : 0 ; path == 1 && N > 1 && beta == 0.0f ) { 855// a single output row stays cuBLAS's GEMV, faster than the conversions; beta = 1: see above 856const int64_t x_rows = std::max < int64_t > ( 1 , std::min < int64_t > ( T , kXSliceElems / K )); 857if (grow( tc_w_ , tc_w_elems_ , N * K ) && grow( tc_x_ , tc_x_elems_ , x_rows * K )) { 858bf16_to_f16( W , tc_w_ , N * K , strata::q_of( stream_ )); 859for ( int64_t t0 = 0 ; t0 < T ; t0 += x_rows ) { 860const int64_t n = std::min < int64_t > ( x_rows , T - t0 ); 861bf16_to_f16( X + t0 * K , tc_x_ , n * K , strata::q_of( stream_ )); 862f16( tc_x_ , tc_w_ , Y + t0 * ldy , n , N , K , ldy , beta ); 863} 864return ; 865} 866} 867#if defined( STRATA_EXPERIMENTAL_SM60 ) 868else if ( path == 2 ) { 869// Pascal: fp32 copies (2 elements of the 2-byte buffers each). Every tile is a disjoint block of Y, so each 870// gets the caller's beta. 871const int64_t x_rows = std::max < int64_t > ( 1 , std::min < int64_t > ( T , kXSliceElems / K )); 872if (grow( tc_w_ , tc_w_elems_ , 2 * N * K ) && grow( tc_x_ , tc_x_elems_ , 2 * x_rows * K )) { 873float * const wf = reinterpret_cast < float *> ( tc_w_ ); 874float * const xf = reinterpret_cast < float *> ( tc_x_ ); 875bf16_to_f32( W , wf , N * K , ( cudaStream_t ) stream_ ); 876for ( int64_t t0 = 0 ; t0 < T ; t0 += x_rows ) { 877const int64_t n = std::min < int64_t > ( x_rows , T - t0 ); 878bf16_to_f32( X + t0 * K , xf , n * K , ( cudaStream_t ) stream_ ); 879ck(cublasSgemm(( cublasHandle_t ) handle_ , CUBLAS_OP_T , CUBLAS_OP_N , ( int ) N , ( int ) n , ( int ) K , & alpha , 880wf , ( int ) K , xf , ( int ) K , & beta , Y + t0 * ldy , ( int ) ldy ), 881"cublasSgemm (bf16 on Pascal)" ); 882} 883return ; 884} 885} 886#endif 887#endif 888if (staged_gemm( * strata::q_of( stream_ ), handle_ , W , ( int ) K , X , ( int ) ( ldx ? ldx : K ), dpct::library_data_t:: real_bfloat16 , N , T , K , 889alpha , beta , Y , ldy )) 890return ; 891// Column-major view: Y^T[N, T] = W[N, K] (stored K x N col-major, transposed) . X^T[K, T]. 892ck(DPCT_CHECK_ERROR(dpct::blas:: gemm ( 893(dpct::blas:: descriptor_ptr ) handle_ , oneapi::mkl::transpose:: trans , 894oneapi::mkl::transpose:: nontrans , ( int ) N , ( int ) T , ( int ) K , & alpha , W , 895dpct::library_data_t:: real_bfloat16 , ( int ) K , X , 896dpct::library_data_t:: real_bfloat16 , ( int )( ldx ? ldx : K ), & beta , Y , 897dpct::library_data_t:: real_float , ( int ) ldy , 898dpct::compute_type:: f32 )), 899"cublasGemmEx" ); 900STRATA_ABSORB_HIPBLAS_STICKY( "cublasGemmEx" ); 901} 902 903void Gemm ::f16( const uint16_t * X , const uint16_t * W , float * Y , int64_t T , int64_t N , int64_t K , int64_t ldy , 904float beta ) { 905if ( T <= 0 || N <= 0 ) return ; 906strata::kprof:: Section kp_sec (strata::q_of( stream_ ), strata::kprof:: enabled () ? "gemm f16 N=" + std::to_string(( long long ) N ) + " K=" + std::to_string(( long long ) K ) : std::string()); 907if ( ldy <= 0 ) ldy = N ; 908#ifdef STRATA_USE_HIP 909// #313 (opt-in STRATA_WMMA_GEMM=1): RDNA3 / RDNA3.5 WMMA dense GEMM, before hipBLASLt (falls through when false) 910static const bool wmma_on = [] { const char * v = std::getenv( "STRATA_WMMA_GEMM" ); return v && v [ 0 ] != 0 && v [ 0 ] != '0' ; }(); 911static const bool pf_on = [] { const char * v = std::getenv( "STRATA_PF_GEMM" ); return v && v [ 0 ] == '1' ; }(); 912static const int64_t pf_min_t = [] { const char * v = std::getenv( "STRATA_PF_SWITCH_MIN_T" ); return v ? ( int64_t ) std::atoll( v ) : ( int64_t ) 0 ; }(); 913if ( pf_on && T >= pf_min_t && strata_pf_gemm_f16( X , W , Y , T , N , K , ldy , beta , stream_ )) return ; // S23: opt-in 914if ( wmma_on && T >= 16 && ( beta == 0.0f || beta == 1.0f ) && 915strata_wmma_gemm_f16( X , W , Y , T , N , K , ldy , beta , stream_ )) { 916return ; 917} 918#endif 919#if defined( __HIPCC__ ) 920if ( f16_io_ && beta == 0.0f ) { f16_inplace( X , W , Y , T , N , K , ldy ); return ; } 921#endif 922workload_trace:: Scope trace ( "gemm.f16_to_f32" , stream_ , T , N , K , K , ldy ); 923const float alpha = 1.0f ; 924#if defined( __HIPCC__ ) && defined( STRATA_HIPBLASLT_AVAILABLE ) 925if (try_hipblaslt( hipblaslt_state_ , strata::prefill::hipblaslt:: InputType :: f16 , X , W , Y , T , N , K , ldy , 926beta , stream_ )) { 927STRATA_ABSORB_HIPBLAS_STICKY( "hipBLASLt f16" ); 928return ; 929} 930#endif 931if (staged_gemm( * strata::q_of( stream_ ), handle_ , W , ( int ) K , X , ( int ) K , dpct::library_data_t:: real_half , N , T , K , alpha , beta , Y , ldy )) 932return ; 933ck(DPCT_CHECK_ERROR(dpct::blas:: gemm ( 934(dpct::blas:: descriptor_ptr ) handle_ , oneapi::mkl::transpose:: trans , 935oneapi::mkl::transpose:: nontrans , ( int ) N , ( int ) T , ( int ) K , & alpha , W , 936dpct::library_data_t:: real_half , ( int ) K , X , 937dpct::library_data_t:: real_half , ( int ) K , & beta , Y , 938dpct::library_data_t:: real_float , ( int ) ldy , 939dpct::compute_type:: f32 )), 940"cublasGemmEx f16" ); 941STRATA_ABSORB_HIPBLAS_STICKY( "cublasGemmEx f16" ); 942} 943 944#if defined( STRATA_PREFILL_MMQ ) && defined( __HIPCC__ ) 945bool Gemm ::native_mmq( const uint16_t * X , int type , const void * W , float * Y , int64_t T , int64_t N , int64_t K , 946int64_t ldy ) { 947namespace mmq = strata::prefill::mmq; 948constexpr int64_t kRows = 1024 , kMaxK = 8192 ; 949static const bool enabled = [] { 950const char * e = std::getenv( "STRATA_DENSE_MMQ" ); 951return e && e [ 0 ] == '1' ; 952}(); 953if (! enabled || mmq_failed_ || !mmq::built() || !mmq::fits( type , N )) return false; 954// K must be a multiple of 256: llama.cpp's MMQ loads the weights in 256-value K chunks, and the 955// chunk past a partial row reads past the row (the next row's bytes - or, for the last weight 956// row, bytes past the tensor, which no caller guarantees to be zeros). The MoE path is safe 957// because its gather buffers carry a zeroed tail; a dense tensor is passed as-is, so a K that 958// is not a full chunk multiple (e.g. the 640-value shared-expert down: 20 blocks of 32) stays on 959// the dequantize + cuBLAS path. 960if ( K > kMaxK || K % 256 != 0 ) return false; 961int64_t R = scratch_elems_ / ( 2 * K ); // FP32 activations for a chunk fit in the FP16 dequant scratch 962if ( R > kRows ) R = kRows ; 963if ( R > T ) R = T ; 964if ( R < 1 ) return false; 965if ( ldy <= 0 ) ldy = N ; 966 967const auto up = []( size_t v ) { return ( v + 255 ) & ~( size_t ) 255 ; }; 968const size_t ident_off = up(mmq::q8_bytes( kRows , kMaxK )); 969const size_t bounds_off = ident_off + up(( size_t ) kRows * 4 ); 970if (! mmq_buf_ ) { 971if (cudaMalloc( & mmq_buf_ , bounds_off + 256 ) != cudaSuccess ) { 972cudaGetLastError(); 973mmq_failed_ = true; 974return false; 975} 976mmq_ctx_ = new mmq:: Context (); 977mmq::iota(( int32_t * ) (( uint8_t * ) mmq_buf_ + ident_off ), kRows , stream_ ); 978std::fprintf( stderr , "prefill gemm: dense MMQ on (STRATA_DENSE_MMQ=1)\n" ); 979} 980void * xq = mmq_buf_ ; 981const int32_t * ident = ( const int32_t * ) (( uint8_t * ) mmq_buf_ + ident_off ); 982int32_t * bounds = ( int32_t * ) (( uint8_t * ) mmq_buf_ + bounds_off ); 983float * xf = ( float * ) scratch_ ; 984auto * ctx = static_cast < mmq:: Context *> ( mmq_ctx_ ); 985 986for ( int64_t r0 = 0 ; r0 < T ; r0 += R ) { 987const int64_t rows = ( T - r0 < R ) ? T - r0 : R ; 988mmq::f16_to_f32( X + r0 * K , xf , rows * K , stream_ ); 989mmq::quantize( xf , nullptr , xq , type , K , K , rows , stream_ ); 990mmq::set_bounds( bounds , ( int32_t ) rows , stream_ ); 991mmq:: Product p ; 992p . w = W ; 993p . type = type ; 994p . w_rows = N ; 995p . w_cols = K ; 996p . expert_bytes = mmq::matrix_bytes( type , N , K ); 997p . n = 1 ; 998p . xq = xq ; 999p . bounds = bounds ; 1000p . ids = ident ; 1001p . total_rows = rows ; 1002p . max_rows = rows ; 1003p . dst = Y + r0 * ldy ; 1004p . ld_dst = ldy ; 1005ctx -> run( p , stream_ ); 1006} 1007return true; 1008} 1009#endif 1010void Gemm ::f16_inplace( const uint16_t * X , const uint16_t * W , float * Y , int64_t T , int64_t N , int64_t K , int64_t ldy ) { 1011#if defined( __HIPCC__ ) 1012const float one = 1.0f , zero = 0.0f ; 1013ck(cublasGemmEx(( cublasHandle_t ) handle_ , CUBLAS_OP_T , CUBLAS_OP_N , ( int ) N , ( int ) T , ( int ) K , & one , W , CUDA_R_16F , 1014( int ) K , X , CUDA_R_16F , ( int ) K , & zero , Y , CUDA_R_16F , ( int ) ( 2 * ldy ), CUBLAS_COMPUTE_32F , 1015CUBLAS_GEMM_DEFAULT ), 1016"cublasGemmEx f16 out" ); 1017static const bool dbg_nan = std::getenv( "STRATA_DBG_NAN" ) != nullptr ; 1018widen_rows_f16 <<<( unsigned ) T , 256 , 0 , ( cudaStream_t ) stream_ > >>( Y , N , ldy , dbg_nan ? 1 : 0 ); 1019if ( dbg_nan ) { // debug only: a sync per GEMM 1020unsigned long long bad = 0 , zero_count = 0 ; 1021( void ) hipStreamSynchronize(( hipStream_t ) stream_ ); 1022if (hipMemcpyFromSymbol( & bad , HIP_SYMBOL( g_f16_nonfinite ), sizeof bad ) == hipSuccess && bad != 0 ) { 1023std::fprintf( stderr , "strata prefill: STRATA_DBG_NAN: %llu non-finite FP16 GEMM outputs (T=%lld N=%lld K=%lld; FP16 ends at 65504)%s" , 1024bad , ( long long ) T , ( long long ) N , ( long long ) K , "\n" ); 1025( void ) hipMemcpyToSymbol(HIP_SYMBOL( g_f16_nonfinite ), & zero_count , sizeof zero_count ); 1026} 1027} 1028#else 1029( void ) X ; ( void ) W ; ( void ) Y ; ( void ) T ; ( void ) N ; ( void ) K ; ( void ) ldy ; 1030#endif 1031} 1032 1033void Gemm ::native( const uint16_t * X , int ggml_type , const void * W_blocks , float * Y , int64_t T , int64_t N , int64_t K , 1034int64_t ldy , float beta , int64_t ldx ) { 1035if ( T <= 0 || N <= 0 ) return ; 1036if ( ldy <= 0 ) ldy = N ; 1037if ( ldx <= 0 ) ldx = K ; 1038auto multiply = [ & ]( int64_t n , float * out ) { 1039workload_trace:: Scope trace ( "gemm.native_f16_to_f32" , stream_ , T , n , K , ldx , ldy , ggml_type ); 1040const float alpha = 1.0f ; 1041ck(DPCT_CHECK_ERROR(dpct::blas:: gemm ( 1042(dpct::blas:: descriptor_ptr ) handle_ , oneapi::mkl::transpose:: trans , 1043oneapi::mkl::transpose:: nontrans , ( int ) n , ( int ) T , ( int ) K , & alpha , scratch_ , 1044dpct::library_data_t:: real_half , ( int ) K , X , 1045dpct::library_data_t:: real_half , ( int ) ldx , & beta , out , 1046dpct::library_data_t:: real_float , ( int ) ldy , 1047dpct::compute_type:: f32 )), 1048"cublasGemmEx native" ); 1049}; 1050if ( N * K > scratch_elems_ ) { 1051// Too large for the scratch at once: in row slices. 1052const int64_t rows = scratch_elems_ / K ; 1053if ( rows <= 0 ) { std::fprintf( stderr , "prefill gemm: scratch too small for K=%lld\n" , ( long long ) K ); std::exit( 1 ); } 1054if ( ldy <= 0 ) ldy = N ; 1055for ( int64_t r0 = 0 ; r0 < N ; r0 += rows ) { 1056const int64_t n = ( N - r0 < rows ) ? N - r0 : rows ; 1057strata::kernels:: dequant_f16 ( ggml_type , W_blocks , r0 , n , K , scratch_ , stream_ ); 1058multiply( n , Y + r0 ); 1059} 1060return ; 1061} 1062strata::kernels:: dequant_f16 ( ggml_type , W_blocks , 0 , N , K , scratch_ , stream_ ); 1063multiply( N , Y ); 1064} 1065 1066} // namespace strata::prefill