Merge with master, all tests passed

Signed-off-by: Micaela Verucchi <micaelaverucchi@gmail.com>
This commit is contained in:
Micaela Verucchi
2021-07-20 12:48:41 +02:00
73 changed files with 5207 additions and 305 deletions
+6
View File
@@ -12,5 +12,11 @@ build/
*.hdf5 *.hdf5
*.pk *.pk
*.table *.table
cmake-build-release/
demo/COCO_val2017 demo/COCO_val2017
demo/BDD100K_val demo/BDD100K_val
/.vs
cmake-build-minsizerel/*
scripts/COCO_val2017/*
scripts/COCO_val2017.zip
scripts/all_labels.txt
+25 -6
View File
@@ -1,8 +1,15 @@
cmake_minimum_required(VERSION 3.5) cmake_minimum_required(VERSION 3.15)
project (tkDNN) project (tkDNN)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fPIC -Wno-deprecated-declarations -Wno-unused-variable") if(UNIX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fPIC -Wno-deprecated-declarations -Wno-unused-variable ")
endif()
if(WIN32)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_FLAGS "/O2 /FS /EHsc")
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
endif(WIN32)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/tkDNN) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/tkDNN)
# project specific flags # project specific flags
@@ -10,7 +17,13 @@ if(DEBUG)
add_definitions(-DDEBUG) add_definitions(-DDEBUG)
endif() endif()
add_definitions(-DTKDNN_PATH="${CMAKE_CURRENT_SOURCE_DIR}") if(TKDNN_PATH)
message("SET TKDNN_PATH:"${TKDNN_PATH})
add_definitions(-DTKDNN_PATH="${TKDNN_PATH}")
else()
add_definitions(-DTKDNN_PATH="${CMAKE_CURRENT_SOURCE_DIR}")
endif()
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
# CUDA # CUDA
@@ -28,19 +41,21 @@ include_directories(${CUDNN_INCLUDE_DIR})
file(GLOB tkdnn_CUSRC "src/kernels/*.cu" "src/sorting.cu") file(GLOB tkdnn_CUSRC "src/kernels/*.cu" "src/sorting.cu")
cuda_include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include ${CUDA_INCLUDE_DIRS} ${CUDNN_INCLUDE_DIRS}) cuda_include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include ${CUDA_INCLUDE_DIRS} ${CUDNN_INCLUDE_DIRS})
cuda_add_library(kernels SHARED ${tkdnn_CUSRC}) cuda_add_library(kernels SHARED ${tkdnn_CUSRC})
target_link_libraries(kernels ${CUDA_CUBLAS_LIBRARIES})
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
# External Libraries # External Libraries
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
find_package(Eigen3 REQUIRED) find_package(Eigen3 REQUIRED)
message("Eigen DIR: " ${EIGEN3_INCLUDE_DIR})
include_directories(${EIGEN3_INCLUDE_DIR}) include_directories(${EIGEN3_INCLUDE_DIR})
find_package(OpenCV REQUIRED) find_package(OpenCV REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DOPENCV") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DOPENCV")
# gives problems in cross-compiling, probably malformed cmake config # gives problems in cross-compiling, probably malformed cmake config
#find_package(yaml-cpp REQUIRED) find_package(yaml-cpp REQUIRED)
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
# Build Libraries # Build Libraries
@@ -48,7 +63,7 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DOPENCV")
file(GLOB tkdnn_SRC "src/*.cpp") file(GLOB tkdnn_SRC "src/*.cpp")
set(tkdnn_LIBS kernels ${CUDA_LIBRARIES} ${CUDA_CUBLAS_LIBRARIES} ${CUDNN_LIBRARIES} ${OpenCV_LIBS} yaml-cpp) set(tkdnn_LIBS kernels ${CUDA_LIBRARIES} ${CUDA_CUBLAS_LIBRARIES} ${CUDNN_LIBRARIES} ${OpenCV_LIBS} yaml-cpp)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include ${CUDA_INCLUDE_DIRS} ${OPENCV_INCLUDE_DIRS} ${NVINFER_INCLUDES}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include ${CUDA_INCLUDE_DIRS} ${OPENCV_INCLUDE_DIRS} ${NVINFER_INCLUDES})
add_library(tkDNN SHARED ${tkdnn_SRC}) add_library(tkDNN SHARED ${tkdnn_SRC})
target_link_libraries(tkDNN ${tkdnn_LIBS}) target_link_libraries(tkDNN ${tkdnn_LIBS})
@@ -77,6 +92,7 @@ foreach(test_SRC ${darknet_SRC})
set(test_NAME test_${test_NAME}) set(test_NAME test_${test_NAME})
add_executable(${test_NAME} ${test_SRC}) add_executable(${test_NAME} ${test_SRC})
target_link_libraries(${test_NAME} tkDNN) target_link_libraries(${test_NAME} tkDNN)
install(TARGETS ${test_NAME} DESTINATION bin)
endforeach() endforeach()
# MOBILENET # MOBILENET
@@ -136,7 +152,10 @@ target_link_libraries(seg_demo tkDNN)
message("install dir:" ${CMAKE_INSTALL_PREFIX}) message("install dir:" ${CMAKE_INSTALL_PREFIX})
install(DIRECTORY include/ DESTINATION include/) install(DIRECTORY include/ DESTINATION include/)
install(TARGETS tkDNN kernels DESTINATION lib) install(TARGETS tkDNN kernels DESTINATION lib)
install(TARGETS test_simple test_mnist test_mnistRT test_rtinference demo map_demo DESTINATION bin)
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/cmake/" # source directory install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/cmake/" # source directory
DESTINATION "share/tkDNN/cmake/" # target directory DESTINATION "share/tkDNN/cmake/" # target directory
) )
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/tests/" # source directory
DESTINATION "share/tkDNN/tests" # target directory
)
+1
View File
@@ -0,0 +1 @@
1)error C2131 @ Yolo3Detection.cpp(97) -> expression doesnt evaluate to a constant caused to read of variable outside its lifetime
+178 -37
View File
@@ -1,44 +1,70 @@
# tkDNN # tkDNN
tkDNN is a Deep Neural Network library built with cuDNN and tensorRT primitives, specifically thought to work on NVIDIA Jetson Boards. It has been tested on TK1(branch cudnn2), TX1, TX2, AGX Xavier and several discrete GPU. tkDNN is a Deep Neural Network library built with cuDNN and tensorRT primitives, specifically thought to work on NVIDIA Jetson Boards. It has been tested on TK1(branch cudnn2), TX1, TX2, AGX Xavier, Nano and several discrete GPUs.
The main goal of this project is to exploit NVIDIA boards as much as possible to obtain the best inference performance. It does not allow training. The main goal of this project is to exploit NVIDIA boards as much as possible to obtain the best inference performance. It does not allow training.
If you use tkDNN in your research, please cite one of the following papers. For use in commercial solutions, write at gattifrancesco@hotmail.it or refer to https://hipert.unimore.it/ . If you use tkDNN in your research, please cite the [following paper](https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=9212130&casa_token=sQTJXi7tJNoAAAAA:BguH9xCIY48MxbtDS3LXzIXzO-9sWArm7Hd7y7BwaLmqRuM_Gx8bOYizFPNMNtpo5K0kB-P-). For use in commercial solutions, write at gattifrancesco@hotmail.it and micaela.verucchi@unimore.it or refer to https://hipert.unimore.it/ .
``` ```
Accepted paper @ IRC 2020, will soon be published. @inproceedings{verucchi2020systematic,
M. Verucchi, L. Bartoli, F. Bagni, F. Gatti, P. Burgio and M. Bertogna, "Real-Time clustering and LiDAR-camera fusion on embedded platforms for self-driving cars", in proceedings in IEEE Robotic Computing (2020) title={A Systematic Assessment of Embedded Neural Networks for Object Detection},
author={Verucchi, Micaela and Brilli, Gianluca and Sapienza, Davide and Verasani, Mattia and Arena, Marco and Gatti, Francesco and Capotondi, Alessandro and Cavicchioli, Roberto and Bertogna, Marko and Solieri, Marco},
Accepted paper @ ETFA 2020, will soon be published. booktitle={2020 25th IEEE International Conference on Emerging Technologies and Factory Automation (ETFA)},
M. Verucchi, G. Brilli, D. Sapienza, M. Verasani, M. Arena, F. Gatti, A. Capotondi, R. Cavicchioli, M. Bertogna, M. Solieri volume={1},
"A Systematic Assessment of Embedded Neural Networks for Object Detection", in IEEE International Conference on Emerging Technologies and Factory Automation (2020) pages={937--944},
year={2020},
organization={IEEE}
}
``` ```
## Results ### What's new (20 July 2021)
Inference FPS of yolov4 with tkDNN, average of 1200 images with the same dimesion as the input size, on - [x] Support to sematic segmentation [REAME](readme/README_seg.md)
- [] Support to TensorRT8 (WIP)
## FPS Results
Inference FPS of yolov4 with tkDNN, average of 1200 images with the same dimension as the input size, on
* RTX 2080Ti (CUDA 10.2, TensorRT 7.0.0, Cudnn 7.6.5); * RTX 2080Ti (CUDA 10.2, TensorRT 7.0.0, Cudnn 7.6.5);
* Xavier AGX, Jetpack 4.3 (CUDA 10.0, CUDNN 7.6.3, tensorrt 6.0.1 ); * Xavier AGX, Jetpack 4.3 (CUDA 10.0, CUDNN 7.6.3, tensorrt 6.0.1 );
* Xavier NX, Jetpack 4.4 (CUDA 10.2, CUDNN 8.0.0, tensorrt 7.1.0 ).
* Tx2, Jetpack 4.2 (CUDA 10.0, CUDNN 7.3.1, tensorrt 5.0.6 ); * Tx2, Jetpack 4.2 (CUDA 10.0, CUDNN 7.3.1, tensorrt 5.0.6 );
* Jetson Nano, Jetpack 4.4 (CUDA 10.2, CUDNN 8.0.0, tensorrt 7.1.0 ). * Jetson Nano, Jetpack 4.4 (CUDA 10.2, CUDNN 8.0.0, tensorrt 7.1.0 ).
| Platform | Network | FP32, B=1 | FP32, B=4 | FP16, B=1 | FP16, B=4 | INT8, B=1 | INT8, B=4 | | Platform | Network | FP32, B=1 | FP32, B=4 | FP16, B=1 | FP16, B=4 | INT8, B=1 | INT8, B=4 |
| :------: | :-----: | :-----: | :-----: | :-----: | :-----: | :-----: | :-----: | | :------: | :-----: | :-----: | :-----: | :-----: | :-----: | :-----: | :-----: |
| RTX 2080Ti | yolo4 320 | 118,59 |237,31 | 207,81 | 443,32 | 262,37 | 530,93 | | RTX 2080Ti | yolo4 320 | 118.59 | 237.31 | 207.81 | 443.32 | 262.37 | 530.93 |
| RTX 2080Ti | yolo4 416 | 104,81 |162,86 | 169,06 | 293,78 | 206,93 | 353,26 | | RTX 2080Ti | yolo4 416 | 104.81 | 162.86 | 169.06 | 293.78 | 206.93 | 353.26 |
| RTX 2080Ti | yolo4 512 | 92,98 |132,43 | 140,36 | 215,17 | 165,35 | 254,96 | | RTX 2080Ti | yolo4 512 | 92.98 | 132.43 | 140.36 | 215.17 | 165.35 | 254.96 |
| RTX 2080Ti | yolo4 608 | 63,77 |81,53 | 111,39 | 152,89 | 127,79 | 184,72 | | RTX 2080Ti | yolo4 608 | 63.77 | 81.53 | 111.39 | 152.89 | 127.79 | 184.72 |
| AGX Xavier | yolo4 320 | 26,78 |32,05 | 57,14 | 79,05 | 73,15 | 97,56 | | AGX Xavier | yolo4 320 | 26.78 | 32.05 | 57.14 | 79.05 | 73.15 | 97.56 |
| AGX Xavier | yolo4 416 | 19,96 |21,52 | 41,01 | 49,00 | 50,81 | 60,61 | | AGX Xavier | yolo4 416 | 19.96 | 21.52 | 41.01 | 49.00 | 50.81 | 60.61 |
| AGX Xavier | yolo4 512 | 16,58 |16,98 | 31,12 | 33,84 | 37,82 | 41,28 | | AGX Xavier | yolo4 512 | 16.58 | 16.98 | 31.12 | 33.84 | 37.82 | 41.28 |
| AGX Xavier | yolo4 608 | 9,45 |10,13 | 21,92 | 23,36 | 27,05 | 28,93 | | AGX Xavier | yolo4 608 | 9.45 | 10.13 | 21.92 | 23.36 | 27.05 | 28.93 |
| Tx2 | yolo4 320 | 11,18 | 12,07 | 15,32 | 16,31 | - | - | | Xavier NX | yolo4 320 | 14.56 | 16.25 | 30.14 | 41.15 | 42.13 | 53.42 |
| Tx2 | yolo4 416 | 7,30 | 7,58 | 9,45 | 9,90 | - | - | | Xavier NX | yolo4 416 | 10.02 | 10.60 | 22.43 | 25.59 | 29.08 | 32.94 |
| Tx2 | yolo4 512 | 5,96 | 5,95 | 7,22 | 7,23 | - | - | | Xavier NX | yolo4 512 | 8.10 | 8.32 | 15.78 | 17.13 | 20.51 | 22.46 |
| Tx2 | yolo4 608 | 3,63 | 3,65 | 4,67 | 4,70 | - | - | | Xavier NX | yolo4 608 | 5.26 | 5.18 | 11.54 | 12.06 | 15.09 | 15.82 |
| Nano | yolo4 320 | 4,23 | 4,55 | 6,14 | 6,53 | - | - | | Tx2 | yolo4 320 | 11.18 | 12.07 | 15.32 | 16.31 | - | - |
| Nano | yolo4 416 | 2,88 | 3,00 | 3,90 | 4,04 | - | - | | Tx2 | yolo4 416 | 7.30 | 7.58 | 9.45 | 9.90 | - | - |
| Nano | yolo4 512 | 2,32 | 2,34 | 3,02 | 3,04 | - | - | | Tx2 | yolo4 512 | 5.96 | 5.95 | 7.22 | 7.23 | - | - |
| Nano | yolo4 608 | 1,40 | 1,41 | 1,92 | 1,93 | - | - | | Tx2 | yolo4 608 | 3.63 | 3.65 | 4.67 | 4.70 | - | - |
| Nano | yolo4 320 | 4.23 | 4.55 | 6.14 | 6.53 | - | - |
| Nano | yolo4 416 | 2.88 | 3.00 | 3.90 | 4.04 | - | - |
| Nano | yolo4 512 | 2.32 | 2.34 | 3.02 | 3.04 | - | - |
| Nano | yolo4 608 | 1.40 | 1.41 | 1.92 | 1.93 | - | - |
## MAP Results
Results for COCO val 2017 (5k images), on RTX 2080Ti, with conf threshold=0.001
| | CodaLab | CodaLab | CodaLab | CodaLab | tkDNN map | tkDNN map |
| -------------------- | :-----------: | :-------: | :-----------: | :---------: | :-----------: | :-------: |
| | **tkDNN** | **tkDNN** | **darknet** | **darknet** | **tkDNN** | **tkDNN** |
| | MAP(0.5:0.95) | AP50 | MAP(0.5:0.95) | AP50 | MAP(0.5:0.95) | AP50 |
| Yolov3 (416x416) | 0.381 | 0.675 | 0.380 | 0.675 | 0.372 | 0.663 |
| yolov4 (416x416) | 0.468 | 0.705 | 0.471 | 0.710 | 0.459 | 0.695 |
| yolov3tiny (416x416) | 0.096 | 0.202 | 0.096 | 0.201 | 0.093 | 0.198 |
| yolov4tiny (416x416) | 0.202 | 0.400 | 0.201 | 0.400 | 0.197 | 0.395 |
| Cnet-dla34 (512x512) | 0.366 | 0.543 | \- | \- | 0.361 | 0.535 |
| mv2SSD (512x512) | 0.226 | 0.381 | \- | \- | 0.223 | 0.378 |
## Index ## Index
- [tkDNN](#tkdnn) - [tkDNN](#tkdnn)
@@ -58,6 +84,14 @@ Inference FPS of yolov4 with tkDNN, average of 1200 images with the same dimesio
- [mAP demo](#map-demo) - [mAP demo](#map-demo)
- [Existing tests and supported networks](#existing-tests-and-supported-networks) - [Existing tests and supported networks](#existing-tests-and-supported-networks)
- [References](#references) - [References](#references)
- [tkDNN on Windows 10 (experimental)](#tkdnn-on-windows-10-experimental)
- [Dependencies-Windows](#dependencies-windows)
- [Compiling tkDNN on Windows](#compiling-tkdnn-on-windows)
- [Run the demo on Windows](#run-the-demo-on-windows)
- [FP16 inference windows](#fp16-inference-windows)
- [INT8 inference windows](#int8-inference-windows)
- [Known issues with tkDNN on Windows](#known-issues-with-tkdnn-on-windows)
@@ -155,7 +189,7 @@ tkDNN implement and easy parser for darknet cfg files, a network can be converte
tk::dnn::Network *net = tk::dnn::darknetParser("yolov4.cfg", "yolov4/layers", "coco.names"); tk::dnn::Network *net = tk::dnn::darknetParser("yolov4.cfg", "yolov4/layers", "coco.names");
net->print(); net->print();
``` ```
All models from darknet are now parsed directly from cfg, you still need to export the weights with the descripted tools in the previus section. All models from darknet are now parsed directly from cfg, you still need to export the weights with the described tools in the previous section.
<details> <details>
<summary>Supported layers</summary> <summary>Supported layers</summary>
convolutional convolutional
@@ -173,19 +207,30 @@ All models from darknet are now parsed directly from cfg, you still need to expo
relu relu
leaky leaky
mish mish
logistic
</details> </details>
## Run the demo ## Run the demo
This is an example using yolov4.
To run the an object detection demo follow these steps (example with yolov3): To run the an object detection first create the .rt file by running:
``` ```
rm yolo3_fp32.rt # be sure to delete(or move) old tensorRT files rm yolo4_fp32.rt # be sure to delete(or move) old tensorRT files
./test_yolo3 # run the yolo test (is slow) ./test_yolo4 # run the yolo test (is slow)
./demo yolo3_fp32.rt ../demo/yolo_test.mp4 y
``` ```
In general the demo program takes 4 parameters: If you get problems in the creation, try to check the error activating the debug of TensorRT in this way:
``` ```
./demo <network-rt-file> <path-to-video> <kind-of-network> <number-of-classes> <n-batches> <show-flag> cmake .. -DDEBUG=True
make
```
Once you have successfully created your rt file, run the demo:
```
./demo yolo4_fp32.rt ../demo/yolo_test.mp4 y
```
In general the demo program takes 7 parameters:
```
./demo <network-rt-file> <path-to-video> <kind-of-network> <number-of-classes> <n-batches> <show-flag> <conf-thresh>
``` ```
where where
* ```<network-rt-file>``` is the rt file generated by a test * ```<network-rt-file>``` is the rt file generated by a test
@@ -194,9 +239,11 @@ where
* ```<number-of-classes>```is the number of classes the network is trained on * ```<number-of-classes>```is the number of classes the network is trained on
* ```<n-batches>``` number of batches to use in inference (N.B. you should first export TKDNN_BATCHSIZE to the required n_batches and create again the rt file for the network). * ```<n-batches>``` number of batches to use in inference (N.B. you should first export TKDNN_BATCHSIZE to the required n_batches and create again the rt file for the network).
* ```<show-flag>``` if set to 0 the demo will not show the visualization but save the video into result.mp4 (if n-batches ==1) * ```<show-flag>``` if set to 0 the demo will not show the visualization but save the video into result.mp4 (if n-batches ==1)
* ```<conf-thresh>``` confidence threshold for the detector. Only bounding boxes with threshold greater than conf-thresh will be displayed.
N.b. By default it is used FP32 inference N.b. By default it is used FP32 inference
![demo](https://user-images.githubusercontent.com/11562617/72547657-540e7800-388d-11ea-83c6-49dfea2a0607.gif) ![demo](https://user-images.githubusercontent.com/11562617/72547657-540e7800-388d-11ea-83c6-49dfea2a0607.gif)
### FP16 inference ### FP16 inference
@@ -221,7 +268,7 @@ You should provide image_list.txt and label_list.txt, using training images. How
``` ```
bash scripts/download_validation.sh COCO bash scripts/download_validation.sh COCO
``` ```
to automatically download COCO2017 validation (inside demo folder) and create those needed file. Use BDD insted of COCO to download BDD validation. to automatically download COCO2017 validation (inside demo folder) and create those needed file. Use BDD instead of COCO to download BDD validation.
Then a complete example using yolo3 and COCO dataset would be: Then a complete example using yolo3 and COCO dataset would be:
``` ```
@@ -243,8 +290,8 @@ N.B.
export TKDNN_BATCHSIZE=2 export TKDNN_BATCHSIZE=2
# build tensorRT files # build tensorRT files
``` ```
This will create a TensorRT file with the desidered **max** batch size. This will create a TensorRT file with the desired **max** batch size.
The test will still run with a batch of 1, but the created tensorRT can manage the desidered batch size. The test will still run with a batch of 1, but the created tensorRT can manage the desired batch size.
### Test batch Inference ### Test batch Inference
This will test the network with random input and check if the output of each batch is the same. This will test the network with random input and check if the output of each batch is the same.
@@ -290,7 +337,7 @@ cd build
./map_demo dla34_cnet_FP32.rt c ../demo/COCO_val2017/all_labels.txt ../demo/config.yaml ./map_demo dla34_cnet_FP32.rt c ../demo/COCO_val2017/all_labels.txt ../demo/config.yaml
``` ```
This demo also creates a json file named ```net_name_COCO_res.json``` containing all the detections computed. The detections are in COCO format, the correct format to subit the results to [CodaLab COCO detection challenge](https://competitions.codalab.org/competitions/20794#participate). This demo also creates a json file named ```net_name_COCO_res.json``` containing all the detections computed. The detections are in COCO format, the correct format to submit the results to [CodaLab COCO detection challenge](https://competitions.codalab.org/competitions/20794#participate).
## Existing tests and supported networks ## Existing tests and supported networks
@@ -317,6 +364,98 @@ This demo also creates a json file named ```net_name_COCO_res.json``` containing
| resnet101_cnet | Centernet (Resnet101 backend)<sup>4</sup> | [COCO 2017](http://cocodataset.org/) | 80 | 512x512 | [weights](https://cloud.hipert.unimore.it/s/5BTjHMWBcJk8g3i/download) | | resnet101_cnet | Centernet (Resnet101 backend)<sup>4</sup> | [COCO 2017](http://cocodataset.org/) | 80 | 512x512 | [weights](https://cloud.hipert.unimore.it/s/5BTjHMWBcJk8g3i/download) |
| csresnext50-panet-spp | Cross Stage Partial Network <sup>7</sup> | [COCO 2014](http://cocodataset.org/) | 80 | 416x416 | [weights](https://cloud.hipert.unimore.it/s/Kcs4xBozwY4wFx8/download) | | csresnext50-panet-spp | Cross Stage Partial Network <sup>7</sup> | [COCO 2014](http://cocodataset.org/) | 80 | 416x416 | [weights](https://cloud.hipert.unimore.it/s/Kcs4xBozwY4wFx8/download) |
| yolo4 | Yolov4 <sup>8</sup> | [COCO 2017](http://cocodataset.org/) | 80 | 416x416 | [weights](https://cloud.hipert.unimore.it/s/d97CFzYqCPCp5Hg/download) | | yolo4 | Yolov4 <sup>8</sup> | [COCO 2017](http://cocodataset.org/) | 80 | 416x416 | [weights](https://cloud.hipert.unimore.it/s/d97CFzYqCPCp5Hg/download) |
| yolo4_berkeley | Yolov4 <sup>8</sup> | [BDD100K ](https://bair.berkeley.edu/blog/2018/05/30/bdd/) | 10 | 540x320 | [weights](https://cloud.hipert.unimore.it/s/nkWFa5fgb4NTdnB/download) |
| yolo4tiny | Yolov4 tiny <sup>9</sup> | [COCO 2017](http://cocodataset.org/) | 80 | 416x416 | [weights](https://cloud.hipert.unimore.it/s/iRnc4pSqmx78gJs/download) |
| yolo4x | Yolov4x-mish <sup>9</sup> | [COCO 2017](http://cocodataset.org/) | 80 | 640x640 | [weights](https://cloud.hipert.unimore.it/s/5MFjtNtgbDGdJEo/download) |
| yolo4x-cps | Scaled Yolov4 <sup>10</sup> | [COCO 2017](http://cocodataset.org/) | 80 | 512x512 | [weights](https://cloud.hipert.unimore.it/s/AfzHE4BfTeEm2gH/download) |
### tkDNN on Windows 10 (experimental)
### Dependencies-Windows
This branch should work on every NVIDIA GPU supported in windows with the following dependencies:
* WINDOWS 10 1803 or HIGHER
* CUDA 10.0 (Recommended CUDA 11.2 )
* CUDNN 7.6 (Recommended CUDNN 8.1.1 )
* TENSORRT 6.0.1 (Recommended TENSORRT 7.2.3.4 )
* OPENCV 3.4 (Recommended OPENCV 4.2.0 )
* MSVC 16.7
* YAML-CPP
* EIGEN3
* 7ZIP (ADD TO PATH)
* NINJA 1.10
All the above mentioned dependencies except 7ZIP can be installed using Microsoft's [VCPKG](https://github.com/microsoft/vcpkg.git) .
After bootstrapping VCPKG the dependencies can be built and installed using the following command :
```
opencv4(normal) - vcpkg.exe install opencv4[tbb,jpeg,tiff,opengl,openmp,png,ffmpeg,eigen]:x64-windows yaml-cpp:x64-windows eigen3:x64-windows --x-install-root=C:\opt --x-buildtrees-root=C:\temp_vcpkg_build
opencv4(cuda) - vcpkg.exe install opencv4[cuda,nonfree,contrib,eigen,tbb,jpeg,tiff,opengl,openmp,png,ffmpeg]:x64-windows yaml-cpp:x64-windows eigen3:x64-windows --x-install-root=C:\opt --x-buildtrees-root=C:\temp_vcpkg_build
```
To build opencv4 with cuda and cudnn version corresponding to your cuda version,vcpkg's cudnn portfile needs to be modified by adding ```$ENV{CUDA_PATH}``` at lines 16 and 17 in the portfile.cmake
After VCPKG finishes building and installing all the packages delete C:\temp_vcpkg_build and add C:\opt\x64-windows\bin and C:\opt\x64-windows\debug\bin to path
### Compiling tkDNN on Windows
tkDNN is built with cmake(3.15+) on windows along with ninja.Msbuild and NMake Makefiles are drastically slower when compiling the library compared to windows
```
git clone https://github.com/ceccocats/tkDNN.git
cd tkdnn-windows
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release -G"Ninja" ..
ninja -j4
```
### Run the demo on Windows
This example uses yolo4_tiny.\
To run the object detection file create .rt file bu running:
```
.\test_yolo4tiny.exe
```
Once the rt file has been successfully create,run the demo using the following command:
```
.\demo.exe yolo4tiny_fp32.rt ..\demo\yolo_test.mp4 y
```
For general info on more demo paramters,check Run the demo section on top
To run the test_all_tests.sh on windows,use git bash or msys2
### FP16 inference windows
This is an untested feature on windows.To run the object detection demo with FP16 interference follow the below steps(example with yolo4tiny):
```
set TKDNN_MODE=FP16
del /f yolo4tiny_fp16.rt
.\test_yolo4tiny.exe
.\demo.exe yolo4tiny_fp16.rt ..\demo\yolo_test.mp4
```
### INT8 inference windows
To run object detection demo with INT8 (example with yolo4tiny):
```
set TKDNN_MODE=INT8
set TKDNN_CALIB_LABEL_PATH=..\demo\COCO_val2017\all_labels.txt
set TKDNN_CALIB_IMG_PATH=..\demo\COCO_val2017\all_images.txt
del /f yolo4tiny_int8.rt # be sure to delete(or move) old tensorRT files
.\test_yolo4tiny.exe # run the yolo test (is slow)
.\demo.exe yolo4tiny_int8.rt ..\demo\yolo_test.mp4 y
```
### Known issues with tkDNN on Windows
Mobilenet and Centernet demos work properly only when built with msvc 16.7 in Release Mode,when built in debug mode for the mentioned networks one might encounter opencv assert errors
All Darknet models work properly with demo using MSVC version(16.7-16.9)
It is recommended to use Nvidia Driver(465+),Cuda unknown errors have been observed when using older drivers on pascal(SM 61) devices.
## References ## References
@@ -329,3 +468,5 @@ This demo also creates a json file named ```net_name_COCO_res.json``` containing
6. He, Kaiming, et al. "Deep residual learning for image recognition." Proceedings of the IEEE conference on computer vision and pattern recognition. 2016. 6. He, Kaiming, et al. "Deep residual learning for image recognition." Proceedings of the IEEE conference on computer vision and pattern recognition. 2016.
7. Wang, Chien-Yao, et al. "CSPNet: A New Backbone that can Enhance Learning Capability of CNN." arXiv preprint arXiv:1911.11929 (2019). 7. Wang, Chien-Yao, et al. "CSPNet: A New Backbone that can Enhance Learning Capability of CNN." arXiv preprint arXiv:1911.11929 (2019).
8. Bochkovskiy, Alexey, Chien-Yao Wang, and Hong-Yuan Mark Liao. "YOLOv4: Optimal Speed and Accuracy of Object Detection." arXiv preprint arXiv:2004.10934 (2020). 8. Bochkovskiy, Alexey, Chien-Yao Wang, and Hong-Yuan Mark Liao. "YOLOv4: Optimal Speed and Accuracy of Object Detection." arXiv preprint arXiv:2004.10934 (2020).
9. Bochkovskiy, Alexey, "Yolo v4, v3 and v2 for Windows and Linux" (https://github.com/AlexeyAB/darknet)
10. Wang, Chien-Yao, Alexey Bochkovskiy, and Hong-Yuan Mark Liao. "Scaled-YOLOv4: Scaling Cross Stage Partial Network." arXiv preprint arXiv:2011.08036 (2020).
+1 -1
View File
@@ -3,5 +3,5 @@ map_points : 101 #number of recall points (0 for all, 101 for COCO, 11 Pascal
map_levels : 10 #number of IoU step for the AP map_levels : 10 #number of IoU step for the AP
map_step : 0.05 #step of IoU map_step : 0.05 #step of IoU
IoU_thresh : 0.5 #starting IoU threshold IoU_thresh : 0.5 #starting IoU threshold
conf_thresh : 0.0 #threshold on the condifence of the bbox conf_thresh : 0.001 #threshold on the condifence of the bbox
verbose : false #print on screen information verbose : false #print on screen information
+13 -5
View File
@@ -1,7 +1,7 @@
#include <iostream> #include <iostream>
#include <signal.h> #include <signal.h>
#include <stdlib.h> /* srand, rand */ #include <stdlib.h> /* srand, rand */
#include <unistd.h> //#include <unistd.h>
#include <mutex> #include <mutex>
#include "CenternetDetection.h" #include "CenternetDetection.h"
@@ -22,10 +22,15 @@ int main(int argc, char *argv[]) {
signal(SIGINT, sig_handler); signal(SIGINT, sig_handler);
std::string net = "yolo3_berkeley.rt"; std::string net = "yolo4tiny_fp32.rt";
if(argc > 1) if(argc > 1)
net = argv[1]; net = argv[1];
std::string input = "../demo/yolo_test.mp4"; #ifdef __linux__
std::string input = "../demo/yolo_test.mp4";
#elif _WIN32
std::string input = "..\\..\\..\\demo\\yolo_test.mp4";
#endif
if(argc > 2) if(argc > 2)
input = argv[2]; input = argv[2];
char ntype = 'y'; char ntype = 'y';
@@ -40,6 +45,9 @@ int main(int argc, char *argv[]) {
bool show = true; bool show = true;
if(argc > 6) if(argc > 6)
show = atoi(argv[6]); show = atoi(argv[6]);
float conf_thresh=0.3;
if(argc > 7)
conf_thresh = atof(argv[7]);
if(n_batch < 1 || n_batch > 64) if(n_batch < 1 || n_batch > 64)
FatalError("Batch dim not supported"); FatalError("Batch dim not supported");
@@ -69,7 +77,7 @@ int main(int argc, char *argv[]) {
FatalError("Network type not allowed (3rd parameter)\n"); FatalError("Network type not allowed (3rd parameter)\n");
} }
detNN->init(net, n_classes, n_batch); detNN->init(net, n_classes, n_batch, conf_thresh);
gRun = true; gRun = true;
@@ -128,7 +136,7 @@ int main(int argc, char *argv[]) {
double mean = 0; double mean = 0;
std::cout<<COL_GREENB<<"\n\nTime stats:\n"; std::cout<<COL_GREENB<<"\n\nTime stats:\n";
std::cout<<"Min: "<<*std::min_element(detNN->stats.begin(), detNN->stats.end())/n_batch<<" ms\n"; std::cout<<"Min: "<<*std::min_element(detNN->stats.begin(), detNN->stats.end())/n_batch<<" ms\n";
std::cout<<"Max: "<<*std::max_element(detNN->stats.begin(), detNN->stats.end())/n_batch<<" ms\n"; std::cout<<"Max: "<<*std::max_element(detNN->stats.begin(), detNN->stats.end())/n_batch<<" ms\n";
for(int i=0; i<detNN->stats.size(); i++) mean += detNN->stats[i]; mean /= detNN->stats.size(); for(int i=0; i<detNN->stats.size(); i++) mean += detNN->stats[i]; mean /= detNN->stats.size();
std::cout<<"Avg: "<<mean/n_batch<<" ms\t"<<1000/(mean/n_batch)<<" FPS\n"<<COL_END; std::cout<<"Avg: "<<mean/n_batch<<" ms\t"<<1000/(mean/n_batch)<<" FPS\n"<<COL_END;
+4 -1
View File
@@ -2,7 +2,10 @@
#include <iostream> #include <iostream>
#include <signal.h> #include <signal.h>
#include <stdlib.h> /* srand, rand */ #include <stdlib.h> /* srand, rand */
#ifdef __linux__
#include <unistd.h> #include <unistd.h>
#endif
#include <mutex> #include <mutex>
#include "utils.h" #include "utils.h"
@@ -105,7 +108,7 @@ int main(int argc, char *argv[])
default: default:
FatalError("Network type not allowed (3rd parameter)\n"); FatalError("Network type not allowed (3rd parameter)\n");
} }
detNN->init(net, n_classes); detNN->init(net, n_classes, 1, conf_thresh);
//read images //read images
std::ifstream all_labels(labels_path); std::ifstream all_labels(labels_path);
+7
View File
@@ -0,0 +1,7 @@
FROM ceccocats/tkdnn:latest
LABEL maintainer "Francesco Gatti"
RUN cd && git clone https://github.com/ceccocats/tkDNN.git && cd tkDNN && mkdir build && cd build \
&& cmake .. && make -j12
+57
View File
@@ -0,0 +1,57 @@
FROM nvidia/cuda:10.2-cudnn7-devel-ubuntu18.04
LABEL maintainer "Francesco Gatti"
ADD nv-tensorrt-repo-ubuntu1804-cuda10.2-trt7.0.0.11-ga-20191216_1-1_amd64.deb /tmp/trt.deb
RUN apt-get update && dpkg -i /tmp/trt.deb && rm /tmp/trt.deb && apt-get update
RUN apt install -y libnvinfer7=7.0.0-1+cuda10.2 libnvinfer-dev=7.0.0-1+cuda10.2
RUN DEBIAN_FRONTEND=noninteractive apt install -y git wget libeigen3-dev libyaml-cpp-dev
RUN cd /tmp && \
wget https://github.com/Kitware/CMake/releases/download/v3.17.3/cmake-3.17.3-Linux-x86_64.sh && \
chmod +x cmake-3.17.3-Linux-x86_64.sh && \
./cmake-3.17.3-Linux-x86_64.sh --prefix=/usr/local --exclude-subdir --skip-license && \
rm ./cmake-3.17.3-Linux-x86_64.sh
RUN echo "INSTALL OPENCV"
RUN apt-get install -y build-essential \
unzip \
pkg-config \
libjpeg-dev \
libpng-dev \
libtiff-dev \
libavcodec-dev \
libavformat-dev \
libswscale-dev \
libv4l-dev \
libxvidcore-dev \
libx264-dev \
libgtk-3-dev \
libatlas-base-dev \
gfortran \
libgstreamer1.0-dev \
libgstreamer-plugins-base1.0-dev \
libdc1394-22-dev \
libavresample-dev
RUN cd && wget https://github.com/opencv/opencv/archive/4.3.0.tar.gz && tar -xf 4.3.0.tar.gz && rm *.tar.gz
RUN cd && wget https://github.com/opencv/opencv_contrib/archive/4.3.0.tar.gz && tar -xf 4.3.0.tar.gz && rm *.tar.gz
RUN cd && \
cd opencv-4.3.0 && mkdir build && cd build && \
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D INSTALL_C_EXAMPLES=OFF \
-D OPENCV_EXTRA_MODULES_PATH='~/opencv_contrib-4.3.0/modules' \
-D BUILD_EXAMPLES=OFF \
-D WITH_CUDA=ON \
-D CUDA_ARCH_BIN=7.2 \
-D CUDA_ARCH_PTX="" \
-D ENABLE_FAST_MATH=ON \
-D CUDA_FAST_MATH=ON \
-D WITH_CUBLAS=ON \
-D WITH_LIBV4L=ON \
-D WITH_GSTREAMER=ON \
-D WITH_GSTREAMER_0_10=OFF \
-D WITH_TBB=ON \
../ && make -j12 && make install
RUN apt clean
+21
View File
@@ -0,0 +1,21 @@
# Use the prebuilt image
```
# build image
docker build -t tkdnn:build -f Dockerfile .
```
# Build Base Docker image
```
# make nvidia docker working
# follow this guide: https://github.com/NVIDIA/nvidia-docker
# dowload tensorrt
# from: https://developer.nvidia.com/compute/machine-learning/tensorrt/secure/7.0/7.0.0.11/local_repo/nv-tensorrt-repo-ubuntu1804-cuda10.2-trt7.0.0.11-ga-20191216_1-1_amd64.deb
# build image
docker build -t ceccocats/tkdnn:latest -f Dockerfile.base .
# run image
docker run -ti --gpus all --rm ceccocats/tkdnn:latest bash
```

