yolov7end2end_trt.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. // Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "ultra_infer/vision/detection/contrib/yolov7end2end_trt.h"
  15. #include "ultra_infer/utils/perf.h"
  16. #include "ultra_infer/vision/utils/utils.h"
  17. #ifdef WITH_GPU
  18. #include "ultra_infer/vision/utils/cuda_utils.h"
  19. #endif // WITH_GPU
  20. namespace ultra_infer {
  21. namespace vision {
  22. namespace detection {
  23. void YOLOv7End2EndTRT::LetterBox(Mat *mat, const std::vector<int> &size,
  24. const std::vector<float> &color, bool _auto,
  25. bool scale_fill, bool scale_up, int stride) {
  26. float scale =
  27. std::min(size[1] * 1.0 / mat->Height(), size[0] * 1.0 / mat->Width());
  28. if (!scale_up) {
  29. scale = std::min(scale, 1.0f);
  30. }
  31. int resize_h = int(round(mat->Height() * scale));
  32. int resize_w = int(round(mat->Width() * scale));
  33. int pad_w = size[0] - resize_w;
  34. int pad_h = size[1] - resize_h;
  35. if (_auto) {
  36. pad_h = pad_h % stride;
  37. pad_w = pad_w % stride;
  38. } else if (scale_fill) {
  39. pad_h = 0;
  40. pad_w = 0;
  41. resize_h = size[1];
  42. resize_w = size[0];
  43. }
  44. if (resize_h != mat->Height() || resize_w != mat->Width()) {
  45. Resize::Run(mat, resize_w, resize_h);
  46. }
  47. if (pad_h > 0 || pad_w > 0) {
  48. float half_h = pad_h * 1.0 / 2;
  49. int top = int(round(half_h - 0.1));
  50. int bottom = int(round(half_h + 0.1));
  51. float half_w = pad_w * 1.0 / 2;
  52. int left = int(round(half_w - 0.1));
  53. int right = int(round(half_w + 0.1));
  54. Pad::Run(mat, top, bottom, left, right, color);
  55. }
  56. }
  57. YOLOv7End2EndTRT::YOLOv7End2EndTRT(const std::string &model_file,
  58. const std::string &params_file,
  59. const RuntimeOption &custom_option,
  60. const ModelFormat &model_format) {
  61. if (model_format == ModelFormat::ONNX) {
  62. valid_cpu_backends = {}; // NO CPU
  63. valid_gpu_backends = {Backend::TRT}; // NO ORT
  64. } else {
  65. valid_cpu_backends = {Backend::PDINFER};
  66. valid_gpu_backends = {Backend::PDINFER};
  67. }
  68. runtime_option = custom_option;
  69. runtime_option.model_format = model_format;
  70. runtime_option.model_file = model_file;
  71. if (runtime_option.device != Device::GPU) {
  72. FDWARNING << runtime_option.device
  73. << " is not support for YOLOv7End2EndTRT,"
  74. << "will fallback to Device::GPU." << std::endl;
  75. runtime_option.device = Device::GPU;
  76. }
  77. if (runtime_option.backend != Backend::UNKNOWN) {
  78. if (runtime_option.backend != Backend::TRT) {
  79. FDWARNING << runtime_option.backend
  80. << " is not support for YOLOv7End2EndTRT,"
  81. << "will fallback to Backend::TRT." << std::endl;
  82. runtime_option.backend = Backend::TRT;
  83. }
  84. }
  85. #ifdef WITH_GPU
  86. cudaSetDevice(runtime_option.device_id);
  87. cudaStream_t stream;
  88. CUDA_CHECK(cudaStreamCreate(&stream));
  89. cuda_stream_ = reinterpret_cast<void *>(stream);
  90. runtime_option.SetExternalStream(cuda_stream_);
  91. #endif // WITH_GPU
  92. initialized = Initialize();
  93. }
  94. bool YOLOv7End2EndTRT::Initialize() {
  95. // parameters for preprocess
  96. size = {640, 640};
  97. padding_value = {114.0, 114.0, 114.0};
  98. is_mini_pad = false;
  99. is_no_pad = false;
  100. is_scale_up = false;
  101. stride = 32;
  102. reused_input_tensors_.resize(1);
  103. if (!InitRuntime()) {
  104. FDERROR << "Failed to initialize ultra_infer backend." << std::endl;
  105. return false;
  106. }
  107. // Check if the input shape is dynamic after Runtime already initialized,
  108. // Note that, We need to force is_mini_pad 'false' to keep static
  109. // shape after padding (LetterBox) when the is_dynamic_shape is 'false'.
  110. is_dynamic_input_ = false;
  111. auto shape = InputInfoOfRuntime(0).shape;
  112. for (int i = 0; i < shape.size(); ++i) {
  113. // if height or width is dynamic
  114. if (i >= 2 && shape[i] <= 0) {
  115. is_dynamic_input_ = true;
  116. break;
  117. }
  118. }
  119. if (!is_dynamic_input_) {
  120. is_mini_pad = false;
  121. }
  122. return true;
  123. }
  124. YOLOv7End2EndTRT::~YOLOv7End2EndTRT() {
  125. #ifdef WITH_GPU
  126. if (use_cuda_preprocessing_) {
  127. CUDA_CHECK(cudaFreeHost(input_img_cuda_buffer_host_));
  128. CUDA_CHECK(cudaFree(input_img_cuda_buffer_device_));
  129. CUDA_CHECK(cudaFree(input_tensor_cuda_buffer_device_));
  130. CUDA_CHECK(cudaStreamDestroy(reinterpret_cast<cudaStream_t>(cuda_stream_)));
  131. }
  132. #endif // WITH_GPU
  133. }
  134. bool YOLOv7End2EndTRT::Preprocess(
  135. Mat *mat, FDTensor *output,
  136. std::map<std::string, std::array<float, 2>> *im_info) {
  137. float ratio = std::min(size[1] * 1.0f / static_cast<float>(mat->Height()),
  138. size[0] * 1.0f / static_cast<float>(mat->Width()));
  139. if (std::fabs(ratio - 1.0f) > 1e-06) {
  140. int interp = cv::INTER_AREA;
  141. if (ratio > 1.0) {
  142. interp = cv::INTER_LINEAR;
  143. }
  144. int resize_h = int(mat->Height() * ratio);
  145. int resize_w = int(mat->Width() * ratio);
  146. Resize::Run(mat, resize_w, resize_h, -1, -1, interp);
  147. }
  148. YOLOv7End2EndTRT::LetterBox(mat, size, padding_value, is_mini_pad, is_no_pad,
  149. is_scale_up, stride);
  150. BGR2RGB::Run(mat);
  151. std::vector<float> alpha = {1.0f / 255.0f, 1.0f / 255.0f, 1.0f / 255.0f};
  152. std::vector<float> beta = {0.0f, 0.0f, 0.0f};
  153. Convert::Run(mat, alpha, beta);
  154. (*im_info)["output_shape"] = {static_cast<float>(mat->Height()),
  155. static_cast<float>(mat->Width())};
  156. HWC2CHW::Run(mat);
  157. Cast::Run(mat, "float");
  158. mat->ShareWithTensor(output);
  159. output->shape.insert(output->shape.begin(), 1); // reshape to n, c, h, w
  160. return true;
  161. }
  162. void YOLOv7End2EndTRT::UseCudaPreprocessing(int max_image_size) {
  163. #ifdef WITH_GPU
  164. use_cuda_preprocessing_ = true;
  165. is_scale_up = true;
  166. if (input_img_cuda_buffer_host_ == nullptr) {
  167. // prepare input data cache in GPU pinned memory
  168. CUDA_CHECK(cudaMallocHost((void **)&input_img_cuda_buffer_host_,
  169. max_image_size * 3));
  170. // prepare input data cache in GPU device memory
  171. CUDA_CHECK(cudaMalloc((void **)&input_img_cuda_buffer_device_,
  172. max_image_size * 3));
  173. CUDA_CHECK(cudaMalloc((void **)&input_tensor_cuda_buffer_device_,
  174. 3 * size[0] * size[1] * sizeof(float)));
  175. }
  176. #else
  177. FDWARNING << "The UltraInfer didn't compile with WITH_GPU=ON." << std::endl;
  178. use_cuda_preprocessing_ = false;
  179. #endif
  180. }
  181. bool YOLOv7End2EndTRT::CudaPreprocess(
  182. Mat *mat, FDTensor *output,
  183. std::map<std::string, std::array<float, 2>> *im_info) {
  184. #ifdef WITH_GPU
  185. if (is_mini_pad != false || is_no_pad != false || is_scale_up != true) {
  186. FDERROR << "Preprocessing with CUDA is only available when the arguments "
  187. "satisfy (is_mini_pad=false, is_no_pad=false, is_scale_up=true)."
  188. << std::endl;
  189. return false;
  190. }
  191. // Record the shape of image and the shape of preprocessed image
  192. (*im_info)["input_shape"] = {static_cast<float>(mat->Height()),
  193. static_cast<float>(mat->Width())};
  194. (*im_info)["output_shape"] = {static_cast<float>(mat->Height()),
  195. static_cast<float>(mat->Width())};
  196. cudaStream_t stream = reinterpret_cast<cudaStream_t>(cuda_stream_);
  197. int src_img_buf_size = mat->Height() * mat->Width() * mat->Channels();
  198. memcpy(input_img_cuda_buffer_host_, mat->Data(), src_img_buf_size);
  199. CUDA_CHECK(cudaMemcpyAsync(input_img_cuda_buffer_device_,
  200. input_img_cuda_buffer_host_, src_img_buf_size,
  201. cudaMemcpyHostToDevice, stream));
  202. utils::CudaYoloPreprocess(input_img_cuda_buffer_device_, mat->Width(),
  203. mat->Height(), input_tensor_cuda_buffer_device_,
  204. size[0], size[1], padding_value, stream);
  205. // Record output shape of preprocessed image
  206. (*im_info)["output_shape"] = {static_cast<float>(size[0]),
  207. static_cast<float>(size[1])};
  208. output->SetExternalData({mat->Channels(), size[0], size[1]}, FDDataType::FP32,
  209. input_tensor_cuda_buffer_device_);
  210. output->device = Device::GPU;
  211. output->shape.insert(output->shape.begin(), 1); // reshape to n, c, h, w
  212. return true;
  213. #else
  214. FDERROR << "CUDA src code was not enabled." << std::endl;
  215. return false;
  216. #endif // WITH_GPU
  217. }
  218. bool YOLOv7End2EndTRT::Postprocess(
  219. std::vector<FDTensor> &infer_results, DetectionResult *result,
  220. const std::map<std::string, std::array<float, 2>> &im_info,
  221. float conf_threshold) {
  222. FDASSERT(infer_results.size() == 4, "Output tensor size must be 4.");
  223. FDTensor &num_tensor = infer_results.at(0); // INT32
  224. FDTensor &boxes_tensor = infer_results.at(1); // FLOAT
  225. FDTensor &scores_tensor = infer_results.at(2); // FLOAT
  226. FDTensor &classes_tensor = infer_results.at(3); // INT32
  227. FDASSERT(num_tensor.dtype == FDDataType::INT32,
  228. "The dtype of num_dets must be INT32.");
  229. FDASSERT(boxes_tensor.dtype == FDDataType::FP32,
  230. "The dtype of det_boxes_tensor must be FP32.");
  231. FDASSERT(scores_tensor.dtype == FDDataType::FP32,
  232. "The dtype of det_scores_tensor must be FP32.");
  233. FDASSERT(classes_tensor.dtype == FDDataType::INT32,
  234. "The dtype of det_classes_tensor must be INT32.");
  235. FDASSERT(num_tensor.shape[0] == 1, "Only support batch=1 now.");
  236. // post-process for end2end yolov7 after trt nms.
  237. float *boxes_data = static_cast<float *>(boxes_tensor.Data()); // (1,100,4)
  238. float *scores_data = static_cast<float *>(scores_tensor.Data()); // (1,100)
  239. int32_t *classes_data =
  240. static_cast<int32_t *>(classes_tensor.Data()); // (1,100)
  241. int32_t num_dets_after_trt_nms = static_cast<int32_t *>(num_tensor.Data())[0];
  242. if (num_dets_after_trt_nms == 0) {
  243. return true;
  244. }
  245. result->Clear();
  246. result->Reserve(num_dets_after_trt_nms);
  247. for (size_t i = 0; i < num_dets_after_trt_nms; ++i) {
  248. float confidence = scores_data[i];
  249. if (confidence <= conf_threshold) {
  250. continue;
  251. }
  252. int32_t label_id = classes_data[i];
  253. float x1 = boxes_data[(i * 4) + 0];
  254. float y1 = boxes_data[(i * 4) + 1];
  255. float x2 = boxes_data[(i * 4) + 2];
  256. float y2 = boxes_data[(i * 4) + 3];
  257. result->boxes.emplace_back(std::array<float, 4>{x1, y1, x2, y2});
  258. result->label_ids.push_back(label_id);
  259. result->scores.push_back(confidence);
  260. }
  261. if (result->boxes.size() == 0) {
  262. return true;
  263. }
  264. // scale the boxes to the origin image shape
  265. auto iter_out = im_info.find("output_shape");
  266. auto iter_ipt = im_info.find("input_shape");
  267. FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(),
  268. "Cannot find input_shape or output_shape from im_info.");
  269. float out_h = iter_out->second[0];
  270. float out_w = iter_out->second[1];
  271. float ipt_h = iter_ipt->second[0];
  272. float ipt_w = iter_ipt->second[1];
  273. float scale = std::min(out_h / ipt_h, out_w / ipt_w);
  274. float pad_h = (out_h - ipt_h * scale) / 2.0f;
  275. float pad_w = (out_w - ipt_w * scale) / 2.0f;
  276. if (is_mini_pad) {
  277. pad_h = static_cast<float>(static_cast<int>(pad_h) % stride);
  278. pad_w = static_cast<float>(static_cast<int>(pad_w) % stride);
  279. }
  280. for (size_t i = 0; i < result->boxes.size(); ++i) {
  281. int32_t label_id = (result->label_ids)[i];
  282. result->boxes[i][0] = std::max((result->boxes[i][0] - pad_w) / scale, 0.0f);
  283. result->boxes[i][1] = std::max((result->boxes[i][1] - pad_h) / scale, 0.0f);
  284. result->boxes[i][2] = std::max((result->boxes[i][2] - pad_w) / scale, 0.0f);
  285. result->boxes[i][3] = std::max((result->boxes[i][3] - pad_h) / scale, 0.0f);
  286. result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f);
  287. result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f);
  288. result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f);
  289. result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f);
  290. }
  291. return true;
  292. }
  293. bool YOLOv7End2EndTRT::Predict(cv::Mat *im, DetectionResult *result,
  294. float conf_threshold) {
  295. Mat mat(*im);
  296. std::map<std::string, std::array<float, 2>> im_info;
  297. // Record the shape of image and the shape of preprocessed image
  298. im_info["input_shape"] = {static_cast<float>(mat.Height()),
  299. static_cast<float>(mat.Width())};
  300. im_info["output_shape"] = {static_cast<float>(mat.Height()),
  301. static_cast<float>(mat.Width())};
  302. if (use_cuda_preprocessing_) {
  303. if (!CudaPreprocess(&mat, &reused_input_tensors_[0], &im_info)) {
  304. FDERROR << "Failed to preprocess input image." << std::endl;
  305. return false;
  306. }
  307. } else {
  308. if (!Preprocess(&mat, &reused_input_tensors_[0], &im_info)) {
  309. FDERROR << "Failed to preprocess input image." << std::endl;
  310. return false;
  311. }
  312. }
  313. reused_input_tensors_[0].name = InputInfoOfRuntime(0).name;
  314. if (!Infer()) {
  315. FDERROR << "Failed to inference." << std::endl;
  316. return false;
  317. }
  318. if (!Postprocess(reused_output_tensors_, result, im_info, conf_threshold)) {
  319. FDERROR << "Failed to post process." << std::endl;
  320. return false;
  321. }
  322. return true;
  323. }
  324. } // namespace detection
  325. } // namespace vision
  326. } // namespace ultra_infer