forked from Monday-Leo/YOLOv8_Tensorrt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfer.cu
445 lines (366 loc) · 12.4 KB
/
infer.cu
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
#include <NvInfer.h>
#include <cuda_runtime.h>
#include <stdarg.h>
#include <fstream>
#include <numeric>
#include <sstream>
#include <unordered_map>
#include "infer.hpp"
#include "Windows.h"
namespace trt {
using namespace std;
using namespace nvinfer1;
#define checkRuntime(call) \
do { \
auto ___call__ret_code__ = (call); \
if (___call__ret_code__ != cudaSuccess) { \
INFO("CUDA Runtime error💥 %s # %s, code = %s [ %d ]", #call, \
cudaGetErrorString(___call__ret_code__), cudaGetErrorName(___call__ret_code__), \
___call__ret_code__); \
abort(); \
} \
} while (0)
#define checkKernel(...) \
do { \
{ (__VA_ARGS__); } \
checkRuntime(cudaPeekAtLastError()); \
} while (0)
#define Assert(op) \
do { \
bool cond = !(!(op)); \
if (!cond) { \
INFO("Assert failed, " #op); \
abort(); \
} \
} while (0)
#define Assertf(op, ...) \
do { \
bool cond = !(!(op)); \
if (!cond) { \
INFO("Assert failed, " #op " : " __VA_ARGS__); \
abort(); \
} \
} while (0)
static string file_name(const string &path, bool include_suffix) {
if (path.empty()) return "";
int p = path.rfind('/');
int e = path.rfind('\\');
p = max(p, e);
p += 1;
// include suffix
if (include_suffix) return path.substr(p);
int u = path.rfind('.');
if (u == -1) return path.substr(p);
if (u <= p) u = path.size();
return path.substr(p, u - p);
}
void __log_func(const char *file, int line, const char *fmt, ...) {
va_list vl;
va_start(vl, fmt);
char buffer[2048];
string filename = file_name(file, true);
int n = snprintf(buffer, sizeof(buffer), "[%s:%d]: ", filename.c_str(), line);
vsnprintf(buffer + n, sizeof(buffer) - n, fmt, vl);
fprintf(stdout, "%s\n", buffer);
}
static std::string format_shape(const Dims &shape) {
stringstream output;
char buf[64];
const char *fmts[] = {"%d", "x%d"};
for (int i = 0; i < shape.nbDims; ++i) {
snprintf(buf, sizeof(buf), fmts[i != 0], shape.d[i]);
output << buf;
}
return output.str();
}
Timer::Timer() {
checkRuntime(cudaEventCreate((cudaEvent_t *)&start_));
checkRuntime(cudaEventCreate((cudaEvent_t *)&stop_));
}
Timer::~Timer() {
checkRuntime(cudaEventDestroy((cudaEvent_t)start_));
checkRuntime(cudaEventDestroy((cudaEvent_t)stop_));
}
void Timer::start(void *stream) {
stream_ = stream;
checkRuntime(cudaEventRecord((cudaEvent_t)start_, (cudaStream_t)stream_));
}
float Timer::stop(const char *prefix, bool print) {
checkRuntime(cudaEventRecord((cudaEvent_t)stop_, (cudaStream_t)stream_));
checkRuntime(cudaEventSynchronize((cudaEvent_t)stop_));
float latency = 0;
checkRuntime(cudaEventElapsedTime(&latency, (cudaEvent_t)start_, (cudaEvent_t)stop_));
if (print) {
printf("[%s]: %.5f ms\n", prefix, latency);
}
return latency;
}
BaseMemory::BaseMemory(void *cpu, size_t cpu_bytes, void *gpu, size_t gpu_bytes) {
reference(cpu, cpu_bytes, gpu, gpu_bytes);
}
void BaseMemory::reference(void *cpu, size_t cpu_bytes, void *gpu, size_t gpu_bytes) {
release();
if (cpu == nullptr || cpu_bytes == 0) {
cpu = nullptr;
cpu_bytes = 0;
}
if (gpu == nullptr || gpu_bytes == 0) {
gpu = nullptr;
gpu_bytes = 0;
}
this->cpu_ = cpu;
this->cpu_capacity_ = cpu_bytes;
this->cpu_bytes_ = cpu_bytes;
this->gpu_ = gpu;
this->gpu_capacity_ = gpu_bytes;
this->gpu_bytes_ = gpu_bytes;
this->owner_cpu_ = !(cpu && cpu_bytes > 0);
this->owner_gpu_ = !(gpu && gpu_bytes > 0);
}
BaseMemory::~BaseMemory() { release(); }
void *BaseMemory::gpu_realloc(size_t bytes) {
if (gpu_capacity_ < bytes) {
release_gpu();
gpu_capacity_ = bytes;
checkRuntime(cudaMalloc(&gpu_, bytes));
// checkRuntime(cudaMemset(gpu_, 0, size));
}
gpu_bytes_ = bytes;
return gpu_;
}
void *BaseMemory::cpu_realloc(size_t bytes) {
if (cpu_capacity_ < bytes) {
release_cpu();
cpu_capacity_ = bytes;
checkRuntime(cudaMallocHost(&cpu_, bytes));
Assert(cpu_ != nullptr);
// memset(cpu_, 0, size);
}
cpu_bytes_ = bytes;
return cpu_;
}
void BaseMemory::release_cpu() {
if (cpu_) {
if (owner_cpu_) {
checkRuntime(cudaFreeHost(cpu_));
}
cpu_ = nullptr;
}
cpu_capacity_ = 0;
cpu_bytes_ = 0;
}
void BaseMemory::release_gpu() {
if (gpu_) {
if (owner_gpu_) {
checkRuntime(cudaFree(gpu_));
}
gpu_ = nullptr;
}
gpu_capacity_ = 0;
gpu_bytes_ = 0;
}
void BaseMemory::release() {
release_cpu();
release_gpu();
}
class __native_nvinfer_logger : public ILogger {
public:
virtual void log(Severity severity, const char *msg) noexcept override {
if (severity == Severity::kINTERNAL_ERROR) {
INFO("NVInfer INTERNAL_ERROR: %s", msg);
abort();
} else if (severity == Severity::kERROR) {
INFO("NVInfer: %s", msg);
}
// else if (severity == Severity::kWARNING) {
// INFO("NVInfer: %s", msg);
// }
// else if (severity == Severity::kINFO) {
// INFO("NVInfer: %s", msg);
// }
// else {
// INFO("%s", msg);
// }
}
};
static __native_nvinfer_logger gLogger;
template <typename _T>
static void destroy_nvidia_pointer(_T *ptr) {
if (ptr) ptr->destroy();
}
static std::vector<uint8_t> load_file(const string &file) {
ifstream in(file, ios::in | ios::binary);
if (!in.is_open()) return {};
in.seekg(0, ios::end);
size_t length = in.tellg();
std::vector<uint8_t> data;
if (length > 0) {
in.seekg(0, ios::beg);
data.resize(length);
in.read((char *)&data[0], length);
}
in.close();
return data;
}
class __native_engine_context {
public:
virtual ~__native_engine_context() { destroy(); }
bool construct(const void *pdata, size_t size) {
destroy();
if (pdata == nullptr || size == 0) return false;
runtime_ = shared_ptr<IRuntime>(createInferRuntime(gLogger), destroy_nvidia_pointer<IRuntime>);
if (runtime_ == nullptr) return false;
engine_ = shared_ptr<ICudaEngine>(runtime_->deserializeCudaEngine(pdata, size, nullptr),
destroy_nvidia_pointer<ICudaEngine>);
if (engine_ == nullptr) return false;
context_ = shared_ptr<IExecutionContext>(engine_->createExecutionContext(),
destroy_nvidia_pointer<IExecutionContext>);
return context_ != nullptr;
}
private:
void destroy() {
context_.reset();
engine_.reset();
runtime_.reset();
}
public:
shared_ptr<IExecutionContext> context_;
shared_ptr<ICudaEngine> engine_;
shared_ptr<IRuntime> runtime_ = nullptr;
};
class InferImpl : public Infer {
public:
shared_ptr<__native_engine_context> context_;
unordered_map<string, int> binding_name_to_index_;
virtual ~InferImpl() = default;
bool construct(const void *data, size_t size) {
context_ = make_shared<__native_engine_context>();
if (!context_->construct(data, size)) {
return false;
}
setup();
return true;
}
bool load(const string &file) {
auto data = load_file(file);
if (data.empty()) {
INFO("An empty file has been loaded. Please confirm your file path: %s", file.c_str());
return false;
}
return this->construct(data.data(), data.size());
}
void setup() {
auto engine = this->context_->engine_;
int nbBindings = engine->getNbBindings();
binding_name_to_index_.clear();
for (int i = 0; i < nbBindings; ++i) {
const char *bindingName = engine->getBindingName(i);
binding_name_to_index_[bindingName] = i;
}
}
virtual int index(const std::string &name) override {
auto iter = binding_name_to_index_.find(name);
Assertf(iter != binding_name_to_index_.end(), "Can not found the binding name: %s",
name.c_str());
return iter->second;
}
virtual bool forward(const std::vector<void *> &bindings, void *stream,
void *input_consum_event) override {
return this->context_->context_->enqueueV2((void**)bindings.data(), (cudaStream_t)stream,
(cudaEvent_t *)input_consum_event);
}
virtual std::vector<int> run_dims(const std::string &name) override {
return run_dims(index(name));
}
virtual std::vector<int> run_dims(int ibinding) override {
auto dim = this->context_->context_->getBindingDimensions(ibinding);
return std::vector<int>(dim.d, dim.d + dim.nbDims);
}
virtual std::vector<int> static_dims(const std::string &name) override {
return static_dims(index(name));
}
virtual std::vector<int> static_dims(int ibinding) override {
auto dim = this->context_->engine_->getBindingDimensions(ibinding);
return std::vector<int>(dim.d, dim.d + dim.nbDims);
}
virtual int num_bindings() override { return this->context_->engine_->getNbBindings(); }
virtual bool is_input(int ibinding) override {
return this->context_->engine_->bindingIsInput(ibinding);
}
virtual bool set_run_dims(const std::string &name, const std::vector<int> &dims) override {
return this->set_run_dims(index(name), dims);
}
virtual bool set_run_dims(int ibinding, const std::vector<int> &dims) override {
Dims d;
memcpy(d.d, dims.data(), sizeof(int) * dims.size());
d.nbDims = dims.size();
return this->context_->context_->setBindingDimensions(ibinding, d);
}
virtual int numel(const std::string &name) override { return numel(index(name)); }
virtual int numel(int ibinding) override {
auto dim = this->context_->context_->getBindingDimensions(ibinding);
return std::accumulate(dim.d, dim.d + dim.nbDims, 1, std::multiplies<int>());
}
virtual DType dtype(const std::string &name) override { return dtype(index(name)); }
virtual DType dtype(int ibinding) override {
return (DType)this->context_->engine_->getBindingDataType(ibinding);
}
virtual bool has_dynamic_dim() override {
// check if any input or output bindings have dynamic shapes
// code from ChatGPT
int numBindings = this->context_->engine_->getNbBindings();
for (int i = 0; i < numBindings; ++i) {
nvinfer1::Dims dims = this->context_->engine_->getBindingDimensions(i);
for (int j = 0; j < dims.nbDims; ++j) {
if (dims.d[j] == -1) return true;
}
}
return false;
}
virtual void print() override {
INFO("Infer %p [%s]", this, has_dynamic_dim() ? "DynamicShape" : "StaticShape");
int num_input = 0;
int num_output = 0;
auto engine = this->context_->engine_;
for (int i = 0; i < engine->getNbBindings(); ++i) {
if (engine->bindingIsInput(i))
num_input++;
else
num_output++;
}
INFO("Inputs: %d", num_input);
for (int i = 0; i < num_input; ++i) {
auto name = engine->getBindingName(i);
auto dim = engine->getBindingDimensions(i);
INFO("\t%d.%s : shape {%s}", i, name, format_shape(dim).c_str());
}
INFO("Outputs: %d", num_output);
for (int i = 0; i < num_output; ++i) {
auto name = engine->getBindingName(i + num_input);
auto dim = engine->getBindingDimensions(i + num_input);
INFO("\t%d.%s : shape {%s}", i, name, format_shape(dim).c_str());
}
}
};
Infer *loadraw(const std::string &file) {
InferImpl *impl = new InferImpl();
if (!impl->load(file)) {
delete impl;
impl = nullptr;
}
return impl;
}
std::shared_ptr<Infer> load(const std::string &file) {
return std::shared_ptr<InferImpl>((InferImpl *)loadraw(file));
}
std::string format_shape(const std::vector<int> &shape) {
stringstream output;
char buf[64];
const char *fmts[] = {"%d", "x%d"};
for (int i = 0; i < (int)shape.size(); ++i) {
snprintf(buf, sizeof(buf), fmts[i != 0], shape[i]);
output << buf;
}
return output.str();
}
}; // namespace trt