okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-037-arc (5eaee81a4)86bed1c92

main
20.1 KiB486 linesraw
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    /*
18    DPCT1000: Error handling if-stmt was detected but could not be
19    rewritten.
20    */
21    if (e != 0) {
22        /*
23        DPCT1009: SYCL reports errors using exceptions and does not use
24        error codes. Please replace the "get_error_string_dummy(...)" with a
25        real error-handling function.
26        */
27        /*
28        DPCT1001: The statement could not be removed.
29        */
30        throw 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) {
39    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
40    const uint64_t i =
41        (uint64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
42        item_ct1.get_local_id(2);
43    if (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);
53    const size_t colon = arch.find(':');
54    if (colon != std::string::npos) arch.resize(colon);
55    return arch;
56}
57
58bool compiled_for(const std::string& arch) {
59    const std::string list = STRATA_HIP_ARCHS;
60    size_t a = 0;
61    while (a <= list.size()) {
62        size_t b = list.find(',', a);
63        if (b == std::string::npos) b = list.size();
64        if (!arch.empty() && list.compare(a, b - a, arch) == 0 && b - a == arch.size()) return true;
65        a = b + 1;
66    }
67    return false;
68}
69
70std::string arch_problem(const cudaDeviceProp& p, int ordinal) {
71    const std::string arch = base_arch(p.gcnArchName);
72    const std::string card = "GPU " + std::to_string(ordinal) + " (" + p.name + ", " + arch + ")";
73    if (!compiled_for(arch)) {
74        return 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    }
78    if (p.warpSize != 32) {
79        return card + " runs wave" + std::to_string(p.warpSize) + "; Strata's HIP kernels need wave32";
80    }
81    return "";
82}
83#endif
84
85}  // namespace
86
87const char* compiled_gpu_archs() {
88#if defined(STRATA_USE_HIP)
89    return STRATA_HIP_ARCHS;
90#else
91    return "";
92#endif
93}
94
95int device_count() try {
96    int count = 0;
97    if (DPCT_CHECK_ERROR(count = dpct::device_count()) !=
98        0) { // HIP without a usable device reports an error, not 0
99        /*
100        DPCT1026: The call to cudaGetLastError was removed because this
101        functionality is redundant in SYCL.
102        */
103        return 0;
104    }
105    return 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{};
115    if (ordinal < 0 || ordinal >= device_count() ||
116        DPCT_CHECK_ERROR(dpct::get_device(ordinal).get_device_info(p)) != 0) {
117        /*
118        DPCT1026: The call to cudaGetLastError was removed because this
119        functionality is redundant in SYCL.
120        */
121        return false;
122    }
123    char 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    /*
129    DPCT1005: The SYCL device version is different from CUDA Compute
130    Compatibility. You may need to rewrite this code.
131    */
132    std::snprintf(buf, sizeof(buf), "compute capability %d.%d, %.1f GiB",
133                  p.get_major_version(), p.get_minor_version(),
134                  (double)p.get_global_mem_size() / (1024.0 * 1024 * 1024));
135#endif
136    name = p.get_name();
137    detail = buf;
138    return 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) {
177    constexpr int kMaxDevices = 16;
178    static std::mutex mu;
179    static IDXGIAdapter3* adapters[kMaxDevices] = {};
180    static bool tried[kMaxDevices] = {};
181    if (device < 0 || device >= kMaxDevices) return nullptr;
182    std::lock_guard<std::mutex> lock(mu);
183    if (tried[device]) return adapters[device];
184    tried[device] = true;
185    hipDeviceProp_t p{};
186    if (hipGetDeviceProperties(&p, device) != hipSuccess) {
187        (void) hipGetLastError();
188        return nullptr;
189    }
190    LUID luid{};
191    std::memcpy(&luid, p.luid, sizeof luid);
192    using CreateFactory = HRESULT(WINAPI*)(REFIID, void**);
193    static HMODULE dxgi = LoadLibraryW(L"dxgi.dll");   // kept for the process' lifetime, like the adapters
194    const auto create = dxgi ? (CreateFactory) (void*) GetProcAddress(dxgi, "CreateDXGIFactory1") : nullptr;
195    IDXGIFactory4* factory = nullptr;
196    if (create == nullptr || FAILED(create(__uuidof(IDXGIFactory4), (void**) &factory))) return nullptr;
197    IDXGIAdapter3* adapter = nullptr;
198    if (FAILED(factory->EnumAdapterByLuid(luid, __uuidof(IDXGIAdapter3), (void**) &adapter))) adapter = nullptr;
199    factory->Release();
200    adapters[device] = adapter;
201    return 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) {
211    static std::atomic<bool> warmed{false}, retried{false};
212    if (!warmed.exchange(true)) (void) hipFree(nullptr);
213    hipError_t e = hipMemGetInfo(free_bytes, total_bytes);
214    if (e == hipErrorInvalidValue && !retried.exchange(true)) {
215        (void) hipGetLastError();
216        std::fprintf(stderr, "strata: hipMemGetInfo failed (%s); retrying once after 250 ms\n", hipGetErrorString(e));
217        Sleep(250);
218        e = hipMemGetInfo(free_bytes, total_bytes);
219        std::fprintf(stderr, "strata: hipMemGetInfo retry: %s\n", e == hipSuccess ? "ok" : hipGetErrorString(e));
220    }
221    return e;
222}
223
224hipError_t mem_get_info(size_t* free_bytes, size_t* total_bytes) {
225    if (free_bytes == nullptr || total_bytes == nullptr) return hipMemGetInfo(free_bytes, total_bytes);
226    const hipError_t e = first_mem_get_info(free_bytes, total_bytes);
227    static const bool off = [] {
228        const char* v = std::getenv("STRATA_WDDM_BUDGET");
229        return v != nullptr && std::atoi(v) == 0;
230    }();
231    if (e != hipSuccess || off || free_bytes == nullptr || total_bytes == nullptr) return e;
232    int device = 0;
233    if (hipGetDevice(&device) != hipSuccess) {
234        (void) hipGetLastError();
235        return e;
236    }
237    IDXGIAdapter3* adapter = budget_adapter(device);
238    DXGI_QUERY_VIDEO_MEMORY_INFO local{};
239    if (adapter == nullptr || FAILED(adapter->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &local)) ||
240        local.Budget == 0 || local.Budget >= *total_bytes)
241        return e;
242    const size_t withheld = *total_bytes - (size_t) local.Budget;   // the desktop's and other programs' share
243    static std::atomic<bool> said{false};
244    if (!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;
250    return 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)
259    int count = 0;
260    if (cudaGetDeviceCount(&count) != cudaSuccess || ordinal < 0 || ordinal >= count) {
261        cudaGetLastError();
262        return "";
263    }
264    cudaDeviceProp p{};
265    if (cudaGetDeviceProperties(&p, ordinal) != cudaSuccess) {
266        cudaGetLastError();
267        return "";
268    }
269    return arch_problem(p, ordinal);
270#else
271    (void) ordinal;
272    return "";
273#endif
274}
275
276std::string device_code_error() try {
277#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
278    return "";   // 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{};
282    const dpct::err0 e = DPCT_CHECK_ERROR(
283        dpct::get_kernel_function_info(&a, (const void *)poison_kernel));
284    if (e == 0) return {};
285    /*
286    DPCT1026: The call to cudaGetLastError was removed because this
287    functionality is redundant in SYCL.
288    */
289    /*
290    DPCT1009: SYCL reports errors using exceptions and does not use error
291    codes. Please replace the "get_error_string_dummy(...)" with a real
292    error-handling function.
293    */
294    return 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) {
304    int count = 0;
305    check(DPCT_CHECK_ERROR(count = dpct::device_count()), "cudaGetDeviceCount");
306    if (count == 0) {
307#if defined(STRATA_USE_HIP)
308        throw CudaError(std::string("no HIP device is present; this engine was compiled for ") + STRATA_HIP_ARCHS, -1);
309#else
310        throw CudaError("no CUDA device is present; Strata needs an NVIDIA GPU (RTX 20 series or newer)", -1);
311#endif
312    }
313    if (ordinal < 0 || ordinal >= count) {
314        throw CudaError("device ordinal " + std::to_string(ordinal) + " is out of range (have " +
315                            std::to_string(count) + ")",
316                        -1);
317    }
318    DeviceInfo d;
319    d.ordinal = ordinal;
320    /*
321    DPCT1093: The "ordinal" device may be not the one intended for use.
322    Adjust the selected device if needed.
323    */
324    check(DPCT_CHECK_ERROR(dpct::select_device(ordinal)), "cudaSetDevice");
325
326    dpct::device_info p{};
327    check(DPCT_CHECK_ERROR(dpct::get_device(ordinal).get_device_info(p)),
328          "cudaGetDeviceProperties");
329    d.name = p.get_name();
330    /*
331    DPCT1005: The SYCL device version is different from CUDA Compute
332    Compatibility. You may need to rewrite this code.
333    */
334    d.cc_major = p.get_major_version();
335    /*
336    DPCT1005: The SYCL device version is different from CUDA Compute
337    Compatibility. You may need to rewrite this code.
338    */
339    d.cc_minor = p.get_minor_version();
340    d.multi_processor_count = p.get_max_compute_units();
341
342    size_t free_b = 0, total_b = 0;
343    /*
344    DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions for
345    device information which may not be supported by all compilers or runtimes.
346    You may need to adjust the code.
347    */
348    check(DPCT_CHECK_ERROR(
349              dpct::get_current_device().get_memory_info(free_b, total_b)),
350          "cudaMemGetInfo");
351    d.free_bytes = free_b;
352    d.total_bytes = total_b;
353
354    /*
355    DPCT1043: The version-related API is different in SYCL. An initial code
356    was generated, but you need to adjust it.
357    */
358    check(DPCT_CHECK_ERROR(d.driver_version = dpct::get_major_version(
359                               dpct::get_current_device())),
360          "cudaDriverGetVersion");
361    /*
362    DPCT1043: The version-related API is different in SYCL. An initial code
363    was generated, but you need to adjust it.
364    */
365    check(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);
380        if (const size_t colon = arch.find(':'); colon != std::string::npos) arch.resize(colon);
381        d.arch = arch;
382    }
383    if (p.gcnArchName[0] != 0) d.name += std::string(" (") + p.gcnArchName + ")";
384#elif defined(STRATA_USE_HIP)
385    d.arch = base_arch(p.gcnArchName);
386    if (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)
391    constexpr int kMinCc = 60;
392    const char* const kNeed = "6.0 or newer (this is the experimental Pascal / Volta build)";
393#else
394    constexpr int kMinCc = 75;
395    const char* const kNeed = "7.5 or newer (RTX 20 / 30 / 40 / 50 series)";
396#endif
397    if (d.cc_major * 10 + d.cc_minor < kMinCc) {
398        throw 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
403    return d;
404}
405
406DeviceArena::DeviceArena(uint64_t bytes, int ordinal, bool poison)
407    : capacity_(bytes), ordinal_(ordinal), poison_(poison) {
408    if (bytes == 0) throw CudaError("DeviceArena of 0 bytes", -1);
409    /*
410    DPCT1093: The "ordinal" device may be not the one intended for use.
411    Adjust the selected device if needed.
412    */
413    check(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.
416    check(DPCT_CHECK_ERROR(base_ = (void *)strata::malloc_device_guarded(
417                               (size_t)bytes, dpct::get_in_order_queue())),
418          "cudaMalloc");
419    if (poison_) {
420        const int threads = 256;
421        const uint64_t n = bytes / sizeof(float);
422        const 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.
425        const uint64_t max_blocks = 0x7FFFFFFFull;
426        for (uint64_t b = 0; b < blocks; b += max_blocks) {
427            const uint64_t chunk = (blocks - b < max_blocks) ? (blocks - b) : max_blocks;
428            {
429                auto 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) {
433                    auto float_base__b_threads_ct0 =
434                        (float *)base_ + b * threads;
435                    auto n_b_threads_ct1 = n - b * threads;
436
437                    cgh.parallel_for<
438                        dpct_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)),
442                        exp_props, [=](sycl::nd_item<3> item_ct1) {
443                            poison_kernel(float_base__b_threads_ct0,
444                                          n_b_threads_ct1);
445                        });
446                });
447            }
448            /*
449            DPCT1010: SYCL uses exceptions to report errors and does not
450            use the error codes. The cudaGetLastError function call was replaced
451            with 0. You need to rewrite this code.
452            */
453            check(0, "poison_kernel");
454        }
455        check(DPCT_CHECK_ERROR(
456                  dpct::get_current_device().queues_wait_and_throw()),
457              "poison sync");
458    }
459}
460
461DeviceArena::~DeviceArena() {
462    if (base_) sycl::free(
463        base_,
464        dpct::get_in_order_queue()); // best effort: a destructor must not throw
465}
466
467void* DeviceArena::alloc(uint64_t bytes, uint64_t align) {
468    if (bytes == 0) return nullptr;
469    if (align == 0 || (align & (align - 1)) != 0) {
470        throw CudaError("DeviceArena::alloc alignment must be a power of two", -1);
471    }
472    const uint64_t start = (used_ + align - 1) & ~(align - 1);
473    if (start + bytes > capacity_) {
474        char 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_);
480        throw CudaError(msg, -1);
481    }
482    used_ = start + bytes;
483    return (char*) base_ + start;
484}
485
486}  // namespace strata::core