Mneme
Mneme a tool allowing recording the execution of a GPU (CUDA/HIP) kernel and replaying that kernel as an independent executable.
Loading...
Searching...
No Matches
DeviceTraits.hpp
Go to the documentation of this file.
1#pragma once
2#include <dlfcn.h>
3#include <map>
4#include <optional>
5#include <utility>
6#include <vector>
7
10
11#ifdef MNEME_ENABLE_HIP
12#include <hip/amd_detail/amd_hip_runtime.h>
13#include <hip/hip_runtime.h>
14#include <hsa/hsa.h>
15#include <hsa/hsa_ext_amd.h>
16
17#define hipErrCheck(CALL) \
18 { \
19 hipError_t err = CALL; \
20 if (err != hipSuccess) { \
21 printf("ERROR @ %s:%d -> %s\n", __FILE__, __LINE__, \
22 hipGetErrorString(err)); \
23 abort(); \
24 } \
25 }
26
27#define hiprtcErrCheck(CALL) \
28 { \
29 hiprtcResult err = CALL; \
30 if (err != HIPRTC_SUCCESS) { \
31 printf("ERROR @ %s:%d -> %s\n", __FILE__, __LINE__, \
32 hiprtcGetErrorString(err)); \
33 abort(); \
34 } \
35 }
36
37#elif defined(MNEME_ENABLE_CUDA)
38#include <cuda.h>
39#include <cuda_runtime.h>
40
41#define cudaErrCheck(CALL) \
42 { \
43 cudaError_t err = CALL; \
44 if (err != cudaSuccess) { \
45 printf("ERROR @ %s:%d -> %s\n", __FILE__, __LINE__, \
46 hipGetErrorString(err)); \
47 abort(); \
48 } \
49 }
50
51#define cuErrCheck(CALL) \
52 { \
53 CUresult err = CALL; \
54 if (err != CUDA_SUCCESS) { \
55 const char *name = nullptr, *desc = nullptr; \
56 cuGetErrorName(err, &name); \
57 cuGetErrorString(err, &desc); \
58 fprintf(stderr, "CUDA Driver Error [%s]: %s\n", name ? name : "Unknown", \
59 desc ? desc : "No description"); \
60 abort(); \
61 } \
62 }
63
64#endif
65
66namespace mneme {
68
70
72
73template <DeviceVendors Type> struct DeviceTraits;
74
75// A null handle would make dlsym resolve Mneme's own wrappers.
76inline void *loadRTLib(const char *Name) {
77 void *Lib = dlopen(Name, RTLD_NOW);
78 if (!Lib)
79 LOG_FATAL("Could not load {}: {}", Name, dlerror());
80 return Lib;
81}
82
83#if defined(MNEME_ENABLE_HIP)
84template <> struct DeviceTraits<DeviceVendors::HIP> {
85 using DeviceError_t = hipError_t;
86 using DeviceStream_t = hipStream_t;
87 using KernelFunction_t = hipFunction_t;
88 using MemoryAllocationHandle_t = hipMemGenericAllocationHandle_t;
89 using DeviceModule_t = hipModule_t;
90 using DevicePtr_t = hipDeviceptr_t;
91 using DeviceHandle_t = hipDevice_t;
92 using DeviceContext_t = hipCtx_t;
93 using DeviceFunction_t = hipFunction_t;
94 using DeviceEvent_t = hipEvent_t;
95 static constexpr auto DeviceSuccess = hipSuccess;
96 static constexpr auto DeviceOutOfMemory = hipErrorOutOfMemory;
97 // Unit that device address reservations should cover; none on HIP.
98 static constexpr uint64_t VABlockSize = 1;
99 // The runtime maps managed memory with a fresh anonymous mmap, which the
100 // record preload hooks to choose the address.
101 static constexpr bool PlacesManagedMemory = true;
102
103 static inline void *getRTLib() {
104 static void *Lib = loadRTLib("libamdhip64.so");
105 return Lib;
106 }
107 static constexpr const char *getLaunchKernelFnName() {
108 return "hipLaunchKernel";
109 }
110 static constexpr const char *getDeviceMallocFnName() { return "hipMalloc"; }
111 static constexpr const char *getPinnedMallocFnName() {
112 return "hipHostMalloc";
113 }
114 static constexpr const char *getManagedMallocFnName() {
115 return "hipMallocManaged";
116 }
117 static constexpr const char *getDeviceFreeFnName() { return "hipFree"; }
118 static constexpr const char *getAsyncFreeFnName() { return "hipFreeAsync"; }
119 static constexpr const char *getPinnedFreeFnName() { return "hipHostFree"; }
120
121 static const char *getDeviceGetIDFnName() { return "hipGetDevice"; }
122 static const char *getDeviceSetIDFnName() { return "hipSetDevice"; }
123
124 static constexpr bool hasFatBinEnd = false;
125
126 static inline std::optional<std::string>
127 DeviceErrorCheck(hipError_t ErrorCode) {
128 if (ErrorCode == hipSuccess)
129 return std::nullopt;
130 return std::string(hipGetErrorString(ErrorCode));
131 }
132
133 static hipError_t DeviceStreamSynchronize(hipStream_t Stream) {
134 return hipStreamSynchronize(Stream);
135 }
136
137 static hipError_t DeviceMemset(void *DevPtr, int Value, size_t Bytes) {
138 auto EC = hipMemset(DevPtr, Value, Bytes);
139 return EC;
140 }
141
142 static hipError_t DeviceMalloc(void **ptr, size_t size) {
143 return hipMalloc(ptr, size);
144 }
145
146 static hipError_t DeviceFree(void *ptr) { return hipFree(ptr); }
147
148 static hipError_t DeviceCopy(void *Dest, void *Src, size_t SizeBytes,
149 hipMemcpyKind Kind) {
150 return hipMemcpy(Dest, Src, SizeBytes, Kind);
151 }
152
153 static hipError_t DeviceCopyAsync(void *Dest, void *Src, size_t SizeBytes,
154 hipMemcpyKind Kind, hipStream_t Stream) {
155 return hipMemcpyAsync(Dest, Src, SizeBytes, Kind, Stream);
156 }
157
158 static hipError_t DeviceSynchronize() { return hipDeviceSynchronize(); }
159
160 // Whether Stream is capturing is meaningful only when the error is success.
161 static std::pair<hipError_t, bool>
162 deviceStreamIsCapturing(hipStream_t Stream) {
163 hipStreamCaptureStatus Status;
164 hipError_t Err = hipStreamIsCapturing(Stream, &Status);
165 return {Err, Err == hipSuccess && Status == hipStreamCaptureStatusActive};
166 }
167
168 static std::string GetDeviceArch() {
169 DeviceHandle_t Dev;
170 DeviceContext_t Ctx;
171 auto EC = DeviceErrorCheck(hipInit(0));
172 if (EC)
173 LOG_FATAL("Could not initialize device\n EC:" + EC.value());
174
175 EC = DeviceErrorCheck(hipGetDevice(&Dev));
176 if (EC)
177 LOG_FATAL("Could not get device\n EC:" + EC.value());
178
179 hipDeviceProp_t device_prop;
180
181 // Get properties of the current device
182 EC = DeviceErrorCheck(hipGetDeviceProperties(&device_prop, Dev));
183 if (EC)
184 LOG_FATAL("Could not get device properties\n EC:" + EC.value());
185
186 std::string arch_name = device_prop.gcnArchName;
187 LOG_DEBUG("Architecture name is {}", arch_name);
188
189 std::string HipArch = arch_name.substr(0, arch_name.find(':'));
190
191 return std::string(HipArch);
192 }
193
194 static DeviceModule_t getDeviceModuleFromImage(const void *Image) {
195 hipModule_t HipModule;
196
197 auto EC = DeviceErrorCheck(hipModuleLoadData(&HipModule, Image));
198 if (EC)
199 LOG_FATAL("Error with loading data from module\nEC:" + EC.value());
200 return HipModule;
201 }
202
203 static void DeviceModuleUnload(DeviceModule_t Module) {
204 auto EC = DeviceErrorCheck(hipModuleUnload(Module));
205 if (EC)
206 LOG_FATAL("Cannot unload module\nEC:" + EC.value());
207 }
208
209 static std::pair<void *, size_t>
210 getGlobalAddrFromModule(hipModule_t &HipModule,
211 const std::string &GlobalName) {
212 size_t Size;
213 hipDeviceptr_t DevPtr;
214 auto EC = DeviceErrorCheck(
215 hipModuleGetGlobal(&DevPtr, &Size, HipModule, GlobalName.c_str()));
216 if (EC)
217 LOG_FATAL("Could not load global variable '" + GlobalName +
218 "' from device module\n:EC:" + EC.value());
219 return std::make_pair((void *)DevPtr, Size);
220 }
221
222 static hipFunction_t getKernelFunctionFromImage(hipModule_t &HipModule,
223 std::string &KernelName) {
224 hipFunction_t KernelFunc;
225 auto EC = DeviceErrorCheck(
226 hipModuleGetFunction(&KernelFunc, HipModule, KernelName.c_str()));
227 if (EC)
228 LOG_FATAL("Error with loading kernel from Module");
229
230 return KernelFunc;
231 }
232
233 static hipError_t getDeviceCount(int &devCount) {
234 return hipGetDeviceCount(&devCount);
235 }
236
237 static hipError_t setDevice(int DeviceId) { return hipSetDevice(DeviceId); }
238
239 static hipError_t getDevice(int &DeviceId) { return hipGetDevice(&DeviceId); }
240
241 static hipError_t launchKernelFunction(hipFunction_t KernelFunc, dim3 GridDim,
242 dim3 BlockDim, void **KernelArgs,
243 uint64_t ShmemSize,
244 hipStream_t Stream) {
245 return hipModuleLaunchKernel(KernelFunc, GridDim.x, GridDim.y, GridDim.z,
246 BlockDim.x, BlockDim.y, BlockDim.z, ShmemSize,
247 Stream, KernelArgs, nullptr);
248 }
249
250 static inline uint64_t
251 getPageSize(int DeviceID,
252 const hipMemAllocationGranularity_flags Granularity) {
253 uint64_t PageSize;
254 hipMemAllocationProp Prop = {};
255 Prop.type = hipMemAllocationTypePinned;
256 Prop.location.type = hipMemLocationTypeDevice;
257 Prop.location.id = DeviceID;
258 // TODO: I could not find any documentation regarding the compressionType in
259 // HIP. I will leave unitialized a.t.m.
260 // Prop.allocFlags.compressionType = CU_MEM_ALLOCATION_COMP_GENERIC;
261
262 hipErrCheck(hipMemGetAllocationGranularity(&PageSize, &Prop, Granularity));
263 return PageSize;
264 }
265
266 static constexpr hipMemcpyKind MemcpyHostToDeviceKind() {
267 return hipMemcpyHostToDevice;
268 }
269
270 static constexpr hipMemcpyKind MemcpyDeviceToHostKind() {
271 return hipMemcpyDeviceToHost;
272 }
273
274 static constexpr hipMemcpyKind MemcpyDeviceToDeviceKind() {
275 return hipMemcpyDeviceToDevice;
276 }
277
278 // On integrated GPUs, applications expect device memory to be
279 // host-accessible, but VMM mappings are GPU-only by default. Grant the CPU
280 // access through ROCr, since hipMemSetAccess may ignore host locations.
281 static void grantHostAccess(void *Addr, uint64_t Size, int DeviceID) {
282 int Integrated = 0;
283 hipErrCheck(hipDeviceGetAttribute(&Integrated, hipDeviceAttributeIntegrated,
284 DeviceID));
285 if (!Integrated)
286 return;
287
288 static hsa_agent_t CpuAgent = [] {
289 hsa_agent_t Agent{0};
290 hsa_iterate_agents(
291 [](hsa_agent_t A, void *Data) {
292 hsa_device_type_t Type;
293 hsa_agent_get_info(A, HSA_AGENT_INFO_DEVICE, &Type);
294 if (Type != HSA_DEVICE_TYPE_CPU)
295 return HSA_STATUS_SUCCESS;
296 *static_cast<hsa_agent_t *>(Data) = A;
297 return HSA_STATUS_INFO_BREAK;
298 },
299 &Agent);
300 return Agent;
301 }();
302 if (!CpuAgent.handle)
303 LOG_FATAL("Cannot find the HSA CPU agent to grant host access");
304
305 hsa_amd_memory_access_desc_t Desc{HSA_ACCESS_PERMISSION_RW, CpuAgent};
306 if (hsa_amd_vmem_set_access(Addr, Size, &Desc, 1) != HSA_STATUS_SUCCESS)
307 LOG_FATAL("Cannot grant host access to device memory at {} size {}", Addr,
308 Size);
309 }
310
311 static uint64_t getMinPageSize(int DeviceID) {
312 return getPageSize(DeviceID, hipMemAllocationGranularityMinimum);
313 }
314
315 // Before ROCm 6.4.2 (HIP 60443484) hipMemRelease never returns memory to the
316 // device, so there unmapped handles are kept and reused for the same device
317 // and size. The pool is leaked so blobs released during static destruction
318 // can still use it.
319 static std::vector<hipMemGenericAllocationHandle_t> &
320 freeHandles(int DeviceID, uint64_t Size) {
321 static auto *Pool =
322 new std::map<std::pair<int, uint64_t>,
323 std::vector<hipMemGenericAllocationHandle_t>>();
324 return (*Pool)[{DeviceID, Size}];
325 }
326
327 static void releaseHandle(int DeviceID, uint64_t Size,
328 hipMemGenericAllocationHandle_t H) {
329 static const bool ReleaseLeaks = [] {
330 int Version = 0;
331 (void)hipRuntimeGetVersion(&Version);
332 return Version < 60443484;
333 }();
334 if (ReleaseLeaks)
335 freeHandles(DeviceID, Size).push_back(H);
336 else
337 (void)hipMemRelease(H);
338 }
339
340 // The driver treats Addr as a hint, so a reservation elsewhere is Occupied.
341 static MapStatus mapFixed(void *Addr, uint64_t Size, uint64_t Alignment,
342 int DeviceID, hipMemGenericAllocationHandle_t &H) {
343 void *Got = nullptr;
344 hipError_t Err = hipMemAddressReserve(&Got, Size, Alignment, Addr, 0);
345 if (Err == hipErrorOutOfMemory)
347 if (Err != hipSuccess)
348 LOG_FATAL("Cannot reserve {} bytes at {}: {}", Size, Addr,
349 hipGetErrorString(Err));
350 if (Got != Addr) {
351 (void)hipMemAddressFree(Got, Size);
352 return MapStatus::Occupied;
353 }
354
355 auto &Free = freeHandles(DeviceID, Size);
356 if (!Free.empty()) {
357 H = Free.back();
358 Free.pop_back();
359 } else {
360 hipMemAllocationProp Prop = {};
361 Prop.type = hipMemAllocationTypePinned;
362 Prop.location.type = hipMemLocationTypeDevice;
363 Prop.location.id = DeviceID;
364 if (hipMemCreate(&H, Size, &Prop, 0) != hipSuccess) {
365 (void)hipMemAddressFree(Addr, Size);
367 }
368 }
369
370 hipMemAccessDesc ADesc = {};
371 ADesc.location.type = hipMemLocationTypeDevice;
372 ADesc.location.id = DeviceID;
373 ADesc.flags = hipMemAccessFlagsProtReadWrite;
374 if (hipMemMap(Addr, Size, 0, H, 0) == hipSuccess) {
375 if (hipMemSetAccess(Addr, Size, &ADesc, 1) == hipSuccess) {
376 grantHostAccess(Addr, Size, DeviceID);
377 return MapStatus::Mapped;
378 }
379 (void)hipMemUnmap(Addr, Size);
380 }
381 releaseHandle(DeviceID, Size, H);
382 (void)hipMemAddressFree(Addr, Size);
384 }
385
386 static void unmapFixed(void *Addr, uint64_t Size, int DeviceID,
387 hipMemGenericAllocationHandle_t H) {
388 auto EC = DeviceErrorCheck(hipMemUnmap(Addr, Size));
389 if (!EC) {
390 releaseHandle(DeviceID, Size, H);
391 EC = DeviceErrorCheck(hipMemAddressFree(Addr, Size));
392 }
393 if (EC)
394 LOG_WARN("Could not unmap {}: {}", Addr, *EC);
395 }
396
397 // From ROCm 7 a failed call stays the last error until the app reads it.
398 static void clearLastError() { (void)hipGetLastError(); }
399
400 static hipError_t DeviceStreamCreate(hipStream_t *Stream) {
401 return hipStreamCreate(Stream);
402 }
403
404 static hipError_t deviceStreamDestroy(hipStream_t Stream) {
405 return hipStreamDestroy(Stream);
406 }
407
408 static hipError_t deviceLaunchKernel(const void *function_address,
409 dim3 numBlocks, dim3 dimBlocks,
410 void **args, size_t sharedMemBytes,
411 hipStream_t stream) {
412 return hipLaunchKernel(function_address, numBlocks, dimBlocks, args,
413 sharedMemBytes, stream);
414 }
415
416 static hipError_t deviceGetSymbolAddress(void **devPtr, const void *symbol) {
417 return hipGetSymbolAddress(devPtr, symbol);
418 }
419
420 static hipError_t deviceEventCreate(hipEvent_t *event) {
421 return hipEventCreate(event);
422 }
423
424 static hipError_t deviceEventRecord(hipEvent_t event, hipStream_t stream) {
425 return hipEventRecord(event, stream);
426 }
427
428 static hipError_t deviceEventDestroy(hipEvent_t event) {
429 return hipEventDestroy(event);
430 }
431
432 static hipError_t deviceEventSynchronize(hipEvent_t event) {
433 return hipEventSynchronize(event);
434 }
435
436 static hipError_t deviceEventElapsedTime(float *ms, hipEvent_t start,
437 hipEvent_t stop) {
438 return hipEventElapsedTime(ms, start, stop);
439 }
440
441 static hipError_t deviceGetAttribute(hipFunction_t &Func,
442 FuncAttributes Attribute, int &Value) {
443 LOG_DEBUG("Going to request attributes of {}", (void *)Func);
444
445 switch (Attribute) {
446 case REGISTER_USAGE:
447 return hipFuncGetAttribute(&Value, HIP_FUNC_ATTRIBUTE_NUM_REGS, Func);
448 case LOCALMEM_USAGE:
449 return hipFuncGetAttribute(&Value, HIP_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES,
450 Func);
451 case CONSTMEM_USAGE:
452 return hipFuncGetAttribute(&Value, HIP_FUNC_ATTRIBUTE_CONST_SIZE_BYTES,
453 Func);
454 default:
455 LOG_FATAL("Request unknown attribute");
456 break;
457 }
458 return hipErrorInvalidValue;
459 }
460};
461#elif defined(MNEME_ENABLE_CUDA)
462template <> struct DeviceTraits<DeviceVendors::CUDA> {
463
464 using DeviceError_t = cudaError_t;
465 using DeviceDriverError_t = CUresult;
466
467 using DeviceStream_t = cudaStream_t;
468
469 using KernelFunction_t = CUfunction;
470
471 using MemoryAllocationHandle_t = CUmemGenericAllocationHandle;
472
473 using DeviceModule_t = CUmodule;
474 using DevicePtr_t = CUdeviceptr;
475
476 using DeviceHandle_t = CUdevice;
477 using DeviceContext_t = CUcontext;
478 using DeviceFunction_t = CUfunction;
479
480 using DeviceEvent_t = cudaEvent_t;
481 static constexpr auto DeviceSuccess = cudaSuccess;
482 static constexpr auto DeviceDriverSuccess = CUDA_SUCCESS;
483 static constexpr auto DeviceOutOfMemory = cudaErrorMemoryAllocation;
484 // The driver reserves address space in 32 MiB blocks and puts its own
485 // allocations in the unreserved part of a block, which then stays reserved
486 // after we free ours. Reservations should cover whole blocks.
487 static constexpr uint64_t VABlockSize = 32ULL << 20;
488 // Managed memory is not placed, so it is not recorded.
489 static constexpr bool PlacesManagedMemory = false;
490
491 static inline void *getRTLib() {
492 static void *Lib = loadRTLib("libcudart.so");
493 return Lib;
494 }
495 static constexpr const char *getLaunchKernelFnName() {
496 return "cudaLaunchKernel";
497 }
498 static constexpr const char *getDeviceMallocFnName() { return "cudaMalloc"; }
499 static constexpr const char *getPinnedMallocFnName() {
500 return "cudaHostAlloc";
501 }
502 static constexpr const char *getManagedMallocFnName() {
503 return "cudaMallocManaged";
504 }
505 static constexpr const char *getDeviceFreeFnName() { return "cudaFree"; }
506 static constexpr const char *getAsyncFreeFnName() { return "cudaFreeAsync"; }
507 static constexpr const char *getPinnedFreeFnName() { return "cudaFreeHost"; }
508 static constexpr const char *getUURegisterFunctionFnName() {
509 return "__cudaRegisterFunction";
510 }
511 static const char *getUURegisterVarFnName() { return "__cudaRegisterVar"; }
512 static const char *getUURegisterFatbinFnName() {
513 return "__cudaRegisterFatBinary";
514 }
515
516 static const char *getUURegisterFatbinEndFnName() {
517 return "__cudaRegisterFatBinaryEnd";
518 }
519
520 static const char *getUUUnRegisterFatBinaryFnName() {
521 return "__cudaUnregisterFatBinary";
522 }
523
524 static const char *getDeviceGetIDFnName() { return "cudaGetDevice"; }
525 static const char *getDeviceSetIDFnName() { return "cudaSetDevice"; }
526
527 static constexpr bool hasFatBinEnd = true;
528
529 static inline std::optional<std::string>
530 DeviceErrorCheck(DeviceError_t ErrorCode) {
531 if (ErrorCode == DeviceSuccess)
532 return std::nullopt;
533 return std::string(cudaGetErrorString(ErrorCode));
534 }
535
536 static inline std::optional<std::string>
537 DeviceErrorCheck(DeviceDriverError_t ErrorCode) {
538 if (ErrorCode == DeviceDriverSuccess)
539 return std::nullopt;
540
541 if (ErrorCode == CUDA_ERROR_DEINITIALIZED) {
542 LOG_WARN("Device is deinitialized ignoring errors");
543 return std::nullopt;
544 }
545
546 const char *name = nullptr, *desc = nullptr;
547 cuGetErrorName(ErrorCode, &name);
548 cuGetErrorString(ErrorCode, &desc);
549 auto EC = std::string("Error:") + std::to_string(ErrorCode) + ":";
550 if (name)
551 EC += std::string(name);
552 if (desc)
553 EC += std::string(" description:") + std::string(name);
554
555 return EC;
556 }
557
558 static DeviceError_t DeviceStreamSynchronize(DeviceStream_t Stream) {
559 return cudaStreamSynchronize(Stream);
560 }
561
562 static DeviceError_t DeviceMemset(void *DevPtr, int Value, size_t Bytes) {
563 auto EC = cudaMemset(DevPtr, Value, Bytes);
564 return EC;
565 }
566
567 static DeviceError_t DeviceMalloc(void **ptr, size_t size) {
568 return cudaMalloc(ptr, size);
569 }
570
571 static DeviceError_t DeviceFree(void *ptr) { return cudaFree(ptr); }
572
573 static DeviceError_t DeviceCopy(void *Dest, void *Src, size_t SizeBytes,
574 cudaMemcpyKind Kind) {
575 return cudaMemcpy(Dest, Src, SizeBytes, Kind);
576 }
577
578 static DeviceError_t DeviceCopyAsync(void *Dest, void *Src, size_t SizeBytes,
579 cudaMemcpyKind Kind,
580 DeviceStream_t Stream) {
581 return cudaMemcpyAsync(Dest, Src, SizeBytes, Kind, Stream);
582 }
583
584 static DeviceError_t DeviceSynchronize() { return cudaDeviceSynchronize(); }
585
586 // Whether Stream is capturing is meaningful only when the error is success.
587 static std::pair<DeviceError_t, bool>
588 deviceStreamIsCapturing(DeviceStream_t Stream) {
589 cudaStreamCaptureStatus Status;
590 DeviceError_t Err = cudaStreamIsCapturing(Stream, &Status);
591 return {Err, Err == cudaSuccess && Status == cudaStreamCaptureStatusActive};
592 }
593
594 static std::string GetDeviceArch() {
595 DeviceHandle_t Dev;
596 DeviceContext_t Ctx;
597 auto EC = DeviceErrorCheck(cuInit(0));
598 if (EC)
599 LOG_FATAL("Could not initialize device\n EC:" + EC.value());
600
601 EC = DeviceErrorCheck(cudaGetDevice(&Dev));
602 if (EC)
603 LOG_FATAL("Could not get device\n EC:" + EC.value());
604
605 EC = DeviceErrorCheck(cuCtxGetCurrent(&Ctx));
606 if (EC)
607 LOG_FATAL("Could not get current CUDA context\nEC:" + EC.value());
608
609 if (!Ctx) {
610 EC = DeviceErrorCheck(cuCtxCreate(&Ctx, 0, Dev));
611 if (EC)
612 LOG_FATAL("Could not create new context\nEC:" + EC.value());
613 }
614
615 int CCMajor;
616 EC = DeviceErrorCheck(cuDeviceGetAttribute(
617 &CCMajor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, Dev));
618 if (EC)
619 LOG_FATAL("Could not get device major attribute\n EC:" + EC.value());
620 int CCMinor;
621 DeviceErrorCheck(cuDeviceGetAttribute(
622 &CCMinor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, Dev));
623 if (EC)
624 LOG_FATAL("Could not get device minor attribute\n EC:" + EC.value());
625
626 std::string DeviceArch = "sm_" + std::to_string(CCMajor * 10 + CCMinor);
627
628 return DeviceArch;
629 }
630
631 static DeviceModule_t getDeviceModuleFromImage(const void *Image) {
632 DeviceModule_t cudaModule;
633
634 auto EC = DeviceErrorCheck(cuModuleLoadData(&cudaModule, Image));
635 if (EC)
636 LOG_FATAL("Error with loading data from module\nEC:" + EC.value());
637 return cudaModule;
638 }
639
640 static void DeviceModuleUnload(DeviceModule_t Module) {
641 auto EC = DeviceErrorCheck(cuModuleUnload(Module));
642 if (EC)
643 LOG_FATAL("Cannot unload module\nEC:" + EC.value());
644 }
645
646 static std::pair<void *, size_t>
647 getGlobalAddrFromModule(DeviceModule_t &cudaModule,
648 const std::string &GlobalName) {
649 size_t Size;
650 DevicePtr_t DevPtr;
651 auto EC = DeviceErrorCheck(
652 cuModuleGetGlobal(&DevPtr, &Size, cudaModule, GlobalName.c_str()));
653 if (EC)
654 LOG_FATAL("Could not load global variable '" + GlobalName +
655 "' from device module\n:EC:" + EC.value());
656 return std::make_pair((void *)DevPtr, Size);
657 }
658
659 static DeviceFunction_t getKernelFunctionFromImage(DeviceModule_t &Module,
660 std::string &KernelName) {
661 DeviceFunction_t KernelFunc;
662 auto EC = DeviceErrorCheck(
663 cuModuleGetFunction(&KernelFunc, Module, KernelName.c_str()));
664 if (EC)
665 LOG_FATAL("Error with loading kernel from Module");
666
667 return KernelFunc;
668 }
669
670 static cudaError_t getDeviceCount(int &devCount) {
671 return cudaGetDeviceCount(&devCount);
672 }
673
674 static cudaError_t setDevice(int DeviceId) { return cudaSetDevice(DeviceId); }
675
676 static cudaError_t getDevice(int &DeviceId) {
677 return cudaGetDevice(&DeviceId);
678 }
679
680 static DeviceDriverError_t launchKernelFunction(DeviceFunction_t KernelFunc,
681 dim3 GridDim, dim3 BlockDim,
682 void **KernelArgs,
683 uint64_t ShmemSize,
684 cudaStream_t Stream) {
685 return cuLaunchKernel(KernelFunc, GridDim.x, GridDim.y, GridDim.z,
686 BlockDim.x, BlockDim.y, BlockDim.z, ShmemSize, Stream,
687 KernelArgs, nullptr);
688 }
689
690 static inline uint64_t
691 getPageSize(int DeviceID,
692 const CUmemAllocationGranularity_flags Granularity) {
693 uint64_t PageSize;
694 CUmemAllocationProp Prop = {};
695 Prop.type = CUmemAllocationType::CU_MEM_ALLOCATION_TYPE_PINNED;
696 Prop.location.type = CUmemLocationType::CU_MEM_LOCATION_TYPE_DEVICE;
697 Prop.location.id = DeviceID;
698
699 auto EC = DeviceErrorCheck(
700 cuMemGetAllocationGranularity(&PageSize, &Prop, Granularity));
701 if (EC)
702 LOG_FATAL("Could not get Allocation Granularity\nEC:" + EC.value());
703 return PageSize;
704 }
705
706 static constexpr cudaMemcpyKind MemcpyHostToDeviceKind() {
707 return cudaMemcpyHostToDevice;
708 }
709
710 static constexpr cudaMemcpyKind MemcpyDeviceToHostKind() {
711 return cudaMemcpyDeviceToHost;
712 }
713
714 static constexpr cudaMemcpyKind MemcpyDeviceToDeviceKind() {
715 return cudaMemcpyDeviceToDevice;
716 }
717
718 static uint64_t getMinPageSize(int DeviceID) {
719 return getPageSize(DeviceID, CU_MEM_ALLOC_GRANULARITY_MINIMUM);
720 }
721
722 // The driver treats Addr as a hint, so a reservation elsewhere is Occupied.
723 static MapStatus mapFixed(void *Addr, uint64_t Size, uint64_t Alignment,
724 int DeviceID, MemoryAllocationHandle_t &H) {
725 DevicePtr_t Want = reinterpret_cast<DevicePtr_t>(Addr);
726 DevicePtr_t Got = 0;
727 CUresult Err = cuMemAddressReserve(&Got, Size, Alignment, Want, 0);
728 if (Err == CUDA_ERROR_OUT_OF_MEMORY)
730 if (auto EC = DeviceErrorCheck(Err))
731 LOG_FATAL("Cannot reserve {} bytes at {}: {}", Size, Addr, *EC);
732 if (Got != Want) {
733 (void)cuMemAddressFree(Got, Size);
734 return MapStatus::Occupied;
735 }
736
737 CUmemAllocationProp Prop = {};
738 Prop.type = CU_MEM_ALLOCATION_TYPE_PINNED;
739 Prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
740 Prop.location.id = DeviceID;
741 if (cuMemCreate(&H, Size, &Prop, 0) != CUDA_SUCCESS) {
742 (void)cuMemAddressFree(Want, Size);
744 }
745
746 CUmemAccessDesc ADesc = {};
747 ADesc.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
748 ADesc.location.id = DeviceID;
749 ADesc.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE;
750 if (cuMemMap(Want, Size, 0, H, 0) == CUDA_SUCCESS) {
751 if (cuMemSetAccess(Want, Size, &ADesc, 1) == CUDA_SUCCESS)
752 return MapStatus::Mapped;
753 (void)cuMemUnmap(Want, Size);
754 }
755 (void)cuMemRelease(H);
756 (void)cuMemAddressFree(Want, Size);
758 }
759
760 static void unmapFixed(void *Addr, uint64_t Size, int,
761 MemoryAllocationHandle_t H) {
762 DevicePtr_t Ptr = reinterpret_cast<DevicePtr_t>(Addr);
763 auto EC = DeviceErrorCheck(cuMemUnmap(Ptr, Size));
764 if (!EC)
765 EC = DeviceErrorCheck(cuMemRelease(H));
766 if (!EC)
767 EC = DeviceErrorCheck(cuMemAddressFree(Ptr, Size));
768 if (EC)
769 LOG_WARN("Could not unmap {}: {}", Addr, *EC);
770 }
771
772 // Driver API failures do not set the runtime's last error.
773 static void clearLastError() {}
774
775 static bool compareDeviceBlobs(const char *Blob1, const char *Blob2,
776 uint64_t NumBytes);
777
778 static DeviceError_t DeviceStreamCreate(DeviceStream_t *Stream) {
779 return cudaStreamCreate(Stream);
780 }
781
782 static DeviceError_t deviceStreamDestroy(DeviceStream_t Stream) {
783 return cudaStreamDestroy(Stream);
784 }
785
786 static DeviceError_t deviceLaunchKernel(const void *kernelFunc, dim3 gridDim,
787 dim3 blockDim, void **kernelArgs,
788 size_t sharedMemBytes,
789 DeviceStream_t stream) {
790 auto EC = DeviceErrorCheck(cudaLaunchKernel(
791 kernelFunc, gridDim, blockDim, kernelArgs, sharedMemBytes, stream));
792 if (EC)
793 LOG_WARN("Launching Kernel return error {}", EC.value());
794
795 return cudaGetLastError();
796 }
797
798 static DeviceError_t deviceEventCreate(DeviceEvent_t *event) {
799 return cudaEventCreate(event);
800 }
801
802 static DeviceError_t deviceEventRecord(DeviceEvent_t event,
803 DeviceStream_t stream) {
804 return cudaEventRecord(event, stream);
805 }
806
807 static DeviceError_t deviceEventDestroy(DeviceEvent_t event) {
808 return cudaEventDestroy(event);
809 }
810
811 static DeviceError_t deviceEventSynchronize(DeviceEvent_t event) {
812 return cudaEventSynchronize(event);
813 }
814
815 static DeviceError_t deviceEventElapsedTime(float *ms, DeviceEvent_t start,
816 DeviceEvent_t stop) {
817 return cudaEventElapsedTime(ms, start, stop);
818 }
819
820 static DeviceError_t deviceGetSymbolAddress(void **devPtr,
821 const void *symbol) {
822 return cudaGetSymbolAddress(devPtr, symbol);
823 }
824
825 static DeviceDriverError_t deviceGetAttribute(cudaFunction_t &Func,
826 FuncAttributes Attribute,
827 int &Value) {
828 LOG_DEBUG("Going to request attributes of {}", (void *)Func);
829
830 switch (Attribute) {
831 case REGISTER_USAGE:
832 return cuFuncGetAttribute(&Value, CU_FUNC_ATTRIBUTE_NUM_REGS, Func);
833
834 case LOCALMEM_USAGE:
835 return cuFuncGetAttribute(&Value, CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES,
836 Func);
837
838 case CONSTMEM_USAGE:
839 return cuFuncGetAttribute(&Value, CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES,
840 Func);
841 default:
842 LOG_FATAL("Request unknown attribute");
843 break;
844 }
845 }
846};
847#else
848#endif
849
850// The vendor runtime's own implementation of a function that Mneme intercepts.
851// Calling the function by name from Mneme would call Mneme's wrapper instead.
852template <DeviceVendors Vendor, typename FnT>
853FnT getRuntimeFn(const char *Name) {
854 auto Fn =
855 reinterpret_cast<FnT>(dlsym(DeviceTraits<Vendor>::getRTLib(), Name));
856 if (!Fn)
857 LOG_FATAL("Could not find {} in the device runtime", Name);
858 return Fn;
859}
860
861} // namespace mneme
#define LOG_DEBUG(...)
Definition MnemeLogger.hpp:109
#define LOG_FATAL(...)
Definition MnemeLogger.hpp:113
#define LOG_WARN(...)
Definition MnemeLogger.hpp:111
cudaError_t cudaFree(void *ptr)
Definition MnemeRecordPreloadCUDA.cpp:113
cudaError_t cudaGetDevice(int *deviceID)
Definition MnemeRecordPreloadCUDA.cpp:145
cudaError_t cudaMalloc(void **ptr, size_t size)
Definition MnemeRecordPreloadCUDA.cpp:43
cudaError_t cudaSetDevice(int deviceID)
Definition MnemeRecordPreloadCUDA.cpp:139
hipError_t hipMalloc(void **ptr, size_t size)
Definition MnemeRecordPreloadHIP.cpp:79
hipError_t hipFree(void *ptr)
Definition MnemeRecordPreloadHIP.cpp:158
hipError_t hipSetDevice(int deviceID)
Definition MnemeRecordPreloadHIP.cpp:182
hipError_t hipGetDevice(int *deviceID)
Definition MnemeRecordPreloadHIP.cpp:188
int64_t u64 Size
Definition cupti_profile.cpp:179
Definition MnemeAnnotation.cpp:3
void * loadRTLib(const char *Name)
Definition DeviceTraits.hpp:76
FuncAttributes
Definition DeviceTraits.hpp:69
@ LOCALMEM_USAGE
Definition DeviceTraits.hpp:69
@ CONSTMEM_USAGE
Definition DeviceTraits.hpp:69
@ REGISTER_USAGE
Definition DeviceTraits.hpp:69
CompareResult compareDeviceBlobs(const char *Blob1, const char *Blob2, uint64_t NumBytes, Metadata Md)
Definition MnemeDeviceCode.cpp:237
MapStatus
Definition DeviceTraits.hpp:71
@ Mapped
Definition DeviceTraits.hpp:71
@ OutOfMemory
Definition DeviceTraits.hpp:71
@ Occupied
Definition DeviceTraits.hpp:71
DeviceVendors
Definition DeviceTraits.hpp:67
@ CUDA
Definition DeviceTraits.hpp:67
@ HIP
Definition DeviceTraits.hpp:67
FnT getRuntimeFn(const char *Name)
Definition DeviceTraits.hpp:853
@ Bytes
Definition MnemeConfig.hpp:24
Definition DeviceTraits.hpp:73