-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtools.h
93 lines (78 loc) · 2.43 KB
/
tools.h
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
#include <stdexcept>
#include <iostream>
#include "NvInfer.h"
#include <cuda_runtime.h>
#include <memory>
void checkCudaErrors(cudaError_t err)
{
if (err != cudaSuccess)
throw std::runtime_error(cudaGetErrorName(err));
}
constexpr int divUp(int a, int b) { return (a + b - 1) / b; }
// RAII helpers to automatically manage memory resource and TensorRT objects.
template <typename T>
struct TrtDeleter
{
void operator()(T* p) noexcept { p->destroy(); }
};
template <typename T>
struct CuMemDeleter
{
void operator()(T* p) noexcept { checkCudaErrors(cudaFree(p)); }
};
template <typename T, template <typename> typename DeleterType = TrtDeleter>
using UniqPtr = std::unique_ptr<T, DeleterType<T>>;
template <typename T>
UniqPtr<T, CuMemDeleter> mallocCudaMem(size_t nbElems)
{
T* ptr = nullptr;
checkCudaErrors(cudaMalloc((void**)&ptr, sizeof(T) * nbElems));
return UniqPtr<T, CuMemDeleter>{ptr};
}
// Logger for TensorRT info/warning/errors
class Logger : public nvinfer1::ILogger
{
public:
Logger(Severity severity = Severity::kWARNING)
: reportableSeverity(severity)
{
}
void log(Severity severity, const char* msg) override
{
// suppress messages with severity enum value greater than the reportable
if (severity > reportableSeverity)
return;
switch (severity)
{
case Severity::kINTERNAL_ERROR: std::cerr << "INTERNAL_ERROR: "; break;
case Severity::kERROR: std::cerr << "ERROR: "; break;
case Severity::kWARNING: std::cerr << "WARNING: "; break;
case Severity::kINFO: std::cerr << "INFO: "; break;
default: std::cerr << "UNKNOWN: "; break;
}
std::cerr << msg << std::endl;
}
Severity reportableSeverity;
};
extern Logger gLogger;
struct StreamDeleter
{
void operator()(CUstream_st* stream) noexcept {
checkCudaErrors(cudaStreamDestroy(stream));
}
};
std::unique_ptr<CUstream_st, StreamDeleter> makeCudaStream(int flags = cudaStreamDefault) {
cudaStream_t stream;
checkCudaErrors(cudaStreamCreateWithFlags(&stream, flags));
return std::unique_ptr<CUstream_st, StreamDeleter>{ stream };
}
struct EventDeleter {
void operator()(CUevent_st* event) noexcept {
checkCudaErrors(cudaEventDestroy(event));
}
};
std::unique_ptr<CUevent_st, EventDeleter> makeCudaEvent(int flags = cudaEventDefault) {
cudaEvent_t event;
checkCudaErrors(cudaEventCreateWithFlags(&event, flags));
return std::unique_ptr<CUevent_st, EventDeleter>{event};
}