Before

Width:  |  Height:  |  Size: 6.3 MiB

After

Width:  |  Height:  |  Size: 6.3 MiB

+1 -1
View File
@@ -73,7 +73,7 @@ public:
CenternetDetection() {}; CenternetDetection() {};
~CenternetDetection() {}; ~CenternetDetection() {};
bool init(const std::string& tensor_path, const int n_classes=80, const int n_batches=1); bool init(const std::string& tensor_path, const int n_classes=80, const int n_batches=1, const float conf_thresh=0.3);
void preprocess(cv::Mat &frame, const int bi=0); void preprocess(cv::Mat &frame, const int bi=0);
void postprocess(const int bi=0,const bool mAP=false); void postprocess(const int bi=0,const bool mAP=false);
}; };
+4
View File
@@ -11,6 +11,7 @@ namespace tk { namespace dnn {
int channels = 3; int channels = 3;
int batch_normalize=0; int batch_normalize=0;
int groups = 1; int groups = 1;
int group_id = 0;
int filters=1; int filters=1;
int size_x=1; int size_x=1;
int size_y=1; int size_y=1;
@@ -23,7 +24,10 @@ namespace tk { namespace dnn {
int num = 1; int num = 1;
int pad = 0; int pad = 0;
int coords = 4; int coords = 4;
int nms_kind = 0;
int new_coords= 0;
float scale_xy = 1; float scale_xy = 1;
float nms_thresh = 0.45;
std::vector<int> layers; std::vector<int> layers;
std::string activation = "linear"; std::string activation = "linear";
+9 -7
View File
@@ -4,7 +4,10 @@
#include <iostream> #include <iostream>
#include <signal.h> #include <signal.h>
#include <stdlib.h> #include <stdlib.h>
#ifdef __linux__
#include <unistd.h> #include <unistd.h>
#endif
#include <mutex> #include <mutex>
#include "utils.h" #include "utils.h"
@@ -14,7 +17,7 @@
#include "tkdnn.h" #include "tkdnn.h"
// #define OPENCV_CUDACONTRIB //if OPENCV has been compiled with CUDA and contrib. //#define OPENCV_CUDACONTRIB //if OPENCV has been compiled with CUDA and contrib.
#ifdef OPENCV_CUDACONTRIB #ifdef OPENCV_CUDACONTRIB
#include <opencv2/cudawarping.hpp> #include <opencv2/cudawarping.hpp>
@@ -76,15 +79,15 @@ class DetectionNN {
~DetectionNN(){}; ~DetectionNN(){};
/** /**
* Method used to inialize the class, allocate memory and compute * Method used to initialize the class, allocate memory and compute
* needed data. * needed data.
* *
* @param tensor_path path to the rt file og the NN. * @param tensor_path path to the rt file of the NN.
* @param n_classes number of classes for the given dataset. * @param n_classes number of classes for the given dataset.
* @param n_batches maximum number of batches to use in inference * @param n_batches maximum number of batches to use in inference
* @return true if everything is correct, false otherwise. * @return true if everything is correct, false otherwise.
*/ */
virtual bool init(const std::string& tensor_path, const int n_classes=80, const int n_batches=1) = 0; virtual bool init(const std::string& tensor_path, const int n_classes=80, const int n_batches=1, const float conf_thresh=0.3) = 0;
/** /**
* This method performs the whole detection of the NN. * This method performs the whole detection of the NN.
@@ -141,16 +144,15 @@ class DetectionNN {
} }
/** /**
* Method to draw boundixg boxes and labels on a frame. * Method to draw bounding boxes and labels on a frame.
* *
* @param frames orginal frame to draw bounding box on. * @param frames original frame to draw bounding box on.
*/ */
void draw(std::vector<cv::Mat>& frames) { void draw(std::vector<cv::Mat>& frames) {
tk::dnn::box b; tk::dnn::box b;
int x0, w, x1, y0, h, y1; int x0, w, x1, y0, h, y1;
int objClass; int objClass;
std::string det_class; std::string det_class;
int baseline = 0; int baseline = 0;
float font_scale = 0.5; float font_scale = 0.5;
int thickness = 2; int thickness = 2;
+9 -2
View File
@@ -1,7 +1,14 @@
#include <iostream> #include <iostream>
#include <signal.h> #include <signal.h>
#include <stdlib.h> /* srand, rand */ #include <stdlib.h> /* srand, rand */
#ifdef __linux__
#include <unistd.h> #include <unistd.h>
#elif _WIN32
#define _USE_MATH_DEFINES
#include <math.h>
#endif
#include <mutex> #include <mutex>
#include <Eigen/Dense> #include <Eigen/Dense>
#include "utils.h" #include "utils.h"
@@ -44,7 +51,7 @@ class ImuOdom {
virtual ~ImuOdom() {} virtual ~ImuOdom() {}
/** /**
* Method used for inizialize the class * Method used for initialize the class
* *
* @return Success of the initialization * @return Success of the initialization
*/ */
@@ -141,7 +148,7 @@ class ImuOdom {
//odomPOS = odomPOS + deltaP.cast<double>(); // V2 //odomPOS = odomPOS + deltaP.cast<double>(); // V2
odomROT = odomROT * q.normalized().toRotationMatrix(); odomROT = odomROT * q.normalized().toRotationMatrix();
// compute euler // compute Euler
auto newEULER = odomROT.eulerAngles(0, 1, 2); auto newEULER = odomROT.eulerAngles(0, 1, 2);
for(int i=0; i<3; i++) { for(int i=0; i<3; i++) {
while( fabs(newEULER(i) - odomEULER(i)) > M_PI_2 ) { while( fabs(newEULER(i) - odomEULER(i)) > M_PI_2 ) {
+3
View File
@@ -12,7 +12,10 @@
#include <iomanip> #include <iomanip>
#include <signal.h> #include <signal.h>
#include <stdlib.h> #include <stdlib.h>
#ifdef __linux__
#include <unistd.h> #include <unistd.h>
#endif
#include <mutex> #include <mutex>
#include "NvInfer.h" #include "NvInfer.h"
+30 -19
View File
@@ -19,6 +19,7 @@ enum layerType_t {
LAYER_ACTIVATION_CRELU, LAYER_ACTIVATION_CRELU,
LAYER_ACTIVATION_LEAKY, LAYER_ACTIVATION_LEAKY,
LAYER_ACTIVATION_MISH, LAYER_ACTIVATION_MISH,
LAYER_ACTIVATION_LOGISTIC,
LAYER_FLATTEN, LAYER_FLATTEN,
LAYER_RESHAPE, LAYER_RESHAPE,
LAYER_RESIZE, LAYER_RESIZE,
@@ -69,6 +70,7 @@ public:
case LAYER_ACTIVATION_CRELU: return "ActivationCReLU"; case LAYER_ACTIVATION_CRELU: return "ActivationCReLU";
case LAYER_ACTIVATION_LEAKY: return "ActivationLeaky"; case LAYER_ACTIVATION_LEAKY: return "ActivationLeaky";
case LAYER_ACTIVATION_MISH: return "ActivationMish"; case LAYER_ACTIVATION_MISH: return "ActivationMish";
case LAYER_ACTIVATION_LOGISTIC: return "ActivationLogistic";
case LAYER_FLATTEN: return "Flatten"; case LAYER_FLATTEN: return "Flatten";
case LAYER_RESHAPE: return "Reshape"; case LAYER_RESHAPE: return "Reshape";
case LAYER_RESIZE: return "Resize"; case LAYER_RESIZE: return "Resize";
@@ -173,7 +175,7 @@ public:
/** /**
Input layer (it doesnt need weigths) Input layer (it doesn't need weights)
*/ */
class Input : public Layer { class Input : public Layer {
@@ -209,16 +211,17 @@ public:
/** /**
Avaible activation functions Available activation functions
*/ */
typedef enum { typedef enum {
ACTIVATION_ELU = 100, ACTIVATION_ELU = 100,
ACTIVATION_LEAKY = 101, ACTIVATION_LEAKY = 101,
ACTIVATION_MISH = 102 ACTIVATION_MISH = 102,
ACTIVATION_LOGISTIC = 103
} tkdnnActivationMode_t; } tkdnnActivationMode_t;
/** /**
Activation layer (it doesnt need weigths) Activation layer (it doesn't need weights)
*/ */
class Activation : public Layer { class Activation : public Layer {
@@ -236,6 +239,8 @@ public:
return LAYER_ACTIVATION_LEAKY; return LAYER_ACTIVATION_LEAKY;
else if (act_mode == ACTIVATION_MISH) else if (act_mode == ACTIVATION_MISH)
return LAYER_ACTIVATION_MISH; return LAYER_ACTIVATION_MISH;
else if (act_mode == ACTIVATION_LOGISTIC)
return LAYER_ACTIVATION_LOGISTIC;
else else
return LAYER_ACTIVATION; return LAYER_ACTIVATION;
}; };
@@ -276,8 +281,8 @@ public:
protected: protected:
cudnnFilterDescriptor_t filterDesc; cudnnFilterDescriptor_t filterDesc;
cudnnConvolutionDescriptor_t convDesc; cudnnConvolutionDescriptor_t convDesc;
cudnnConvolutionFwdAlgo_t algo; cudnnConvolutionFwdAlgoPerf_t algo;
cudnnConvolutionBwdDataAlgo_t bwAlgo; cudnnConvolutionBwdDataAlgoPerf_t bwAlgo;
cudnnTensorDescriptor_t biasTensorDesc; cudnnTensorDescriptor_t biasTensorDesc;
void initCUDNN(bool back = false); void initCUDNN(bool back = false);
@@ -321,9 +326,9 @@ public:
virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); virtual dnnType* infer(dataDim_t &dim, dnnType* srcData);
const bool bidirectional = true; /**> is the net bidir */ const bool bidirectional = true; /**> is the net bidir */
bool returnSeq = false; /**> if false return only the result of last timestep */ bool returnSeq = false; /**> if false return only the result of last timestamp */
int stateSize = 0; /**> number of hidden states */ int stateSize = 0; /**> number of hidden states */
int seqLen = 0; /**> number of timesteps */ int seqLen = 0; /**> number of timestamp */
int numLayers = 1; /**> number of internal layers */ int numLayers = 1; /**> number of internal layers */
protected: protected:
@@ -370,7 +375,7 @@ public:
/** /**
Deformable Convolutionl 2d layer Deformable Convolutional 2d layer
*/ */
class DeformConv2d : public LayerWgs { class DeformConv2d : public LayerWgs {
@@ -469,7 +474,7 @@ protected:
/** /**
Avaible pooling functions (padding on tkDNN is not supported) Available pooling functions (padding on tkDNN is not supported)
*/ */
typedef enum { typedef enum {
POOLING_MAX = 0, POOLING_MAX = 0,
@@ -480,7 +485,7 @@ typedef enum {
/** /**
Pooling layer Pooling layer
currenty supported only 2d pooing (also on 3d input) currently supported only 2d pooing (also on 3d input)
*/ */
class Pooling : public Layer { class Pooling : public Layer {
@@ -529,7 +534,7 @@ public:
class Route : public Layer { class Route : public Layer {
public: public:
Route(Network *net, Layer **layers, int layers_n); Route(Network *net, Layer **layers, int layers_n, int groups = 1, int group_id = 0);
virtual ~Route(); virtual ~Route();
virtual layerType_t getLayerType() { return LAYER_ROUTE; }; virtual layerType_t getLayerType() { return LAYER_ROUTE; };
@@ -539,12 +544,14 @@ public:
static const int MAX_LAYERS = 32; static const int MAX_LAYERS = 32;
Layer *layers[MAX_LAYERS]; //ids of layers to be merged Layer *layers[MAX_LAYERS]; //ids of layers to be merged
int layers_n; //number of layers int layers_n; //number of layers
int groups;
int group_id;
}; };
/** /**
Reorg layer Reorg layer
Mantain same dimension but change C*H*W distribution Maintains same dimension but change C*H*W distribution
*/ */
class Reorg : public Layer { class Reorg : public Layer {
@@ -578,7 +585,7 @@ public:
/** /**
Upsample layer Upsample layer
Mantain same dimension but change C*H*W distribution Maintains same dimension but change C*H*W distribution
*/ */
class Upsample : public Layer { class Upsample : public Layer {
@@ -629,24 +636,28 @@ public:
int sort_class; int sort_class;
}; };
Yolo(Network *net, int classes, int num, std::string fname_weights,int n_masks=3, float scale_xy=1); enum nmsKind_t {GREEDY_NMS=0, DIOU_NMS=1};
Yolo(Network *net, int classes, int num, std::string fname_weights,int n_masks=3, float scale_xy=1, double nms_thresh=0.45, nmsKind_t nsm_kind=GREEDY_NMS, int new_coords=0);
virtual ~Yolo(); virtual ~Yolo();
virtual layerType_t getLayerType() { return LAYER_YOLO; }; virtual layerType_t getLayerType() { return LAYER_YOLO; };
int classes, num, n_masks; int classes, num, n_masks, new_coords;
dnnType *mask_h, *mask_d; //anchors dnnType *mask_h, *mask_d; //anchors
dnnType *bias_h, *bias_d; //anchors dnnType *bias_h, *bias_d; //anchors
float scaleXY; float scaleXY;
double nms_thresh;
nmsKind_t nsm_kind;
std::vector<std::string> classesNames; std::vector<std::string> classesNames;
virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); virtual dnnType* infer(dataDim_t &dim, dnnType* srcData);
int computeDetections(Yolo::detection *dets, int &ndets, int netw, int neth, float thresh); int computeDetections(Yolo::detection *dets, int &ndets, int netw, int neth, float thresh, int new_coords=0);
dnnType *predictions; dnnType *predictions;
static const int MAX_DETECTIONS = 8192; static const int MAX_DETECTIONS = 8192*2;
static Yolo::detection *allocateDetections(int nboxes, int classes); static Yolo::detection *allocateDetections(int nboxes, int classes);
static void mergeDetections(Yolo::detection *dets, int ndets, int classes); static void mergeDetections(Yolo::detection *dets, int ndets, int classes, double nms_thresh=0.45, nmsKind_t nsm_kind=GREEDY_NMS);
}; };
/** /**
+1 -1
View File
@@ -65,7 +65,7 @@ public:
MobilenetDetection() {}; MobilenetDetection() {};
~MobilenetDetection() {}; ~MobilenetDetection() {};
bool init(const std::string& tensor_path, const int n_classes, const int n_batches=1); bool init(const std::string& tensor_path, const int n_classes, const int n_batches=1, const float conf_thresh=0.3);
void preprocess(cv::Mat &frame, const int bi=0); void preprocess(cv::Mat &frame, const int bi=0);
void postprocess(const int bi=0,const bool mAP=false); void postprocess(const int bi=0,const bool mAP=false);
}; };
+4 -4
View File
@@ -7,12 +7,12 @@
namespace tk { namespace dnn { namespace tk { namespace dnn {
/** /**
Data rapresentation beetween layers Data representation between layers
n = batch size n = batch size
c = channels c = channels
h = heigth (lines) h = height (lines)
w = width (rows) w = width (rows)
l = lenght (3rd dimension) l = length (3rd dimension)
*/ */
struct dataDim_t { struct dataDim_t {
@@ -43,7 +43,7 @@ public:
void releaseLayers(); void releaseLayers();
/** /**
Do inferece for every added layer Do inference for every added layer
*/ */
dnnType* infer(dataDim_t &dim, dnnType* data); dnnType* infer(dataDim_t &dim, dnnType* data);
+8 -2
View File
@@ -6,6 +6,7 @@
#include "Network.h" #include "Network.h"
#include "Layer.h" #include "Layer.h"
#include "NvInfer.h" #include "NvInfer.h"
#include <memory>
namespace tk { namespace dnn { namespace tk { namespace dnn {
@@ -24,11 +25,12 @@ template<typename T> T readBUF(const char*& buffer)
using namespace nvinfer1; using namespace nvinfer1;
#include "pluginsRT/ActivationLeakyRT.h" #include "pluginsRT/ActivationLeakyRT.h"
#include "pluginsRT/ActivationLogisticRT.h"
#include "pluginsRT/ActivationReLUCeilingRT.h" #include "pluginsRT/ActivationReLUCeilingRT.h"
#include "pluginsRT/ActivationMishRT.h" #include "pluginsRT/ActivationMishRT.h"
#include "pluginsRT/ReorgRT.h" #include "pluginsRT/ReorgRT.h"
#include "pluginsRT/RegionRT.h" #include "pluginsRT/RegionRT.h"
//#include "pluginsRT/RouteRT.h" #include "pluginsRT/RouteRT.h"
#include "pluginsRT/ShortcutRT.h" #include "pluginsRT/ShortcutRT.h"
#include "pluginsRT/YoloRT.h" #include "pluginsRT/YoloRT.h"
#include "pluginsRT/UpsampleRT.h" #include "pluginsRT/UpsampleRT.h"
@@ -59,6 +61,7 @@ public:
#if NV_TENSORRT_MAJOR >= 6 #if NV_TENSORRT_MAJOR >= 6
nvinfer1::IBuilderConfig *configRT; nvinfer1::IBuilderConfig *configRT;
#endif #endif
nvinfer1::ICudaEngine *engineRT; nvinfer1::ICudaEngine *engineRT;
nvinfer1::IExecutionContext *contextRT; nvinfer1::IExecutionContext *contextRT;
@@ -91,7 +94,7 @@ public:
} }
/** /**
Do inferece Do inference
*/ */
dnnType* infer(dataDim_t &dim, dnnType* data); dnnType* infer(dataDim_t &dim, dnnType* data);
void enqueue(int batchSize = 1); void enqueue(int batchSize = 1);
@@ -115,6 +118,9 @@ public:
bool serialize(const char *filename); bool serialize(const char *filename);
bool deserialize(const char *filename); bool deserialize(const char *filename);
}; };
}} }}
+1 -1
View File
@@ -24,7 +24,7 @@ public:
Yolo3Detection() {}; Yolo3Detection() {};
~Yolo3Detection() {}; ~Yolo3Detection() {};
bool init(const std::string& tensor_path, const int n_classes=80, const int n_batches=1); bool init(const std::string& tensor_path, const int n_classes=80, const int n_batches=1, const float conf_thresh=0.3);
void preprocess(cv::Mat &frame, const int bi=0); void preprocess(cv::Mat &frame, const int bi=0);
void postprocess(const int bi=0,const bool mAP=false); void postprocess(const int bi=0,const bool mAP=false);
}; };
+4 -4
View File
@@ -73,12 +73,12 @@ double computeMap( std::vector<Frame> &images,const int classes,
* all the recall levels are evaluated, otherwise only * all the recall levels are evaluated, otherwise only
* map_point recall levels are used. For COCO evaluation * map_point recall levels are used. For COCO evaluation
* 101 points are used. * 101 points are used.
* @param map_step step used to increment IoU theshold * @param map_step step used to increment IoU threshold
* @param map_levels number of IoU step to perform * @param map_levels number of IoU step to perform
* @param verbose is set to true, prints on screen additional info * @param verbose is set to true, prints on screen additional info
* @param write_on_file if set to true, the results produced by this function * @param write_on_file if set to true, the results produced by this function
* are written on file * are written on file
* @param net name of the considerd neural network * @param net name of the considered neural network
* *
* @return mAP IoU_tresh:IoU_tresh+map_step*map_levels (e.g. mAP 0.5:0.95 when * @return mAP IoU_tresh:IoU_tresh+map_step*map_levels (e.g. mAP 0.5:0.95 when
* map_step=0.05 and map_levels=10) * map_step=0.05 and map_levels=10)
@@ -89,7 +89,7 @@ double computeMapNIoULevels(std::vector<Frame> &images,const int classes,
const int map_levels=10, const bool verbose=false, const int map_levels=10, const bool verbose=false,
const bool write_on_file = false, std::string net = ""); const bool write_on_file = false, std::string net = "");
/** /**
* This method computes the numper of True Positive (TP), False Positive (FP), * This method computes the number of True Positive (TP), False Positive (FP),
* False Negative (FN), precision, recall and f1-score. * False Negative (FN), precision, recall and f1-score.
* Those values are computer over all the detections, over all the classes. * Those values are computer over all the detections, over all the classes.
* *
@@ -101,7 +101,7 @@ double computeMapNIoULevels(std::vector<Frame> &images,const int classes,
* @param verbose is set to true, prints on screen additional info * @param verbose is set to true, prints on screen additional info
* @param write_on_file if set to true, the results produced by this function * @param write_on_file if set to true, the results produced by this function
* are written on file * are written on file
* @param net name of the considerd neural network * @param net name of the considered neural network
*/ */
void computeTPFPFN( std::vector<Frame> &images,const int classes, void computeTPFPFN( std::vector<Frame> &images,const int classes,
const float IoU_thresh=0.5, const float conf_thresh=0.3, const float IoU_thresh=0.5, const float conf_thresh=0.3,
+2 -2
View File
@@ -51,9 +51,9 @@ public:
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a=buf;
tk::dnn::writeBUF(buf, slope);
tk::dnn::writeBUF(buf, size); tk::dnn::writeBUF(buf, size);
assert(buf == a + getSerializationSize());
} }
int size; int size;
@@ -0,0 +1,60 @@
#include<cassert>
#include "../kernels.h"
class ActivationLogisticRT : public IPlugin {
public:
ActivationLogisticRT() {
}
~ActivationLogisticRT(){
}
int getNbOutputs() const override {
return 1;
}
Dims getOutputDimensions(int index, const Dims* inputs, int nbInputDims) override {
return inputs[0];
}
void configure(const Dims* inputDims, int nbInputs, const Dims* outputDims, int nbOutputs, int maxBatchSize) override {
size = 1;
for(int i=0; i<outputDims[0].nbDims; i++)
size *= outputDims[0].d[i];
}
int initialize() override {
return 0;
}
virtual void terminate() override {
}
virtual size_t getWorkspaceSize(int maxBatchSize) const override {
return 0;
}
virtual int enqueue(int batchSize, const void*const * inputs, void** outputs, void* workspace, cudaStream_t stream) override {
activationLOGISTICForward((dnnType*)reinterpret_cast<const dnnType*>(inputs[0]),
reinterpret_cast<dnnType*>(outputs[0]), batchSize*size, stream);
return 0;
}
virtual size_t getSerializationSize() override {
return 1*sizeof(int);
}
virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer);
tk::dnn::writeBUF(buf, size);
}
int size;
};
+2 -1
View File
@@ -52,8 +52,9 @@ public:
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a=buf;
tk::dnn::writeBUF(buf, size); tk::dnn::writeBUF(buf, size);
assert(buf == a + getSerializationSize());
} }
int size; int size;
@@ -51,9 +51,10 @@ public:
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a=buf;
tk::dnn::writeBUF(buf, ceiling); tk::dnn::writeBUF(buf, ceiling);
tk::dnn::writeBUF(buf, size); tk::dnn::writeBUF(buf, size);
assert(buf = a + getSerializationSize());
} }
@@ -52,8 +52,9 @@ public:
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a=buf;
tk::dnn::writeBUF(buf, size); tk::dnn::writeBUF(buf, size);
assert(buf == a + getSerializationSize());
} }
int size; int size;
+3 -2
View File
@@ -89,7 +89,7 @@ public:
for(int b=0; b<batchSize; b++) { for(int b=0; b<batchSize; b++) {
checkCuda(cudaMemcpy(offset, output_conv + b * 3 * chunk_dim, 2*chunk_dim*sizeof(dnnType), cudaMemcpyDeviceToDevice)); checkCuda(cudaMemcpy(offset, output_conv + b * 3 * chunk_dim, 2*chunk_dim*sizeof(dnnType), cudaMemcpyDeviceToDevice));
checkCuda(cudaMemcpy(mask, output_conv + b * 3 * chunk_dim + 2*chunk_dim, chunk_dim*sizeof(dnnType), cudaMemcpyDeviceToDevice)); checkCuda(cudaMemcpy(mask, output_conv + b * 3 * chunk_dim + 2*chunk_dim, chunk_dim*sizeof(dnnType), cudaMemcpyDeviceToDevice));
// kernel sigmoide // kernel sigmoid
activationSIGMOIDForward(mask, mask, chunk_dim); activationSIGMOIDForward(mask, mask, chunk_dim);
// deformable convolution // deformable convolution
dcnV2CudaForward(stat, handle, dcnV2CudaForward(stat, handle,
@@ -116,7 +116,7 @@ public:
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a=buf;
tk::dnn::writeBUF(buf, chunk_dim); tk::dnn::writeBUF(buf, chunk_dim);
tk::dnn::writeBUF(buf, kh); tk::dnn::writeBUF(buf, kh);
tk::dnn::writeBUF(buf, kw); tk::dnn::writeBUF(buf, kw);
@@ -163,6 +163,7 @@ public:
for(int i=0; i<dim_ones; i++) for(int i=0; i<dim_ones; i++)
tk::dnn::writeBUF(buf, aus[i]); tk::dnn::writeBUF(buf, aus[i]);
free(aus); free(aus);
assert(buf == a + getSerializationSize());
} }
cublasStatus_t stat; cublasStatus_t stat;
+2 -1
View File
@@ -65,12 +65,13 @@ public:
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a = buf;
tk::dnn::writeBUF(buf, c); tk::dnn::writeBUF(buf, c);
tk::dnn::writeBUF(buf, h); tk::dnn::writeBUF(buf, h);
tk::dnn::writeBUF(buf, w); tk::dnn::writeBUF(buf, w);
tk::dnn::writeBUF(buf, rows); tk::dnn::writeBUF(buf, rows);
tk::dnn::writeBUF(buf, cols); tk::dnn::writeBUF(buf, cols);
assert(buf == a + getSerializationSize());
} }
int c, h, w; int c, h, w;
@@ -55,7 +55,7 @@ public:
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a=buf;
tk::dnn::writeBUF(buf, this->c); tk::dnn::writeBUF(buf, this->c);
tk::dnn::writeBUF(buf, this->h); tk::dnn::writeBUF(buf, this->h);
@@ -65,6 +65,7 @@ public:
tk::dnn::writeBUF(buf, this->stride_W); tk::dnn::writeBUF(buf, this->stride_W);
tk::dnn::writeBUF(buf, this->winSize); tk::dnn::writeBUF(buf, this->winSize);
tk::dnn::writeBUF(buf, this->padding); tk::dnn::writeBUF(buf, this->padding);
assert(buf == a + getSerializationSize());
} }
int n, c, h, w; int n, c, h, w;
+2 -1
View File
@@ -73,13 +73,14 @@ public:
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a=buf;
tk::dnn::writeBUF(buf, classes); tk::dnn::writeBUF(buf, classes);
tk::dnn::writeBUF(buf, coords); tk::dnn::writeBUF(buf, coords);
tk::dnn::writeBUF(buf, num); tk::dnn::writeBUF(buf, num);
tk::dnn::writeBUF(buf, c); tk::dnn::writeBUF(buf, c);
tk::dnn::writeBUF(buf, h); tk::dnn::writeBUF(buf, h);
tk::dnn::writeBUF(buf, w); tk::dnn::writeBUF(buf, w);
assert(buf == a + getSerializationSize());
} }
int c, h, w; int c, h, w;
+2 -1
View File
@@ -52,11 +52,12 @@ public:
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a=buf;
tk::dnn::writeBUF(buf, stride); tk::dnn::writeBUF(buf, stride);
tk::dnn::writeBUF(buf, c); tk::dnn::writeBUF(buf, c);
tk::dnn::writeBUF(buf, h); tk::dnn::writeBUF(buf, h);
tk::dnn::writeBUF(buf, w); tk::dnn::writeBUF(buf, w);
assert(buf == a + getSerializationSize());
} }
int c, h, w, stride; int c, h, w, stride;
+2 -1
View File
@@ -50,11 +50,12 @@ public:
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a = buf;
tk::dnn::writeBUF(buf, n); tk::dnn::writeBUF(buf, n);
tk::dnn::writeBUF(buf, c); tk::dnn::writeBUF(buf, c);
tk::dnn::writeBUF(buf, h); tk::dnn::writeBUF(buf, h);
tk::dnn::writeBUF(buf, w); tk::dnn::writeBUF(buf, w);
assert(buf == a + getSerializationSize());
} }
int n, c, h, w; int n, c, h, w;
+2 -1
View File
@@ -52,7 +52,7 @@ public:
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a=buf;
tk::dnn::writeBUF(buf, o_c); tk::dnn::writeBUF(buf, o_c);
tk::dnn::writeBUF(buf, o_h); tk::dnn::writeBUF(buf, o_h);
@@ -61,6 +61,7 @@ public:
tk::dnn::writeBUF(buf, i_c); tk::dnn::writeBUF(buf, i_c);
tk::dnn::writeBUF(buf, i_h); tk::dnn::writeBUF(buf, i_h);
tk::dnn::writeBUF(buf, i_w); tk::dnn::writeBUF(buf, i_w);
assert(buf == a + getSerializationSize());
} }
int i_c, i_h, i_w, o_c, o_h, o_w; int i_c, i_h, i_w, o_c, o_h, o_w;
+20 -10
View File
@@ -8,7 +8,9 @@ class RouteRT : public IPlugin {
*/ */
public: public:
RouteRT() { RouteRT(int groups, int group_id) {
this->groups = groups;
this->group_id = group_id;
} }
~RouteRT(){ ~RouteRT(){
@@ -22,7 +24,7 @@ public:
Dims getOutputDimensions(int index, const Dims* inputs, int nbInputDims) override { Dims getOutputDimensions(int index, const Dims* inputs, int nbInputDims) override {
int out_c = 0; int out_c = 0;
for(int i=0; i<nbInputDims; i++) out_c += inputs[i].d[0]; for(int i=0; i<nbInputDims; i++) out_c += inputs[i].d[0];
return DimsCHW{out_c, inputs[0].d[1], inputs[0].d[2]}; return DimsCHW{out_c/groups, inputs[0].d[1], inputs[0].d[2]};
} }
void configure(const Dims* inputDims, int nbInputs, const Dims* outputDims, int nbOutputs, int maxBatchSize) override { void configure(const Dims* inputDims, int nbInputs, const Dims* outputDims, int nbOutputs, int maxBatchSize) override {
@@ -34,6 +36,7 @@ public:
} }
h = inputDims[0].d[1]; h = inputDims[0].d[1];
w = inputDims[0].d[2]; w = inputDims[0].d[2];
c /= groups;
} }
int initialize() override { int initialize() override {
@@ -52,12 +55,15 @@ public:
dnnType *dstData = reinterpret_cast<dnnType*>(outputs[0]); dnnType *dstData = reinterpret_cast<dnnType*>(outputs[0]);
int offset = 0; for(int b=0; b<batchSize; b++) {
for(int i=0; i<in; i++) { int offset = 0;
dnnType *input = (dnnType*)reinterpret_cast<const dnnType*>(inputs[i]); for(int i=0; i<in; i++) {
int in_dim = c_in[i]*h*w; dnnType *input = (dnnType*)reinterpret_cast<const dnnType*>(inputs[i]);
checkCuda( cudaMemcpyAsync(dstData + offset, input, in_dim*sizeof(dnnType), cudaMemcpyDeviceToDevice, stream) ); int in_dim = c_in[i]*h*w;
offset += in_dim; int part_in_dim = in_dim / this->groups;
checkCuda( cudaMemcpyAsync(dstData + b*c*w*h + offset, input + b*c*w*h*groups + this->group_id*part_in_dim, part_in_dim*sizeof(dnnType), cudaMemcpyDeviceToDevice, stream) );
offset += part_in_dim;
}
} }
return 0; return 0;
@@ -65,11 +71,13 @@ public:
virtual size_t getSerializationSize() override { virtual size_t getSerializationSize() override {
return (4+MAX_INPUTS)*sizeof(int); return (6+MAX_INPUTS)*sizeof(int);
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a=buf;
tk::dnn::writeBUF(buf, groups);
tk::dnn::writeBUF(buf, group_id);
tk::dnn::writeBUF(buf, in); tk::dnn::writeBUF(buf, in);
for(int i=0; i<MAX_INPUTS; i++) for(int i=0; i<MAX_INPUTS; i++)
tk::dnn::writeBUF(buf, c_in[i]); tk::dnn::writeBUF(buf, c_in[i]);
@@ -77,10 +85,12 @@ public:
tk::dnn::writeBUF(buf, c); tk::dnn::writeBUF(buf, c);
tk::dnn::writeBUF(buf, h); tk::dnn::writeBUF(buf, h);
tk::dnn::writeBUF(buf, w); tk::dnn::writeBUF(buf, w);
assert(buf == a + getSerializationSize());
} }
static const int MAX_INPUTS = 4; static const int MAX_INPUTS = 4;
int in; int in;
int c_in[MAX_INPUTS]; int c_in[MAX_INPUTS];
int c, h, w; int c, h, w;
int groups, group_id;
}; };
+2 -1
View File
@@ -59,7 +59,7 @@ public:
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a=buf;
tk::dnn::writeBUF(buf, bc); tk::dnn::writeBUF(buf, bc);
tk::dnn::writeBUF(buf, bh); tk::dnn::writeBUF(buf, bh);
tk::dnn::writeBUF(buf, bw); tk::dnn::writeBUF(buf, bw);
@@ -67,6 +67,7 @@ public:
tk::dnn::writeBUF(buf, c); tk::dnn::writeBUF(buf, c);
tk::dnn::writeBUF(buf, h); tk::dnn::writeBUF(buf, h);
tk::dnn::writeBUF(buf, w); tk::dnn::writeBUF(buf, w);
assert(buf == a + getSerializationSize());
} }
+2 -1
View File
@@ -54,11 +54,12 @@ public:
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a=buf;
tk::dnn::writeBUF(buf, stride); tk::dnn::writeBUF(buf, stride);
tk::dnn::writeBUF(buf, c); tk::dnn::writeBUF(buf, c);
tk::dnn::writeBUF(buf, h); tk::dnn::writeBUF(buf, h);
tk::dnn::writeBUF(buf, w); tk::dnn::writeBUF(buf, w);
assert(buf == a + getSerializationSize());
} }
int c, h, w, stride; int c, h, w, stride;
+43 -23
View File
@@ -8,12 +8,15 @@ class YoloRT : public IPlugin {
public: public:
YoloRT(int classes, int num, tk::dnn::Yolo *yolo = nullptr, int n_masks=3, float scale_xy=1) { YoloRT(int classes, int num, tk::dnn::Yolo *yolo = nullptr, int n_masks=3, float scale_xy=1, float nms_thresh=0.45, int nms_kind=0, int new_coords=0) {
this->classes = classes; this->classes = classes;
this->num = num; this->num = num;
this->n_masks = n_masks; this->n_masks = n_masks;
this->scaleXY = scale_xy; this->scaleXY = scale_xy;
this->nms_thresh = nms_thresh;
this->nms_kind = nms_kind;
this->new_coords = new_coords;
mask = new dnnType[n_masks]; mask = new dnnType[n_masks];
bias = new dnnType[num*n_masks*2]; bias = new dnnType[num*n_masks*2];
@@ -61,17 +64,23 @@ public:
checkCuda( cudaMemcpyAsync(dstData, srcData, batchSize*c*h*w*sizeof(dnnType), cudaMemcpyDeviceToDevice, stream)); checkCuda( cudaMemcpyAsync(dstData, srcData, batchSize*c*h*w*sizeof(dnnType), cudaMemcpyDeviceToDevice, stream));
for (int b = 0; b < batchSize; ++b){
for(int n = 0; n < n_masks; ++n){
int index = entry_index(b, n*w*h, 0);
activationLOGISTICForward(srcData + index, dstData + index, 2*w*h, stream);
if (this->scaleXY != 1) scalAdd(dstData + index, 2 * w*h, this->scaleXY, -0.5*(this->scaleXY - 1), 1); for (int b = 0; b < batchSize; ++b){
for(int n = 0; n < n_masks; ++n){
int index = entry_index(b, n*w*h, 0);
if (new_coords == 1){
if (this->scaleXY != 1) scalAdd(dstData + index, 2 * w*h, this->scaleXY, -0.5*(this->scaleXY - 1), 1);
}
else{
activationLOGISTICForward(srcData + index, dstData + index, 2*w*h, stream); //x,y
index = entry_index(b, n*w*h, 4); if (this->scaleXY != 1) scalAdd(dstData + index, 2 * w*h, this->scaleXY, -0.5*(this->scaleXY - 1), 1);
activationLOGISTICForward(srcData + index, dstData + index, (1+classes)*w*h, stream);
} index = entry_index(b, n*w*h, 4);
} activationLOGISTICForward(srcData + index, dstData + index, (1+classes)*w*h, stream);
}
}
}
//std::cout<<"YOLO END\n"; //std::cout<<"YOLO END\n";
return 0; return 0;
@@ -79,22 +88,29 @@ public:
virtual size_t getSerializationSize() override { virtual size_t getSerializationSize() override {
return 6*sizeof(int) + sizeof(float)+ n_masks*sizeof(dnnType) + num*n_masks*2*sizeof(dnnType) + YOLORT_CLASSNAME_W*classes*sizeof(char); return 8*sizeof(int) + 2*sizeof(float)+ n_masks*sizeof(dnnType) + num*n_masks*2*sizeof(dnnType) + YOLORT_CLASSNAME_W*classes*sizeof(char);
} }
virtual void serialize(void* buffer) override { virtual void serialize(void* buffer) override {
char *buf = reinterpret_cast<char*>(buffer); char *buf = reinterpret_cast<char*>(buffer),*a=buf;
tk::dnn::writeBUF(buf, classes); tk::dnn::writeBUF(buf, classes); //std::cout << "Classes :" << classes << std::endl;
tk::dnn::writeBUF(buf, num); tk::dnn::writeBUF(buf, num); //std::cout << "Num : " << num << std::endl;
tk::dnn::writeBUF(buf, n_masks); tk::dnn::writeBUF(buf, n_masks); //std::cout << "N_Masks" << n_masks << std::endl;
tk::dnn::writeBUF(buf, c); tk::dnn::writeBUF(buf, scaleXY); //std::cout << "ScaleXY :" << scaleXY << std::endl;
tk::dnn::writeBUF(buf, h); tk::dnn::writeBUF(buf, nms_thresh); //std::cout << "nms_thresh :" << nms_thresh << std::endl;
tk::dnn::writeBUF(buf, w); tk::dnn::writeBUF(buf, nms_kind); //std::cout << "nms_kind : " << nms_kind << std::endl;
tk::dnn::writeBUF(buf, scaleXY); tk::dnn::writeBUF(buf, new_coords); //std::cout << "new_coords : " << new_coords << std::endl;
for(int i=0; i<n_masks; i++) tk::dnn::writeBUF(buf, c); //std::cout << "C : " << c << std::endl;
tk::dnn::writeBUF(buf, mask[i]); tk::dnn::writeBUF(buf, h); //std::cout << "H : " << h << std::endl;
for(int i=0; i<n_masks*2*num; i++) tk::dnn::writeBUF(buf, w); //std::cout << "C : " << c << std::endl;
tk::dnn::writeBUF(buf, bias[i]); for (int i = 0; i < n_masks; i++)
{
tk::dnn::writeBUF(buf, mask[i]); //std::cout << "mask[i] : " << mask[i] << std::endl;
}
for (int i = 0; i < n_masks * 2 * num; i++)
{
tk::dnn::writeBUF(buf, bias[i]); //std::cout << "bias[i] : " << bias[i] << std::endl;
}
// save classes names // save classes names
for(int i=0; i<classes; i++) { for(int i=0; i<classes; i++) {
@@ -104,11 +120,15 @@ public:
tk::dnn::writeBUF(buf, tmp[j]); tk::dnn::writeBUF(buf, tmp[j]);
} }
} }
assert(buf == a + getSerializationSize());
} }
int c, h, w; int c, h, w;
int classes, num, n_masks; int classes, num, n_masks;
float scaleXY; float scaleXY;
float nms_thresh;
int nms_kind;
int new_coords;
std::vector<std::string> classesNames; std::vector<std::string> classesNames;
dnnType *mask; dnnType *mask;
+5 -4
View File
@@ -20,7 +20,7 @@ int testInference(std::vector<std::string> input_bins, std::vector<std::string>
} }
if(output_bins.size() != outputs.size()) { if(output_bins.size() != outputs.size()) {
std::cout<<output_bins.size()<<" "<<outputs.size()<<"\n"; std::cout<<output_bins.size()<<" "<<outputs.size()<<"\n";
FatalError("outputs size missmatch"); FatalError("outputs size mismatch");
} }
// Load input // Load input
@@ -29,7 +29,8 @@ int testInference(std::vector<std::string> input_bins, std::vector<std::string>
readBinaryFile(input_bins[0], net->input_dim.tot(), &input_h, &data); readBinaryFile(input_bins[0], net->input_dim.tot(), &input_h, &data);
// outputs // outputs
dnnType *cudnn_out[outputs.size()], *rt_out[outputs.size()]; //dnnType *cudnn_out[outputs.size()], *rt_out[outputs.size()];
std::vector<dnnType *> cudnn_out,rt_out;
tk::dnn::dataDim_t dim1 = net->input_dim; //input dim tk::dnn::dataDim_t dim1 = net->input_dim; //input dim
printCenteredTitle(" CUDNN inference ", '=', 30); { printCenteredTitle(" CUDNN inference ", '=', 30); {
@@ -39,7 +40,7 @@ int testInference(std::vector<std::string> input_bins, std::vector<std::string>
TKDNN_TSTOP TKDNN_TSTOP
dim1.print(); dim1.print();
} }
for(int i=0; i<outputs.size(); i++) cudnn_out[i] = outputs[i]->dstData; for(int i=0; i<outputs.size(); i++) cudnn_out.push_back(outputs[i]->dstData);
if(netRT != nullptr) { if(netRT != nullptr) {
tk::dnn::dataDim_t dim2 = net->input_dim; tk::dnn::dataDim_t dim2 = net->input_dim;
@@ -50,7 +51,7 @@ int testInference(std::vector<std::string> input_bins, std::vector<std::string>
TKDNN_TSTOP TKDNN_TSTOP
dim2.print(); dim2.print();
} }
for(int i=0; i<outputs.size(); i++) rt_out[i] = (dnnType*)netRT->buffersRT[i+1]; for(int i=0; i<outputs.size(); i++) rt_out.push_back((dnnType*)netRT->buffersRT[i+1]);
} }
int ret_cudnn = 0, ret_tensorrt = 0, ret_cudnn_tensorrt = 0; int ret_cudnn = 0, ret_tensorrt = 0, ret_cudnn_tensorrt = 0;
+13
View File
@@ -12,8 +12,12 @@
#include <cublas_v2.h> #include <cublas_v2.h>
#include <cudnn.h> #include <cudnn.h>
#ifdef __linux__
#include <unistd.h> #include <unistd.h>
#endif
#include <ios> #include <ios>
#include <chrono>
#define dnnType float #define dnnType float
@@ -39,6 +43,7 @@
#define TKDNN_VERBOSE 1 #define TKDNN_VERBOSE 1
// Simple Timer // Simple Timer
#ifdef __linux__
#define TKDNN_TSTART timespec start, end; \ #define TKDNN_TSTART timespec start, end; \
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
@@ -48,6 +53,14 @@
if(show) std::cout<<col<<"Time:"<<std::setw(16)<<t_ns<<" ms\n"<<COL_END; if(show) std::cout<<col<<"Time:"<<std::setw(16)<<t_ns<<" ms\n"<<COL_END;
#define TKDNN_TSTOP TKDNN_TSTOP_C(COL_CYANB, TKDNN_VERBOSE) #define TKDNN_TSTOP TKDNN_TSTOP_C(COL_CYANB, TKDNN_VERBOSE)
#elif _WIN32
#define TKDNN_TSTART auto start = std::chrono::high_resolution_clock::now();
#define TKDNN_TSTOP auto stop = std::chrono::high_resolution_clock::now(); \
std::chrono::duration<double> duration = stop -start; \
auto time_ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration);\
double t_ns = time_ms.count();
#endif
/******************************************************** /********************************************************
* Prints the error message, and exits * Prints the error message, and exits
+39
View File
@@ -0,0 +1,39 @@
import os
import urllib.request as dowReq
import zipfile
val = input("Enter BDD or COCO :")
if(val == "COCO"):
url = "https://cloud.hipert.unimore.it/s/LNxBDk4wzqXPL8c/download"
lib = "..\demo\COCO_val2017"
lib_zip = "COCO_val2017.zip"
elif(val == "BDD"):
url = "https://cloud.hipert.unimore.it/s/bikqk3FzCq2tg4D/download"
lib = "..\demo\BDD100k_val"
lib_zip = "BDD100k_val.zip"
dowReq.urlretrieve(url,lib_zip)
with zipfile.ZipFile(lib_zip,'r') as zip_ref:
zip_ref.extractall(lib)
labelFolder = lib + "\labels"
imageFolder = lib + "\images"
file1 = open(".\\..\\demo\\all_labels.txt","a")
path1 = os.path.realpath(labelFolder)
for file in os.listdir(labelFolder):
valTemp = path1 + "\\" + file
valTemp = valTemp + '\n'
file1.write(valTemp)
file1.close()
file2 = open(".\\..\\demo\\all_images.txt","a")
path2 = os.path.realpath(imageFolder)
for file in os.listdir(imageFolder):
pathtemp = path2 + "\\" + file
pathtemp = pathtemp + '\n'
file2.write(pathtemp)
file2.close()
print("Completed")
+6 -2
View File
@@ -69,12 +69,16 @@ do
echo -e "${ORANGE}Batch $TKDNN_BATCHSIZE ${NC}" echo -e "${ORANGE}Batch $TKDNN_BATCHSIZE ${NC}"
test_net mnist test_net mnist
./test_imuodom &>> $out_file # ./test_imuodom &>> $out_file
print_output $? imuodom # print_output $? imuodom
test_net shelfnet test_net shelfnet
test_net shelfnet_berkeley
test_net yolo4 test_net yolo4
test_net yolo4-csp
test_net yolo4x
test_net yolo4_berkeley test_net yolo4_berkeley
test_net yolo4tiny
test_net yolo3 test_net yolo3
test_net yolo3_berkeley test_net yolo3_berkeley
test_net yolo3_coco4 test_net yolo3_coco4
+4
View File
@@ -52,6 +52,10 @@ dnnType* Activation::infer(dataDim_t &dim, dnnType* srcData) {
else if(act_mode == ACTIVATION_MISH) { else if(act_mode == ACTIVATION_MISH) {
activationMishForward(srcData, dstData, dim.tot()); activationMishForward(srcData, dstData, dim.tot());
}
else if(act_mode == ACTIVATION_LOGISTIC) {
activationLOGISTICForward(srcData, dstData, dim.tot());
} else { } else {
dnnType alpha = dnnType(1); dnnType alpha = dnnType(1);
dnnType beta = dnnType(0); dnnType beta = dnnType(0);
+6 -5
View File
@@ -3,11 +3,12 @@
namespace tk { namespace dnn { namespace tk { namespace dnn {
bool CenternetDetection::init(const std::string& tensor_path, const int n_classes, const int n_batches){ bool CenternetDetection::init(const std::string& tensor_path, const int n_classes, const int n_batches, const float conf_thresh){
std::cout<<(tensor_path).c_str()<<"\n"; std::cout<<(tensor_path).c_str()<<"\n";
netRT = new tk::dnn::NetworkRT(NULL, (tensor_path).c_str() ); netRT = new tk::dnn::NetworkRT(NULL, (tensor_path).c_str() );
classes = n_classes; classes = n_classes;
nBatches = n_batches; nBatches = n_batches;
confThreshold = conf_thresh;
dim = netRT->input_dim; dim = netRT->input_dim;
@@ -371,10 +372,10 @@ void CenternetDetection::postprocess(const int bi, const bool mAP){
// std::cout<<"th: "<<scores[j]<<" - cl: "<<clses[j]<<" i: "<<i<<std::endl; // std::cout<<"th: "<<scores[j]<<" - cl: "<<clses[j]<<" i: "<<i<<std::endl;
//add coco bbox //add coco bbox
//det[0:4], i, det[4] //det[0:4], i, det[4]
int x0 = target_coords[j*4]; float x0 = target_coords[j*4];
int y0 = target_coords[j*4+1]; float y0 = target_coords[j*4+1];
int x1 = target_coords[j*4+2]; float x1 = target_coords[j*4+2];
int y1 = target_coords[j*4+3]; float y1 = target_coords[j*4+3];
int obj_class = clses[j]; int obj_class = clses[j];
float prob = scores[j]; float prob = scores[j];
// std::cout<<"("<<x0<<", "<<y0<<"),("<<x1<<", "<<y1<<")"<<std::endl; // std::cout<<"("<<x0<<", "<<y0<<"),("<<x1<<", "<<y1<<")"<<std::endl;
+18 -13
View File
@@ -62,25 +62,30 @@ void Conv2d::initCUDNN(bool back) {
// init workspace // init workspace
workSpace = NULL; workSpace = NULL;
ws_sizeInBytes = 0; ws_sizeInBytes = 0;
int algo_count = 0;
if(back) { if(back) {
checkCUDNN( cudnnGetConvolutionBackwardDataAlgorithm(net->cudnnHandle, checkCUDNN( cudnnGetConvolutionBackwardDataAlgorithm_v7(net->cudnnHandle,
filterDesc, dstTensor, convDesc, srcTensor, filterDesc, dstTensor, convDesc, srcTensor, 1, &algo_count, &bwAlgo) );
CUDNN_CONVOLUTION_BWD_DATA_PREFER_FASTEST, 0, &bwAlgo) );
checkCUDNN(cudnnGetConvolutionBackwardDataWorkspaceSize(net->cudnnHandle, checkCUDNN(cudnnGetConvolutionBackwardDataWorkspaceSize(net->cudnnHandle,
filterDesc, dstTensor, convDesc, srcTensor, filterDesc, dstTensor, convDesc, srcTensor,
bwAlgo, &ws_sizeInBytes)); bwAlgo.algo, &ws_sizeInBytes));
// invert tensors // invert tensors
srcTensorDesc = dstTensor; srcTensorDesc = dstTensor;
dstTensorDesc = srcTensor; dstTensorDesc = srcTensor;
} else { } else {
checkCUDNN( cudnnGetConvolutionForwardAlgorithm(net->cudnnHandle,
srcTensor, filterDesc, convDesc, dstTensor, checkCUDNN( cudnnGetConvolutionForwardAlgorithm_v7(net->cudnnHandle,
CUDNN_CONVOLUTION_FWD_PREFER_FASTEST, 0, &algo) ); srcTensor, filterDesc, convDesc, dstTensor,
checkCUDNN(cudnnGetConvolutionForwardWorkspaceSize(net->cudnnHandle, 1, &algo_count, &algo) );
srcTensor, filterDesc, convDesc, dstTensor, checkCUDNN(cudnnGetConvolutionForwardWorkspaceSize(net->cudnnHandle,
algo, &ws_sizeInBytes)); srcTensor, filterDesc, convDesc, dstTensor,
algo.algo, &ws_sizeInBytes));
} }
if(algo_count < 1)
FatalError("Cannot retrieve convolutional algo");
} }
void Conv2d::inferCUDNN(dnnType* srcData, bool back) { void Conv2d::inferCUDNN(dnnType* srcData, bool back) {
@@ -91,12 +96,12 @@ void Conv2d::inferCUDNN(dnnType* srcData, bool back) {
checkCUDNN(cudnnConvolutionBackwardData(net->cudnnHandle, checkCUDNN(cudnnConvolutionBackwardData(net->cudnnHandle,
&alpha, filterDesc, data_d, &alpha, filterDesc, data_d,
srcTensorDesc, srcData, srcTensorDesc, srcData,
convDesc, bwAlgo, workSpace, ws_sizeInBytes, convDesc, bwAlgo.algo, workSpace, ws_sizeInBytes,
&beta, dstTensorDesc, dstData)); &beta, dstTensorDesc, dstData));
} else { } else {
checkCUDNN(cudnnConvolutionForward(net->cudnnHandle, checkCUDNN(cudnnConvolutionForward(net->cudnnHandle,
&alpha, srcTensorDesc, srcData, filterDesc, &alpha, srcTensorDesc, srcData, filterDesc,
data_d, convDesc, algo, workSpace, ws_sizeInBytes, data_d, convDesc, algo.algo, workSpace, ws_sizeInBytes,
&beta, dstTensorDesc, dstData)); &beta, dstTensorDesc, dstData));
} }
+17 -4
View File
@@ -37,7 +37,10 @@ namespace tk { namespace dnn {
std::string name,value; std::string name,value;
if(!divideNameAndValue(line, name, value)) if(!divideNameAndValue(line, name, value))
return false; return false;
if(name.find("width") != std::string::npos)
if(name.find("new_coords") != std::string::npos)
fields.new_coords = std::stoi(value);
else if(name.find("width") != std::string::npos)
fields.width = std::stoi(value); fields.width = std::stoi(value);
else if(name.find("height") != std::string::npos) else if(name.find("height") != std::string::npos)
fields.height = std::stoi(value); fields.height = std::stoi(value);
@@ -75,8 +78,17 @@ namespace tk { namespace dnn {
fields.coords = std::stoi(value); fields.coords = std::stoi(value);
else if(name.find("groups") != std::string::npos) else if(name.find("groups") != std::string::npos)
fields.groups = std::stoi(value); fields.groups = std::stoi(value);
else if(name.find("group_id") != std::string::npos)
fields.group_id = std::stoi(value);
else if(name.find("scale_x_y") != std::string::npos) else if(name.find("scale_x_y") != std::string::npos)
fields.scale_xy = std::stof(value); fields.scale_xy = std::stof(value);
else if(name.find("beta_nms") != std::string::npos)
fields.nms_thresh = std::stof(value);
else if(name.find("nms_kind") != std::string::npos){
if(value == "greedynms") fields.nms_kind = 0;
else if(value == "diounms") fields.nms_kind = 1;
else std::cout<<"Not supported nms_kind "<<value<<", setting to greedynms"<<std::endl;
}
else if(name.find("from") != std::string::npos) else if(name.find("from") != std::string::npos)
fields.layers.push_back(std::stof(value)); fields.layers.push_back(std::stof(value));
else if(name.find("mask") != std::string::npos){ else if(name.find("mask") != std::string::npos){
@@ -148,7 +160,7 @@ namespace tk { namespace dnn {
//std::cout<<"Route to "<<layerIdx<<" "<<netLayers[layerIdx]->getLayerName()<<"\n"; //std::cout<<"Route to "<<layerIdx<<" "<<netLayers[layerIdx]->getLayerName()<<"\n";
layers.push_back(netLayers[layerIdx]); layers.push_back(netLayers[layerIdx]);
} }
netLayers.push_back(new tk::dnn::Route(net, layers.data(), layers.size())); netLayers.push_back(new tk::dnn::Route(net, layers.data(), layers.size(), f.groups, f.group_id));
} else if(f.type == "reorg") { } else if(f.type == "reorg") {
netLayers.push_back(new tk::dnn::Reorg(net, f.stride_x)); netLayers.push_back(new tk::dnn::Reorg(net, f.stride_x));
@@ -159,7 +171,7 @@ namespace tk { namespace dnn {
} else if(f.type == "yolo") { } else if(f.type == "yolo") {
std::string wgs = wgs_path + "/g" + std::to_string(netLayers.size()) + ".bin"; std::string wgs = wgs_path + "/g" + std::to_string(netLayers.size()) + ".bin";
//printf("%d %d %s %d %f\n", f.classes, f.num/f.n_mask, wgs.c_str(), f.n_mask, f.scale_xy); //printf("%d %d %s %d %f\n", f.classes, f.num/f.n_mask, wgs.c_str(), f.n_mask, f.scale_xy);
tk::dnn::Yolo *l = new tk::dnn::Yolo(net, f.classes, f.num/f.n_mask, wgs, f.n_mask, f.scale_xy); tk::dnn::Yolo *l = new tk::dnn::Yolo(net, f.classes, f.num/f.n_mask, wgs, f.n_mask, f.scale_xy, f.nms_thresh, (tk::dnn::Yolo::nmsKind_t) f.nms_kind, f.new_coords);
if(names.size() != f.classes) if(names.size() != f.classes)
FatalError("Mismatch between number of classes and names"); FatalError("Mismatch between number of classes and names");
l->classesNames = names; l->classesNames = names;
@@ -175,6 +187,7 @@ namespace tk { namespace dnn {
if(f.activation == "relu") act = tkdnnActivationMode_t(CUDNN_ACTIVATION_RELU); if(f.activation == "relu") act = tkdnnActivationMode_t(CUDNN_ACTIVATION_RELU);
else if(f.activation == "leaky") act = tk::dnn::ACTIVATION_LEAKY; else if(f.activation == "leaky") act = tk::dnn::ACTIVATION_LEAKY;
else if(f.activation == "mish") act = tk::dnn::ACTIVATION_MISH; else if(f.activation == "mish") act = tk::dnn::ACTIVATION_MISH;
else if(f.activation == "logistic") act = tk::dnn::ACTIVATION_LOGISTIC;
else { FatalError("activation not supported: " + f.activation); } else { FatalError("activation not supported: " + f.activation); }
netLayers[netLayers.size()-1] = new tk::dnn::Activation(net, act); netLayers[netLayers.size()-1] = new tk::dnn::Activation(net, act);
}; };
@@ -199,7 +212,7 @@ namespace tk { namespace dnn {
tk::dnn::Network *net = nullptr; tk::dnn::Network *net = nullptr;
// layers without activations to retrive correct id number // layers without activations to retrieve correct id number
std::vector<tk::dnn::Layer*> netLayers; std::vector<tk::dnn::Layer*> netLayers;
std::ifstream if_cfg(cfg_file); std::ifstream if_cfg(cfg_file);
+1 -1
View File
@@ -95,7 +95,7 @@ dnnType* DeformConv2d::infer(dataDim_t &dim, dnnType* srcData) {
// split conv2d outputs into offset and mask // split conv2d outputs into offset and mask
checkCuda(cudaMemcpy(offset, output_conv, 2*chunk_dim*sizeof(dnnType), cudaMemcpyDeviceToDevice)); checkCuda(cudaMemcpy(offset, output_conv, 2*chunk_dim*sizeof(dnnType), cudaMemcpyDeviceToDevice));
checkCuda(cudaMemcpy(mask, output_conv + 2*chunk_dim, chunk_dim*sizeof(dnnType), cudaMemcpyDeviceToDevice)); checkCuda(cudaMemcpy(mask, output_conv + 2*chunk_dim, chunk_dim*sizeof(dnnType), cudaMemcpyDeviceToDevice));
// kernel sigmoide // kernel sigmoid
activationSIGMOIDForward(mask, mask, chunk_dim); activationSIGMOIDForward(mask, mask, chunk_dim);
// deformable convolution // deformable convolution
+1 -1
View File
@@ -37,7 +37,7 @@ dnnType* Dense::infer(dataDim_t &dim, dnnType* srcData) {
// place bias into dstData // place bias into dstData
checkCuda( cudaMemcpy(dstData, bias_d, dim_y*sizeof(dnnType), cudaMemcpyDeviceToDevice) ); checkCuda( cudaMemcpy(dstData, bias_d, dim_y*sizeof(dnnType), cudaMemcpyDeviceToDevice) );
//do matrix moltiplication //do matrix multiplication
checkERROR( cublasSgemv(net->cublasHandle, CUBLAS_OP_T, checkERROR( cublasSgemv(net->cublasHandle, CUBLAS_OP_T,
dim_x, dim_y, dim_x, dim_y,
&alpha, &alpha,
+6 -13
View File
@@ -132,21 +132,14 @@ void BatchStream::readCVimage(std::string inputFileName, std::vector<float>& res
void BatchStream::readLabels(std::string inputFileName, std::vector<float>& ris) { void BatchStream::readLabels(std::string inputFileName, std::vector<float>& ris) {
std::ifstream is(inputFileName.c_str()); std::ifstream is(inputFileName.c_str());
//read only the first number: the image sub-portion class
while (true) { std::string line;
while (std::getline(is, line))
{
std::istringstream iss(line);
float val; float val;
is >> val; if(!(iss >> val)) { break; } // error
if (!is) {
break;
}
// insert the first number and skip all others
ris.push_back(val); ris.push_back(val);
while( true ) {
char c;
is >> c;
if (is.peek() == '\n') //detect "\n"
break;
}
} }
} }
+14 -9
View File
@@ -87,17 +87,22 @@ LSTM::LSTM( Network *net, int hiddensize, bool returnSeq, std::string fname_weig
checkCUDNN(cudnnCreateRNNDescriptor(&rnnDesc)); checkCUDNN(cudnnCreateRNNDescriptor(&rnnDesc));
#if CUDNN_MAJOR > 7 #if CUDNN_MAJOR > 7
checkCUDNN(cudnnSetRNNDescriptor_v6(net->cudnnHandle, checkCUDNN(cudnnSetRNNDescriptor_v6(net->cudnnHandle,rnnDesc, stateSize, numLayers, dropoutDesc,
cudnnRNNInputMode_t::CUDNN_LINEAR_INPUT,
//(bidirectional ? cudnnDirectionMode_t::CUDNN_BIDIRECTIONAL : cudnnDirectionMode_t::CUDNN_UNIDIRECTIONAL),
cudnnDirectionMode_t::CUDNN_UNIDIRECTIONAL,
cudnnRNNMode_t::CUDNN_LSTM,
cudnnRNNAlgo_t::CUDNN_RNN_ALGO_STANDARD,
net->dataType));
#else #else
checkCUDNN(cudnnSetRNNDescriptor(net->cudnnHandle, checkCUDNN(cudnnSetRNNDescriptor(net->cudnnHandle,rnnDesc, stateSize, numLayers, dropoutDesc,
#endif
rnnDesc, stateSize, numLayers, dropoutDesc,
cudnnRNNInputMode_t::CUDNN_LINEAR_INPUT, cudnnRNNInputMode_t::CUDNN_LINEAR_INPUT,
//(bidirectional ? cudnnDirectionMode_t::CUDNN_BIDIRECTIONAL : cudnnDirectionMode_t::CUDNN_UNIDIRECTIONAL), //(bidirectional ? cudnnDirectionMode_t::CUDNN_BIDIRECTIONAL : cudnnDirectionMode_t::CUDNN_UNIDIRECTIONAL),
cudnnDirectionMode_t::CUDNN_UNIDIRECTIONAL, cudnnDirectionMode_t::CUDNN_UNIDIRECTIONAL,
cudnnRNNMode_t::CUDNN_LSTM, cudnnRNNMode_t::CUDNN_LSTM,
cudnnRNNAlgo_t::CUDNN_RNN_ALGO_STANDARD, cudnnRNNAlgo_t::CUDNN_RNN_ALGO_STANDARD,
net->dataType)); net->dataType));
#endif
// Get temp space sizes // Get temp space sizes
@@ -133,7 +138,7 @@ LSTM::LSTM( Network *net, int hiddensize, bool returnSeq, std::string fname_weig
output_dim = input_dim; output_dim = input_dim;
output_dim.c = stateSize*(bidirectional ? 2 : 1); output_dim.c = stateSize*(bidirectional ? 2 : 1);
// if retunseq is disabled only the last timestep is returned // if retunseq is disabled only the last timestamp is returned
if(!returnSeq) { if(!returnSeq) {
output_dim.h = 1; output_dim.h = 1;
output_dim.w = 1; output_dim.w = 1;
@@ -254,7 +259,7 @@ dnnType* LSTM::infer(dataDim_t &dim, dnnType* srcData) {
rnnDesc, rnnDesc,
seqLen, // number of time steps (nT) seqLen, // number of time steps (nT)
x_desc_vec_.data(), // input array of desc (nT*nC_in) x_desc_vec_.data(), // input array of desc (nT*nC_in)
srcF, // input pointer srcF, // input pointer
hx_desc_, // initial hidden state desc hx_desc_, // initial hidden state desc
hx_ptr, // initial hidden state pointer hx_ptr, // initial hidden state pointer
cx_desc_, // initial cell state desc cx_desc_, // initial cell state desc
@@ -281,7 +286,7 @@ dnnType* LSTM::infer(dataDim_t &dim, dnnType* srcData) {
rnnDesc, rnnDesc,
seqLen, // number of time steps (nT) seqLen, // number of time steps (nT)
x_desc_vec_.data(), // input array of desc (nT*nC_in) x_desc_vec_.data(), // input array of desc (nT*nC_in)
srcB, // input pointer srcB, // input pointer
hx_desc_, // initial hidden state desc hx_desc_, // initial hidden state desc
hx_ptr, // initial hidden state pointer hx_ptr, // initial hidden state pointer
cx_desc_, // initial cell state desc cx_desc_, // initial cell state desc
@@ -289,7 +294,7 @@ dnnType* LSTM::infer(dataDim_t &dim, dnnType* srcData) {
w_desc_, // weights desc w_desc_, // weights desc
wb_ptr, // weights pointer wb_ptr, // weights pointer
y_desc_vec_.data(), // output desc (nT*nC_out) y_desc_vec_.data(), // output desc (nT*nC_out)
dstB_NR, // output pointer dstB_NR, // output pointer
hy_desc_, // final hidden state desc hy_desc_, // final hidden state desc
hy_ptr, // final hidden state pointer hy_ptr, // final hidden state pointer
cy_desc_, // final cell state desc cy_desc_, // final cell state desc
@@ -307,7 +312,7 @@ dnnType* LSTM::infer(dataDim_t &dim, dnnType* srcData) {
one_output_dim.c*sizeof(dnnType), cudaMemcpyDeviceToDevice)); one_output_dim.c*sizeof(dnnType), cudaMemcpyDeviceToDevice));
} }
// if retunseq is disabled only the last timestep is returned // if retunseq is disabled only the last timestamp is returned
if(returnSeq) { if(returnSeq) {
// forward transpose // forward transpose
matrixTranspose(net->cublasHandle, dstF, dstData, matrixTranspose(net->cublasHandle, dstF, dstData,
+1 -1
View File
@@ -106,7 +106,7 @@ LayerWgs::LayerWgs(Network *net, int inputs, int outputs,
float2half(tmp_d, variance16_d, b_size); float2half(tmp_d, variance16_d, b_size);
cudaMemcpy(variance16_h, variance16_d, b_size*sizeof(__half), cudaMemcpyDeviceToHost); cudaMemcpy(variance16_h, variance16_d, b_size*sizeof(__half), cudaMemcpyDeviceToHost);
//conver scales //convert scales
float2half(scales_d, scales16_d, b_size); float2half(scales_d, scales16_d, b_size);
cudaMemcpy(scales16_h, scales16_d, b_size*sizeof(__half), cudaMemcpyDeviceToHost); cudaMemcpy(scales16_h, scales16_d, b_size*sizeof(__half), cudaMemcpyDeviceToHost);
+2 -1
View File
@@ -126,12 +126,13 @@ float MobilenetDetection::iou(const tk::dnn::box &a, const tk::dnn::box &b){
return iou; return iou;
} }
bool MobilenetDetection::init(const std::string& tensor_path, const int n_classes, const int n_batches){ bool MobilenetDetection::init(const std::string& tensor_path, const int n_classes, const int n_batches, const float conf_thresh){
std::cout<<(tensor_path).c_str()<<"\n"; std::cout<<(tensor_path).c_str()<<"\n";
netRT = new tk::dnn::NetworkRT(NULL, (tensor_path).c_str()); netRT = new tk::dnn::NetworkRT(NULL, (tensor_path).c_str());
imageSize = netRT->input_dim.h; imageSize = netRT->input_dim.h;
classes = n_classes; classes = n_classes;
nBatches = n_batches; nBatches = n_batches;
confThreshold = conf_thresh;
SSDSpec specs[N_SSDSPEC]; SSDSpec specs[N_SSDSPEC];
+1 -1
View File
@@ -12,7 +12,7 @@ MulAdd::MulAdd(Network *net, dnnType mul, dnnType add) : Layer(net) {
int size = input_dim.tot(); int size = input_dim.tot();
// create a vector with all value setted to add // create a vector with all value set to add
dnnType *add_vector_h = new dnnType[size]; dnnType *add_vector_h = new dnnType[size];
for(int i=0; i<size; i++) for(int i=0; i<size; i++)
add_vector_h[i] = add; add_vector_h[i] = add;
+103 -39
View File
@@ -140,6 +140,7 @@ NetworkRT::NetworkRT(Network *net, const char *name) {
engineRT = builderRT->buildEngineWithConfig(*networkRT, *configRT); engineRT = builderRT->buildEngineWithConfig(*networkRT, *configRT);
#else #else
engineRT = builderRT->buildCudaEngine(*networkRT); engineRT = builderRT->buildCudaEngine(*networkRT);
//engineRT = std::shared_ptr<nvinfer1::ICudaEngine>(builderRT->buildCudaEngine(*networkRT));
#endif #endif
if(engineRT == nullptr) if(engineRT == nullptr)
FatalError("cloud not build cuda engine") FatalError("cloud not build cuda engine")
@@ -163,7 +164,7 @@ NetworkRT::NetworkRT(Network *net, const char *name) {
// note that indices are guaranteed to be less than IEngine::getNbBindings() // note that indices are guaranteed to be less than IEngine::getNbBindings()
buf_input_idx = engineRT->getBindingIndex("data"); buf_input_idx = engineRT->getBindingIndex("data");
buf_output_idx = engineRT->getBindingIndex("out"); buf_output_idx = engineRT->getBindingIndex("out");
std::cout<<"input idex = "<<buf_input_idx<<" -> output index = "<<buf_output_idx<<"\n"; std::cout<<"input index = "<<buf_input_idx<<" -> output index = "<<buf_output_idx<<"\n";
Dims iDim = engineRT->getBindingDimensions(buf_input_idx); Dims iDim = engineRT->getBindingDimensions(buf_input_idx);
@@ -226,7 +227,7 @@ ILayer* NetworkRT::convert_layer(ITensor *input, Layer *l) {
return convert_layer(input, (Conv2d*) l); return convert_layer(input, (Conv2d*) l);
if(type == LAYER_POOLING) if(type == LAYER_POOLING)
return convert_layer(input, (Pooling*) l); return convert_layer(input, (Pooling*) l);
if(type == LAYER_ACTIVATION || type == LAYER_ACTIVATION_CRELU || type == LAYER_ACTIVATION_LEAKY || type == LAYER_ACTIVATION_MISH) if(type == LAYER_ACTIVATION || type == LAYER_ACTIVATION_CRELU || type == LAYER_ACTIVATION_LEAKY || type == LAYER_ACTIVATION_MISH || type == LAYER_ACTIVATION_LOGISTIC)
return convert_layer(input, (Activation*) l); return convert_layer(input, (Activation*) l);
if(type == LAYER_SOFTMAX) if(type == LAYER_SOFTMAX)
return convert_layer(input, (Softmax*) l); return convert_layer(input, (Softmax*) l);
@@ -423,6 +424,12 @@ ILayer* NetworkRT::convert_layer(ITensor *input, Activation *l) {
checkNULL(lRT); checkNULL(lRT);
return lRT; return lRT;
} }
else if(l->act_mode == ACTIVATION_LOGISTIC) {
IPlugin *plugin = new ActivationLogisticRT();
IPluginLayer *lRT = networkRT->addPlugin(&input, 1, *plugin);
checkNULL(lRT);
return lRT;
}
else { else {
FatalError("this Activation mode is not yet implemented"); FatalError("this Activation mode is not yet implemented");
return NULL; return NULL;
@@ -452,11 +459,14 @@ ILayer* NetworkRT::convert_layer(ITensor *input, Route *l) {
// std::cout<<"\n"; // std::cout<<"\n";
} }
if(l->groups > 1){
IPlugin *plugin = new RouteRT(l->groups, l->group_id);
IPluginLayer *lRT = networkRT->addPlugin(tens, l->layers_n, *plugin);
checkNULL(lRT);
return lRT;
}
IConcatenationLayer *lRT = networkRT->addConcatenation(tens, l->layers_n); IConcatenationLayer *lRT = networkRT->addConcatenation(tens, l->layers_n);
//IPlugin *plugin = new RouteRT();
//IPluginLayer *lRT = networkRT->addPlugin(tens, l->layers_n, *plugin);
checkNULL(lRT); checkNULL(lRT);
return lRT; return lRT;
} }
@@ -538,7 +548,7 @@ ILayer* NetworkRT::convert_layer(ITensor *input, Yolo *l) {
//std::cout<<"convert Yolo\n"; //std::cout<<"convert Yolo\n";
//std::cout<<"New plugin YOLO\n"; //std::cout<<"New plugin YOLO\n";
IPlugin *plugin = new YoloRT(l->classes, l->num, l, l->n_masks, l->scaleXY); IPlugin *plugin = new YoloRT(l->classes, l->num, l, l->n_masks, l->scaleXY, l->nms_thresh, l->nsm_kind, l->new_coords);
IPluginLayer *lRT = networkRT->addPlugin(&input, 1, *plugin); IPluginLayer *lRT = networkRT->addPlugin(&input, 1, *plugin);
checkNULL(lRT); checkNULL(lRT);
return lRT; return lRT;
@@ -570,7 +580,7 @@ ILayer* NetworkRT::convert_layer(ITensor *input, DeformConv2d *l) {
IPluginLayer *lRT = networkRT->addPlugin(inputs, 2, *plugin); IPluginLayer *lRT = networkRT->addPlugin(inputs, 2, *plugin);
checkNULL(lRT); checkNULL(lRT);
lRT->setName( ("Deformable" + std::to_string(l->id)).c_str() ); lRT->setName( ("Deformable" + std::to_string(l->id)).c_str() );
delete(inputs); delete[](inputs);
// batchnorm // batchnorm
void *bias_b, *power_b, *mean_b, *variance_b, *scales_b; void *bias_b, *power_b, *mean_b, *variance_b, *scales_b;
if(dtRT == DataType::kHALF) { if(dtRT == DataType::kHALF) {
@@ -647,7 +657,7 @@ bool NetworkRT::deserialize(const char *filename) {
IPlugin* PluginFactory::createPlugin(const char* layerName, const void* serialData, size_t serialLength) { IPlugin* PluginFactory::createPlugin(const char* layerName, const void* serialData, size_t serialLength) {
const char * buf = reinterpret_cast<const char*>(serialData); const char * buf = reinterpret_cast<const char*>(serialData),*bufCheck = buf;
std::string name(layerName); std::string name(layerName);
//std::cout<<name<<std::endl; //std::cout<<name<<std::endl;
@@ -655,35 +665,53 @@ IPlugin* PluginFactory::createPlugin(const char* layerName, const void* serialDa
if(name.find("ActivationLeaky") == 0) { if(name.find("ActivationLeaky") == 0) {
ActivationLeakyRT *a = new ActivationLeakyRT(readBUF<float>(buf)); ActivationLeakyRT *a = new ActivationLeakyRT(readBUF<float>(buf));
a->size = readBUF<int>(buf); a->size = readBUF<int>(buf);
assert(buf == bufCheck + serialLength);
return a; return a;
} }
if(name.find("ActivationMish") == 0) { if(name.find("ActivationMish") == 0) {
ActivationMishRT *a = new ActivationMishRT(); ActivationMishRT *a = new ActivationMishRT();
a->size = readBUF<int>(buf); a->size = readBUF<int>(buf);
assert(buf == bufCheck + serialLength);
return a;
}
if(name.find("ActivationLogistic") == 0) {
ActivationLogisticRT *a = new ActivationLogisticRT();
a->size = readBUF<int>(buf);
return a;
}
if(name.find("ActivationLogistic") == 0) {
ActivationLogisticRT *a = new ActivationLogisticRT();
a->size = readBUF<int>(buf);
return a; return a;
} }
if(name.find("ActivationCReLU") == 0) { if(name.find("ActivationCReLU") == 0) {
ActivationReLUCeiling *a = new ActivationReLUCeiling(readBUF<float>(buf)); float activationReluTemp = readBUF<float>(buf);
ActivationReLUCeiling* a = new ActivationReLUCeiling(activationReluTemp);
a->size = readBUF<int>(buf); a->size = readBUF<int>(buf);
assert(buf == bufCheck + serialLength);
return a; return a;
} }
if(name.find("Region") == 0) { if(name.find("Region") == 0) {
RegionRT *r = new RegionRT(readBUF<int>(buf), //classes int classesTemp = readBUF<int>(buf);
readBUF<int>(buf), //coords int coordsTemp = readBUF<int>(buf);
readBUF<int>(buf)); //num int numTemp = readBUF<int>(buf);
RegionRT* r = new RegionRT(classesTemp, coordsTemp, numTemp);
r->c = readBUF<int>(buf); r->c = readBUF<int>(buf);
r->h = readBUF<int>(buf); r->h = readBUF<int>(buf);
r->w = readBUF<int>(buf); r->w = readBUF<int>(buf);
assert(buf == bufCheck + serialLength);
return r; return r;
} }
if(name.find("Reorg") == 0) { if(name.find("Reorg") == 0) {
ReorgRT *r = new ReorgRT(readBUF<int>(buf)); //stride int strideTemp = readBUF<int>(buf);
ReorgRT *r = new ReorgRT(strideTemp);
r->c = readBUF<int>(buf); r->c = readBUF<int>(buf);
r->h = readBUF<int>(buf); r->h = readBUF<int>(buf);
r->w = readBUF<int>(buf); r->w = readBUF<int>(buf);
assert(buf == bufCheck + serialLength);
return r; return r;
} }
@@ -699,27 +727,34 @@ IPlugin* PluginFactory::createPlugin(const char* layerName, const void* serialDa
r->h = readBUF<int>(buf); r->h = readBUF<int>(buf);
r->w = readBUF<int>(buf); r->w = readBUF<int>(buf);
return r; return r;
assert(buf == bufCheck + serialLength);
} }
if(name.find("Pooling") == 0) { if(name.find("Pooling") == 0) {
MaxPoolFixedSizeRT *r = new MaxPoolFixedSizeRT( readBUF<int>(buf), //c int cTemp = readBUF<int>(buf);
readBUF<int>(buf), //h int hTemp = readBUF<int>(buf);
readBUF<int>(buf), //w int wTemp = readBUF<int>(buf);
readBUF<int>(buf), //n int nTemp = readBUF<int>(buf);
readBUF<int>(buf), //strideH int strideHTemp = readBUF<int>(buf);
readBUF<int>(buf), //strideW int strideWTemp = readBUF<int>(buf);
readBUF<int>(buf), //winSize int winSizeTemp = readBUF<int>(buf);
readBUF<int>(buf)); //padding int paddingTemp = readBUF<int>(buf);
MaxPoolFixedSizeRT* r = new MaxPoolFixedSizeRT(cTemp, hTemp, wTemp, nTemp, strideHTemp, strideWTemp, winSizeTemp, paddingTemp);
assert(buf == bufCheck + serialLength);
return r; return r;
} }
if(name.find("Resize") == 0) { if(name.find("Resize") == 0) {
ResizeLayerRT *r = new ResizeLayerRT(readBUF<int>(buf), //o_c int o_cTemp = readBUF<int>(buf);
readBUF<int>(buf), //o_h int o_hTemp = readBUF<int>(buf);
readBUF<int>(buf)); //o_w int o_wTemp = readBUF<int>(buf);
ResizeLayerRT* r = new ResizeLayerRT(o_cTemp, o_hTemp, o_wTemp);
r->i_c = readBUF<int>(buf); r->i_c = readBUF<int>(buf);
r->i_h = readBUF<int>(buf); r->i_h = readBUF<int>(buf);
r->i_w = readBUF<int>(buf); r->i_w = readBUF<int>(buf);
assert(buf == bufCheck + serialLength);
return r; return r;
} }
@@ -730,6 +765,7 @@ IPlugin* PluginFactory::createPlugin(const char* layerName, const void* serialDa
r->w = readBUF<int>(buf); r->w = readBUF<int>(buf);
r->rows = readBUF<int>(buf); r->rows = readBUF<int>(buf);
r->cols = readBUF<int>(buf); r->cols = readBUF<int>(buf);
assert(buf == bufCheck + serialLength);
return r; return r;
} }
@@ -741,19 +777,28 @@ IPlugin* PluginFactory::createPlugin(const char* layerName, const void* serialDa
new_dim.h = readBUF<int>(buf); new_dim.h = readBUF<int>(buf);
new_dim.w = readBUF<int>(buf); new_dim.w = readBUF<int>(buf);
ReshapeRT *r = new ReshapeRT(new_dim); ReshapeRT *r = new ReshapeRT(new_dim);
assert(buf == bufCheck + serialLength);
return r; return r;
} }
if(name.find("Yolo") == 0) { if(name.find("Yolo") == 0) {
YoloRT *r = new YoloRT(readBUF<int>(buf), //classes
readBUF<int>(buf), //num int classes_temp = readBUF<int>(buf);
nullptr, int num_temp = readBUF<int>(buf);
readBUF<int>(buf)); //n_masks int n_masks_temp = readBUF<int>(buf);
float scale_xy_temp = readBUF<float>(buf);
float nms_thresh_temp = readBUF<float>(buf);
int nms_kind_temp = readBUF<int>(buf);
int new_coords_temp = readBUF<int>(buf);
YoloRT *r = new YoloRT(classes_temp,num_temp,nullptr,n_masks_temp,scale_xy_temp,nms_thresh_temp,nms_kind_temp,new_coords_temp);
r->c = readBUF<int>(buf); r->c = readBUF<int>(buf);
r->h = readBUF<int>(buf); r->h = readBUF<int>(buf);
r->w = readBUF<int>(buf); r->w = readBUF<int>(buf);
r->scaleXY = readBUF<float>(buf);
for(int i=0; i<r->n_masks; i++) for(int i=0; i<r->n_masks; i++)
r->mask[i] = readBUF<dnnType>(buf); r->mask[i] = readBUF<dnnType>(buf);
for(int i=0; i<r->n_masks*2*r->num; i++) for(int i=0; i<r->n_masks*2*r->num; i++)
@@ -767,36 +812,54 @@ IPlugin* PluginFactory::createPlugin(const char* layerName, const void* serialDa
tmp[j] = readBUF<char>(buf); tmp[j] = readBUF<char>(buf);
r->classesNames[i] = std::string(tmp); r->classesNames[i] = std::string(tmp);
} }
assert(buf == bufCheck + serialLength);
yolos[n_yolos++] = r; yolos[n_yolos++] = r;
return r; return r;
} }
if(name.find("Upsample") == 0) { if(name.find("Upsample") == 0) {
UpsampleRT *r = new UpsampleRT(readBUF<int>(buf)); //stride int strideTemp = readBUF<int>(buf);
UpsampleRT* r = new UpsampleRT(strideTemp);
r->c = readBUF<int>(buf); r->c = readBUF<int>(buf);
r->h = readBUF<int>(buf); r->h = readBUF<int>(buf);
r->w = readBUF<int>(buf); r->w = readBUF<int>(buf);
assert(buf == bufCheck + serialLength);
return r; return r;
} }
/*
if(name.find("Route") == 0) { if(name.find("Route") == 0) {
RouteRT *r = new RouteRT(); int groupsTemp = readBUF<int>(buf);
int group_idTemp = readBUF<int>(buf);
RouteRT* r = new RouteRT(groupsTemp, group_idTemp);
r->in = readBUF<int>(buf); r->in = readBUF<int>(buf);
for(int i=0; i<RouteRT::MAX_INPUTS; i++) for(int i=0; i<RouteRT::MAX_INPUTS; i++)
r->c_in[i] = readBUF<int>(buf); r->c_in[i] = readBUF<int>(buf);
r->c = readBUF<int>(buf); r->c = readBUF<int>(buf);
r->h = readBUF<int>(buf); r->h = readBUF<int>(buf);
r->w = readBUF<int>(buf); r->w = readBUF<int>(buf);
assert(buf == bufCheck + serialLength);
return r; return r;
} }
*/
if(name.find("Deformable") == 0) { if(name.find("Deformable") == 0) {
DeformableConvRT *r = new DeformableConvRT(readBUF<int>(buf), readBUF<int>(buf), readBUF<int>(buf), int chuck_dimTemp = readBUF<int>(buf);
readBUF<int>(buf), readBUF<int>(buf), readBUF<int>(buf), int khTemp = readBUF<int>(buf);
readBUF<int>(buf), readBUF<int>(buf), int kwTemp = readBUF<int>(buf);
readBUF<int>(buf),readBUF<int>(buf),readBUF<int>(buf),readBUF<int>(buf), int shTemp = readBUF<int>(buf);
readBUF<int>(buf),readBUF<int>(buf),readBUF<int>(buf),readBUF<int>(buf), int swTemp = readBUF<int>(buf);
nullptr); int phTemp = readBUF<int>(buf);
int pwTemp = readBUF<int>(buf);
int deformableGroupTemp = readBUF<int>(buf);
int i_nTemp = readBUF<int>(buf);
int i_cTemp = readBUF<int>(buf);
int i_hTemp = readBUF<int>(buf);
int i_wTemp = readBUF<int>(buf);
int o_nTemp = readBUF<int>(buf);
int o_cTemp = readBUF<int>(buf);
int o_hTemp = readBUF<int>(buf);
int o_wTemp = readBUF<int>(buf);
DeformableConvRT* r = new DeformableConvRT(chuck_dimTemp, khTemp, kwTemp, shTemp, swTemp, phTemp, pwTemp, deformableGroupTemp, i_nTemp, i_cTemp, i_hTemp, i_wTemp, o_nTemp, o_cTemp, o_hTemp, o_wTemp, nullptr);
dnnType *aus = new dnnType[r->chunk_dim*2]; dnnType *aus = new dnnType[r->chunk_dim*2];
for(int i=0; i<r->chunk_dim*2; i++) for(int i=0; i<r->chunk_dim*2; i++)
aus[i] = readBUF<dnnType>(buf); aus[i] = readBUF<dnnType>(buf);
@@ -827,6 +890,7 @@ IPlugin* PluginFactory::createPlugin(const char* layerName, const void* serialDa
aus[i] = readBUF<dnnType>(buf); aus[i] = readBUF<dnnType>(buf);
checkCuda( cudaMemcpy(r->ones_d2, aus, sizeof(dnnType)*r->dim_ones, cudaMemcpyHostToDevice) ); checkCuda( cudaMemcpy(r->ones_d2, aus, sizeof(dnnType)*r->dim_ones, cudaMemcpyHostToDevice) );
free(aus); free(aus);
assert(buf == bufCheck + serialLength);
return r; return r;
} }
+1 -1
View File
@@ -63,7 +63,7 @@ dnnType* Region::infer(dataDim_t &dim, dnnType* srcData) {
} }
/* Intepret class */ /* Interpret class */
RegionInterpret::RegionInterpret(dataDim_t input_dim, dataDim_t output_dim, RegionInterpret::RegionInterpret(dataDim_t input_dim, dataDim_t output_dim,
int classes, int coords, int num, float thresh, std::string fname_weights) { int classes, int coords, int num, float thresh, std::string fname_weights) {
+7 -3
View File
@@ -5,7 +5,7 @@
namespace tk { namespace dnn { namespace tk { namespace dnn {
Route::Route(Network *net, Layer **layers, int layers_n) : Layer(net) { Route::Route(Network *net, Layer **layers, int layers_n, int groups, int group_id) : Layer(net) {
// copy input layers // copy input layers
if(layers_n > MAX_LAYERS) { if(layers_n > MAX_LAYERS) {
@@ -15,6 +15,8 @@ Route::Route(Network *net, Layer **layers, int layers_n) : Layer(net) {
this->layers[i] = layers[i]; this->layers[i] = layers[i];
} }
this->layers_n = layers_n; this->layers_n = layers_n;
this->groups = groups;
this->group_id = group_id;
//get dims //get dims
output_dim.l = 1; output_dim.l = 1;
@@ -32,6 +34,7 @@ Route::Route(Network *net, Layer **layers, int layers_n) : Layer(net) {
output_dim.c += layers[i]->output_dim.c; output_dim.c += layers[i]->output_dim.c;
} }
output_dim.c /= this->groups;
input_dim = output_dim; input_dim = output_dim;
checkCuda( cudaMalloc(&dstData, output_dim.tot()*sizeof(dnnType)) ); checkCuda( cudaMalloc(&dstData, output_dim.tot()*sizeof(dnnType)) );
@@ -49,8 +52,9 @@ dnnType* Route::infer(dataDim_t &dim, dnnType* srcData) {
for(int i=0; i<layers_n; i++) { for(int i=0; i<layers_n; i++) {
dnnType *input = layers[i]->dstData; dnnType *input = layers[i]->dstData;
int in_dim = layers[i]->output_dim.tot(); int in_dim = layers[i]->output_dim.tot();
checkCuda( cudaMemcpy(dstData + offset, input, in_dim*sizeof(dnnType), cudaMemcpyDeviceToDevice)); int part_in_dim = in_dim / this->groups;
offset += in_dim; checkCuda( cudaMemcpy(dstData + offset, input + this->group_id*part_in_dim, part_in_dim*sizeof(dnnType), cudaMemcpyDeviceToDevice));
offset += part_in_dim;
} }
//update data dimensions //update data dimensions
+61 -18
View File
@@ -9,9 +9,10 @@
#include "Layer.h" #include "Layer.h"
#include "kernels.h" #include "kernels.h"
namespace tk { namespace dnn { namespace tk { namespace dnn {
Yolo::Yolo(Network *net, int classes, int num, std::string fname_weights, int n_masks, float scale_xy) : Yolo::Yolo(Network *net, int classes, int num, std::string fname_weights, int n_masks, float scale_xy, double nms_thresh, nmsKind_t nsm_kind, int new_coords) :
Layer(net) { Layer(net) {
this->final = true; this->final = true;
@@ -19,6 +20,9 @@ Yolo::Yolo(Network *net, int classes, int num, std::string fname_weights, int n_
this->num = num; this->num = num;
this->n_masks = n_masks; this->n_masks = n_masks;
this->scaleXY = scale_xy; this->scaleXY = scale_xy;
this->nms_thresh = nms_thresh;
this->nsm_kind = nsm_kind;
this->new_coords = new_coords;
// load anchors // load anchors
if(fname_weights != "") { if(fname_weights != "") {
@@ -59,12 +63,21 @@ int entry_index(int batch, int location, int entry,
entry*input_dim.w*input_dim.h + loc; entry*input_dim.w*input_dim.h + loc;
} }
Yolo::box get_yolo_box(float *x, float *biases, int n, int index, int i, int j, int lw, int lh, int w, int h, int stride) { Yolo::box get_yolo_box(float *x, float *biases, int n, int index, int i, int j, int lw, int lh, int w, int h, int stride, int new_coords) {
Yolo::box b; Yolo::box b;
b.x = (i + x[index + 0*stride]) / lw;
b.y = (j + x[index + 1*stride]) / lh; if(new_coords == 0){
b.w = exp(x[index + 2*stride]) * biases[2*n] / w; b.x = (i + x[index + 0*stride]) / lw;
b.h = exp(x[index + 3*stride]) * biases[2*n+1] / h; b.y = (j + x[index + 1*stride]) / lh;
b.w = exp(x[index + 2*stride]) * biases[2*n] / w;
b.h = exp(x[index + 3*stride]) * biases[2*n+1] / h;
}
else{
b.x = (i + x[index + 0 * stride] ) / lw;
b.y = (j + x[index + 1 * stride] ) / lh;
b.w = x[index + 2 * stride] * x[index + 2 * stride] * 4 * biases[2 * n] / w;
b.h = x[index + 3 * stride] * x[index + 3 * stride] * 4 * biases[2 * n + 1] / h;
}
return b; return b;
} }
@@ -75,12 +88,17 @@ dnnType* Yolo::infer(dataDim_t &dim, dnnType* srcData) {
for (int b = 0; b < dim.n; ++b){ for (int b = 0; b < dim.n; ++b){
for(int n = 0; n < n_masks; ++n){ for(int n = 0; n < n_masks; ++n){
int index = entry_index(b, n*dim.w*dim.h, 0, classes, input_dim, output_dim); int index = entry_index(b, n*dim.w*dim.h, 0, classes, input_dim, output_dim);
activationLOGISTICForward(srcData + index, dstData + index, 2*dim.w*dim.h); std::cout<<"new_coords"<<new_coords<<std::endl;
if (new_coords == 1){
if (this->scaleXY != 1) scalAdd(dstData + index, 2 * dim.w*dim.h, this->scaleXY, -0.5*(this->scaleXY - 1), 1);
}
else{
activationLOGISTICForward(srcData + index, dstData + index, 2*dim.w*dim.h);
if (this->scaleXY != 1) scalAdd(dstData + index, 2 * dim.w*dim.h, this->scaleXY, -0.5*(this->scaleXY - 1), 1); if (this->scaleXY != 1) scalAdd(dstData + index, 2 * dim.w*dim.h, this->scaleXY, -0.5*(this->scaleXY - 1), 1);
index = entry_index(b, n*dim.w*dim.h, 4, classes, input_dim, output_dim);
index = entry_index(b, n*dim.w*dim.h, 4, classes, input_dim, output_dim); activationLOGISTICForward(srcData + index, dstData + index, (1+classes)*dim.w*dim.h);
activationLOGISTICForward(srcData + index, dstData + index, (1+classes)*dim.w*dim.h); }
} }
} }
@@ -116,7 +134,7 @@ void correct_yolo_boxes(Yolo::detection *dets, int n, int w, int h, int netw, in
} }
} }
int Yolo::computeDetections(Yolo::detection *dets, int &ndets, int netw, int neth, float thresh) { int Yolo::computeDetections(Yolo::detection *dets, int &ndets, int netw, int neth, float thresh, int new_coords) {
if(predictions == nullptr) if(predictions == nullptr)
predictions = new dnnType[output_dim.tot()]; predictions = new dnnType[output_dim.tot()];
@@ -140,7 +158,7 @@ int Yolo::computeDetections(Yolo::detection *dets, int &ndets, int netw, int net
if(objectness <= thresh) continue; if(objectness <= thresh) continue;
int box_index = entry_index(0, n*lw*lh + i, 0, classes, input_dim, output_dim); int box_index = entry_index(0, n*lw*lh + i, 0, classes, input_dim, output_dim);
dets[count].bbox = get_yolo_box(predictions, bias_h, mask_h[n], box_index, col, row, lw, lh, netw, neth, lw*lh); dets[count].bbox = get_yolo_box(predictions, bias_h, mask_h[n], box_index, col, row, lw, lh, netw, neth, lw*lh, new_coords);
dets[count].objectness = objectness; dets[count].objectness = objectness;
dets[count].classes = classes; dets[count].classes = classes;
for(j = 0; j < classes; ++j){ for(j = 0; j < classes; ++j){
@@ -193,6 +211,32 @@ float yolo_box_iou(Yolo::box a, Yolo::box b)
return yolo_box_intersection(a, b)/yolo_box_union(a, b); return yolo_box_intersection(a, b)/yolo_box_union(a, b);
} }
void box_c(const Yolo::box a, const Yolo::box b, float& top, float& bot, float& left, float& right) {
top = (std::min)(a.y - a.h / 2, b.y - b.h / 2);
bot = (std::max)(a.y + a.h / 2, b.y + b.h / 2);
left = (std::min)(a.x - a.w / 2, b.x - b.w / 2);
right = (std::max)(a.x + a.w / 2, b.x + b.w / 2);
}
// https://github.com/Zzh-tju/DIoU-darknet
// https://arxiv.org/abs/1911.08287
float yolo_box_diou(const Yolo::box a, const Yolo::box b, const float nms_thresh=0.6)
{
float top, bot, left, right;
box_c(a, b, top, bot, left, right);
float w = right - left;
float h = bot - top;
float c = w * w + h * h;
float iou = yolo_box_iou(a, b);
if (c == 0)
return iou;
float d = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
float u = pow(d / c, nms_thresh);
float diou_term = u;
return iou - diou_term;
}
int yolo_nms_comparator(const void *pa, const void *pb) int yolo_nms_comparator(const void *pa, const void *pb)
{ {
Yolo::detection a = *(Yolo::detection *)pa; Yolo::detection a = *(Yolo::detection *)pa;
@@ -219,8 +263,7 @@ Yolo::detection *Yolo::allocateDetections(int nboxes, int classes) {
return dets; return dets;
} }
void Yolo::mergeDetections(Yolo::detection *dets, int ndets, int classes) { void Yolo::mergeDetections(Yolo::detection *dets, int ndets, int classes, double nms_thresh, nmsKind_t nsm_kind) {
double nms_thresh = 0.45;
int total = ndets; int total = ndets;
int i, j, k; int i, j, k;
@@ -246,13 +289,13 @@ void Yolo::mergeDetections(Yolo::detection *dets, int ndets, int classes) {
box a = dets[i].bbox; box a = dets[i].bbox;
for(j = i+1; j < total; ++j){ for(j = i+1; j < total; ++j){
box b = dets[j].bbox; box b = dets[j].bbox;
if (yolo_box_iou(a, b) > nms_thresh){ if (nsm_kind == GREEDY_NMS && yolo_box_iou(a, b) > nms_thresh)
dets[j].prob[k] = 0;
else if (nsm_kind == DIOU_NMS && yolo_box_diou(a, b, nms_thresh) > nms_thresh)
dets[j].prob[k] = 0; dets[j].prob[k] = 0;
}
} }
} }
} }
} }
}} }}
+38 -32
View File
@@ -3,13 +3,14 @@
namespace tk { namespace dnn { namespace tk { namespace dnn {
bool Yolo3Detection::init(const std::string& tensor_path, const int n_classes, const int n_batches) { bool Yolo3Detection::init(const std::string& tensor_path, const int n_classes, const int n_batches, const float conf_thresh) {
//convert network to tensorRT //convert network to tensorRT
std::cout<<(tensor_path).c_str()<<"\n"; std::cout<<(tensor_path).c_str()<<"\n";
netRT = new tk::dnn::NetworkRT(NULL, (tensor_path).c_str() ); netRT = new tk::dnn::NetworkRT(NULL, (tensor_path).c_str() );
nBatches = n_batches; nBatches = n_batches;
confThreshold = conf_thresh;
tk::dnn::dataDim_t idim = netRT->input_dim; tk::dnn::dataDim_t idim = netRT->input_dim;
idim.n = nBatches; idim.n = nBatches;
@@ -31,6 +32,9 @@ bool Yolo3Detection::init(const std::string& tensor_path, const int n_classes, c
memcpy(yolo[i]->bias_h, yRT->bias, sizeof(dnnType)*num*nMasks*2); memcpy(yolo[i]->bias_h, yRT->bias, sizeof(dnnType)*num*nMasks*2);
yolo[i]->input_dim = yolo[i]->output_dim = tk::dnn::dataDim_t(1, yRT->c, yRT->h, yRT->w); yolo[i]->input_dim = yolo[i]->output_dim = tk::dnn::dataDim_t(1, yRT->c, yRT->h, yRT->w);
yolo[i]->classesNames = yRT->classesNames; yolo[i]->classesNames = yRT->classesNames;
yolo[i]->nms_thresh = yRT->nms_thresh;
yolo[i]->nsm_kind = (tk::dnn::Yolo::nmsKind_t) yRT->nms_kind;
yolo[i]->new_coords = yRT->new_coords;
} }
dets = tk::dnn::Yolo::allocateDetections(tk::dnn::Yolo::MAX_DETECTIONS, classes); dets = tk::dnn::Yolo::allocateDetections(tk::dnn::Yolo::MAX_DETECTIONS, classes);
@@ -90,9 +94,10 @@ void Yolo3Detection::preprocess(cv::Mat &frame, const int bi){
void Yolo3Detection::postprocess(const int bi, const bool mAP){ void Yolo3Detection::postprocess(const int bi, const bool mAP){
//get yolo outputs //get yolo outputs
dnnType *rt_out[netRT->pluginFactory->n_yolos]; std::vector<float *> rt_out;
//dnnType *rt_out[netRT->pluginFactory->n_yolos];
for(int i=0; i<netRT->pluginFactory->n_yolos; i++) for(int i=0; i<netRT->pluginFactory->n_yolos; i++)
rt_out[i] = (dnnType*)netRT->buffersRT[i+1] + netRT->buffersDIM[i+1].tot()*bi; rt_out.push_back((dnnType*)netRT->buffersRT[i+1] + netRT->buffersDIM[i+1].tot()*bi);
float x_ratio = float(originalSize[bi].width) / float(netRT->input_dim.w); float x_ratio = float(originalSize[bi].width) / float(netRT->input_dim.w);
float y_ratio = float(originalSize[bi].height) / float(netRT->input_dim.h); float y_ratio = float(originalSize[bi].height) / float(netRT->input_dim.h);
@@ -101,46 +106,47 @@ void Yolo3Detection::postprocess(const int bi, const bool mAP){
nDets = 0; nDets = 0;
for(int i=0; i<netRT->pluginFactory->n_yolos; i++) { for(int i=0; i<netRT->pluginFactory->n_yolos; i++) {
yolo[i]->dstData = rt_out[i]; yolo[i]->dstData = rt_out[i];
yolo[i]->computeDetections(dets, nDets, netRT->input_dim.w, netRT->input_dim.h, confThreshold); yolo[i]->computeDetections(dets, nDets, netRT->input_dim.w, netRT->input_dim.h, confThreshold, yolo[i]->new_coords);
} }
tk::dnn::Yolo::mergeDetections(dets, nDets, classes); tk::dnn::Yolo::mergeDetections(dets, nDets, classes, yolo[0]->nms_thresh, yolo[0]->nsm_kind);
// fill detected // fill detected
detected.clear(); detected.clear();
for(int j=0; j<nDets; j++) { for(int j=0; j<nDets; j++) {
tk::dnn::Yolo::box b = dets[j].bbox; tk::dnn::Yolo::box b = dets[j].bbox;
int x0 = (b.x-b.w/2.); float x0 = (b.x-b.w/2.);
int x1 = (b.x+b.w/2.); float x1 = (b.x+b.w/2.);
int y0 = (b.y-b.h/2.); float y0 = (b.y-b.h/2.);
int y1 = (b.y+b.h/2.); float y1 = (b.y+b.h/2.);
int obj_class = -1;
float prob = 0; // convert to image coords
x0 = x_ratio*x0;
x1 = x_ratio*x1;
y0 = y_ratio*y0;
y1 = y_ratio*y1;
for(int c=0; c<classes; c++) { for(int c=0; c<classes; c++) {
if(dets[j].prob[c] >= confThreshold) { if(dets[j].prob[c] >= confThreshold) {
obj_class = c; int obj_class = c;
prob = dets[j].prob[c]; float prob = dets[j].prob[c];
tk::dnn::box res;
res.cl = obj_class;
res.prob = prob;
res.x = x0;
res.y = y0;
res.w = x1 - x0;
res.h = y1 - y0;
// FIXME: this shuld be useless
// if(mAP)
// for(int c=0; c<classes; c++)
// res.probs.push_back(dets[j].prob[c]);
detected.push_back(res);
} }
} }
if(obj_class >= 0) {
// convert to image coords
x0 = x_ratio*x0;
x1 = x_ratio*x1;
y0 = y_ratio*y0;
y1 = y_ratio*y1;
tk::dnn::box res;
res.cl = obj_class;
res.prob = prob;
res.x = x0;
res.y = y0;
res.w = x1 - x0;
res.h = y1 - y0;
if(mAP)
for(int c=0; c<classes; c++)
res.probs.push_back(dets[j].prob[c]);
detected.push_back(res);
}
} }
batchDetected.push_back(detected); batchDetected.push_back(detected);
} }
+3 -3
View File
@@ -63,7 +63,7 @@ double computeMap( std::vector<Frame> &images,const int classes,
int gt_checked = 0; int gt_checked = 0;
// for each detection comput IoU with groundtruth and match detetcion and // for each detection compute IoU with groundtruth and match detetcion and
// groundtruth with IoU greater than IoU_thresh // groundtruth with IoU greater than IoU_thresh
for(auto &img:images){ for(auto &img:images){
for(size_t i=0; i<img.det.size(); i++){ for(size_t i=0; i<img.det.size(); i++){
@@ -153,7 +153,7 @@ double computeMap( std::vector<Frame> &images,const int classes,
} }
} }
//compute average precision for each class. Two methods are avaible, //compute average precision for each class. Two methods are available,
//based on map_points required //based on map_points required
double mean_average_precision = 0; double mean_average_precision = 0;
double last_recall, last_precision, delta_recall; double last_recall, last_precision, delta_recall;
@@ -287,7 +287,7 @@ void computeTPFPFN( std::vector<Frame> &images,const int classes,
} }
} }
//count all TP, FP, FN and compute precsion, recall and f1-score //count all TP, FP, FN and compute precision, recall and f1-score
double avg_precision = 0, avg_recall = 0, f1_score = 0; double avg_precision = 0, avg_recall = 0, f1_score = 0;
int TP = 0, FP = 0, FN = 0; int TP = 0, FP = 0, FN = 0;
for(size_t i=0; i<classes; i++){ for(size_t i=0; i<classes; i++){
+1 -1
View File
@@ -18,7 +18,7 @@ inline int GET_BLOCKS(const int N)
} }
__device__ float dmcn_im2col_bilinear(const float *bottom_data, const int data_width, __device__ __host__ float dmcn_im2col_bilinear(const float *bottom_data, const int data_width,
const int height, const int width, float h, float w) { const int height, const int width, float h, float w) {
int h_low = floor(h); int h_low = floor(h);
int w_low = floor(w); int w_low = floor(w);
+15 -2
View File
@@ -23,14 +23,23 @@ bool fileExist(const char *fname) {
void downloadWeightsifDoNotExist(const std::string& input_bin, const std::string& test_folder, const std::string& weights_url){ void downloadWeightsifDoNotExist(const std::string& input_bin, const std::string& test_folder, const std::string& weights_url){
if(!fileExist(input_bin.c_str())){ if(!fileExist(input_bin.c_str())){
std::string mkdir_cmd = "mkdir " + test_folder; std::string mkdir_cmd = "mkdir " + test_folder;
std::string wget_cmd = "wget " + weights_url + " -O " + test_folder + "/weights.zip"; std::string wget_cmd = "curl " + weights_url + " --output " + test_folder + "/weights.zip";
#ifdef __linux__
std::string unzip_cmd = "unzip " + test_folder + "/weights.zip -d" + test_folder; std::string unzip_cmd = "unzip " + test_folder + "/weights.zip -d" + test_folder;
std::string rm_cmd = "rm " + test_folder + "/weights.zip"; std::string rm_cmd = "rm " + test_folder + "/weights.zip";
#elif _WIN32
std::string unzip_cmd = "7z x " + test_folder + "/weights.zip -o" + test_folder;
#endif
int err = 0; int err = 0;
err = system(mkdir_cmd.c_str()); err = system(mkdir_cmd.c_str());
err = system(wget_cmd.c_str()); err = system(wget_cmd.c_str());
err = system(unzip_cmd.c_str()); err = system(unzip_cmd.c_str());
#ifdef __linux__
err = system(rm_cmd.c_str()); err = system(rm_cmd.c_str());
#endif
} }
} }
@@ -192,8 +201,12 @@ void getMemUsage(double& vm_usage_kb, double& resident_set_kb){
>> O >> itrealvalue >> starttime >> vsize >> rss; >> O >> itrealvalue >> starttime >> vsize >> rss;
stat_stream.close(); stat_stream.close();
#ifdef __linux__
long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
#elif _WIN32
long page_size_kb = 4096/1024;
#endif
vm_usage_kb = vsize / 1024.0; vm_usage_kb = vsize / 1024.0;
resident_set_kb = rss * page_size_kb; resident_set_kb = rss * page_size_kb;
} }
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+281
View File
@@ -0,0 +1,281 @@
[net]
# Testing
#batch=1
#subdivisions=1
# Training
batch=64
subdivisions=1
width=416
height=416
channels=3
momentum=0.9
decay=0.0005
angle=0
saturation = 1.5
exposure = 1.5
hue=.1
learning_rate=0.00261
burn_in=1000
max_batches = 500200
policy=steps
steps=400000,450000
scales=.1,.1
[convolutional]
batch_normalize=1
filters=32
size=3
stride=2
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=64
size=3
stride=2
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=64
size=3
stride=1
pad=1
activation=leaky
[route]
layers=-1
groups=2
group_id=1
[convolutional]
batch_normalize=1
filters=32
size=3
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=32
size=3
stride=1
pad=1
activation=leaky
[route]
layers = -1,-2
[convolutional]
batch_normalize=1
filters=64
size=1
stride=1
pad=1
activation=leaky
[route]
layers = -6,-1
[maxpool]
size=2
stride=2
[convolutional]
batch_normalize=1
filters=128
size=3
stride=1
pad=1
activation=leaky
[route]
layers=-1
groups=2
group_id=1
[convolutional]
batch_normalize=1
filters=64
size=3
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=64
size=3
stride=1
pad=1
activation=leaky
[route]
layers = -1,-2
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[route]
layers = -6,-1
[maxpool]
size=2
stride=2
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky
[route]
layers=-1
groups=2
group_id=1
[convolutional]
batch_normalize=1
filters=128
size=3
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=128
size=3
stride=1
pad=1
activation=leaky
[route]
layers = -1,-2
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[route]
layers = -6,-1
[maxpool]
size=2
stride=2
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky
##################################
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky
[convolutional]
size=1
stride=1
pad=1
filters=255
activation=linear
[yolo]
mask = 3,4,5
anchors = 10,14, 23,27, 37,58, 81,82, 135,169, 344,319
classes=80
num=6
jitter=.3
scale_x_y = 1.05
cls_normalizer=1.0
iou_normalizer=0.07
iou_loss=ciou
ignore_thresh = .7
truth_thresh = 1
random=0
resize=1.5
nms_kind=greedynms
beta_nms=0.6
[route]
layers = -4
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[upsample]
stride=2
[route]
layers = -1, 23
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky
[convolutional]
size=1
stride=1
pad=1
filters=255
activation=linear
[yolo]
mask = 1,2,3
anchors = 10,14, 23,27, 37,58, 81,82, 135,169, 344,319
classes=80
num=6
jitter=.3
scale_x_y = 1.05
cls_normalizer=1.0
iou_normalizer=0.07
iou_loss=ciou
ignore_thresh = .7
truth_thresh = 1
random=0
resize=1.5
nms_kind=greedynms
beta_nms=0.6
File diff suppressed because it is too large Load Diff
@@ -17,8 +17,7 @@ int main() {
std::string wgs_path = bin_path + "/layers"; std::string wgs_path = bin_path + "/layers";
std::string cfg_path = std::string(TKDNN_PATH) + "/tests/darknet/cfg/csresnext50-panet-spp_berkeley.cfg"; std::string cfg_path = std::string(TKDNN_PATH) + "/tests/darknet/cfg/csresnext50-panet-spp_berkeley.cfg";
std::string name_path = std::string(TKDNN_PATH) + "/tests/darknet/names/berkeley.names"; std::string name_path = std::string(TKDNN_PATH) + "/tests/darknet/names/berkeley.names";
// FIXME: wrong weights downloadWeightsifDoNotExist(input_bins[0], bin_path, "https://cloud.hipert.unimore.it/s/q82qHAtqpoaFYo5/download");
// downloadWeightsifDoNotExist(input_bins[0], bin_path, "https://cloud.hipert.unimore.it/s//download");
// parse darknet network // parse darknet network
tk::dnn::Network *net = tk::dnn::darknetParser(cfg_path, wgs_path, name_path); tk::dnn::Network *net = tk::dnn::darknetParser(cfg_path, wgs_path, name_path);
+4
View File
@@ -0,0 +1,4 @@
blue-cone
yellow-cone
orange-cone
big-orange-cone
+34
View File
@@ -0,0 +1,34 @@
#include<iostream>
#include<vector>
#include "tkdnn.h"
#include "test.h"
#include "DarknetParser.h"
int main() {
std::string bin_path = "yolo4-csp";
std::vector<std::string> input_bins = {
bin_path + "/layers/input.bin"
};
std::vector<std::string> output_bins = {
bin_path + "/debug/layer144_out.bin",
bin_path + "/debug/layer159_out.bin",
bin_path + "/debug/layer174_out.bin"
};
std::string wgs_path = bin_path + "/layers";
std::string cfg_path = std::string(TKDNN_PATH) + "/tests/darknet/cfg/yolo4-csp.cfg";
std::string name_path = std::string(TKDNN_PATH) + "/tests/darknet/names/coco.names";
downloadWeightsifDoNotExist(input_bins[0], bin_path, "https://cloud.hipert.unimore.it/s/AfzHE4BfTeEm2gH/download");
// parse darknet network
tk::dnn::Network *net = tk::dnn::darknetParser(cfg_path, wgs_path, name_path);
net->print();
//convert network to tensorRT
tk::dnn::NetworkRT *netRT = new tk::dnn::NetworkRT(net, net->getNetworkRTName(bin_path.c_str()));
int ret = testInference(input_bins, output_bins, net, netRT);
net->releaseLayers();
delete net;
delete netRT;
return ret;
}
+34
View File
@@ -0,0 +1,34 @@
#include<iostream>
#include<vector>
#include "tkdnn.h"
#include "test.h"
#include "DarknetParser.h"
int main() {
std::string bin_path = "yolo4_mmr";
std::vector<std::string> input_bins = {
bin_path + "/layers/input.bin"
};
std::vector<std::string> output_bins = {
bin_path + "/debug/layer139_out.bin",
bin_path + "/debug/layer150_out.bin",
bin_path + "/debug/layer161_out.bin"
};
std::string wgs_path = bin_path + "/layers";
std::string cfg_path = std::string(TKDNN_PATH) + "/tests/darknet/cfg/yolo4_mmr.cfg";
std::string name_path = std::string(TKDNN_PATH) + "/tests/darknet/names/mmr.names";
// downloadWeightsifDoNotExist(input_bins[0], bin_path, "");
// parse darknet network
tk::dnn::Network *net = tk::dnn::darknetParser(cfg_path, wgs_path, name_path);
net->print();
//convert network to tensorRT
tk::dnn::NetworkRT *netRT = new tk::dnn::NetworkRT(net, net->getNetworkRTName(bin_path.c_str()));
int ret = testInference(input_bins, output_bins, net, netRT);
net->releaseLayers();
delete net;
delete netRT;
return ret;
}
+33
View File
@@ -0,0 +1,33 @@
#include<iostream>
#include<vector>
#include "tkdnn.h"
#include "test.h"
#include "DarknetParser.h"
int main() {
std::string bin_path = "yolo4tiny";
std::vector<std::string> input_bins = {
bin_path + "/layers/input.bin"
};
std::vector<std::string> output_bins = {
bin_path + "/debug/layer30_out.bin",
bin_path + "/debug/layer37_out.bin"
};
std::string wgs_path = bin_path + "/layers";
std::string cfg_path = std::string(TKDNN_PATH) + "/tests/darknet/cfg/yolo4tiny.cfg";
std::string name_path = std::string(TKDNN_PATH) + "/tests/darknet/names/coco.names";
downloadWeightsifDoNotExist(input_bins[0], bin_path, "https://cloud.hipert.unimore.it/s/iRnc4pSqmx78gJs/download");
// parse darknet network
tk::dnn::Network *net = tk::dnn::darknetParser(cfg_path, wgs_path, name_path);
net->print();
//convert network to tensorRT
tk::dnn::NetworkRT *netRT = new tk::dnn::NetworkRT(net, net->getNetworkRTName(bin_path.c_str()));
int ret = testInference(input_bins, output_bins, net, netRT);
net->releaseLayers();
delete net;
delete netRT;
return ret;
}
+36
View File
@@ -0,0 +1,36 @@
#include<iostream>
#include<vector>
#include "tkdnn.h"
#include "test.h"
#include "DarknetParser.h"
int main() {
std::string bin_path = "yolo4x";
std::vector<std::string> input_bins = {
bin_path + "/layers/input.bin"
};
std::vector<std::string> output_bins = {
bin_path + "/debug/layer168_out.bin",
bin_path + "/debug/layer185_out.bin",
bin_path + "/debug/layer202_out.bin"
};
std::string wgs_path = bin_path + "/layers";
std::string cfg_path = std::string(TKDNN_PATH) + "/tests/darknet/cfg/yolo4x.cfg";
std::string name_path = std::string(TKDNN_PATH) + "/tests/darknet/names/coco.names";
downloadWeightsifDoNotExist(input_bins[0], bin_path, "https://cloud.hipert.unimore.it/s/5MFjtNtgbDGdJEo/download");
// parse darknet network
tk::dnn::Network *net = tk::dnn::darknetParser(cfg_path, wgs_path, name_path);
net->print();
//convert network to tensorRT
tk::dnn::NetworkRT *netRT = new tk::dnn::NetworkRT(net, net->getNetworkRTName(bin_path.c_str()));
int ret = testInference(input_bins, output_bins, net, netRT);
net->releaseLayers();
delete net;
delete netRT;
return ret;
}
+2 -1
View File
@@ -83,7 +83,8 @@ const char *trans[] = {
int main() int main()
{ {
downloadWeightsifDoNotExist(input_bin, "shelfnet_mapillary", "https://cloud.hipert.unimore.it/s/6WnZCKLjik7xrny/download"); // downloadWeightsifDoNotExist(input_bin, "shelfnet_mapillary", "");
// download the weights from here: https://cloud.hipert.unimore.it/f/652476
// Mapillary Vistas has originally 66 classes, but we reduced them to 15 to improve the results on the categories of our interest. // Mapillary Vistas has originally 66 classes, but we reduced them to 15 to improve the results on the categories of our interest.
int classes = 15; int classes = 15;