/
CUDACommon.cpp
401 lines (306 loc) · 10.8 KB
/
CUDACommon.cpp
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
#include <CUDACommon.hpp>
bool TorchCompatibleAllocator::allocate(cuda::GpuMat* mat, int rows, int cols, size_t elemSize) {
if (rows * cols == 0) {
THError("You tried to allocate a Tensor with zero rows or columns");
return false;
}
// See https://github.com/torch/cutorch/blob/master/lib/THC/generic/THCStorage.c#L69
THCState *state = this->cutorchState;
const THCDeviceAllocator *allocator = state->cudaDeviceAllocator;
void *allocatorContext = state->cudaDeviceAllocator->state;
THCHeapUpdate(state, rows * cols * elemSize);
cudaError_t err = (*allocator->malloc)(
allocatorContext,
(void **) &(mat->data),
rows * cols * elemSize,
THCState_getCurrentStream(state));
if (err != cudaSuccess) {
THCHeapUpdate(state, -rows * cols * elemSize);
THCudaCheck(err);
return false;
}
THCudaCheck(err);
mat->step = elemSize * cols;
mat->refcount = (int*) cv::fastMalloc(sizeof(int));
return true;
}
void TorchCompatibleAllocator::free(cuda::GpuMat* mat) {
// See https://github.com/torch/cutorch/blob/master/lib/THC/generic/THCStorage.c#L180
THCState *state = this->cutorchState;
const THCDeviceAllocator *allocator = state->cudaDeviceAllocator;
void *allocatorContext = state->cudaDeviceAllocator->state;
THCHeapUpdate(state, -mat->step * mat->rows);
THCudaCheck((*allocator->free)(allocatorContext, mat->data));
cv::fastFree(mat->refcount);
}
static TorchCompatibleAllocator torchCompatibleAllocator;
extern "C"
void initAllocatorCUDA(cutorchInfo info) {
torchCompatibleAllocator.cutorchState = info.state;
cuda::GpuMat::setDefaultAllocator(&torchCompatibleAllocator);
}
GpuMatT::GpuMatT(cuda::GpuMat & mat) {
this->mat = mat;
this->tensor = nullptr;
}
GpuMatT::GpuMatT(cuda::GpuMat && mat) {
new (this) GpuMatT(mat);
}
GpuMatT::GpuMatT() {
this->tensor = nullptr;
}
TensorWrapper::TensorWrapper(GpuMatT & matT, THCState *state) {
if (matT.tensor != nullptr) {
// Mat is already constructed on another Tensor, so return that
this->tensorPtr = reinterpret_cast<THByteTensor *>(matT.tensor);
this->definedInLua = true;
this->typeCode = static_cast<char>(matT.mat.depth());
THAtomicIncrementRef(&this->tensorPtr->storage->refcount);
} else {
new (this) TensorWrapper(matT.mat, state);
}
}
TensorWrapper::TensorWrapper(GpuMatT && mat, THCState *state) {
new (this) TensorWrapper(mat, state);
}
cuda::GpuMat TensorWrapper::toGpuMat(int depth) {
if (this->tensorPtr == nullptr or this->tensorPtr->nDimension == 0) {
return cuda::GpuMat();
}
THCudaTensor *tensorPtr = reinterpret_cast<THCudaTensor *>(this->tensorPtr);
assert(tensorPtr->nDimension <= 3);
int numChannels = 1;
if (tensorPtr->nDimension == 3) {
numChannels = tensorPtr->size[2];
}
return cuda::GpuMat(
tensorPtr->size[0],
tensorPtr->size[1],
(depth == -1 ? CV_32FC(numChannels) : CV_MAKE_TYPE(depth, numChannels)),
tensorPtr->storage->data + tensorPtr->storageOffset * cv::getElemSize(CV_32F),
tensorPtr->stride[0] * sizeof(float)
);
}
TensorWrapper::TensorWrapper(cuda::GpuMat & mat, THCState *state) {
this->definedInLua = false;
if (mat.empty()) {
this->typeCode = CV_CUDA;
this->tensorPtr = nullptr;
return;
}
this->typeCode = CV_CUDA;
THCudaTensor *outputPtr = THCudaTensor_new(state);
// Build new storage on top of the Mat
outputPtr->storage = THCudaStorage_newWithData(
state,
reinterpret_cast<float *>(mat.data),
mat.step * mat.rows * mat.channels() / cv::getElemSize(mat.depth())
);
int sizeMultiplier;
if (mat.channels() == 1) {
outputPtr->nDimension = 2;
sizeMultiplier = cv::getElemSize(mat.depth());
} else {
outputPtr->nDimension = 3;
sizeMultiplier = mat.elemSize1();
}
outputPtr->size = static_cast<long *>(THAlloc(sizeof(long) * outputPtr->nDimension));
outputPtr->stride = static_cast<long *>(THAlloc(sizeof(long) * outputPtr->nDimension));
if (mat.channels() > 1) {
outputPtr->size[2] = mat.channels();
outputPtr->stride[2] = 1;
}
outputPtr->size[0] = mat.rows;
outputPtr->size[1] = mat.cols;
outputPtr->stride[0] = mat.step / sizeMultiplier;
outputPtr->stride[1] = mat.channels();
outputPtr->storageOffset = 0;
// Make OpenCV treat underlying data as user-allocated
mat.refcount = nullptr;
this->tensorPtr = reinterpret_cast<THByteTensor *>(outputPtr);
}
TensorWrapper::TensorWrapper(cuda::GpuMat && mat, THCState *state) {
// invokes TensorWrapper(cuda::GpuMat & mat)
new (this) TensorWrapper(mat, state);
}
// Kill "destination" and assign "source" data to it.
// "destination" is always supposed to be an empty CudaTensor
extern "C"
void transfer_tensor_CUDA(THCState *state, THCudaTensor *dst, struct TensorWrapper srcWrapper) {
THCudaTensor *src = reinterpret_cast<THCudaTensor *>(srcWrapper.tensorPtr);
dst->nDimension = src->nDimension;
dst->refcount = src->refcount;
dst->storage = src->storage;
if (!srcWrapper.definedInLua) {
// Don't let Torch deallocate size and stride arrays
dst->size = src->size;
dst->stride = src->stride;
src->size = nullptr;
src->stride = nullptr;
THAtomicIncrementRef(&src->storage->refcount);
THCudaTensor_free(state, src);
} else {
dst->size = static_cast<long *>(THAlloc(sizeof(long) * dst->nDimension));
dst->stride = static_cast<long *>(THAlloc(sizeof(long) * dst->nDimension));
memcpy(dst->size, src->size, src->nDimension * sizeof(long));
memcpy(dst->stride, src->stride, src->nDimension * sizeof(long));
}
}
TensorArray::TensorArray(std::vector<cuda::GpuMat> & matList, THCState *state):
tensors(static_cast<TensorWrapper *>(malloc(matList.size() * sizeof(TensorWrapper)))),
size(matList.size())
{
for (size_t i = 0; i < matList.size(); ++i) {
// invoke the constructor, memory is already allocated
new (tensors + i) TensorWrapper(matList[i], state);
}
}
std::vector<cv::cuda::GpuMat> TensorArray::toGpuMatList() {
std::vector<cuda::GpuMat> retval(this->size);
for (int i = 0; i < this->size; ++i) {
// TODO: avoid temporary object
retval[i] = this->tensors[i].toGpuMat();
}
return retval;
}
/************* Fake "custom memory stack impl for OpenCV" to use cutorch streams *************/
FakeDefaultDeviceInitializer initializer;
unsigned char* FakeMemoryStack::requestMemory(size_t size)
{
const size_t freeMem = dataend - tip;
if (size > freeMem)
return 0;
unsigned char* ptr = tip;
tip += size;
#if !defined(NDEBUG)
allocations.push_back(size);
#endif
return ptr;
}
void FakeMemoryStack::returnMemory(unsigned char* ptr)
{
CV_DbgAssert( ptr >= datastart && ptr < dataend );
#if !defined(NDEBUG)
const size_t allocSize = tip - ptr;
CV_Assert( allocSize == allocations.back() );
allocations.pop_back();
#endif
tip = ptr;
}
void FakeMemoryPool::initilizeImpl()
{
const size_t totalSize = stackSize_ * stackCount_;
if (totalSize > 0)
{
cudaError_t err = cudaMalloc(&mem_, totalSize);
if (err != cudaSuccess)
return;
stacks_.resize(stackCount_);
unsigned char* ptr = mem_;
for (int i = 0; i < stackCount_; ++i)
{
stacks_[i].datastart = ptr;
stacks_[i].dataend = ptr + stackSize_;
stacks_[i].tip = ptr;
stacks_[i].isFree = true;
stacks_[i].pool = this;
ptr += stackSize_;
}
initialized_ = true;
}
}
FakeMemoryStack* FakeMemoryPool::getFreeMemStack()
{
cv::AutoLock lock(mtx_);
if (!initialized_)
initilizeImpl();
if (!mem_)
return 0;
for (int i = 0; i < stackCount_; ++i)
{
if (stacks_[i].isFree)
{
stacks_[i].isFree = false;
return &stacks_[i];
}
}
return 0;
}
FakeDefaultDeviceInitializer::FakeDefaultDeviceInitializer() {}
FakeDefaultDeviceInitializer::~FakeDefaultDeviceInitializer() {
streams_.clear();
for (size_t i = 0; i < pools_.size(); ++i)
{
cudaSetDevice(static_cast<int>(i));
pools_[i].release();
}
pools_.clear();
}
FakeStream & FakeDefaultDeviceInitializer::getNullStream(int deviceId) {
cv::AutoLock lock(streams_mtx_);
if (streams_.empty())
{
int deviceCount = cuda::getCudaEnabledDeviceCount();
if (deviceCount > 0)
streams_.resize(deviceCount);
}
CV_DbgAssert( deviceId >= 0 && deviceId < static_cast<int>(streams_.size()) );
if (streams_[deviceId].empty())
{
cudaStream_t stream = NULL;
cv::Ptr<FakeStreamImpl> impl = cv::makePtr<FakeStreamImpl>(stream);
streams_[deviceId] = cv::Ptr<FakeStream>(new FakeStream(impl));
}
return *streams_[deviceId];
}
FakeMemoryPool* FakeDefaultDeviceInitializer::getMemoryPool(int deviceId) {
cv::AutoLock lock(pools_mtx_);
if (pools_.empty())
{
int deviceCount = cuda::getCudaEnabledDeviceCount();
if (deviceCount > 0)
pools_.resize(deviceCount);
}
CV_DbgAssert( deviceId >= 0 && deviceId < static_cast<int>(pools_.size()) );
return &pools_[deviceId];
}
FakeStackAllocator::FakeStackAllocator(cudaStream_t stream) : stream_(stream), memStack_(0) {
const int deviceId = cuda::getDevice();
memStack_ = initializer.getMemoryPool(deviceId)->getFreeMemStack();
cuda::DeviceInfo devInfo(deviceId);
alignment_ = devInfo.textureAlignment();
}
bool FakeStackAllocator::allocate(cuda::GpuMat* mat, int rows, int cols, size_t elemSize) {
if (memStack_ == 0)
return false;
size_t pitch, memSize;
if (rows > 1 && cols > 1)
{
pitch = alignUp(cols * elemSize, alignment_);
memSize = pitch * rows;
}
else
{
// Single row or single column must be continuous
pitch = elemSize * cols;
memSize = alignUp(elemSize * cols * rows, 64);
}
unsigned char* ptr = memStack_->requestMemory(memSize);
if (ptr == 0)
return false;
mat->data = ptr;
mat->step = pitch;
mat->refcount = (int*) cv::fastMalloc(sizeof(int));
return true;
}
void FakeStackAllocator::free(cuda::GpuMat* mat) {
if (memStack_ == 0)
return;
memStack_->returnMemory(mat->datastart);
cv::fastFree(mat->refcount);
}
cuda::Stream & prepareStream(cutorchInfo info) {
cuda::setDevice(info.deviceID - 1);
fakeStream.impl_ = cv::makePtr<FakeStreamImpl>(THCState_getCurrentStream(info.state));
return *reinterpret_cast<cuda::Stream *>(&fakeStream);
}