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
| class Cifar100CNN { private: std::string onnx_path; std::string engine_path;
TRTPtr<nvinfer1::ICudaEngine> engine; TRTPtr<TRTInference> inference;
float* input_buffer; float* output_buffer;
void* gpu_input; void* gpu_output;
void set_tensor_addresses();
void preprocess(std::vector<cv::Mat>::const_iterator input, size_t batch_size); void postprocess(std::vector<int>::iterator output, size_t batch_size); void infer(size_t batch_size); auto InputData(size_t batch_size); auto OutputData(size_t batch_size);
public: Cifar100CNN(std::string onnx_path, std::string engine_path, TRTLogger& logger, bool always_rebuild = false); ~Cifar100CNN() noexcept; std::vector<int> infer(const std::vector<cv::Mat>& input, size_t batch_size = 0); };
using InputImg = TensorSpec<32, 32, 3>; using OutputRes = TensorSpec<100>; using Mean = FloatArraySpec<0.5071f, 0.4865f, 0.4409f>; using Std = FloatArraySpec<0.2673f, 0.2564f, 0.2761f>; using ChannelMap = ChannelMapSpec<2, 1, 0>; using Cifar100Processor = ConvertHWC2CHW<InputImg, Mean, Std, ChannelMap>;
using BatchSize = TensorSpec<1, 64, 256>; using Input = TensorSpec<BatchSize::dims()[2], 3, 32, 32>; using Output = TensorSpec<BatchSize::dims()[2], 100>;
void Cifar100CNN::set_tensor_addresses() { inference->set_tensor_address("input", gpu_input); inference->set_tensor_address("output", gpu_output); }
void Cifar100CNN::preprocess(std::vector<cv::Mat>::const_iterator input, size_t batch_size) { size_t img_size = InputImg::total_size();
#pragma omp parallel for for (size_t i = 0; i < batch_size; ++i) { Cifar100Processor::process(*(input + i), input_buffer + i * img_size); } }
void Cifar100CNN::postprocess(std::vector<int>::iterator output, size_t batch_size) { size_t res_size = OutputRes::total_size();
#pragma omp parallel for for (size_t i = 0; i < batch_size; ++i) { float* output_buffer_idx = output_buffer + i * res_size; int class_id = std::distance( output_buffer_idx, std::max_element(output_buffer_idx, output_buffer_idx + res_size)); *(output + i) = class_id; } }
void Cifar100CNN::infer(size_t batch_size) { inference->infer([batch_size](nvinfer1::IExecutionContext* context) { context->setInputShape( "input", nvinfer1::Dims4 {(int64_t) batch_size, 3, 32, 32}); }); }
auto Cifar100CNN::InputData(size_t batch_size) { return cudaMemcpyAsync(gpu_input, input_buffer, sizeof(float) * InputImg::total_size() * batch_size, cudaMemcpyHostToDevice, inference->get_stream()); }
auto Cifar100CNN::OutputData(size_t batch_size) { return cudaMemcpyAsync(output_buffer, gpu_output, sizeof(float) * OutputRes::total_size() * batch_size, cudaMemcpyDeviceToHost, inference->get_stream()); }
Cifar100CNN::Cifar100CNN(std::string onnx_path, std::string engine_path, TRTLogger& logger, bool always_rebuild) : onnx_path(onnx_path), engine_path(engine_path) { auto builder = TRTModelBuilder(logger); if (always_rebuild || !(engine = builder.loadFromPlan(engine_path))) { engine = builder.buildFromOnnx( onnx_path, engine_path, [](nvinfer1::IBuilderConfig* config, nvinfer1::INetworkDefinition* network, nvinfer1::IBuilder* builder) { auto profile = builder->createOptimizationProfile(); const char* inputName = network->getInput(0)->getName(); auto batch_sizes = BatchSize::dims(); profile->setDimensions( inputName, nvinfer1::OptProfileSelector::kMIN, nvinfer1::Dims4 {(int64_t) batch_sizes[0], 3, 32, 32}); profile->setDimensions( inputName, nvinfer1::OptProfileSelector::kOPT, nvinfer1::Dims4 {(int64_t) batch_sizes[1], 3, 32, 32}); profile->setDimensions( inputName, nvinfer1::OptProfileSelector::kMAX, nvinfer1::Dims4 {(int64_t) batch_sizes[2], 3, 32, 32}); config->addOptimizationProfile(profile);
if (builder->platformHasFastFp16()) { config->setFlag(nvinfer1::BuilderFlag::kFP16); } }); } inference = TRTPtr<TRTInference>(new TRTInference(*engine));
cudaHostAlloc((void**) &input_buffer, sizeof(float) * Input::total_size(), cudaHostAllocDefault); cudaHostAlloc((void**) &output_buffer, sizeof(float) * Output::total_size(), cudaHostAllocDefault); cudaMalloc(&gpu_input, sizeof(float) * Input::total_size()); cudaMalloc(&gpu_output, sizeof(float) * Output::total_size());
set_tensor_addresses(); }
Cifar100CNN::~Cifar100CNN() noexcept { cudaFree(gpu_input); cudaFree(gpu_output); cudaFreeHost(input_buffer); cudaFreeHost(output_buffer); }
std::vector<int> Cifar100CNN::infer(const std::vector<cv::Mat>& input, size_t batch_size) { size_t input_size = input.size(); std::vector<int> res(input_size);
auto batch_sizes = BatchSize::dims(); if (batch_size == 0) { batch_size = batch_sizes[1]; } else if (batch_size > batch_sizes[2]) { batch_size = batch_sizes[2]; }
size_t batches = input_size / batch_size + (((input_size % batch_size) == 0) ? 0 : 1);
for (size_t i = 0; i < batches; ++i) { size_t cur_batch_size = std::min(batch_size, input_size - i * batch_size); preprocess(input.cbegin() + i * batch_size, cur_batch_size); InputData(cur_batch_size); infer(cur_batch_size); OutputData(cur_batch_size); cudaStreamSynchronize(inference->get_stream()); postprocess(res.begin() + i * batch_size, cur_batch_size);
std::cout << std::format("batch {} with size {} finished\n", i, cur_batch_size); }
return res; }
|