cuda_acxxel.cpp
18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//===--- cuda_acxxel.cpp - CUDA implementation of the Acxxel API ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// This file defines the standard CUDA implementation of the Acxxel API.
///
//===----------------------------------------------------------------------===//
#include "acxxel.h"
#include "cuda.h"
#include "cuda_runtime.h"
#include <array>
#include <cassert>
#include <sstream>
#include <vector>
namespace acxxel {
namespace {
static std::string getCUErrorMessage(CUresult Result) {
if (!Result)
return "success";
const char *ErrorName = "UNKNOWN_ERROR_NAME";
const char *ErrorDescription = "UNKNOWN_ERROR_DESCRIPTION";
cuGetErrorName(Result, &ErrorName);
cuGetErrorString(Result, &ErrorDescription);
std::ostringstream OutStream;
OutStream << "CUDA driver error: code = " << Result
<< ", name = " << ErrorName
<< ", description = " << ErrorDescription;
return OutStream.str();
}
static Status getCUError(CUresult Result, const std::string &Message) {
if (!Result)
return Status();
std::ostringstream OutStream;
OutStream << getCUErrorMessage(Result) << ", message = " << Message;
return Status(OutStream.str());
}
static std::string getCUDAErrorMessage(cudaError_t E) {
if (!E)
return "success";
std::ostringstream OutStream;
OutStream << "CUDA runtime error: code = " << E
<< ", name = " << cudaGetErrorName(E)
<< ", description = " << cudaGetErrorString(E);
return OutStream.str();
}
static Status getCUDAError(cudaError_t E, const std::string &Message) {
if (!E)
return Status();
std::ostringstream OutStream;
OutStream << getCUDAErrorMessage(E) << ", message = " << Message;
return Status(OutStream.str());
}
static void logCUWarning(CUresult Result, const std::string &Message) {
if (Result) {
std::ostringstream OutStream;
OutStream << Message << ": " << getCUErrorMessage(Result);
logWarning(OutStream.str());
}
}
/// A CUDA Platform implementation.
class CUDAPlatform : public Platform {
public:
~CUDAPlatform() override = default;
static Expected<CUDAPlatform> create();
Expected<int> getDeviceCount() override;
Expected<Stream> createStream(int DeviceIndex) override;
Status streamSync(void *Stream) override;
Status streamWaitOnEvent(void *Stream, void *Event) override;
Expected<Event> createEvent(int DeviceIndex) override;
protected:
Expected<void *> rawMallocD(ptrdiff_t ByteCount, int DeviceIndex) override;
HandleDestructor getDeviceMemoryHandleDestructor() override;
void *getDeviceMemorySpanHandle(void *BaseHandle, size_t ByteSize,
size_t ByteOffset) override;
virtual void rawDestroyDeviceMemorySpanHandle(void *Handle) override;
Expected<void *> rawGetDeviceSymbolAddress(const void *Symbol,
int DeviceIndex) override;
Expected<ptrdiff_t> rawGetDeviceSymbolSize(const void *Symbol,
int DeviceIndex) override;
Status rawRegisterHostMem(const void *Memory, ptrdiff_t ByteCount) override;
HandleDestructor getUnregisterHostMemoryHandleDestructor() override;
Expected<void *> rawMallocRegisteredH(ptrdiff_t ByteCount) override;
HandleDestructor getFreeHostMemoryHandleDestructor() override;
Status asyncCopyDToD(const void *DeviceSrc, ptrdiff_t DeviceSrcByteOffset,
void *DeviceDst, ptrdiff_t DeviceDstByteOffset,
ptrdiff_t ByteCount, void *Stream) override;
Status asyncCopyDToH(const void *DeviceSrc, ptrdiff_t DeviceSrcByteOffset,
void *HostDst, ptrdiff_t ByteCount,
void *Stream) override;
Status asyncCopyHToD(const void *HostSrc, void *DeviceDst,
ptrdiff_t DeviceDstByteOffset, ptrdiff_t ByteCount,
void *Stream) override;
Status asyncMemsetD(void *DeviceDst, ptrdiff_t ByteOffset,
ptrdiff_t ByteCount, char ByteValue,
void *Stream) override;
Status addStreamCallback(Stream &Stream, StreamCallback Callback) override;
Expected<Program> createProgramFromSource(Span<const char> Source,
int DeviceIndex) override;
Status enqueueEvent(void *Event, void *Stream) override;
bool eventIsDone(void *Event) override;
Status eventSync(void *Event) override;
Expected<float> getSecondsBetweenEvents(void *StartEvent,
void *EndEvent) override;
Expected<void *> rawCreateKernel(void *Program,
const std::string &Name) override;
HandleDestructor getKernelHandleDestructor() override;
Status rawEnqueueKernelLaunch(void *Stream, void *Kernel,
KernelLaunchDimensions LaunchDimensions,
Span<void *> Arguments,
Span<size_t> ArgumentSizes,
size_t SharedMemoryBytes) override;
private:
explicit CUDAPlatform(const std::vector<CUcontext> &Contexts)
: TheContexts(Contexts) {}
Status setContext(int DeviceIndex) {
if (DeviceIndex < 0 ||
static_cast<size_t>(DeviceIndex) >= TheContexts.size())
return Status("invalid deivce index " + std::to_string(DeviceIndex));
return getCUError(cuCtxSetCurrent(TheContexts[DeviceIndex]),
"cuCtxSetCurrent");
}
// Vector of contexts for each device.
std::vector<CUcontext> TheContexts;
};
Expected<CUDAPlatform> CUDAPlatform::create() {
std::vector<CUcontext> Contexts;
if (CUresult Result = cuInit(0))
return getCUError(Result, "cuInit");
int DeviceCount = 0;
if (CUresult Result = cuDeviceGetCount(&DeviceCount))
return getCUError(Result, "cuDeviceGetCount");
for (int I = 0; I < DeviceCount; ++I) {
CUdevice Device;
if (CUresult Result = cuDeviceGet(&Device, I))
return getCUError(Result, "cuDeviceGet");
CUcontext Context;
if (CUresult Result = cuDevicePrimaryCtxRetain(&Context, Device))
return getCUError(Result, "cuDevicePrimaryCtxRetain");
if (CUresult Result = cuCtxSetCurrent(Context))
return getCUError(Result, "cuCtxSetCurrent");
Contexts.emplace_back(Context);
}
return CUDAPlatform(Contexts);
}
Expected<int> CUDAPlatform::getDeviceCount() {
int Count = 0;
if (CUresult Result = cuDeviceGetCount(&Count))
return getCUError(Result, "cuDeviceGetCount");
return Count;
}
static void cudaDestroyStream(void *H) {
logCUWarning(cuStreamDestroy(static_cast<CUstream_st *>(H)),
"cuStreamDestroy");
}
Expected<Stream> CUDAPlatform::createStream(int DeviceIndex) {
Status S = setContext(DeviceIndex);
if (S.isError())
return S;
unsigned int Flags = CU_STREAM_DEFAULT;
CUstream Handle;
if (CUresult Result = cuStreamCreate(&Handle, Flags))
return getCUError(Result, "cuStreamCreate");
return constructStream(this, DeviceIndex, Handle, cudaDestroyStream);
}
Status CUDAPlatform::streamSync(void *Stream) {
return getCUError(cuStreamSynchronize(static_cast<CUstream_st *>(Stream)),
"cuStreamSynchronize");
}
Status CUDAPlatform::streamWaitOnEvent(void *Stream, void *Event) {
// CUDA docs says flags must be 0.
unsigned int Flags = 0u;
return getCUError(cuStreamWaitEvent(static_cast<CUstream_st *>(Stream),
static_cast<CUevent_st *>(Event), Flags),
"cuStreamWaitEvent");
}
static void cudaDestroyEvent(void *H) {
logCUWarning(cuEventDestroy(static_cast<CUevent_st *>(H)), "cuEventDestroy");
}
Expected<Event> CUDAPlatform::createEvent(int DeviceIndex) {
Status S = setContext(DeviceIndex);
if (S.isError())
return S;
unsigned int Flags = CU_EVENT_DEFAULT;
CUevent Handle;
if (CUresult Result = cuEventCreate(&Handle, Flags))
return getCUError(Result, "cuEventCreate");
return constructEvent(this, DeviceIndex, Handle, cudaDestroyEvent);
}
Status CUDAPlatform::enqueueEvent(void *Event, void *Stream) {
return getCUError(cuEventRecord(static_cast<CUevent_st *>(Event),
static_cast<CUstream_st *>(Stream)),
"cuEventRecord");
}
bool CUDAPlatform::eventIsDone(void *Event) {
return cuEventQuery(static_cast<CUevent_st *>(Event)) != CUDA_ERROR_NOT_READY;
}
Status CUDAPlatform::eventSync(void *Event) {
return getCUError(cuEventSynchronize(static_cast<CUevent_st *>(Event)),
"cuEventSynchronize");
}
Expected<float> CUDAPlatform::getSecondsBetweenEvents(void *StartEvent,
void *EndEvent) {
float Milliseconds;
if (CUresult Result = cuEventElapsedTime(
&Milliseconds, static_cast<CUevent_st *>(StartEvent),
static_cast<CUevent_st *>(EndEvent)))
return getCUError(Result, "cuEventElapsedTime");
return Milliseconds * 1e-6;
}
Expected<void *> CUDAPlatform::rawMallocD(ptrdiff_t ByteCount,
int DeviceIndex) {
Status S = setContext(DeviceIndex);
if (S.isError())
return S;
if (!ByteCount)
return nullptr;
CUdeviceptr Pointer;
if (CUresult Result = cuMemAlloc(&Pointer, ByteCount))
return getCUError(Result, "cuMemAlloc");
return reinterpret_cast<void *>(Pointer);
}
static void cudaDestroyDeviceMemory(void *H) {
logCUWarning(cuMemFree(reinterpret_cast<CUdeviceptr>(H)), "cuMemFree");
}
HandleDestructor CUDAPlatform::getDeviceMemoryHandleDestructor() {
return cudaDestroyDeviceMemory;
}
void *CUDAPlatform::getDeviceMemorySpanHandle(void *BaseHandle, size_t,
size_t ByteOffset) {
return static_cast<char *>(BaseHandle) + ByteOffset;
}
void CUDAPlatform::rawDestroyDeviceMemorySpanHandle(void *) {
// Do nothing for this platform.
}
Expected<void *> CUDAPlatform::rawGetDeviceSymbolAddress(const void *Symbol,
int DeviceIndex) {
Status S = setContext(DeviceIndex);
if (S.isError())
return S;
void *Address;
if (cudaError_t Status = cudaGetSymbolAddress(&Address, Symbol))
return getCUDAError(Status, "cudaGetSymbolAddress");
return Address;
}
Expected<ptrdiff_t> CUDAPlatform::rawGetDeviceSymbolSize(const void *Symbol,
int DeviceIndex) {
Status S = setContext(DeviceIndex);
if (S.isError())
return S;
size_t Size;
if (cudaError_t Status = cudaGetSymbolSize(&Size, Symbol))
return getCUDAError(Status, "cudaGetSymbolSize");
return Size;
}
static const void *offsetVoidPtr(const void *Ptr, ptrdiff_t ByteOffset) {
return static_cast<const void *>(static_cast<const char *>(Ptr) + ByteOffset);
}
static void *offsetVoidPtr(void *Ptr, ptrdiff_t ByteOffset) {
return static_cast<void *>(static_cast<char *>(Ptr) + ByteOffset);
}
Status CUDAPlatform::rawRegisterHostMem(const void *Memory,
ptrdiff_t ByteCount) {
unsigned int Flags = 0;
return getCUError(
cuMemHostRegister(const_cast<void *>(Memory), ByteCount, Flags),
"cuMemHostRegiser");
}
static void cudaUnregisterHostMemoryHandleDestructor(void *H) {
logCUWarning(cuMemHostUnregister(H), "cuMemHostUnregister");
}
HandleDestructor CUDAPlatform::getUnregisterHostMemoryHandleDestructor() {
return cudaUnregisterHostMemoryHandleDestructor;
}
Expected<void *> CUDAPlatform::rawMallocRegisteredH(ptrdiff_t ByteCount) {
unsigned int Flags = 0;
void *Memory;
if (CUresult Result = cuMemHostAlloc(&Memory, ByteCount, Flags))
return getCUError(Result, "cuMemHostAlloc");
return Memory;
}
static void cudaFreeHostMemoryHandleDestructor(void *H) {
logCUWarning(cuMemFreeHost(H), "cuMemFreeHost");
}
HandleDestructor CUDAPlatform::getFreeHostMemoryHandleDestructor() {
return cudaFreeHostMemoryHandleDestructor;
}
Status CUDAPlatform::asyncCopyDToD(const void *DeviceSrc,
ptrdiff_t DeviceSrcByteOffset,
void *DeviceDst,
ptrdiff_t DeviceDstByteOffset,
ptrdiff_t ByteCount, void *Stream) {
return getCUError(
cuMemcpyDtoDAsync(reinterpret_cast<CUdeviceptr>(
offsetVoidPtr(DeviceDst, DeviceDstByteOffset)),
reinterpret_cast<CUdeviceptr>(
offsetVoidPtr(DeviceSrc, DeviceSrcByteOffset)),
ByteCount, static_cast<CUstream_st *>(Stream)),
"cuMemcpyDtoDAsync");
}
Status CUDAPlatform::asyncCopyDToH(const void *DeviceSrc,
ptrdiff_t DeviceSrcByteOffset, void *HostDst,
ptrdiff_t ByteCount, void *Stream) {
return getCUError(
cuMemcpyDtoHAsync(HostDst, reinterpret_cast<CUdeviceptr>(offsetVoidPtr(
DeviceSrc, DeviceSrcByteOffset)),
ByteCount, static_cast<CUstream_st *>(Stream)),
"cuMemcpyDtoHAsync");
}
Status CUDAPlatform::asyncCopyHToD(const void *HostSrc, void *DeviceDst,
ptrdiff_t DeviceDstByteOffset,
ptrdiff_t ByteCount, void *Stream) {
return getCUError(
cuMemcpyHtoDAsync(reinterpret_cast<CUdeviceptr>(
offsetVoidPtr(DeviceDst, DeviceDstByteOffset)),
HostSrc, ByteCount, static_cast<CUstream_st *>(Stream)),
"cuMemcpyHtoDAsync");
}
Status CUDAPlatform::asyncMemsetD(void *DeviceDst, ptrdiff_t ByteOffset,
ptrdiff_t ByteCount, char ByteValue,
void *Stream) {
return getCUError(
cuMemsetD8Async(
reinterpret_cast<CUdeviceptr>(offsetVoidPtr(DeviceDst, ByteOffset)),
ByteValue, ByteCount, static_cast<CUstream_st *>(Stream)),
"cuMemsetD8Async");
}
struct StreamCallbackUserData {
StreamCallbackUserData(Stream &Stream, StreamCallback Function)
: TheStream(Stream), TheFunction(std::move(Function)) {}
Stream &TheStream;
StreamCallback TheFunction;
};
static void CUDA_CB cuStreamCallbackShim(CUstream HStream, CUresult Status,
void *UserData) {
std::unique_ptr<StreamCallbackUserData> Data(
static_cast<StreamCallbackUserData *>(UserData));
Stream &TheStream = Data->TheStream;
assert(static_cast<CUstream_st *>(TheStream) == HStream);
Data->TheFunction(TheStream,
getCUError(Status, "stream callback error state"));
}
Status CUDAPlatform::addStreamCallback(Stream &Stream,
StreamCallback Callback) {
// CUDA docs say flags must always be 0 here.
unsigned int Flags = 0u;
std::unique_ptr<StreamCallbackUserData> UserData(
new StreamCallbackUserData(Stream, std::move(Callback)));
return getCUError(cuStreamAddCallback(Stream, cuStreamCallbackShim,
UserData.release(), Flags),
"cuStreamAddCallback");
}
static void cudaDestroyProgram(void *H) {
logCUWarning(cuModuleUnload(static_cast<CUmod_st *>(H)), "cuModuleUnload");
}
Expected<Program> CUDAPlatform::createProgramFromSource(Span<const char> Source,
int DeviceIndex) {
Status S = setContext(DeviceIndex);
if (S.isError())
return S;
CUmodule Module;
constexpr int LogBufferSizeBytes = 1024;
char InfoLogBuffer[LogBufferSizeBytes];
char ErrorLogBuffer[LogBufferSizeBytes];
constexpr size_t OptionsCount = 4;
std::array<CUjit_option, OptionsCount> OptionNames = {
{CU_JIT_INFO_LOG_BUFFER, CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES,
CU_JIT_ERROR_LOG_BUFFER, CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES}};
std::array<void *, OptionsCount> OptionValues = {
{InfoLogBuffer, const_cast<int *>(&LogBufferSizeBytes), ErrorLogBuffer,
const_cast<int *>(&LogBufferSizeBytes)}};
if (CUresult Result =
cuModuleLoadDataEx(&Module, Source.data(), OptionsCount,
OptionNames.data(), OptionValues.data())) {
InfoLogBuffer[LogBufferSizeBytes - 1] = '\0';
ErrorLogBuffer[LogBufferSizeBytes - 1] = '\0';
std::ostringstream OutStream;
OutStream << "Error creating program from source: "
<< getCUErrorMessage(Result)
<< "\nINFO MESSAGES\n================\n"
<< InfoLogBuffer << "\nERROR MESSAGES\n==================\n"
<< ErrorLogBuffer;
return Status(OutStream.str());
}
return constructProgram(this, Module, cudaDestroyProgram);
}
Expected<void *> CUDAPlatform::rawCreateKernel(void *Program,
const std::string &Name) {
CUmodule Module = static_cast<CUmodule>(Program);
CUfunction Kernel;
if (CUresult Result = cuModuleGetFunction(&Kernel, Module, Name.c_str()))
return getCUError(Result, "cuModuleGetFunction");
return Kernel;
}
static void cudaDestroyKernel(void *) {
// Do nothing.
}
HandleDestructor CUDAPlatform::getKernelHandleDestructor() {
return cudaDestroyKernel;
}
Status CUDAPlatform::rawEnqueueKernelLaunch(
void *Stream, void *Kernel, KernelLaunchDimensions LaunchDimensions,
Span<void *> Arguments, Span<size_t>, size_t SharedMemoryBytes) {
return getCUError(
cuLaunchKernel(static_cast<CUfunction>(Kernel), LaunchDimensions.GridX,
LaunchDimensions.GridY, LaunchDimensions.GridZ,
LaunchDimensions.BlockX, LaunchDimensions.BlockY,
LaunchDimensions.BlockZ, SharedMemoryBytes,
static_cast<CUstream>(Stream), Arguments.data(), nullptr),
"cuLaunchKernel");
}
} // namespace
namespace cuda {
/// Gets the CUDAPlatform instance and returns it as an unowned pointer to a
/// Platform.
Expected<Platform *> getPlatform() {
static auto MaybePlatform = []() -> Expected<CUDAPlatform *> {
Expected<CUDAPlatform> CreationResult = CUDAPlatform::create();
if (CreationResult.isError())
return CreationResult.getError();
else
return new CUDAPlatform(CreationResult.takeValue());
}();
return MaybePlatform;
}
} // namespace cuda
} // namespace acxxel