okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
86bed1c92
main
1// src/core/device.cu - P2.S1: the CUDA side of the runtime core. 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/core/device.hpp" 8 9#include <cstdio> 10#include <cstring> 11 12namespace strata::core { 13 14namespace { 15 16void check (dpct::err0 e ,const char * what ) { 17/* 18DPCT1000: Error handling if-stmt was detected but could not be 19rewritten. 20*/ 21if (e != 0 ) { 22/* 23DPCT1009: SYCL reports errors using exceptions and does not use 24error codes. Please replace the "get_error_string_dummy(...)" with a 25real error-handling function. 26*/ 27/* 28DPCT1001: The statement could not be removed. 29*/ 30throw CudaError ( 31 std::string (what )+ ": " + dpct::get_error_string_dummy (e ), (int )e ); 32 } 33} 34 35// A NaN pattern, not zero. Zeros read from uninitialised memory are indistinguishable from real zeros in a 36// dequantized weight or a masked attention score, which is exactly the kind of wrong-but-plausible value the 37// Phase 1 harnesses kept catching. 38__dpct_inline__ void poison_kernel (float * p ,uint64_t n_floats ) { 39auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 40const uint64_t i = 41 (uint64_t )item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 42item_ct1 .get_local_id (2 ); 43if (i < n_floats )p [i ]= sycl::bit_cast < float > (0x7fc00000 ); 44} 45 46#if defined(STRATA_USE_HIP ) 47#if !defined(STRATA_HIP_ARCHS ) 48#error "STRATA_HIP_ARCHS (the compiled HIP architectures) is set by cmake/hip_backend.cmake" 49#endif 50// "gfx1201:sramecc-:xnack-" -> "gfx1201" 51std::string base_arch (const char * gcn_arch_name ) { 52 std::string arch (gcn_arch_name ); 53const size_t colon = arch .find (':' ); 54if (colon != std::string::npos )arch .resize (colon ); 55return arch ; 56} 57 58bool compiled_for (const std::string & arch ) { 59const std::string list = STRATA_HIP_ARCHS ; 60size_t a = 0 ; 61while (a <=list .size ()) { 62size_t b = list .find (',' ,a ); 63if (b == std::string::npos )b = list .size (); 64if (!arch .empty ()&& list .compare (a ,b - a ,arch )== 0 && b - a == arch .size ())return true; 65a = b + 1 ; 66 } 67return false; 68} 69 70std::string arch_problem (const cudaDeviceProp & p ,int ordinal ) { 71const std::string arch = base_arch (p .gcnArchName ); 72const std::string card = "GPU " + std::to_string (ordinal )+ " (" + p .name + ", " + arch + ")" ; 73if (!compiled_for (arch )) { 74return card + " is not an architecture this Strata engine was compiled for (" + STRATA_HIP_ARCHS + 75"); compile it for this card (./setup.sh --backend hip, or -DCMAKE_HIP_ARCHITECTURES=" + arch + 76", docs/AMD_HIP.md) or choose another GPU with HIP_VISIBLE_DEVICES" ; 77 } 78if (p .warpSize != 32 ) { 79return card + " runs wave" + std::to_string (p .warpSize )+ "; Strata's HIP kernels need wave32" ; 80 } 81return "" ; 82} 83#endif 84 85}// namespace 86 87const char * compiled_gpu_archs () { 88#if defined(STRATA_USE_HIP ) 89return STRATA_HIP_ARCHS ; 90#else 91return "" ; 92#endif 93} 94 95int device_count ()try { 96int count = 0 ; 97if (DPCT_CHECK_ERROR (count = dpct::device_count ())!= 980 ) {// HIP without a usable device reports an error, not 0 99/* 100DPCT1026: The call to cudaGetLastError was removed because this 101functionality is redundant in SYCL. 102*/ 103return 0 ; 104 } 105return count < 0 ?0 :count ; 106} 107catch (sycl::exception const & exc ) { 108 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 109 <<", line:" <<__LINE__ << std::endl ; 110 std::exit (1 ); 111} 112 113bool device_summary (int ordinal , std::string & name , std::string & detail )try { 114 dpct::device_info p {}; 115if (ordinal < 0 || ordinal >=device_count ()|| 116DPCT_CHECK_ERROR (dpct::get_device (ordinal ).get_device_info (p ))!= 0 ) { 117/* 118DPCT1026: The call to cudaGetLastError was removed because this 119functionality is redundant in SYCL. 120*/ 121return false; 122 } 123char buf [160 ]; 124#if defined(STRATA_USE_HIP ) 125 std::snprintf (buf ,sizeof (buf ),"arch %s, %.1f GiB, wave%d" ,base_arch (p .gcnArchName ).c_str (), 126 (double )p .totalGlobalMem / (1024.0 * 1024 * 1024 ),p .warpSize ); 127#else 128/* 129DPCT1005: The SYCL device version is different from CUDA Compute 130Compatibility. You may need to rewrite this code. 131*/ 132 std::snprintf (buf ,sizeof (buf ),"compute capability %d.%d, %.1f GiB" , 133p .get_major_version (),p .get_minor_version (), 134 (double )p .get_global_mem_size () / (1024.0 * 1024 * 1024 )); 135#endif 136name = p .get_name (); 137detail = buf ; 138return true; 139} 140catch (sycl::exception const & exc ) { 141 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 142 <<", line:" <<__LINE__ << std::endl ; 143 std::exit (1 ); 144} 145 146}// namespace strata::core 147 148#if defined(STRATA_USE_HIP )&& defined(_WIN32 ) 149// The free VRAM figure on Windows HIP (include/strata/hip_compat/cuda_runtime.h maps cudaMemGetInfo here). 150// 151// hipMemGetInfo (ROCclr's PAL backend, Device::globalFreeMemory) is the card's size minus this process's own 152// allocations: it asks Windows for this process's usage only, never for what the desktop and other programs hold. 153// So on a card that also drives the desktop the engine counted ~930 MiB that was not there, the expert cache filled 154// the card, and WDDM moved memory out to system RAM: decode at 30 tok/s instead of 41 (RX 6800, HIP SDK 7.2). 155// Windows itself gives each process a video memory budget (DXGI QueryVideoMemoryInfo) that does account for the 156// others. Measured on that card: the budget sits 0.8 GiB below the card's size while this process is small and 157// 1.8 GiB below once it holds 11 GiB; allocations past it still succeed, and are what Windows moves out. The 158// free figure here is hipMemGetInfo's lowered by what the budget withholds (the card's size minus the budget). 159// Subtracting from HIP's own figure, rather than taking the budget minus DXGI's usage, keeps memory the HIP runtime 160// has freed and holds in its cache counted as free, as hipMemGetInfo counts it. dxgi.dll is loaded at run time, so 161// nothing new is linked; when it or the card's adapter cannot be found, hipMemGetInfo's figure stands. 162#ifndef WIN32_LEAN_AND_MEAN 163#define WIN32_LEAN_AND_MEAN 164#endif 165#ifndef NOMINMAX 166#define NOMINMAX 167#endif 168#include <windows.h> 169#include <dxgi1_4.h> 170#include <atomic> 171#include <cstdlib> 172#include <mutex> 173 174namespace strata::hip_compat { 175namespace { 176IDXGIAdapter3 * budget_adapter (int device ) { 177constexpr int kMaxDevices = 16 ; 178static std::mutex mu ; 179static IDXGIAdapter3 * adapters [kMaxDevices ]= {}; 180static bool tried [kMaxDevices ]= {}; 181if (device < 0 || device >=kMaxDevices )return nullptr ; 182 std::lock_guard < std::mutex > lock (mu ); 183if (tried [device ])return adapters [device ]; 184tried [device ]= true; 185hipDeviceProp_t p {}; 186if (hipGetDeviceProperties (& p ,device )!= hipSuccess ) { 187 (void )hipGetLastError (); 188return nullptr ; 189 } 190LUID luid {}; 191 std::memcpy (& luid ,p .luid ,sizeof luid ); 192using CreateFactory = HRESULT (WINAPI * )(REFIID ,void ** ); 193static HMODULE dxgi = LoadLibraryW (L"dxgi.dll" );// kept for the process' lifetime, like the adapters 194const auto create = dxgi ? (CreateFactory ) (void * )GetProcAddress (dxgi ,"CreateDXGIFactory1" ) :nullptr ; 195IDXGIFactory4 * factory = nullptr ; 196if (create == nullptr || FAILED (create (__uuidof (IDXGIFactory4 ), (void ** )& factory )))return nullptr ; 197IDXGIAdapter3 * adapter = nullptr ; 198if (FAILED (factory -> EnumAdapterByLuid (luid ,__uuidof (IDXGIAdapter3 ), (void ** )& adapter )))adapter = nullptr ; 199factory -> Release (); 200adapters [device ]= adapter ; 201return adapter ; 202} 203}// namespace 204 205// #873 / #654: on some Windows setups the first hipMemGetInfo of a process fails with hipErrorInvalidValue because the ROCm 206// runtime has not finished initialising against the Adrenalin WDDM driver, and the first kernel launch after that 207// crashes (0xC0000005 in amdhip64_7.dll). A hipFree(0) before the first query initialises the context, and one 208// failed query gets one retry after 250 ms. Both happen once per process, before the DXGI budget below; any other 209// error, and a failure of the retry, are returned as they are (a real failure is never retried). 210static hipError_t first_mem_get_info (size_t * free_bytes ,size_t * total_bytes ) { 211static std::atomic < bool > warmed {false},retried {false}; 212if (!warmed .exchange (true)) (void )hipFree (nullptr ); 213hipError_t e = hipMemGetInfo (free_bytes ,total_bytes ); 214if (e == hipErrorInvalidValue && !retried .exchange (true)) { 215 (void )hipGetLastError (); 216 std::fprintf (stderr ,"strata: hipMemGetInfo failed (%s); retrying once after 250 ms\n" ,hipGetErrorString (e )); 217Sleep (250 ); 218e = hipMemGetInfo (free_bytes ,total_bytes ); 219 std::fprintf (stderr ,"strata: hipMemGetInfo retry: %s\n" ,e == hipSuccess ?"ok" :hipGetErrorString (e )); 220 } 221return e ; 222} 223 224hipError_t mem_get_info (size_t * free_bytes ,size_t * total_bytes ) { 225if (free_bytes == nullptr || total_bytes == nullptr )return hipMemGetInfo (free_bytes ,total_bytes ); 226const hipError_t e = first_mem_get_info (free_bytes ,total_bytes ); 227static const bool off = [] { 228const char * v = std::getenv ("STRATA_WDDM_BUDGET" ); 229return v != nullptr && std::atoi (v )== 0 ; 230 }(); 231if (e != hipSuccess || off || free_bytes == nullptr || total_bytes == nullptr )return e ; 232int device = 0 ; 233if (hipGetDevice (& device )!= hipSuccess ) { 234 (void )hipGetLastError (); 235return e ; 236 } 237IDXGIAdapter3 * adapter = budget_adapter (device ); 238DXGI_QUERY_VIDEO_MEMORY_INFO local {}; 239if (adapter == nullptr || FAILED (adapter -> QueryVideoMemoryInfo (0 ,DXGI_MEMORY_SEGMENT_GROUP_LOCAL ,& local ))|| 240local .Budget == 0 || local .Budget >=* total_bytes ) 241return e ; 242const size_t withheld = * total_bytes - (size_t )local .Budget ;// the desktop's and other programs' share 243static std::atomic < bool > said {false}; 244if (!said .exchange (true)) { 245 std::fprintf (stderr ,"strata: Windows budgets %llu of this card's %llu MiB for this process; free VRAM is " 246"counted within that (STRATA_WDDM_BUDGET=0: off)\n" , 247 (unsigned long long ) (local .Budget >>20 ), (unsigned long long ) (* total_bytes >>20 )); 248 } 249* free_bytes = * free_bytes > withheld ?* free_bytes - withheld :0 ; 250return e ; 251} 252}// namespace strata::hip_compat 253#endif 254 255namespace strata::core { 256 257std::string gpu_arch_problem (int ordinal ) { 258#if defined(STRATA_USE_HIP ) 259int count = 0 ; 260if (cudaGetDeviceCount (& count )!= cudaSuccess || ordinal < 0 || ordinal >=count ) { 261cudaGetLastError (); 262return "" ; 263 } 264cudaDeviceProp p {}; 265if (cudaGetDeviceProperties (& p ,ordinal )!= cudaSuccess ) { 266cudaGetLastError (); 267return "" ; 268 } 269return arch_problem (p ,ordinal ); 270#else 271 (void )ordinal ; 272return "" ; 273#endif 274} 275 276std::string device_code_error ()try { 277#if defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 ) 278return "" ;// gpu_arch_problem() checks the HIP architectures against STRATA_HIP_ARCHS, before this point 279#else 280// every .cu of the engine is compiled for the same CMAKE_CUDA_ARCHITECTURES, so this kernel stands for all 281 dpct::kernel_function_info a {}; 282const dpct::err0 e = DPCT_CHECK_ERROR ( 283 dpct::get_kernel_function_info (& a , (const void * )poison_kernel )); 284if (e == 0 )return {}; 285/* 286DPCT1026: The call to cudaGetLastError was removed because this 287functionality is redundant in SYCL. 288*/ 289/* 290DPCT1009: SYCL reports errors using exceptions and does not use error 291codes. Please replace the "get_error_string_dummy(...)" with a real 292error-handling function. 293*/ 294return dpct::get_error_string_dummy (e ); 295#endif 296} 297catch (sycl::exception const & exc ) { 298 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 299 <<", line:" <<__LINE__ << std::endl ; 300 std::exit (1 ); 301} 302 303DeviceInfo device_info (int ordinal ) { 304int count = 0 ; 305check (DPCT_CHECK_ERROR (count = dpct::device_count ()),"cudaGetDeviceCount" ); 306if (count == 0 ) { 307#if defined(STRATA_USE_HIP ) 308throw CudaError (std::string ("no HIP device is present; this engine was compiled for " )+ STRATA_HIP_ARCHS ,-1 ); 309#else 310throw CudaError ("no CUDA device is present; Strata needs an NVIDIA GPU (RTX 20 series or newer)" ,-1 ); 311#endif 312 } 313if (ordinal < 0 || ordinal >=count ) { 314throw CudaError ("device ordinal " + std::to_string (ordinal )+ " is out of range (have " + 315 std::to_string (count )+ ")" , 316-1 ); 317 } 318DeviceInfo d ; 319d .ordinal = ordinal ; 320/* 321DPCT1093: The "ordinal" device may be not the one intended for use. 322Adjust the selected device if needed. 323*/ 324check (DPCT_CHECK_ERROR (dpct::select_device (ordinal )),"cudaSetDevice" ); 325 326 dpct::device_info p {}; 327check (DPCT_CHECK_ERROR (dpct::get_device (ordinal ).get_device_info (p )), 328"cudaGetDeviceProperties" ); 329d .name = p .get_name (); 330/* 331DPCT1005: The SYCL device version is different from CUDA Compute 332Compatibility. You may need to rewrite this code. 333*/ 334d .cc_major = p .get_major_version (); 335/* 336DPCT1005: The SYCL device version is different from CUDA Compute 337Compatibility. You may need to rewrite this code. 338*/ 339d .cc_minor = p .get_minor_version (); 340d .multi_processor_count = p .get_max_compute_units (); 341 342size_t free_b = 0 ,total_b = 0 ; 343/* 344DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions for 345device information which may not be supported by all compilers or runtimes. 346You may need to adjust the code. 347*/ 348check (DPCT_CHECK_ERROR ( 349 dpct::get_current_device ().get_memory_info (free_b ,total_b )), 350"cudaMemGetInfo" ); 351d .free_bytes = free_b ; 352d .total_bytes = total_b ; 353 354/* 355DPCT1043: The version-related API is different in SYCL. An initial code 356was generated, but you need to adjust it. 357*/ 358check (DPCT_CHECK_ERROR (d .driver_version = dpct::get_major_version ( 359 dpct::get_current_device ())), 360"cudaDriverGetVersion" ); 361/* 362DPCT1043: The version-related API is different in SYCL. An initial code 363was generated, but you need to adjust it. 364*/ 365check (DPCT_CHECK_ERROR (d .runtime_version = dpct::get_major_version ( 366 dpct::get_current_device ())), 367"cudaRuntimeGetVersion" ); 368 369// The engine supports compute capability 7.5 and newer (Turing: the QSA scorer's tf32 mma has a portable 370// fp32-FMA fallback below sm_80, the tensor-core prompt kernels refuse and fall back). Compiling for a 371// supported arch is enforced by CMake; RUNNING on an older card is caught here, because a binary can be carried 372// to a machine with an older card and would otherwise silently take whatever path the driver chose. The HIP 373// backend checks the card against the architectures the binary was compiled for (and wave32). 374#if defined(STRATA_HIP_GFX906 ) 375// AMD gfx906 (the STRATA_HIP_GFX906 compat build, not STRATA_USE_HIP): the build targets one gfx arch 376// (CMAKE_HIP_ARCHITECTURES, wave64); a card of another arch fails at the first kernel launch with 377// hipErrorInvalidDeviceFunction. gcnArchName says which it is. 378 { 379 std::string arch (p .gcnArchName ); 380if (const size_t colon = arch .find (':' );colon != std::string::npos )arch .resize (colon ); 381d .arch = arch ; 382 } 383if (p .gcnArchName [0 ]!= 0 )d .name += std::string (" (" )+ p .gcnArchName + ")" ; 384#elif defined(STRATA_USE_HIP ) 385d .arch = base_arch (p .gcnArchName ); 386if (const std::string why = arch_problem (p ,ordinal ); !why .empty ())throw CudaError (why ,-1 ); 387#else 388// #236: the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON: Pascal sm_60, Volta sm_70) runs on the cards it 389// was built for - refusing them below 7.5 there made the flag useless; the release engine keeps 7.5 390#if defined(STRATA_EXPERIMENTAL_SM60 ) 391constexpr int kMinCc = 60 ; 392const char * const kNeed = "6.0 or newer (this is the experimental Pascal / Volta build)" ; 393#else 394constexpr int kMinCc = 75 ; 395const char * const kNeed = "7.5 or newer (RTX 20 / 30 / 40 / 50 series)" ; 396#endif 397if (d .cc_major * 10 + d .cc_minor < kMinCc ) { 398throw CudaError ("device " + d .name + " reports compute capability " + std::to_string (d .cc_major )+ 399"." + std::to_string (d .cc_minor )+ "; Strata needs compute capability " + kNeed , 400-1 ); 401 } 402#endif 403return d ; 404} 405 406DeviceArena ::DeviceArena (uint64_t bytes ,int ordinal ,bool poison ) 407 :capacity_ (bytes ),ordinal_ (ordinal ),poison_ (poison ) { 408if (bytes == 0 )throw CudaError ("DeviceArena of 0 bytes" ,-1 ); 409/* 410DPCT1093: The "ordinal" device may be not the one intended for use. 411Adjust the selected device if needed. 412*/ 413check (DPCT_CHECK_ERROR (dpct::select_device (ordinal )),"cudaSetDevice" ); 414// One allocation for the whole region. cudaMalloc of a large block is the thing that can fail late, so it 415// happens once, here, before anything depends on it. 416check (DPCT_CHECK_ERROR (base_ = (void * )strata::malloc_device_guarded ( 417 (size_t )bytes , dpct::get_in_order_queue ())), 418"cudaMalloc" ); 419if (poison_ ) { 420const int threads = 256 ; 421const uint64_t n = bytes /sizeof (float ); 422const uint64_t blocks = (n + threads - 1 ) /threads ; 423// gridDim.x is 32-bit, so a large region needs a loop. 12 GB of floats is 3e9 elements = 1.2e7 424// blocks, which fits, but the loop keeps it correct for any size rather than for today's sizes. 425const uint64_t max_blocks = 0x7FFFFFFFull ; 426for (uint64_t b = 0 ;b < blocks ;b += max_blocks ) { 427const uint64_t chunk = (blocks - b < max_blocks ) ? (blocks - b ) :max_blocks ; 428 { 429auto exp_props = sycl::ext::oneapi::experimental::properties { 430 sycl::ext::oneapi::experimental::use_root_sync }; 431 432 strata::kprof::kp (& dpct::get_in_order_queue (),__FILE__ ,__func__ ,__LINE__ )-> submit ([& ](sycl::handler & cgh ) { 433auto float_base__b_threads_ct0 = 434 (float * )base_ + b * threads ; 435auto n_b_threads_ct1 = n - b * threads ; 436 437cgh .parallel_for < 438dpct_kernel_name < class poison_kernel_58fc0a >> ( 439 sycl::nd_range < 3 > (sycl::range (1 ,1 , (unsigned )chunk )* 440 sycl::range (1 ,1 ,threads ), 441 sycl::range (1 ,1 ,threads )), 442exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 443poison_kernel (float_base__b_threads_ct0 , 444n_b_threads_ct1 ); 445 }); 446 }); 447 } 448/* 449DPCT1010: SYCL uses exceptions to report errors and does not 450use the error codes. The cudaGetLastError function call was replaced 451with 0. You need to rewrite this code. 452*/ 453check (0 ,"poison_kernel" ); 454 } 455check (DPCT_CHECK_ERROR ( 456 dpct::get_current_device ().queues_wait_and_throw ()), 457"poison sync" ); 458 } 459} 460 461DeviceArena ::~DeviceArena () { 462if (base_ ) sycl::free ( 463base_ , 464 dpct::get_in_order_queue ());// best effort: a destructor must not throw 465} 466 467void * DeviceArena ::alloc (uint64_t bytes ,uint64_t align ) { 468if (bytes == 0 )return nullptr ; 469if (align == 0 || (align & (align - 1 ))!= 0 ) { 470throw CudaError ("DeviceArena::alloc alignment must be a power of two" ,-1 ); 471 } 472const uint64_t start = (used_ + align - 1 )& ~(align - 1 ); 473if (start + bytes > capacity_ ) { 474char msg [256 ]; 475 std::snprintf (msg ,sizeof (msg ), 476"DeviceArena out of memory: asked for %llu B at offset %llu (align %llu) in a %llu B " 477"region - the plan from P1.S9 did not close" , 478 (unsigned long long )bytes , (unsigned long long )start , (unsigned long long )align , 479 (unsigned long long )capacity_ ); 480throw CudaError (msg ,-1 ); 481 } 482used_ = start + bytes ; 483return (char * )base_ + start ; 484} 485 486}// namespace strata::core