okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7c5e84612
main
1// src/core/device.cu - P2.S1: the CUDA side of the runtime core. 2#include "strata/core/device.hpp" 3 4#include <cuda_runtime.h> 5 6#include <cstdio> 7#include <cstring> 8 9namespace strata::core { 10 11namespace { 12 13void check(cudaError_t e, const char* what) { 14 if (e != cudaSuccess) { 15 throw CudaError(std::string(what) + ": " + cudaGetErrorString(e), (int) e); 16 } 17} 18 19// A NaN pattern, not zero. Zeros read from uninitialised memory are indistinguishable from real zeros in a 20// dequantized weight or a masked attention score, which is exactly the kind of wrong-but-plausible value the 21// Phase 1 harnesses kept catching. 22#if !defined(STRATA_GPU_METAL) 23__global__ void poison_kernel(float* p, uint64_t n_floats) { 24 const uint64_t i = (uint64_t) blockIdx.x * blockDim.x + threadIdx.x; 25 if (i < n_floats) p[i] = __int_as_float(0x7fc00000); 26} 27#endif 28 29#if defined(STRATA_USE_HIP) 30#if !defined(STRATA_HIP_ARCHS) 31#error "STRATA_HIP_ARCHS (the compiled HIP architectures) is set by cmake/hip_backend.cmake" 32#endif 33// "gfx1201:sramecc-:xnack-" -> "gfx1201" 34std::string base_arch(const char* gcn_arch_name) { 35 std::string arch(gcn_arch_name); 36 const size_t colon = arch.find(':'); 37 if (colon != std::string::npos) arch.resize(colon); 38 return arch; 39} 40 41bool compiled_for(const std::string& arch) { 42 const std::string list = STRATA_HIP_ARCHS; 43 size_t a = 0; 44 while (a <= list.size()) { 45 size_t b = list.find(',', a); 46 if (b == std::string::npos) b = list.size(); 47 if (!arch.empty() && list.compare(a, b - a, arch) == 0 && b - a == arch.size()) return true; 48 a = b + 1; 49 } 50 return false; 51} 52 53std::string arch_problem(const cudaDeviceProp& p, int ordinal) { 54 const std::string arch = base_arch(p.gcnArchName); 55 const std::string card = "GPU " + std::to_string(ordinal) + " (" + p.name + ", " + arch + ")"; 56 if (!compiled_for(arch)) { 57 return card + " is not an architecture this Strata engine was compiled for (" + STRATA_HIP_ARCHS + 58 "); compile it for this card (./setup.sh --backend hip, or -DCMAKE_HIP_ARCHITECTURES=" + arch + 59 ", docs/AMD_HIP.md) or choose another GPU with HIP_VISIBLE_DEVICES"; 60 } 61 if (p.warpSize != 32) { 62 return card + " runs wave" + std::to_string(p.warpSize) + "; Strata's HIP kernels need wave32"; 63 } 64 return ""; 65} 66#endif 67 68} // namespace 69 70const char* compiled_gpu_archs() { 71#if defined(STRATA_USE_HIP) 72 return STRATA_HIP_ARCHS; 73#else 74 return ""; 75#endif 76} 77 78int device_count() { 79 int count = 0; 80 if (cudaGetDeviceCount(&count) != cudaSuccess) { // HIP without a usable device reports an error, not 0 81 cudaGetLastError(); 82 return 0; 83 } 84 return count < 0 ? 0 : count; 85} 86 87// STRATA_PRIMARY_DEVICE: see the declaration in device.hpp. 0 = upstream's behavior (the runtime's first 88// visible device). Set once, before any context exists, by generate.cpp's STRATA_PRIMARY_DEVICE handling. 89static int g_primary_device = 0; 90 91void set_primary_device(int ordinal) { g_primary_device = ordinal; } 92int primary_device() { return g_primary_device; } 93 94bool device_summary(int ordinal, std::string& name, std::string& detail) { 95 cudaDeviceProp p{}; 96 if (ordinal < 0 || ordinal >= device_count() || cudaGetDeviceProperties(&p, ordinal) != cudaSuccess) { 97 cudaGetLastError(); 98 return false; 99 } 100 char buf[160]; 101#if defined(STRATA_USE_HIP) 102 std::snprintf(buf, sizeof(buf), "arch %s, %.1f GiB, wave%d", base_arch(p.gcnArchName).c_str(), 103 (double) p.totalGlobalMem / (1024.0 * 1024 * 1024), p.warpSize); 104#else 105 std::snprintf(buf, sizeof(buf), "compute capability %d.%d, %.1f GiB", p.major, p.minor, 106 (double) p.totalGlobalMem / (1024.0 * 1024 * 1024)); 107#endif 108 name = p.name; 109 detail = buf; 110 return true; 111} 112 113} // namespace strata::core 114 115#if defined(STRATA_USE_HIP) && defined(_WIN32) 116// The free VRAM figure on Windows HIP (include/strata/hip_compat/cuda_runtime.h maps cudaMemGetInfo here). 117// 118// hipMemGetInfo (ROCclr's PAL backend, Device::globalFreeMemory) is the card's size minus this process's own 119// allocations: it asks Windows for this process's usage only, never for what the desktop and other programs hold. 120// So on a card that also drives the desktop the engine counted ~930 MiB that was not there, the expert cache filled 121// the card, and WDDM moved memory out to system RAM: decode at 30 tok/s instead of 41 (RX 6800, HIP SDK 7.2). 122// Windows itself gives each process a video memory budget (DXGI QueryVideoMemoryInfo) that does account for the 123// others. Measured on that card: the budget sits 0.8 GiB below the card's size while this process is small and 124// 1.8 GiB below once it holds 11 GiB; allocations past it still succeed, and are what Windows moves out. The 125// free figure here is hipMemGetInfo's lowered by what the budget withholds (the card's size minus the budget). 126// Subtracting from HIP's own figure, rather than taking the budget minus DXGI's usage, keeps memory the HIP runtime 127// has freed and holds in its cache counted as free, as hipMemGetInfo counts it. dxgi.dll is loaded at run time, so 128// nothing new is linked; when it or the card's adapter cannot be found, hipMemGetInfo's figure stands. 129#ifndef WIN32_LEAN_AND_MEAN 130#define WIN32_LEAN_AND_MEAN 131#endif 132#ifndef NOMINMAX 133#define NOMINMAX 134#endif 135#include <windows.h> 136#include <dxgi1_4.h> 137#include <atomic> 138#include <cstdlib> 139#include <mutex> 140 141namespace strata::hip_compat { 142namespace { 143IDXGIAdapter3* budget_adapter(int device) { 144 constexpr int kMaxDevices = 16; 145 static std::mutex mu; 146 static IDXGIAdapter3* adapters[kMaxDevices] = {}; 147 static bool tried[kMaxDevices] = {}; 148 if (device < 0 || device >= kMaxDevices) return nullptr; 149 std::lock_guard<std::mutex> lock(mu); 150 if (tried[device]) return adapters[device]; 151 tried[device] = true; 152 hipDeviceProp_t p{}; 153 if (hipGetDeviceProperties(&p, device) != hipSuccess) { 154 (void) hipGetLastError(); 155 return nullptr; 156 } 157 LUID luid{}; 158 std::memcpy(&luid, p.luid, sizeof luid); 159 using CreateFactory = HRESULT(WINAPI*)(REFIID, void**); 160 static HMODULE dxgi = LoadLibraryW(L"dxgi.dll"); // kept for the process' lifetime, like the adapters 161 const auto create = dxgi ? (CreateFactory) (void*) GetProcAddress(dxgi, "CreateDXGIFactory1") : nullptr; 162 IDXGIFactory4* factory = nullptr; 163 if (create == nullptr || FAILED(create(__uuidof(IDXGIFactory4), (void**) &factory))) return nullptr; 164 IDXGIAdapter3* adapter = nullptr; 165 if (FAILED(factory->EnumAdapterByLuid(luid, __uuidof(IDXGIAdapter3), (void**) &adapter))) adapter = nullptr; 166 factory->Release(); 167 adapters[device] = adapter; 168 return adapter; 169} 170} // namespace 171 172// #873 / #654: on some Windows setups the first hipMemGetInfo of a process fails with hipErrorInvalidValue because the ROCm 173// runtime has not finished initialising against the Adrenalin WDDM driver, and the first kernel launch after that 174// crashes (0xC0000005 in amdhip64_7.dll). A hipFree(0) before the first query initialises the context, and one 175// failed query gets one retry after 250 ms. Both happen once per process, before the DXGI budget below; any other 176// error, and a failure of the retry, are returned as they are (a real failure is never retried). 177static hipError_t first_mem_get_info(size_t* free_bytes, size_t* total_bytes) { 178 static std::atomic<bool> warmed{false}, retried{false}; 179 if (!warmed.exchange(true)) (void) hipFree(nullptr); 180 hipError_t e = hipMemGetInfo(free_bytes, total_bytes); 181 if (e == hipErrorInvalidValue && !retried.exchange(true)) { 182 (void) hipGetLastError(); 183 std::fprintf(stderr, "strata: hipMemGetInfo failed (%s); retrying once after 250 ms\n", hipGetErrorString(e)); 184 Sleep(250); 185 e = hipMemGetInfo(free_bytes, total_bytes); 186 std::fprintf(stderr, "strata: hipMemGetInfo retry: %s\n", e == hipSuccess ? "ok" : hipGetErrorString(e)); 187 } 188 return e; 189} 190 191hipError_t mem_get_info(size_t* free_bytes, size_t* total_bytes) { 192 if (free_bytes == nullptr || total_bytes == nullptr) return hipMemGetInfo(free_bytes, total_bytes); 193 const hipError_t e = first_mem_get_info(free_bytes, total_bytes); 194 static const bool off = [] { 195 const char* v = std::getenv("STRATA_WDDM_BUDGET"); 196 return v != nullptr && std::atoi(v) == 0; 197 }(); 198 if (e != hipSuccess || off || free_bytes == nullptr || total_bytes == nullptr) return e; 199 int device = 0; 200 if (hipGetDevice(&device) != hipSuccess) { 201 (void) hipGetLastError(); 202 return e; 203 } 204 IDXGIAdapter3* adapter = budget_adapter(device); 205 DXGI_QUERY_VIDEO_MEMORY_INFO local{}; 206 if (adapter == nullptr || FAILED(adapter->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &local)) || 207 local.Budget == 0 || local.Budget >= *total_bytes) 208 return e; 209 const size_t withheld = *total_bytes - (size_t) local.Budget; // the desktop's and other programs' share 210 static std::atomic<bool> said{false}; 211 if (!said.exchange(true)) { 212 std::fprintf(stderr, "strata: Windows budgets %llu of this card's %llu MiB for this process; free VRAM is " 213 "counted within that (STRATA_WDDM_BUDGET=0: off)\n", 214 (unsigned long long) (local.Budget >> 20), (unsigned long long) (*total_bytes >> 20)); 215 } 216 *free_bytes = *free_bytes > withheld ? *free_bytes - withheld : 0; 217 return e; 218} 219} // namespace strata::hip_compat 220#endif 221 222namespace strata::core { 223 224std::string gpu_arch_problem(int ordinal) { 225#if defined(STRATA_USE_HIP) 226 int count = 0; 227 if (cudaGetDeviceCount(&count) != cudaSuccess || ordinal < 0 || ordinal >= count) { 228 cudaGetLastError(); 229 return ""; 230 } 231 cudaDeviceProp p{}; 232 if (cudaGetDeviceProperties(&p, ordinal) != cudaSuccess) { 233 cudaGetLastError(); 234 return ""; 235 } 236 return arch_problem(p, ordinal); 237#else 238 (void) ordinal; 239 return ""; 240#endif 241} 242 243std::string device_code_error() { 244#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL) 245 return ""; // gpu_arch_problem() checks the HIP architectures against STRATA_HIP_ARCHS, before this point 246#else 247 // every .cu of the engine is compiled for the same CMAKE_CUDA_ARCHITECTURES, so this kernel stands for all 248 cudaFuncAttributes a{}; 249 const cudaError_t e = cudaFuncGetAttributes(&a, poison_kernel); 250 if (e == cudaSuccess) return {}; 251 cudaGetLastError(); 252 return cudaGetErrorString(e); 253#endif 254} 255 256DeviceInfo device_info(int ordinal) { 257 int count = 0; 258 check(cudaGetDeviceCount(&count), "cudaGetDeviceCount"); 259 if (count == 0) { 260#if defined(STRATA_USE_HIP) 261 throw CudaError(std::string("no HIP device is present; this engine was compiled for ") + STRATA_HIP_ARCHS, -1); 262#else 263 throw CudaError("no CUDA device is present; Strata needs an NVIDIA GPU (RTX 20 series or newer)", -1); 264#endif 265 } 266 if (ordinal < 0 || ordinal >= count) { 267 throw CudaError("device ordinal " + std::to_string(ordinal) + " is out of range (have " + 268 std::to_string(count) + ")", 269 -1); 270 } 271 DeviceInfo d; 272 d.ordinal = ordinal; 273 check(cudaSetDevice(ordinal), "cudaSetDevice"); 274 275 cudaDeviceProp p{}; 276 check(cudaGetDeviceProperties(&p, ordinal), "cudaGetDeviceProperties"); 277 d.name = p.name; 278 d.cc_major = p.major; 279 d.cc_minor = p.minor; 280 d.multi_processor_count = p.multiProcessorCount; 281 282 size_t free_b = 0, total_b = 0; 283 check(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo"); 284 d.free_bytes = free_b; 285 d.total_bytes = total_b; 286 287 check(cudaDriverGetVersion(&d.driver_version), "cudaDriverGetVersion"); 288 check(cudaRuntimeGetVersion(&d.runtime_version), "cudaRuntimeGetVersion"); 289 290 // The engine supports compute capability 7.5 and newer (Turing: the QSA scorer's tf32 mma has a portable 291 // fp32-FMA fallback below sm_80, the tensor-core prompt kernels refuse and fall back). Compiling for a 292 // supported arch is enforced by CMake; RUNNING on an older card is caught here, because a binary can be carried 293 // to a machine with an older card and would otherwise silently take whatever path the driver chose. The HIP 294 // backend checks the card against the architectures the binary was compiled for (and wave32). 295#if defined(STRATA_HIP_GFX906) 296 // AMD gfx906 (the STRATA_HIP_GFX906 compat build, not STRATA_USE_HIP): the build targets one gfx arch 297 // (CMAKE_HIP_ARCHITECTURES, wave64); a card of another arch fails at the first kernel launch with 298 // hipErrorInvalidDeviceFunction. gcnArchName says which it is. 299 { 300 std::string arch(p.gcnArchName); 301 if (const size_t colon = arch.find(':'); colon != std::string::npos) arch.resize(colon); 302 d.arch = arch; 303 } 304 if (p.gcnArchName[0] != 0) d.name += std::string(" (") + p.gcnArchName + ")"; 305#elif defined(STRATA_USE_HIP) 306 d.arch = base_arch(p.gcnArchName); 307 if (const std::string why = arch_problem(p, ordinal); !why.empty()) throw CudaError(why, -1); 308#else 309 // #236: the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON: Pascal sm_60, Volta sm_70) runs on the cards it 310 // was built for - refusing them below 7.5 there made the flag useless; the release engine keeps 7.5 311#if defined(STRATA_EXPERIMENTAL_SM60) 312 constexpr int kMinCc = 60; 313 const char* const kNeed = "6.0 or newer (this is the experimental Pascal / Volta build)"; 314#else 315 constexpr int kMinCc = 75; 316 const char* const kNeed = "7.5 or newer (RTX 20 / 30 / 40 / 50 series)"; 317#endif 318 if (d.cc_major * 10 + d.cc_minor < kMinCc) { 319 throw CudaError("device " + d.name + " reports compute capability " + std::to_string(d.cc_major) + 320 "." + std::to_string(d.cc_minor) + "; Strata needs compute capability " + kNeed, 321 -1); 322 } 323#endif 324 return d; 325} 326 327DeviceArena::DeviceArena(uint64_t bytes, int ordinal, bool poison) 328 : capacity_(bytes), ordinal_(ordinal), poison_(poison) { 329 if (bytes == 0) throw CudaError("DeviceArena of 0 bytes", -1); 330 check(cudaSetDevice(ordinal), "cudaSetDevice"); 331 // One allocation for the whole region. cudaMalloc of a large block is the thing that can fail late, so it 332 // happens once, here, before anything depends on it. 333 check(cudaMalloc(&base_, (size_t) bytes), "cudaMalloc"); 334#if defined(STRATA_GPU_METAL) // unified memory: the CPU writes the pattern through the allocation's CPU view 335 if (poison_) { 336 uint32_t* h = (uint32_t*) strata::gpu::host_view(base_); 337 for (uint64_t i = 0; i < bytes / sizeof(float); ++i) h[i] = 0x7fc00000u; 338 } 339#else 340 if (poison_) { 341 const int threads = 256; 342 const uint64_t n = bytes / sizeof(float); 343 const uint64_t blocks = (n + threads - 1) / threads; 344 // gridDim.x is 32-bit, so a large region needs a loop. 12 GB of floats is 3e9 elements = 1.2e7 345 // blocks, which fits, but the loop keeps it correct for any size rather than for today's sizes. 346 const uint64_t max_blocks = 0x7FFFFFFFull; 347 for (uint64_t b = 0; b < blocks; b += max_blocks) { 348 const uint64_t chunk = (blocks - b < max_blocks) ? (blocks - b) : max_blocks; 349 poison_kernel<<<(unsigned) chunk, threads>>>((float*) base_ + b * threads, n - b * threads); 350 check(cudaGetLastError(), "poison_kernel"); 351 } 352 check(cudaDeviceSynchronize(), "poison sync"); 353 } 354#endif 355} 356 357DeviceArena::~DeviceArena() { 358 if (base_) cudaFree(base_); // best effort: a destructor must not throw 359} 360 361void* DeviceArena::alloc(uint64_t bytes, uint64_t align) { 362 if (bytes == 0) return nullptr; 363 if (align == 0 || (align & (align - 1)) != 0) { 364 throw CudaError("DeviceArena::alloc alignment must be a power of two", -1); 365 } 366 const uint64_t start = (used_ + align - 1) & ~(align - 1); 367 if (start + bytes > capacity_) { 368 char msg[256]; 369 std::snprintf(msg, sizeof(msg), 370 "DeviceArena out of memory: asked for %llu B at offset %llu (align %llu) in a %llu B " 371 "region - the plan from P1.S9 did not close", 372 (unsigned long long) bytes, (unsigned long long) start, (unsigned long long) align, 373 (unsigned long long) capacity_); 374 throw CudaError(msg, -1); 375 } 376 used_ = start + bytes; 377 return (char*) base_ + start; 378} 379 380} // namespace strata::core