diff --git a/.gitignore b/.gitignore
index 02f2a8e..c1d362c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,4 +8,15 @@ build/
*.h5
*.tar.gz
*.weights
-.idea/
\ No newline at end of file
+.idea/
+*.hdf5
+*.pk
+*.table
+cmake-build-release/
+demo/COCO_val2017
+demo/BDD100K_val
+/.vs
+cmake-build-minsizerel/*
+scripts/COCO_val2017/*
+scripts/COCO_val2017.zip
+scripts/all_labels.txt
\ No newline at end of file
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 7af66c0..56d4fff 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,8 +1,18 @@
cmake_minimum_required(VERSION 3.5)
-
+set(PROJ_NAME tkDNN)
project (tkDNN)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fPIC")
+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)
+#add extras for baggage
+endif(WIN32)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/tkDNN)
# project specific flags
@@ -10,6 +20,7 @@ if(DEBUG)
add_definitions(-DDEBUG)
endif()
+add_definitions(-DTKDNN_PATH="${CMAKE_CURRENT_SOURCE_DIR}")
#-------------------------------------------------------------------------------
# CUDA
@@ -17,97 +28,82 @@ endif()
find_package(CUDA 9.0 REQUIRED)
SET(CUDA_SEPARABLE_COMPILATION ON)
#set(CUDA_NVCC_FLAGS "${CUDA_NVCC_FLAGS} -arch=sm_30 --compiler-options '-fPIC'")
+set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS} --maxrregcount=32)
find_package(CUDNN REQUIRED)
+include_directories(${CUDNN_INCLUDE_DIR})
+
# compile
-file(GLOB tkdnn_CUSRC "src/kernels/*.cu" "src/*.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_add_library(kernels SHARED ${tkdnn_CUSRC})
+target_link_libraries(kernels ${CUDA_CUBLAS_LIBRARIES})
#-------------------------------------------------------------------------------
# External Libraries
#-------------------------------------------------------------------------------
+find_package(Eigen3 REQUIRED)
+include_directories(${EIGEN3_INCLUDE_DIR})
+
find_package(OpenCV REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DOPENCV")
+# gives problems in cross-compiling, probably malformed cmake config
+find_package(yaml-cpp REQUIRED)
#-------------------------------------------------------------------------------
# Build Libraries
#-------------------------------------------------------------------------------
-file(GLOB tkdnn_SRC "src/*.cpp")
-set(tkdnn_LIBS kernels ${CUDA_LIBRARIES} ${CUDA_CUBLAS_LIBRARIES} ${CUDNN_LIBRARIES} ${OpenCV_LIBS})
+file(GLOB tkdnn_SRC "src/*.cpp",src/*.c)
+set(tkdnn_LIBS kernels ${CUDA_LIBRARIES} ${CUDA_CUBLAS_LIBRARIES} ${CUDNN_LIBRARIES} ${OpenCV_LIBS} yaml-cpp)
-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -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})
add_library(tkDNN SHARED ${tkdnn_SRC})
target_link_libraries(tkDNN ${tkdnn_LIBS})
+####compile
+#set(PROJ_NAME BaggageAIApi)
+# Path to BaggageAI project folder.
+set(BAGGAGEAI_PATH /home/baggageai/files)
+# Give a custom name to shared library which is provided by DIMENSIONLESS.
+#set(BAGGAGEAI_LIB_NAME libBaggageAI)
+# Define C++ level, could be 11 or 17 as well.
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
+# Define compiler optimization level.
+set(CMAKE_CXX_FLAGS "-O3")
+# Do print warnings uppon compilation, let's keep our code as clean as possible.
+set(CMAKE_CXX_FLAGS "-Wall -Wextra")
+# Apply flags.
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -DBOOST_LOG_DYN_LINK")
+set(Casablanca_LIBRARIES "-lboost_log -lboost_log_setup -lboost_thread -lboost_system -lcrypto -lssl -lcpprest -lpthread")
+
+
+# Note: We do not recommend using GLOB or GLOB_RECURSE to collect a list of source files from your source tree.
+# If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know
+# when to ask CMake to regenerate.
+
+file(GLOB_RECURSE SOURCE_FILES "main.cpp" "handler.cpp" "src/*.cpp","src/*.c")
+
+add_executable(baggageAPI ${SOURCE_FILES})
+set(Casablanca_LIBRARIES "-lboost_log -lboost_log_setup -lboost_thread -lboost_system -lcrypto -lssl -lcpprest -lpthread" )
+set(tkdnn_LIBS kernels ${Casablanca_LIBRARIES} ${CUDA_LIBRARIES} ${CUDA_CUBLAS_LIBRARIES} ${CUDNN_LIBRARIES} ${OpenCV_LIBS} yaml-cpp)
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
+# Link BaggageAI library' include folder.
+include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include ${CUDA_INCLUDE_DIRS} ${OPENCV_INCLUDE_DIRS} ${NVINFER_INCLUDES} ${Casablanca_LIBRARIES} ${CMAKE_CXX_FLAGS})
+# Define BaggageAI library' shared library.
+#add_library(${BAGGAGEAI_LIB_NAME} SHARED IMPORTED)
+# Set a path to BaggageAI library' shared library
+#set_property(TARGET ${BAGGAGEAI_LIB_NAME} PROPERTY IMPORTED_LOCATION "${BAGGAGEAI_PATH}/libBaggageAI.so")
+
+# Link all libraries together.
+target_link_libraries(baggageAPI ${tkdnn_LIBS})
#static
-#add_library(tkDNN_static STATIC ${tkdnn_SRC})
-#target_link_libraries(tkDNN_static ${tkdnn_LIBS})
-
-add_executable(test_simple tests/simple/test_simple.cpp)
-target_link_libraries(test_simple tkDNN)
-
-add_executable(test_mnist tests/mnist/test_mnist.cpp)
-target_link_libraries(test_mnist tkDNN)
-
-add_executable(test_mnistRT tests/mnist/test_mnistRT.cpp)
-target_link_libraries(test_mnistRT tkDNN)
-
-## YOLO NETS
-add_executable(test_yolo tests/yolo/yolo.cpp)
-target_link_libraries(test_yolo tkDNN)
-
-add_executable(test_yolo_voc tests/yolo_voc/yolo_voc.cpp)
-target_link_libraries(test_yolo_voc tkDNN)
-
-add_executable(test_yolo_tiny tests/yolo_tiny/yolo_tiny.cpp)
-target_link_libraries(test_yolo_tiny tkDNN)
-
-add_executable(test_yolo_relu tests/yolo_relu/yolo_relu.cpp)
-target_link_libraries(test_yolo_relu tkDNN)
-
-
-add_executable(test_yolo_224 tests/yolo_224/yolo_224.cpp)
-target_link_libraries(test_yolo_224 tkDNN)
-
-add_executable(test_yolo_berkeley tests/yolo_berkeley/yolo_berkeley.cpp)
-target_link_libraries(test_yolo_berkeley tkDNN)
-
-add_executable(test_yolo3_coco4 tests/yolo3_coco4/yolo3_coco4.cpp)
-target_link_libraries(test_yolo3_coco4 tkDNN)
-
-add_executable(test_yolo3 tests/yolo3/yolo3.cpp)
-target_link_libraries(test_yolo3 tkDNN)
-
-add_executable(test_yolo3_tiny tests/yolo3_tiny/yolo3_tiny.cpp)
-target_link_libraries(test_yolo3_tiny tkDNN)
-
-add_executable(test_yolo3_berkeley tests/yolo3_berkeley/yolo3_berkeley.cpp)
-target_link_libraries(test_yolo3_berkeley tkDNN)
-
-add_executable(test_yolo3_flir tests/yolo3_flir/yolo3_flir.cpp)
-target_link_libraries(test_yolo3_flir tkDNN)
-
-
-add_executable(test_resnet101 tests/resnet101/resnet101.cpp)
-target_link_libraries(test_resnet101 tkDNN)
-
-add_executable(test_resnet101_cnet tests/resnet101_cnet/resnet101_cnet.cpp)
-target_link_libraries(test_resnet101_cnet tkDNN)
-
-################################################################################
-
-
-add_executable(test_rtinference tests/test_rtinference/rtinference.cpp)
-target_link_libraries(test_rtinference tkDNN)
-
-add_executable(yolo3_demo demo/demo/demo.cpp)
-target_link_libraries(yolo3_demo tkDNN)
-
+#add_executable(demo demo/inf.cpp)
+#target_link_libraries(demo tkDNN)
#-------------------------------------------------------------------------------
# Install
@@ -123,18 +119,3 @@ install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/cmake/" # source directory
DESTINATION "share/tkDNN/cmake/" # target directory
)
-
-#-------------------------------------------------------------------------------
-# Prepare for test
-#-------------------------------------------------------------------------------
-set(TEST_DATA true CACHE BOOL "If true download deps")
-if( ${TEST_DATA} )
- message("Launching pre-build dependency installer script...")
-
- execute_process (COMMAND bash -c "bash build_models.sh download"
- WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/tests)
-
- set(TEST_DATA false CACHE BOOL "If true download deps" FORCE)
- message("Finished dowloading test weights")
-endif()
-
diff --git a/README.md b/README.md
index 3b16ec3..f64709d 100644
--- a/README.md
+++ b/README.md
@@ -1,51 +1,148 @@
-# tkDNN
-tkDNN is a Deep Neural Network library built with cuDNN primitives specifically thought to work on NVIDIA TK1(and all successive) board.
-The main scope is to do high performance inference on already trained models.
-this branch actually work on every NVIDIA GPU that support the dependencies:
-* CUDA 10.0
-* CUDNN 7.603
-* TENSORRT 6.01
-* OPENCV 4.1
+# Steps to build docker image
+## Docker
+Docker version 19.03 will be required.
-## Workflow
-The recommended workflow follow these step:
-* Build and train a model in Keras (on any PC)
-* Export weights and bias
-* Define the model on tkDNN
-* Do inference (on TK1)
+## For running with GPU
+### NVIDIA Drivers
+This drivers should be installed in the host system.
+### For Ubuntu:
+```
+$ sudo apt-get install linux-headers-$(uname -r) gcc g++ make
+$ wget http://in.download.nvidia.com/tesla/418.67/NVIDIA-Linux-x86_64-418.67.run
+$ chmod 777 NVIDIA-Linux-x86_64-418.67.run
+$ bash NVIDIA-Linux-x86_64-418.67.run
+```
-## Compile the library
-Build with cmake
+### For CentOS
```
-mkdir build
-cd build
-cmake ..
-# use -DTEST_DATA=False to skip dataset download
-make
+$ sudo yum -y install kernel-devel-$(uname -r) kernel-header-$(uname -r) gcc make
+$ wget http://in.download.nvidia.com/tesla/418.67/NVIDIA-Linux-x86_64-418.67.run
+$ chmod 777 NVIDIA-Linux-x86_64-418.67.run
+$ bash NVIDIA-Linux-x86_64-418.67.run
```
-during the cmake configuration it will be dowloaded the weights needed for running
-the tests
-## Test
-Assumiung you have correctly builded the library these are the test ready to exec:
-* test_simple: a simple convolutional and dense network (CUDNN only)
-* test_mnist: the famous mnist netwok (CUDNN and TENSORRT)
-* test_mnistRT: the mnist network hardcoded in using tensorRT apis (TENSORRT only)
-* test_yolo: YOLO detection network (CUDNN and TENSORRT)
-* test_yolo_tiny: smaller version of YOLO (CUDNN and TENSRRT)
-* test_yolo3_berkeley: our yolo3 version trained with BDD100K dateset
+### NVIDIA Container Toolkit
+This toolkit should be installed in the host system.
+### For Ubuntu
+```
+$ distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
+$ curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add -
+$ curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list
-## yolo3 berkeley demo detection
-For the live detection you need to precompile the tensorRT file by luncing the desidered network test, this is the recommended process:
+$ sudo apt-get update && sudo apt-get install -y nvidia-container-toolkit
+$ sudo systemctl restart docker
```
-export TKDNN_MODE=FP16 # set the half floating point optimization
-rm yolo3_berkeley.rt # be sure to delete(or move) old tensorRT files
-./test_yolo3_berkeley # run the yolo test (is slow)
-# with f16 inference the result will be a bit incorrect
+
+### For CentOS
```
-this will genereate a yolo3_berkeley.rt file that can be used for live detection:
+$ distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
+$ curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo
+
+$ sudo yum install -y nvidia-container-toolkit
+$ sudo systemctl restart docker
```
-./yolo3_demo # launch detection on a demo video
-./yolo3_demo yolo3_berkeley.rt /dev/video0 # launch detection on device 0
+
+### Building docker image
+
+* Go to ``TKDNN/`` then run following command.
+ ```$ docker build -t baggageai:server -f docker/Dockerfile .```
+ #### Note:
+1. have to copy weights into a TKDNN/config/ (tkdnn converted weights) current support api (fp32X4 and fp16X1)
+2. setup number of classes accrding to weights in TKDNN/config/config.yml
+3. give path of this weights into handler.cpp line number 117-121.
+
+### Run docker image
```
+$ docker run --gpus all -p 8080:8080 -d
+```
+Now server will be started in the container. You can check server is running or not using ``docker ps``
+
+
+
+
+### Run docker image
+```
+$ docker run -p 8080:8080 -d
+```
+
+
+# Using docker-compose file
+## Docker Compose
+Install docker-compose version 1.24.1
+[https://docs.docker.com/compose/install/](https://docs.docker.com/compose/install/)
+
+## Create Volume
+Create a volume named ``BAI_logs`` using following command:
+```
+$ docker volume create BAI_logs
+```
+Change permission of the directory of docker volume, so that logs can be written to that directory.
+```
+$ cd /var/lib/docker/volumes/BAI_logs
+$ chmod 757 _data/
+```
+```
+## For running with GPU
+Install nvidia-container-runtime:
+```
+$ curl -s -L https://nvidia.github.io/nvidia-container-runtime/gpgkey | \
+ sudo apt-key add -
+$ distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
+$ curl -s -L https://nvidia.github.io/nvidia-container-runtime/$distribution/nvidia-container-runtime.list | \
+ sudo tee /etc/apt/sources.list.d/nvidia-container-runtime.list
+$ sudo apt-get update
+$ sudo apt-get install nvidia-container-runtime
+```
+
+Add nvidia runtime in ``/etc/docker/daemon.json ``
+```
+{
+ "runtimes": {
+ "nvidia": {
+ "path": "/usr/bin/nvidia-container-runtime",
+ "runtimeArgs": []
+ }
+ },
+ "default-runtime": "nvidia"
+
+}
+```
+After editing changes restart the docker.
+``systemctl restart docker ``
+
+Go to ``BaggageAI-Darknet-API/baggageai/dist/server/with-gpu`` and run:
+```
+$ docker-compose up -d
+```
+
+## Running containers in stack
+First of all initialize a swarm.
+```
+$ docker swarm init
+```
+You can add a worker node using ``docker swarm join`` command displayed on terminal.
+
+
+Check the statsus using
+```
+$ docker service ls
+$ docker stack ls
+```
+
+### With GPU
+Go to ``TKDNN/docker/`` and run:
+```
+$ docker stack deploy -c docker-compose.yml
+```
+
+# Calling the API
+```
+curl -X POST http://localhost:8080?name= --data-binary "@"
+```
+Example,
+```
+curl -X POST http://localhost:8080?name=S0240628297_20180812164749_L-4_3.jpg \
+--data-binary "@/home/ubuntu/BaggageAI/S0240628297_20180812164749_L-4_3.jpg"
+```
+
diff --git a/bag_server.cpp b/bag_server.cpp
new file mode 100644
index 0000000..b44d1f6
--- /dev/null
+++ b/bag_server.cpp
@@ -0,0 +1,248 @@
+#define STB_IMAGE_IMPLEMENTATION
+#include
+#include
+#include /* srand, rand */
+#ifdef __linux__
+#include
+#endif
+#define STB_IMAGE_WRITE_IMPLEMENTATION
+#include "stb_image_write.h"
+#include "stb_image.h"
+#include
+#include "utils.h"
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "Yolo3Detection.h"
+//#include "CenternetDetection.h"
+//#include "MobilenetDetection.h"
+#include "evaluation.h"
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "opencv2/core/core.hpp"
+#include
+
+#include //socket
+#include
+#include
+
+using namespace std;
+using namespace cv;
+
+#define PORT 8080
+
+#define FRAME_WIDTH 640
+#define FRAME_HEIGHT 480
+
+void error(const char *msg)
+{
+ perror(msg);
+ exit(1);
+} int sockfd, newsockfd, portno, n, imgSize, bytes=0, IM_HEIGHT, IM_WIDTH;;
+ socklen_t clilen;
+ char buffer[256];
+ // struct sockaddr_in serv_addr, cli_addr;
+// sockfd=socket(AF_INET, SOCK_STREAM, 0);
+ cv::Mat img;
+ char ntype = 'y';
+ const char *config_filename = "../demo/config.yaml";
+ const char * net = "../demo/yolo4_fp32.rt";
+// const char * img_path = "../demo/demo.jpg";
+ char * img_data;
+ bool show = false;
+ bool verbose;
+ int classes, map_points, map_levels;
+ float map_step, IoU_thresh, conf_thresh;
+ tk::dnn::Yolo3Detection yolo;
+ // tk::dnn::CenternetDetection cnet;
+// tk::dnn::MobilenetDetection mbnet;
+ tk::dnn::DetectionNN *detNN;
+ int n_classes = classes;
+ std::vector images;
+ std::vector detected_bbox;
+ tk::dnn::Frame f;
+
+ void init_bag(){tk::dnn::readmAPParams(config_filename, classes, map_points, map_levels, map_step,
+ IoU_thresh, conf_thresh, verbose);
+
+
+ //extract network name from rt path
+ std::string net_name;
+ removePathAndExtension(net, net_name);
+ std::cout<<"Network: "<init(net, n_classes, 1, conf_thresh);
+
+ //read images
+ // std::ifstream all_labels(labels_path);
+// std::cout << timeSinceEpochMillisec() << std::endl;
+ std::string l_filename;
+
+ if(show)
+ cv::namedWindow("detection", cv::WINDOW_NORMAL);
+ return;}
+// init_bag();
+// int images_done;
+ // for (images_done=0 ; std::getline(all_labels, l_filename) && images_done < n_images ; ++images_done) {
+ // std::cout < batch_frames;
+ batch_frames.push_back(frame);
+ int height = frame.rows;
+ int width = frame.cols;
+ std::cout< batch_dnn_input;
+ batch_dnn_input.push_back(frame.clone());
+ std::cout<<"test1"<<"\n";
+ //inference
+ detected_bbox.clear();
+ detNN->update(batch_dnn_input,1);
+ detNN->draw(batch_frames);
+ detected_bbox = detNN->detected;
+ std::cout<<"test2"<<"\n";
+ //try{
+ //json::value response;
+ //vector jsonArray;
+ // save detections labels
+ for(auto d:detected_bbox){
+ //convert detected bb in the same format as label
+ /// / / /
+ tk::dnn::BoundingBox b;
+ b.x = (d.x + d.w/2) / width;
+ b.y = (d.y + d.h/2) / height;
+ b.w = d.w / width;
+ b.h = d.h / height;
+ b.prob = d.prob;
+ b.cl = d.cl;
+ //f.det.push_back(b);
+
+ /*json::value detection;
+ detection["label"] = json::value::number(b.cl);
+ detection["x"] = json::value::number(b.x);
+ detection["y"] = json::value::number(b.y);
+ detection["w"] = json::value::number(b.w);
+ detection["h"] = json::value::number(b.h);
+ detection["prob"] = json::value::number(b.prob);
+ jsonArray.push_back(detection);*/
+ std::cout<< d.cl << " "<< d.prob << " "<< b.x << " "<< b.y << " "<< b.w << " "<< b.h <<"\n";
+
+ if(show)// draw rectangle for detection
+ cv::rectangle(batch_frames[0], cv::Point(d.x, d.y), cv::Point(d.x + d.w, d.y + d.h), cv::Scalar(0, 0, 255), 2);
+ }
+ //images.push_back(f);
+
+ if(show){
+ cv::imshow("detection", batch_frames[0]);
+ cv::waitKey(0);
+ }
+ // response["detections"] = json::value::array(jsonArray); //JSON Response
+
+ // std::cout << timeSinceEpochMillisec() << std::endl;
+ return ;
+ }
+
+int main()
+{
+// int sockfd, newsockfd, portno, n, imgSize, bytes=0, IM_HEIGHT, IM_WIDTH;;
+ // socklen_t clilen;
+ char buffer[256];
+ struct sockaddr_in serv_addr, cli_addr;
+ //init_bag()
+// cv::Mat img;
+
+ sockfd=socket(AF_INET, SOCK_STREAM, 0);
+ if(sockfd<0) error("ERROR opening socket");
+
+ bzero((char*)&serv_addr, sizeof(serv_addr));
+ portno = PORT;
+
+ serv_addr.sin_family=AF_INET;
+ serv_addr.sin_addr.s_addr=INADDR_ANY;
+ serv_addr.sin_port=htons(portno);
+
+ if(bind(sockfd, (struct sockaddr *) &serv_addr,
+ sizeof(serv_addr))<0) error("ERROR on binding");
+
+ listen(sockfd,5);
+ clilen=sizeof(cli_addr);
+
+ newsockfd=accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
+ if(newsockfd<0) error("ERROR on accept");
+
+ uchar sock[3];
+ cout << sock <(i,j) = Vec3b(sockData[ptr+0],sockData[ptr+1],sockData[ptr+2]);
+ ptr=ptr+3;
+ }
+ std::cout<<"t3"<<"\n";
+ int height = img.cols;
+ std::cout<
-#include
-#include /* srand, rand */
-#include
-#include
-#include "utils.h"
-
-#include
-#include
-#include
-#include
-
-// #include "Yolo3Detection.h"
-#include "CenternetDetection.h"
-
-bool gRun;
-bool SAVE_RESULT = false;
-
-void sig_handler(int signo) {
- std::cout<<"request gateway stop\n";
- gRun = false;
-}
-
-int main(int argc, char *argv[]) {
-
- std::cout<<"detection\n";
- signal(SIGINT, sig_handler);
-
-
- char *net = "resnet101_cnet.rt";
- if(argc > 1)
- net = argv[1];
- char *input = "../demo/yolo_test.mp4";
- if(argc > 2)
- input = argv[2];
-
- // tk::dnn::Yolo3Detection yolo;
- tk::dnn::CenternetDetection yolo;
- yolo.init(net);
-
- gRun = true;
-
- cv::VideoCapture cap(input);
- if(!cap.isOpened())
- gRun = false;
- else
- std::cout<<"camera started\n";
-
-
- cv::VideoWriter resultVideo;
- if(SAVE_RESULT) {
- int w = cap.get(cv::CAP_PROP_FRAME_WIDTH);
- int h = cap.get(cv::CAP_PROP_FRAME_HEIGHT);
- resultVideo.open("result.mp4", cv::VideoWriter::fourcc('M','P','4','V'), 30, cv::Size(w, h));
- }
-
- cv::Mat frame;
- cv::Mat dnn_input;
- cv::namedWindow("detection", cv::WINDOW_NORMAL);
-
- while(gRun) {
- cap >> frame;
- if(!frame.data) {
- break;
- }
-
- // this will be resized to the net format
- dnn_input = frame.clone();
- // TODO: async infer
- yolo.update(dnn_input);
-
- frame = yolo.draw(dnn_input);
- // // draw dets
- // for(int i=0; iclassesNames[b.cl];
- // float prob = b.prob;
-
- // // std::cout<
+#include
+#include /* srand, rand */
+#ifdef __linux__
+#include
+#endif
+#include "stb_image.h"
+#include
+#include "utils.h"
+#include "baggageDetect.hpp"
+#include "handler.h"
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "Yolo3Detection.h"
+//#include "CenternetDetection.h"
+//#include "MobilenetDetection.h"
+#include "evaluation.h"
+#include "tkdnn.h"
+#include
+#include
+#include
+using namespace std;
+using namespace cv;
+#include
+#include
+#include
+#include "image.h"
+void free_image(image m)
+{
+ if(m.data){
+ free(m.data);
+ }
+}
+image make_empty_image(int w, int h, int c)
+{
+ image out;
+ out.data = 0;
+ out.h = h;
+ out.w = w;
+ out.c = c;
+ return out;
+}
+
+image make_image(int w, int h, int c)
+{
+ image out = make_empty_image(w,h,c);
+ out.data = (float*)calloc(h * w * c, sizeof(float));
+ return out;
+}
+int check_mistakes = 0;
+image load_image_file(unsigned char *image_data, int channels, int antilog, int gray, int width, int height)
+{
+ int w, h, c;
+ unsigned char *data = image_data;
+ w = width;
+ h = height;
+ c = channels;
+
+ if (!image_data) {
+ if (check_mistakes) getchar();
+ return make_image(10, 10, 3);
+
+ }
+ if (channels) c = channels;
+
+ int i,j,k;
+ image im = make_image(w, h, c);
+ for(k = 0; k < c; ++k){
+ for(j = 0; j < h; ++j){
+ for(i = 0; i < w; ++i){
+ int dst_index = i + w*j + w*h*k;
+ int src_index = k + c*i + c*w*j;
+ (im).data[dst_index] = (float)image_data[src_index]/255.;
+ }
+ }
+ }
+ //free(data);
+ return im;
+}
+cv::Mat image_to_mat(image img)
+{
+ int channels = img.c;
+ int width = img.w;
+ int height = img.h;
+ cv::Mat mat = cv::Mat(height, width, CV_8UC(channels));
+ int step = mat.step;
+
+ for (int y = 0; y < img.h; ++y) {
+ for (int x = 0; x < img.w; ++x) {
+ for (int c = 0; c < img.c; ++c) {
+ float val = img.data[c*img.h*img.w + y*img.w + x];
+ mat.data[y*step + x*img.c + c] = (unsigned char)(val * 255);
+ }
+ }
+ }
+ return mat;
+}
+ std::vector classesNames;
+ image im;
+ cv::Mat frame;
+ cv::Mat gray;
+ int h=0;
+ int w=0;
+ int channels;
+ const char *config_filename = "config/config.yaml";
+ const char * net1="config/yolo4x_fp32.rt";
+ const char * net2="config/yolo4x_fp32.rt";
+ const char * net3="config/yolo4x_fp32.rt";
+ const char * net4="config/yolo4x_fp32.rt";
+ const char * net5="config/yolo4x_fp16.rt";
+ int classes1 , classes2 , classes3 , classes4 , classes5,len;
+ char * img_data;
+
+ string ustring;
+ float conf_thresh1 , conf_thresh2 , conf_thresh3 , conf_thresh4 , conf_thresh5;
+ tk::dnn::Yolo3Detection yolo1;
+ tk::dnn::DetectionNN *detNN1;
+ tk::dnn::Yolo3Detection yolo2;
+ tk::dnn::DetectionNN *detNN2;
+ tk::dnn::Yolo3Detection yolo3;
+ tk::dnn::DetectionNN *detNN3;
+ tk::dnn::Yolo3Detection yolo4;
+ tk::dnn::DetectionNN *detNN4;
+ tk::dnn::Yolo3Detection yolo5;
+ tk::dnn::DetectionNN *detNN5;
+ unsigned char * sockData;
+
+ std::vector batch_frames;
+ std::vector batch_dnn_input;
+ std::vector classesNames1;
+ std::vector classesNames2;
+ std::vector classesNames3;
+ std::vector classesNames4;
+ std::vector classesNames5;
+ std::vector images;
+ std::vector detected_bbox1;
+ std::vector detected_bbox2;
+ std::vector detected_bbox3;
+ std::vector detected_bbox4;
+ std::vector detected_bbox5;
+ //read parametersi
+ handler::handler(utility::string_t url):m_listener(url)
+{
+ m_listener.support(methods::POST, bind(&handler::handle_post, this, placeholders::_1));
+
+}
+
+string name_from_path(string path)
+{
+ return path.substr(path.find_last_of("/\\")+1);
+}
+ void handler::init_bag(){tk::dnn::readmAPParams(config_filename, classes1,conf_thresh1, classes2,conf_thresh2
+ , classes3,conf_thresh3, classes4,conf_thresh4,classes5,conf_thresh5);
+
+ detNN1 = &yolo1;
+ detNN1->init(net1, classes1, 1, conf_thresh1);
+ classesNames1=detNN1-> classesNames;
+ detNN2 = &yolo2;
+ detNN2->init(net2, classes2, 1, conf_thresh2);
+ classesNames2=detNN2-> classesNames;
+ detNN3 = &yolo3;
+ detNN3->init(net3, classes3, 1, conf_thresh4);
+ classesNames3=detNN3-> classesNames;
+ detNN4 = &yolo4;
+ detNN4->init(net4, classes4, 1, conf_thresh4);
+ classesNames4=detNN4-> classesNames;
+ detNN5 = &yolo5;
+ detNN5->init(net5, classes5, 1, conf_thresh5);
+ classesNames5=detNN5-> classesNames;
+ return;}
+
+
+ void handler::handle_post(http_request request){
+ BOOST_LOG_TRIVIAL(info) << "[" << name_from_path(string(__FILE__)) << " " << __LINE__ << "] " << request.to_string();
+
+ map http_get_vars = uri::split_query(request.request_uri().query());
+ map::iterator it = http_get_vars.find("name");
+ // int len;
+ if(it == http_get_vars.end())
+ {
+ BOOST_LOG_TRIVIAL(error) << "[" << name_from_path(string(__FILE__)) << " " << __LINE__ << "] " << "Image name not passed in query.";
+ request.reply(status_codes::UnprocessableEntity,"Please pass image name in the query.");
+ return;
+ }https://github.com/baggageai/baggageai-code-one.git
+ // std::cout< v) {
+ ustring = {v.begin(),v.end()};
+ len = ustring.size();
+ }).wait();
+ unsigned char *idata;
+try { //printSize(ustring);
+ BOOST_LOG_TRIVIAL(info) << "[" << name_from_path(string(__FILE__)) << " " << __LINE__ << "] " << "Detection Started";
+ sockData = (unsigned char *)ustring.c_str();
+ idata = stbi_load_from_memory(sockData, len, &w, &h, &channels, 0);
+ im = load_image_file(idata, channels, 0, 0, w, h);
+ batch_dnn_input.clear();
+ //batch_frames.clear();
+ gray=image_to_mat(im);
+// free(im);
+ cv::Mat in[] = {gray, gray,gray};
+ cv::merge(in, 3, frame);
+ batch_dnn_input.push_back(frame.clone());
+ json::value response;
+ vector jsonArray;
+
+ detected_bbox1.clear();
+ detNN1->update(batch_dnn_input,1);
+ detected_bbox1 = detNN1->detected;
+
+ for(auto d1:detected_bbox1){
+ json::value detection;
+ std::cout<<"1"<<" "<< d1.cl << " "<< d1.prob << " "<< d1.x << " "<< d1.y << " "<< d1.w << " "<< d1.h <<"\n";
+ detection["label"] = json::value::string(classesNames1[d1.cl]);
+ detection["x"] = json::value::number(d1.x);
+ detection["y"] = json::value::number(d1.y);
+ detection["w"] = json::value::number(d1.w);
+ detection["h"] = json::value::number(d1.h);
+ detection["prob"] = json::value::number(d1.prob);
+ jsonArray.push_back(detection);
+}
+ detected_bbox2.clear();
+ batch_dnn_input.clear();
+ batch_dnn_input.push_back(frame.clone());
+ detNN2->update(batch_dnn_input,1);
+ // std::cout<detected;
+
+ for(auto d2:detected_bbox2){
+ std::cout<<"2"<<" "<< d2.cl << " "<< d2.prob << " "<< d2.x << " "<< d2.y << " "<< d2.w << " "<< d2.h <<"\n";
+ json::value detection;
+ detection["label"] = json::value::string(classesNames2[d2.cl]);
+ detection["x"] = json::value::number(d2.x);
+ detection["y"] = json::value::number(d2.y);
+ detection["w"] = json::value::number(d2.w);
+ detection["h"] = json::value::number(d2.h);
+ detection["prob"] = json::value::number(d2.prob);
+ jsonArray.push_back(detection);
+}
+ detected_bbox3.clear();
+ batch_dnn_input.clear();
+ batch_dnn_input.push_back(frame.clone());
+ detNN3->update(batch_dnn_input,1);
+ detected_bbox3 = detNN3->detected;
+ for(auto d3:detected_bbox3){
+ std::cout<< "3"<<" "<update(batch_dnn_input,1);
+ detected_bbox4 = detNN4->detected;
+
+ for(auto d4:detected_bbox4){
+ std::cout<<"4"<<" "<update(batch_dnn_input,1);
+ detected_bbox5 = detNN5->detected;
+
+ for(auto d5:detected_bbox5){
+ std::cout<<"5"<<" "<
-#include
-#include
-#include
-#include
-#include
-#include
-
-
-#include "tkdnn.h"
-
-void sort(dnnType *src_begin, dnnType *src_end, int *idsrc);
-void topk(dnnType *src_begin, int *idsrc, int K, float *topk_scores,
- int *topk_inds, float *topk_ys, float *topk_xs);
-void sortAndTopKonDevice(dnnType *src_begin, int *idsrc, float *topk_scores, int *topk_inds, float *topk_ys, float *topk_xs, const int size, const int K, const int n_classes);
-void subtractWithThreshold(dnnType *src_begin, dnnType *src_end, dnnType *src2_begin, dnnType *src_out);
-void topKxyclasses(int *ids_begin, int *ids_end, const int K, const int size, const int wh, int *clses, int *xs, int *ys);
-void topKxyAddOffset(int * ids_begin, const int K, const int size, int *intxs_begin, int *intys_begin, float *xs_begin, float *ys_begin, dnnType *src_begin);
-void bboxes(int * ids_begin, const int K, const int size, float *xs_begin, float *ys_begin, dnnType *src_begin, float *bbx0, float *bbx1, float *bby0, float *bby1);
diff --git a/include/tkDNN/BoundingBox.h b/include/tkDNN/BoundingBox.h
new file mode 100644
index 0000000..7f7449c
--- /dev/null
+++ b/include/tkDNN/BoundingBox.h
@@ -0,0 +1,31 @@
+#ifndef BOUNDINGBOX_H
+#define BOUNDINGBOX_H
+
+#include
+#include "tkdnn.h"
+
+namespace tk { namespace dnn {
+class BoundingBox : public tk::dnn::box
+{
+ float overlap(const float p1, const float l1, const float p2, const float l22);
+ float boxesIntersection(const BoundingBox &b);
+ float boxesUnion(const BoundingBox &b);
+
+ public:
+
+ int uniqueTruthIndex = -1;
+ int truthFlag = 0;
+ float maxIoU = 0;
+
+ float IoU(const BoundingBox &b);
+ void clear();
+
+ friend std::ostream& operator<<(std::ostream& os, const BoundingBox& bb);
+};
+
+std::ostream& operator<<(std::ostream& os, const BoundingBox& bb);
+bool boxComparison (const BoundingBox& a,const BoundingBox& b) ;
+
+}}
+#endif /*BOUNDINGBOX_H*/
+
diff --git a/include/tkDNN/CenternetDetection.h b/include/tkDNN/CenternetDetection.h
index 8071112..3c8cfbb 100644
--- a/include/tkDNN/CenternetDetection.h
+++ b/include/tkDNN/CenternetDetection.h
@@ -1,112 +1,86 @@
-#include
-#include
-#include
-#include /* srand, rand */
-#include
-#include
-#include "utils.h"
-#include
+#ifndef CENTERNETDETECTION_H
+#define CENTERNETDETECTION_H
+
#include "kernels.h"
+#include
+#include "opencv2/opencv.hpp"
+#include
#include
#include // std::iota
#include // std::sort
+#include "DetectionNN.h"
-#include
-#include
-#include
+#include "kernelsThrust.h"
-#include "tkdnn.h"
-#include "sorting.h"
-namespace tk { namespace dnn {
+namespace tk { namespace dnn {
-/**
- *
- * @author Francesco Gatti
- */
-class CenternetDetection {
+class CenternetDetection : public DetectionNN
+{
+private:
+ tk::dnn::dataDim_t dim;
+ tk::dnn::dataDim_t dim2;
+ tk::dnn::dataDim_t dim_hm;
+ tk::dnn::dataDim_t dim_wh;
+ tk::dnn::dataDim_t dim_reg;
+ float *topk_scores;
+ int *topk_inds_;
+ float *topk_ys_;
+ float *topk_xs_;
+ int *ids_d, *ids_, *ids_2, *ids_2d;
- private:
- tk::dnn::NetworkRT *netRT = nullptr;
- dnnType *input_h, *input, *input_d;
+ float *scores, *scores_d;
+ int *clses, *clses_d;
+ int *topk_inds_d;
+ float *topk_ys_d;
+ float *topk_xs_d;
+ int *inttopk_xs_d, *inttopk_ys_d;
- int ndets = 0;
- // tk::dnn::Yolo::detection *dets = nullptr;
- cv::Mat imageF;
- cv::Mat bgr[3];
-
- // variable to test cnet on dog pictures
- tk::dnn::dataDim_t dim;
- tk::dnn::dataDim_t dim2;
- cv::Size sz;
- const char *input_bin = "../tests/resnet101_cnet/debug/input.bin";
-
- // pre-process
- tk::dnn::dataDim_t dim_hm;
- tk::dnn::dataDim_t dim_wh;
- tk::dnn::dataDim_t dim_reg;
- float *topk_scores;
- int *topk_inds_;
- float *topk_ys_;
- float *topk_xs_;
- int *ids_d, *ids_, *ids_2, *ids_2d;
-
- float *scores, *scores_d;
- int *clses, *clses_d;
- int *topk_inds_d;
- float *topk_ys_d;
- float *topk_xs_d;
- int *inttopk_xs_d, *inttopk_ys_d;
+ float *bbx0, *bby0, *bbx1, *bby1;
+ float *bbx0_d, *bby0_d, *bbx1_d, *bby1_d;
+ float *target_coords;
- float *bbx0, *bby0, *bbx1, *bby1;
- float *bbx0_d, *bby0_d, *bbx1_d, *bby1_d;
-
- float *target_coords;
-
+ #ifdef OPENCV_CUDACONTRIB
+ float *mean_d;
+ float *stddev_d;
+ #else
cv::Vec mean;
cv::Vec stddev;
- cv::Mat src;
- cv::Mat dst;
- //processing
- float toll = 0.000001;
- int K = 100;
- int width = 56; // TODO
+ dnnType *input;
+ #endif
+
+ float *d_ptrs;
+
+ cv::Mat src;
+ cv::Mat dst;
+ cv::Mat dst2;
+ cv::Mat trans, trans2;
+ //processing
+ float toll = 0.000001;
+ int K = 100;
+ int width = 128;//56; // TODO
+
+ // pointer used in the kernels
+ float *src_out;
+ int *ids_out;
+
+ struct threshold op;
-
- public:
- dnnType *rt_out[4];
-
- float inp_height = 224;//512;
- float inp_width = 224;//512;
-
- int classes = 80;
- int num = 0;
- int n_masks = 0;
- float thresh = 0.3;
- cv::Scalar colors[256];
-
- // this is filled with results
- std::vector detected;
- // draw
- std::vector coco_class_name;
-
- CenternetDetection() {}
-
- virtual ~CenternetDetection() {}
-
- /**
- * Method used for inizialize the class
- *
- * @return Success of the initialization
- */
- bool init(std::string tensor_path);
- void testdog();
- cv::Mat draw(cv::Mat &frame);
- void update(cv::Mat &frame);
+public:
+ CenternetDetection() {};
+ ~CenternetDetection() {};
+ 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 postprocess(const int bi=0,const bool mAP=false);
};
-}}
+
+} // namespace dnn
+} // namespace tk
+
+
+#endif /*CENTERNETDETECTION_H*/
\ No newline at end of file
diff --git a/include/tkDNN/DarknetParser.h b/include/tkDNN/DarknetParser.h
new file mode 100644
index 0000000..089c4d6
--- /dev/null
+++ b/include/tkDNN/DarknetParser.h
@@ -0,0 +1,51 @@
+#pragma once
+#include
+#include "tkDNN/tkdnn.h"
+
+namespace tk { namespace dnn {
+
+ struct darknetFields_t{
+ std::string type = "";
+ int width = 0;
+ int height = 0;
+ int channels = 3;
+ int batch_normalize=0;
+ int groups = 1;
+ int group_id = 0;
+ int filters=1;
+ int size_x=1;
+ int size_y=1;
+ int stride_x=1;
+ int stride_y=1;
+ int padding_x = 0;
+ int padding_y = 0;
+ int n_mask = 0;
+ int classes = 20;
+ int num = 1;
+ int pad = 0;
+ int coords = 4;
+ int nms_kind = 0;
+ int new_coords= 0;
+ float scale_xy = 1;
+ float nms_thresh = 0.45;
+ std::vector layers;
+ std::string activation = "linear";
+
+ friend std::ostream& operator<<(std::ostream& os, const darknetFields_t& f){
+ os << f.width << " " << f.height << " " << f.channels << " " << f.batch_normalize<< " " << f.filters << " " << f.activation<< " " << f.scale_xy;
+ return os;
+ }
+ };
+
+ std::string darknetParseType(const std::string& line);
+ bool divideNameAndValue(const std::string& line, std::string&name, std::string& value);
+ std::vector fromStringToIntVec(const std::string& line, const char delimiter);
+
+ bool darknetParseFields(const std::string& line, darknetFields_t& fields);
+ tk::dnn::Network *darknetAddNet(darknetFields_t &fields);
+ void darknetAddLayer(tk::dnn::Network *net, darknetFields_t &f, std::string wgs_path,
+ std::vector &netLayers, const std::vector& names);
+ std::vector darknetReadNames(const std::string& names_file);
+ tk::dnn::Network* darknetParser(const std::string& cfg_file, const std::string& wgs_path, const std::string& names_file);
+
+}}
diff --git a/include/tkDNN/DetectionNN.h b/include/tkDNN/DetectionNN.h
new file mode 100644
index 0000000..a8c81f7
--- /dev/null
+++ b/include/tkDNN/DetectionNN.h
@@ -0,0 +1,185 @@
+#ifndef DETECTIONNN_H
+#define DETECTIONNN_H
+
+#include
+#include
+#include
+#ifdef __linux__
+#include
+#endif
+
+#include
+#include "utils.h"
+
+#include
+#include
+#include
+
+#include "tkdnn.h"
+
+//#define OPENCV_CUDACONTRIB //if OPENCV has been compiled with CUDA and contrib.
+
+#ifdef OPENCV_CUDACONTRIB
+#include
+#include
+#endif
+
+
+namespace tk { namespace dnn {
+
+class DetectionNN {
+
+ protected:
+ tk::dnn::NetworkRT *netRT = nullptr;
+ dnnType *input_d;
+
+ std::vector originalSize;
+
+ cv::Scalar colors[256];
+
+ int nBatches = 1;
+
+#ifdef OPENCV_CUDACONTRIB
+ cv::cuda::GpuMat bgr[3];
+ cv::cuda::GpuMat imagePreproc;
+#else
+ cv::Mat bgr[3];
+ cv::Mat imagePreproc;
+ dnnType *input;
+#endif
+
+ /**
+ * This method preprocess the image, before feeding it to the NN.
+ *
+ * @param frame original frame to adapt for inference.
+ * @param bi batch index
+ */
+ virtual void preprocess(cv::Mat &frame, const int bi=0) = 0;
+
+ /**
+ * This method postprocess the output of the NN to obtain the correct
+ * boundig boxes.
+ *
+ * @param bi batch index
+ * @param mAP set to true only if all the probabilities for a bounding
+ * box are needed, as in some cases for the mAP calculation
+ */
+ virtual void postprocess(const int bi=0,const bool mAP=false) = 0;
+
+ public:
+ int classes = 0;
+ float confThreshold = 0.3; /*threshold on the confidence of the boxes*/
+
+ std::vector detected; /*bounding boxes in output*/
+ std::vector> batchDetected; /*bounding boxes in output*/
+ std::vector stats; /*keeps track of inference times (ms)*/
+ std::vector classesNames;
+
+ DetectionNN() {};
+ ~DetectionNN(){};
+
+ /**
+ * Method used to initialize the class, allocate memory and compute
+ * needed data.
+ *
+ * @param tensor_path path to the rt file of the NN.
+ * @param n_classes number of classes for the given dataset.
+ * @param n_batches maximum number of batches to use in inference
+ * @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, const float conf_thresh=0.3) = 0;
+
+ /**
+ * This method performs the whole detection of the NN.
+ *
+ * @param frames frames to run detection on.
+ * @param cur_batches number of batches to use in inference
+ * @param save_times if set to true, preprocess, inference and postprocess times
+ * are saved on a csv file, otherwise not.
+ * @param times pointer to the output stream where to write times
+ * @param mAP set to true only if all the probabilities for a bounding
+ * box are needed, as in some cases for the mAP calculation
+ */
+ void update(std::vector& frames, const int cur_batches=1, bool save_times=false, std::ofstream *times=nullptr, const bool mAP=false){
+ if(save_times && times==nullptr)
+ FatalError("save_times set to true, but no valid ofstream given");
+ if(cur_batches > nBatches)
+ FatalError("A batch size greater than nBatches cannot be used");
+
+ originalSize.clear();
+ if(TKDNN_VERBOSE) printCenteredTitle(" TENSORRT detection ", '=', 30);
+ {
+ TKDNN_TSTART
+ for(int bi=0; biinput_dim;
+ dim.n = cur_batches;
+ {
+ if(TKDNN_VERBOSE) dim.print();
+ TKDNN_TSTART
+ netRT->infer(dim, input_d);
+ TKDNN_TSTOP
+ if(TKDNN_VERBOSE) dim.print();
+ stats.push_back(t_ns);
+ if(save_times) *times<& frames) {
+ tk::dnn::box b;
+ int x0, w, x1, y0, h, y1;
+ int objClass;
+ std::string det_class;
+ int baseline = 0;
+ float font_scale = 0.5;
+ int thickness = 2;
+
+ for(int bi=0; bi
+#include
+#include /* srand, rand */
+
+#ifdef __linux__
+#include
+#elif _WIN32
+#define _USE_MATH_DEFINES
+#include
+#endif
+
+#include
+#include
+#include "utils.h"
+#include "tkdnn.h"
+
+namespace tk { namespace dnn {
+
+/**
+ *
+ * @author Francesco Gatti
+ */
+class ImuOdom {
+
+ public:
+ tk::dnn::Network *net = nullptr;
+
+ // Network input dim
+ tk::dnn::dataDim_t dim0;
+ tk::dnn::dataDim_t dim1;
+ tk::dnn::dataDim_t dim2;
+
+ // Network output dim
+ tk::dnn::dataDim_t odim0;
+ tk::dnn::dataDim_t odim1;
+
+ // input pointers
+ dnnType *i0_d, *i1_d, *i2_d;
+ // output pointers
+ dnnType *o0_d, *o1_d;
+
+ // output eigen CPU
+ Eigen::MatrixXf deltaP, deltaQ;
+
+ Eigen::MatrixXd odomPOS, odomEULER;
+ Eigen::Matrix3d odomROT;
+ Eigen::Isometry3f tf = Eigen::Isometry3f::Identity();
+
+ ImuOdom() {}
+
+ virtual ~ImuOdom() {}
+
+ /**
+ * Method used for initialize the class
+ *
+ * @return Success of the initialization
+ */
+ bool init(std::string layers_path) {
+
+ dim0 = tk::dnn::dataDim_t(1, 4, 1, 100);
+ dim1 = tk::dnn::dataDim_t(1, 3, 1, 100);
+ dim2 = tk::dnn::dataDim_t(1, 3, 1, 100);
+
+ checkCuda( cudaMalloc(&i0_d, dim0.tot()*sizeof(dnnType)) );
+ checkCuda( cudaMalloc(&i1_d, dim1.tot()*sizeof(dnnType)) );
+ checkCuda( cudaMalloc(&i2_d, dim2.tot()*sizeof(dnnType)) );
+
+ std::string c0_bin = layers_path + "/conv1d_7.bin";
+ std::string c1_bin = layers_path + "/conv1d_8.bin";
+ std::string c2_bin = layers_path + "/conv1d_9.bin";
+ std::string c3_bin = layers_path + "/conv1d_10.bin";
+ std::string c4_bin = layers_path + "/conv1d_11.bin";
+ std::string c5_bin = layers_path + "/conv1d_12.bin";
+ std::string l0_bin = layers_path + "/bidirectional_3.bin";
+ std::string l1_bin = layers_path + "/bidirectional_4.bin";
+ std::string d0_bin = layers_path + "/dense_3.bin";
+ std::string d1_bin = layers_path + "/dense_4.bin";
+
+ net = new tk::dnn::Network(dim0);
+ tk::dnn::Input *x0 = new tk::dnn::Input (net, dim0, i0_d);
+ tk::dnn::Conv2d *x0_0 = new tk::dnn::Conv2d (net, 128, 1, 11, 1, 1, 0, 0, c0_bin);
+ tk::dnn::Conv2d *x0_1 = new tk::dnn::Conv2d (net, 128, 1, 11, 1, 1, 0, 0, c1_bin);
+ tk::dnn::Pooling *x0_2 = new tk::dnn::Pooling(net, 1, 3, 1, 3 ,0, 0, tk::dnn::tkdnnPoolingMode_t::POOLING_MAX);
+
+ tk::dnn::Input *x1 = new tk::dnn::Input (net, dim1, i1_d);
+ tk::dnn::Conv2d *x1_0 = new tk::dnn::Conv2d (net, 128, 1, 11, 1, 1, 0, 0, c2_bin);
+ tk::dnn::Conv2d *x1_1 = new tk::dnn::Conv2d (net, 128, 1, 11, 1, 1, 0, 0, c3_bin);
+ tk::dnn::Pooling *x1_2 = new tk::dnn::Pooling(net, 1, 3, 1, 3, 0, 0, tk::dnn::tkdnnPoolingMode_t::POOLING_MAX);
+
+ tk::dnn::Input *x2 = new tk::dnn::Input (net, dim2, i2_d);
+ tk::dnn::Conv2d *x2_0 = new tk::dnn::Conv2d (net, 128, 1, 11, 1, 1, 0, 0, c4_bin);
+ tk::dnn::Conv2d *x2_1 = new tk::dnn::Conv2d (net, 128, 1, 11, 1, 1, 0, 0, c5_bin);
+ tk::dnn::Pooling *x2_2 = new tk::dnn::Pooling(net, 1, 3, 1, 3, 0, 0, tk::dnn::tkdnnPoolingMode_t::POOLING_MAX);
+
+ tk::dnn::Layer *concat_l[3] = { x0_2, x1_2, x2_2 };
+ tk::dnn::Route *concat = new tk::dnn::Route(net, concat_l, 3);
+
+ tk::dnn::LSTM *lstm0 = new tk::dnn::LSTM(net, 128, true, l0_bin);
+ tk::dnn::LSTM *lstm1 = new tk::dnn::LSTM(net, 128, false, l1_bin);
+
+ tk::dnn::Dense *d0 = new tk::dnn::Dense(net, 3, d0_bin);
+
+ tk::dnn::Layer *lstm1_l[1] = { lstm1 };
+ tk::dnn::Route *lstm1_link = new tk::dnn::Route(net, lstm1_l, 1);
+ tk::dnn::Dense *d1 = new tk::dnn::Dense(net, 4, d1_bin);
+
+ net->print();
+
+ // output data
+ o0_d = d0->dstData;
+ o1_d = d1->dstData;
+ odim0 = d0->output_dim;
+ odim1 = d1->output_dim;
+
+ deltaP.resize(odim0.tot(), 1);
+ deltaQ.resize(odim1.tot(), 1);
+
+ odomPOS = Eigen::MatrixXd::Zero(3, 1);
+ odomROT = Eigen::MatrixXd::Identity(3, 3);
+ odomEULER = Eigen::MatrixXd::Zero(3, 1);
+ return true;
+ }
+
+ void close() {
+ // TODO: dealloc :)
+ }
+
+ void update(dnnType *x0, dnnType *x1, dnnType *x2) {
+
+ checkCuda( cudaMemcpy(i0_d, x0, dim0.tot()*sizeof(dnnType), cudaMemcpyHostToDevice) );
+ checkCuda( cudaMemcpy(i1_d, x1, dim1.tot()*sizeof(dnnType), cudaMemcpyHostToDevice) );
+ checkCuda( cudaMemcpy(i2_d, x2, dim2.tot()*sizeof(dnnType), cudaMemcpyHostToDevice) );
+
+ // Inference
+ tk::dnn::dataDim_t dim;
+ net->infer(dim, nullptr);
+
+ checkCuda( cudaMemcpy(deltaP.data(), o0_d, odim0.tot()*sizeof(dnnType), cudaMemcpyDeviceToHost) );
+ checkCuda( cudaMemcpy(deltaQ.data(), o1_d, odim1.tot()*sizeof(dnnType), cudaMemcpyDeviceToHost) );
+
+ // compute odom
+ Eigen::Quaterniond q;
+ q.w() = deltaQ(0);
+ q.x() = deltaQ(1);
+ q.y() = deltaQ(2);
+ q.z() = deltaQ(3);
+ odomPOS = odomPOS + odomROT*deltaP.cast(); // V1
+ //odomPOS = odomPOS + deltaP.cast(); // V2
+ odomROT = odomROT * q.normalized().toRotationMatrix();
+
+ // compute Euler
+ auto newEULER = odomROT.eulerAngles(0, 1, 2);
+ for(int i=0; i<3; i++) {
+ while( fabs(newEULER(i) - odomEULER(i)) > M_PI_2 ) {
+ newEULER(i) += newEULER(i) - odomEULER(i) > 0 ? -M_PI : +M_PI;
+ //std::cout<();
+ tf.matrix().block(0, 3, 3, 1) = odomPOS.cast();
+ }
+
+};
+
+}}
diff --git a/include/tkDNN/Int8BatchStream.h b/include/tkDNN/Int8BatchStream.h
new file mode 100644
index 0000000..c39a11c
--- /dev/null
+++ b/include/tkDNN/Int8BatchStream.h
@@ -0,0 +1,72 @@
+#ifndef INT8BATCHSTREAM_H
+#define INT8BATCHSTREAM_H
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#ifdef __linux__
+#include
+#endif
+
+#include
+
+#include "NvInfer.h"
+#include "utils.h"
+#include "tkdnn.h"
+
+/*
+ * BatchStream implements the stream for the INT8 calibrator.
+ * It reads the two files .txt with the list of image file names
+ * and the list of label file names.
+ * It then iterates on images and labels.
+ */
+class BatchStream {
+public:
+ BatchStream(tk::dnn::dataDim_t dim, int batchSize, int maxBatches, const std::string& fileimglist, const std::string& filelabellist);
+ virtual ~BatchStream() { }
+ void reset(int firstBatch);
+ bool next();
+ void skip(int skipCount);
+ float *getBatch() { return mBatch.data(); }
+ float *getLabels() { return mLabels.data(); }
+ int getBatchesRead() const { return mBatchCount; }
+ int getBatchSize() const { return mBatchSize; }
+ nvinfer1::DimsNCHW getDims() const { return mDims; }
+ float* getFileBatch() { return &mFileBatch[0]; }
+ float* getFileLabels() { return &mFileLabels[0]; }
+ void readInListFile(const std::string& dataFilePath, std::vector& mListIn);
+ void readCVimage(std::string inputFileName, std::vector& res, bool fixshape = true);
+ void readLabels(std::string inputFileName ,std::vector& ris);
+ bool update();
+
+private:
+ int mBatchSize{ 0 };
+ int mMaxBatches{ 0 };
+ int mBatchCount{ 0 };
+ int mFileCount{ 0 };
+ int mFileBatchPos{ 0 };
+ int mImageSize{ 0 };
+
+ nvinfer1::DimsNCHW mDims;
+ std::vector mBatch;
+ std::vector mLabels;
+ std::vector mFileBatch;
+ std::vector mFileLabels;
+
+ int mHeight;
+ int mWidth;
+ std::string mFileImgList;
+ std::vector mListImg;
+ std::string mFileLabelList;
+ std::vector mListLabel;
+};
+
+#endif //INT8BATCHSTREAM
\ No newline at end of file
diff --git a/include/tkDNN/Int8Calibrator.h b/include/tkDNN/Int8Calibrator.h
new file mode 100644
index 0000000..4a0ea47
--- /dev/null
+++ b/include/tkDNN/Int8Calibrator.h
@@ -0,0 +1,49 @@
+#ifndef INT8CALIBRATOR_H
+#define INT8CALIBRATOR_H
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "NvInfer.h"
+
+#include
+#include
+
+#include "Int8BatchStream.h"
+
+#include "tkdnn.h"
+#include "utils.h"
+
+/*
+ * Int8EntropyCalibrator implements the INT8 calibrator to achieve the
+ * INT8 quantization. It uses a BatchStream stream to scroll through
+ * images data. It also implements the calibration cache, a way to
+ * save the calibration process results to reduce the running time:
+ * the calibration process takes a long time.
+ */
+class Int8EntropyCalibrator : public nvinfer1::IInt8EntropyCalibrator {
+public:
+ Int8EntropyCalibrator(BatchStream& stream, int firstBatch, const std::string& calibTableFilePath,
+ const std::string& inputBlobName, bool readCache = true);
+ virtual ~Int8EntropyCalibrator() { checkCuda(cudaFree(mDeviceInput)); }
+ int getBatchSize() const override { return mStream.getBatchSize(); }
+ bool getBatch(void* bindings[], const char* names[], int nbBindings) override;
+ const void* readCalibrationCache(size_t& length) override;
+ void writeCalibrationCache(const void* cache, size_t length) override;
+
+private:
+ BatchStream mStream;
+ const std::string mCalibTableFilePath{ nullptr };
+ const std::string mInputBlobName;
+ bool mReadCache{ true };
+
+ size_t mInputCount;
+ void* mDeviceInput{ nullptr };
+ std::vector mCalibrationCache;
+};
+
+#endif //INT8CALIBRATOR_H
\ No newline at end of file
diff --git a/include/tkDNN/Layer.h b/include/tkDNN/Layer.h
index 2d84a0e..e097372 100644
--- a/include/tkDNN/Layer.h
+++ b/include/tkDNN/Layer.h
@@ -9,12 +9,19 @@
namespace tk { namespace dnn {
enum layerType_t {
+ LAYER_INPUT,
LAYER_DENSE,
LAYER_CONV2D,
LAYER_DECONV2D,
LAYER_DEFORMCONV2D,
+ LAYER_LSTM,
LAYER_ACTIVATION,
+ LAYER_ACTIVATION_CRELU,
+ LAYER_ACTIVATION_LEAKY,
+ LAYER_ACTIVATION_MISH,
+ LAYER_ACTIVATION_LOGISTIC,
LAYER_FLATTEN,
+ LAYER_RESHAPE,
LAYER_MULADD,
LAYER_POOLING,
LAYER_SOFTMAX,
@@ -34,7 +41,7 @@ enum layerType_t {
class Layer {
public:
- Layer(Network *net, bool final = false);
+ Layer(Network *net);
virtual ~Layer();
virtual layerType_t getLayerType() = 0;
@@ -42,9 +49,9 @@ public:
std::cout<<"No infer action for this layer\n";
return NULL;
}
-
+ void setFinal() { this->final = true; }
dataDim_t input_dim, output_dim;
- dnnType *dstData; //where results will be putted
+ dnnType *dstData = nullptr; //where results will be putted
int id = 0;
bool final; //if the layer is the final one
@@ -52,22 +59,29 @@ public:
std::string getLayerName() {
layerType_t type = getLayerType();
switch(type) {
- case LAYER_DENSE: return "Dense";
- case LAYER_CONV2D: return "Conv2d";
- case LAYER_DECONV2D: return "DeConv2d";
- case LAYER_DEFORMCONV2D:return "DeformConv2d";
- case LAYER_ACTIVATION: return "Activation";
- case LAYER_FLATTEN: return "Flatten";
- case LAYER_MULADD: return "MulAdd";
- case LAYER_POOLING: return "Pooling";
- case LAYER_SOFTMAX: return "Softmax";
- case LAYER_ROUTE: return "Route";
- case LAYER_REORG: return "Reorg";
- case LAYER_SHORTCUT: return "Shortcut";
- case LAYER_UPSAMPLE: return "Upsample";
- case LAYER_REGION: return "Region";
- case LAYER_YOLO: return "Yolo";
- default: return "unknown";
+ case LAYER_INPUT: return "Input";
+ case LAYER_DENSE: return "Dense";
+ case LAYER_CONV2D: return "Conv2d";
+ case LAYER_DECONV2D: return "DeConv2d";
+ case LAYER_DEFORMCONV2D: return "DeformConv2d";
+ case LAYER_LSTM: return "LSTM";
+ case LAYER_ACTIVATION: return "Activation";
+ case LAYER_ACTIVATION_CRELU: return "ActivationCReLU";
+ case LAYER_ACTIVATION_LEAKY: return "ActivationLeaky";
+ case LAYER_ACTIVATION_MISH: return "ActivationMish";
+ case LAYER_ACTIVATION_LOGISTIC: return "ActivationLogistic";
+ case LAYER_FLATTEN: return "Flatten";
+ case LAYER_RESHAPE: return "Reshape";
+ case LAYER_MULADD: return "MulAdd";
+ case LAYER_POOLING: return "Pooling";
+ case LAYER_SOFTMAX: return "Softmax";
+ case LAYER_ROUTE: return "Route";
+ case LAYER_REORG: return "Reorg";
+ case LAYER_SHORTCUT: return "Shortcut";
+ case LAYER_UPSAMPLE: return "Upsample";
+ case LAYER_REGION: return "Region";
+ case LAYER_YOLO: return "Yolo";
+ default: return "unknown";
}
}
@@ -85,7 +99,7 @@ class LayerWgs : public Layer {
public:
LayerWgs(Network *net, int inputs, int outputs, int kh, int kw, int kt,
- std::string fname_weights, bool batchnorm = false, bool additional_bias = false, bool final = false);
+ std::string fname_weights, bool batchnorm = false, bool additional_bias = false, bool deConv = false, int groups = 1);
virtual ~LayerWgs();
int inputs, outputs;
@@ -96,23 +110,87 @@ public:
// additional bias for DCN
bool additional_bias;
- dnnType *bias2_h, *bias2_d;
+ dnnType *bias2_h = nullptr, *bias2_d = nullptr;
//batchnorm
bool batchnorm;
- dnnType *power_h;
- dnnType *scales_h, *scales_d;
- dnnType *mean_h, *mean_d;
- dnnType *variance_h, *variance_d;
+ dnnType *power_h = nullptr;
+ dnnType *scales_h = nullptr, *scales_d = nullptr;
+ dnnType *mean_h = nullptr, *mean_d = nullptr;
+ dnnType *variance_h = nullptr, *variance_d = nullptr;
//fp16
- __half *data16_h, *bias16_h;
- __half *data16_d, *bias16_d;
+ __half *data16_h = nullptr, *bias16_h = nullptr;
+ __half *data16_d = nullptr, *bias16_d = nullptr;
+ __half *bias216_h = nullptr, *bias216_d = nullptr;
- __half *power16_h, *power16_d;
- __half *scales16_h, *scales16_d;
- __half *mean16_h, *mean16_d;
- __half *variance16_h, *variance16_d;
+ __half *power16_h = nullptr, *power16_d = nullptr;
+ __half *scales16_h = nullptr, *scales16_d = nullptr;
+ __half *mean16_h = nullptr, *mean16_d = nullptr;
+ __half *variance16_h = nullptr, *variance16_d = nullptr;
+
+ void releaseHost(bool release32 = true, bool release16 = true) {
+ if(release32) {
+ if( data_h != nullptr) { delete [] data_h; data_h = nullptr; }
+ if( bias_h != nullptr) { delete [] bias_h; bias_h = nullptr; }
+ if( bias2_h != nullptr) { delete [] bias2_h; bias2_h = nullptr; }
+ if( scales_h != nullptr) { delete [] scales_h; scales_h = nullptr; }
+ if( mean_h != nullptr) { delete [] mean_h; mean_h = nullptr; }
+ if(variance_h != nullptr) { delete [] variance_h; variance_h = nullptr; }
+ if( power_h != nullptr) { delete [] power_h; power_h = nullptr; }
+ }
+ if(net->fp16 && release16) {
+ if( data16_h != nullptr) { delete [] data16_h; data16_h = nullptr; }
+ if( bias16_h != nullptr) { delete [] bias16_h; bias16_h = nullptr; }
+ if( bias216_h != nullptr) { delete [] bias216_h; bias216_h = nullptr; }
+ if( scales16_h != nullptr) { delete [] scales16_h; scales16_h = nullptr; }
+ if( mean16_h != nullptr) { delete [] mean16_h; mean16_h = nullptr; }
+ if(variance16_h != nullptr) { delete [] variance16_h; variance16_h = nullptr; }
+ if( power16_h != nullptr) { delete [] power16_h; power16_h = nullptr; }
+
+ }
+ }
+ void releaseDevice(bool release32 = true, bool release16 = true) {
+ if(release32) {
+ if( data_d != nullptr) { cudaFree( data_d); data_d = nullptr; }
+ if( bias_d != nullptr) { cudaFree( bias_d); bias_d = nullptr; }
+ if( bias2_d != nullptr) { cudaFree( bias2_d); bias2_d = nullptr; }
+ if( scales_d != nullptr) { cudaFree( scales_d); scales_d = nullptr; }
+ if( mean_d != nullptr) { cudaFree( mean_d); mean_d = nullptr; }
+ if(variance_d != nullptr) { cudaFree(variance_d); variance_d = nullptr; }
+ }
+ if(net->fp16 && release16) {
+ if( data16_d != nullptr) { cudaFree( data16_d); data16_d = nullptr; }
+ if( bias16_d != nullptr) { cudaFree( bias16_d); bias16_d = nullptr; }
+ if( bias216_d != nullptr) { cudaFree( bias216_d); bias216_d = nullptr; }
+ if( scales16_d != nullptr) { cudaFree( scales16_d); scales16_d = nullptr; }
+ if( mean16_d != nullptr) { cudaFree( mean16_d); mean16_d = nullptr; }
+ if(variance16_d != nullptr) { cudaFree(variance16_d); variance16_d = nullptr; }
+ if( power16_d != nullptr) { cudaFree( power16_d); power16_d = nullptr; }
+ }
+ }
+};
+
+
+/**
+ Input layer (it doesn't need weights)
+*/
+class Input : public Layer {
+
+public:
+
+ Input(Network *net, dataDim_t &dim, dnnType* srcData) : Layer(net) {
+ input_dim = dim;
+ output_dim = dim;
+ dstData = srcData;
+ }
+ virtual ~Input() {}
+ virtual layerType_t getLayerType() { return LAYER_INPUT; };
+
+ virtual dnnType* infer(dataDim_t &dim, dnnType* srcData) {
+ dim = output_dim;
+ return dstData;
+ }
};
@@ -131,24 +209,38 @@ public:
/**
- Avaible activation functions
+ Available activation functions
*/
typedef enum {
ACTIVATION_ELU = 100,
- ACTIVATION_LEAKY = 101
+ ACTIVATION_LEAKY = 101,
+ ACTIVATION_MISH = 102,
+ ACTIVATION_LOGISTIC = 103
} tkdnnActivationMode_t;
/**
- Activation layer (it doesnt need weigths)
+ Activation layer (it doesn't need weights)
*/
class Activation : public Layer {
public:
int act_mode;
+ float ceiling;
- Activation(Network *net, int act_mode);
+ Activation(Network *net, int act_mode, const float ceiling=0.0);
virtual ~Activation();
- virtual layerType_t getLayerType() { return LAYER_ACTIVATION; };
+ virtual layerType_t getLayerType() {
+ if(act_mode == CUDNN_ACTIVATION_CLIPPED_RELU)
+ return LAYER_ACTIVATION_CRELU;
+ else if (act_mode == ACTIVATION_LEAKY)
+ return LAYER_ACTIVATION_LEAKY;
+ else if (act_mode == ACTIVATION_MISH)
+ return LAYER_ACTIVATION_MISH;
+ else if (act_mode == ACTIVATION_LOGISTIC)
+ return LAYER_ACTIVATION_LOGISTIC;
+ else
+ return LAYER_ACTIVATION;
+ };
virtual dnnType* infer(dataDim_t &dim, dnnType* srcData);
@@ -159,26 +251,35 @@ protected:
/**
Convolutional 2D layer
+
+ WEIGHTS shape: OUTCH, INCH, KH, KW ...
+ BIAS shape: OUTCH
+
+ with BATCHNORM:
+ scales: OUTCH
+ means: OUTCH
+ variance: OUTCH
*/
class Conv2d : public LayerWgs {
public:
Conv2d( Network *net, int out_ch, int kernelH, int kernelW,
int strideH, int strideW, int paddingH, int paddingW,
- std::string fname_weights, bool batchnorm = false, bool deConv = false, bool final = false);
+ std::string fname_weights, bool batchnorm = false, bool deConv = false, int groups = 1, bool additional_bias=false);
virtual ~Conv2d();
virtual layerType_t getLayerType() { return LAYER_CONV2D; };
virtual dnnType* infer(dataDim_t &dim, dnnType* srcData);
int kernelH, kernelW, strideH, strideW, paddingH, paddingW;
- bool deConv;
+ bool deConv, additional_bias;
+ int groups;
protected:
cudnnFilterDescriptor_t filterDesc;
cudnnConvolutionDescriptor_t convDesc;
- cudnnConvolutionFwdAlgo_t algo;
- cudnnConvolutionBwdDataAlgo_t bwAlgo;
+ cudnnConvolutionFwdAlgoPerf_t algo;
+ cudnnConvolutionBwdDataAlgoPerf_t bwAlgo;
cudnnTensorDescriptor_t biasTensorDesc;
void initCUDNN(bool back = false);
@@ -187,6 +288,71 @@ protected:
size_t ws_sizeInBytes;
};
+/**
+ Bidirectional LSTM layer
+ ONLY BIDIRECTIONAL (TODO: more configurable)
+ currently implemented as 2 inferences: forward and backward (TODO: only 1 cudnn inference)
+
+ implementation info:
+ https://github.com/jiangnanhugo/seq2seq_cuda/blob/e4dbdcfa0517c972bfd4beea9f11a5233954093c/src/rnn.cpp
+ https://github.com/Jeffery-Song/mxnet-test/blob/aab666faad44011f7a67b527b5f6c960367d0422/src/operator/cudnn_rnn-inl.h
+ https://stackoverflow.com/a/38737941
+ https://colah.github.io/posts/2015-08-Understanding-LSTMs/
+
+ PARAMS (numlayers*2):
+ layer0:
+ ( INCH, ? ) ???
+ ( HIDDEN, ? ) ???
+ ( HIDDEN * 8 ) ???
+ layer2:
+ ( INCH, ? ) ???
+ ( HIDDEN, ? ) ???
+ ( HIDDEN * 8 ) ???
+
+ OUTPUT shape:
+ (N, C, 1, W) ---> LSTM(HIDDEN, returnSeq=True) ---> (N, 2*HIDDEN, 1, W) # W is seqLength
+ (N, C, 1, W) ---> LSTM(HIDDEN, returnSeq=False) ---> (N, 2*HIDDEN, 1, 1)
+*/
+class LSTM : public Layer {
+
+public:
+ LSTM(Network *net, int hiddensize, bool returnSeq, std::string fname_weights);
+ virtual ~LSTM();
+ virtual layerType_t getLayerType() { return LAYER_LSTM; };
+
+ virtual dnnType* infer(dataDim_t &dim, dnnType* srcData);
+
+ const bool bidirectional = true; /**> is the net bidir */
+ bool returnSeq = false; /**> if false return only the result of last timestamp */
+ int stateSize = 0; /**> number of hidden states */
+ int seqLen = 0; /**> number of timestamp */
+ int numLayers = 1; /**> number of internal layers */
+
+protected:
+ cudnnRNNDescriptor_t rnnDesc;
+ cudnnDropoutDescriptor_t dropoutDesc;
+ dnnType *dropout_states_, *work_space_;
+
+ size_t workspace_byte_, dropout_byte_;
+ int workspace_size_, dropout_size_;
+
+ std::vector x_desc_vec_, y_desc_vec_;
+ cudnnTensorDescriptor_t hx_desc_, cx_desc_;
+ cudnnTensorDescriptor_t hy_desc_, cy_desc_;
+ dnnType *hx_ptr, *cx_ptr, *hy_ptr, *cy_ptr;
+ int stateDataDim;
+
+ cudnnFilterDescriptor_t w_desc_;
+ dnnType *w_ptr;
+ dnnType *w_h;
+ dnnType *wf_ptr, *wb_ptr; // params pointer forward and backward layer
+
+ // used during inference
+ dataDim_t one_output_dim; // output dim of as single inference
+ dnnType *srcF, *srcB; // input of single inference
+ dnnType *dstF, *dstB_NR, *dstB; // output of single inference, dstB_NR = dstB not reversed
+};
+
/**
Convolutional 2D layer
@@ -196,8 +362,8 @@ class DeConv2d : public Conv2d {
public:
DeConv2d( Network *net, int out_ch, int kernelH, int kernelW,
int strideH, int strideW, int paddingH, int paddingW,
- std::string fname_weights, bool batchnorm = false) :
- Conv2d(net, out_ch, kernelH, kernelW, strideH, strideW, paddingH, paddingW, fname_weights, batchnorm, true) {}
+ std::string fname_weights, bool batchnorm = false, int groups = 1) :
+ Conv2d(net, out_ch, kernelH, kernelW, strideH, strideW, paddingH, paddingW, fname_weights, batchnorm, true, groups) {}
virtual ~DeConv2d() {}
virtual layerType_t getLayerType() { return LAYER_DECONV2D; };
@@ -206,7 +372,7 @@ public:
/**
- Deformable Convolutionl 2d layer
+ Deformable Convolutional 2d layer
*/
class DeformConv2d : public LayerWgs {
@@ -228,6 +394,9 @@ public:
dnnType *offset, *mask;
dnnType *output_conv;
+ cublasStatus_t stat;
+ cublasHandle_t handle;
+
protected:
cudnnTensorDescriptor_t biasTensorDesc;
@@ -249,6 +418,20 @@ public:
virtual dnnType* infer(dataDim_t &dim, dnnType* srcData);
};
+/**
+ Reshape layer
+*/
+class Reshape : public Layer {
+
+public:
+ Reshape(Network *net, dataDim_t new_dim);
+ virtual ~Reshape();
+ virtual layerType_t getLayerType() { return LAYER_RESHAPE; };
+
+ virtual dnnType* infer(dataDim_t &dim, dnnType* srcData);
+
+};
+
/**
MulAdd layer
@@ -271,17 +454,18 @@ protected:
/**
- Avaible pooling functions (padding on tkDNN is not supported)
+ Available pooling functions (padding on tkDNN is not supported)
*/
typedef enum {
POOLING_MAX = 0,
- POOLING_AVERAGE = 1, // count for average includes padded values
- POOLING_AVERAGE_EXCLUDE_PADDING = 2 // count for average does not include padded values
+ POOLING_AVERAGE = 1, // count for average includes padded values
+ POOLING_AVERAGE_EXCLUDE_PADDING = 2, // count for average does not include padded values
+ POOLING_MAX_FIXEDSIZE = 100 // max pool darknet fashion
} tkdnnPoolingMode_t;
/**
Pooling layer
- currenty supported only 2d pooing (also on 3d input)
+ currently supported only 2d pooing (also on 3d input)
*/
class Pooling : public Layer {
@@ -289,12 +473,13 @@ public:
int winH, winW;
int strideH, strideW;
int paddingH, paddingW;
+ bool size;
tkdnnPoolingMode_t pool_mode;
Pooling(Network *net, int winH, int winW,
int strideH, int strideW,
- int paddingH = 0, int paddingW = 0,
- tkdnnPoolingMode_t pool_mode = POOLING_MAX, bool final = false);
+ int paddingH, int paddingW,
+ tkdnnPoolingMode_t pool_mode);
virtual ~Pooling();
virtual layerType_t getLayerType() { return LAYER_POOLING; };
@@ -313,11 +498,13 @@ protected:
class Softmax : public Layer {
public:
- Softmax(Network *net);
+ Softmax(Network *net, const tk::dnn::dataDim_t* dim=nullptr, const cudnnSoftmaxMode_t mode=CUDNN_SOFTMAX_MODE_CHANNEL);
virtual ~Softmax();
virtual layerType_t getLayerType() { return LAYER_SOFTMAX; };
virtual dnnType* infer(dataDim_t &dim, dnnType* srcData);
+ dataDim_t dim;
+ cudnnSoftmaxMode_t mode;
};
/**
@@ -327,22 +514,24 @@ public:
class Route : public Layer {
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 layerType_t getLayerType() { return LAYER_ROUTE; };
virtual dnnType* infer(dataDim_t &dim, dnnType* srcData);
public:
- static const int MAX_INPUT_LAYERS = 16;
- Layer *layers[MAX_INPUT_LAYERS]; //ids of layers to be merged
+ static const int MAX_LAYERS = 32;
+ Layer *layers[MAX_LAYERS]; //ids of layers to be merged
int layers_n; //number of layers
+ int groups;
+ int group_id;
};
/**
Reorg layer
- Mantain same dimension but change C*H*W distribution
+ Maintains same dimension but change C*H*W distribution
*/
class Reorg : public Layer {
@@ -375,7 +564,7 @@ public:
/**
Upsample layer
- Mantain same dimension but change C*H*W distribution
+ Maintains same dimension but change C*H*W distribution
*/
class Upsample : public Layer {
@@ -394,6 +583,12 @@ struct box {
int cl;
float x, y, w, h;
float prob;
+ std::vector probs;
+
+ void print()
+ {
+ std::cout<<"x: "< classesNames;
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;
- static const int MAX_DETECTIONS = 256;
+ static const int MAX_DETECTIONS = 8192*2;
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);
};
/**
diff --git a/include/tkDNN/MobilenetDetection.h b/include/tkDNN/MobilenetDetection.h
new file mode 100644
index 0000000..9a5fedc
--- /dev/null
+++ b/include/tkDNN/MobilenetDetection.h
@@ -0,0 +1,77 @@
+#ifndef MOBILENETDETECTION_H
+#define MOBILENETDETECTION_H
+
+#include
+#include "opencv2/opencv.hpp"
+
+#include "DetectionNN.h"
+
+#define N_COORDS 4
+#define N_SSDSPEC 6
+
+namespace tk { namespace dnn {
+
+struct SSDSpec
+{
+ int featureSize = 0;
+ int shrinkage = 0;
+ int boxWidth = 0;
+ int boxHeight = 0;
+ int ratio1 = 0;
+ int ratio2 = 0;
+
+ SSDSpec() {}
+ SSDSpec(int feature_size, int shrinkage, int box_width, int box_height, int ratio1, int ratio2) :
+ featureSize(feature_size), shrinkage(shrinkage), boxWidth(box_width),
+ boxHeight(box_height), ratio1(ratio1), ratio2(ratio2) {}
+ void setAll(int feature_size, int shrinkage, int box_width, int box_height, int ratio1, int ratio2)
+ {
+ this->featureSize = feature_size;
+ this->shrinkage = shrinkage;
+ this->boxWidth = box_width;
+ this->boxHeight = box_height;
+ this->ratio1 = ratio1;
+ this->ratio2 = ratio2;
+ }
+ void print()
+ {
+ std::cout << "fsize: " << featureSize << "\tshrinkage: " << shrinkage <<
+ "\t box W:" << boxWidth << "\tbox H: " << boxHeight <<
+ "\t x ratio:" << ratio1 << "\t y ratio:" << ratio2 << std::endl;
+ }
+};
+
+class MobilenetDetection : public DetectionNN
+{
+private:
+ float IoUThreshold = 0.45;
+ float centerVariance = 0.1;
+ float sizeVariance = 0.2;
+ int imageSize;
+
+ float *priors = nullptr;
+ int nPriors = 0;
+ float *locations_h, *confidences_h;
+
+
+
+ void generate_ssd_priors(const SSDSpec *specs, const int n_specs, bool clamp = true);
+ void convert_locatios_to_boxes_and_center();
+ float iou(const tk::dnn::box &a, const tk::dnn::box &b);
+
+
+
+public:
+ MobilenetDetection() {};
+ ~MobilenetDetection() {};
+
+ 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 postprocess(const int bi=0,const bool mAP=false);
+};
+
+
+} // namespace dnn
+} // namespace tk
+
+#endif /*MOBILENETDETECTION_H*/
\ No newline at end of file
diff --git a/include/tkDNN/Network.h b/include/tkDNN/Network.h
index b234f71..b78acff 100644
--- a/include/tkDNN/Network.h
+++ b/include/tkDNN/Network.h
@@ -1,17 +1,18 @@
#ifndef NETWORK_H
#define NETWORK_H
+#include
#include "utils.h"
namespace tk { namespace dnn {
/**
- Data rapresentation beetween layers
+ Data representation between layers
n = batch size
c = channels
- h = heigth (lines)
+ h = height (lines)
w = width (rows)
- l = lenght (3rd dimension)
+ l = length (3rd dimension)
*/
struct dataDim_t {
@@ -39,14 +40,16 @@ class Network {
public:
Network(dataDim_t input_dim);
virtual ~Network();
+ void releaseLayers();
/**
- Do inferece for every added layer
+ Do inference for every added layer
*/
dnnType* infer(dataDim_t &dim, dnnType* data);
bool addLayer(Layer *l);
void print();
+ const char *getNetworkRTName(const char *network_name);
cudnnDataType_t dataType;
cudnnTensorFormat_t tensorFormat;
@@ -59,8 +62,14 @@ public:
dataDim_t input_dim;
dataDim_t getOutputDim();
- bool fp16, dla;
+ bool fp16, dla, int8;
+ int maxBatchSize;
bool dontLoadWeights;
+ std::string fileImgList;
+ std::string fileLabelList;
+ std::string networkName;
+ std::string networkNameRT;
+
};
}}
diff --git a/include/tkDNN/NetworkRT.h b/include/tkDNN/NetworkRT.h
index 82d082a..29cacf5 100644
--- a/include/tkDNN/NetworkRT.h
+++ b/include/tkDNN/NetworkRT.h
@@ -6,6 +6,7 @@
#include "Network.h"
#include "Layer.h"
#include "NvInfer.h"
+#include
namespace tk { namespace dnn {
@@ -24,15 +25,20 @@ template T readBUF(const char*& buffer)
using namespace nvinfer1;
#include "pluginsRT/ActivationLeakyRT.h"
+#include "pluginsRT/ActivationLogisticRT.h"
+#include "pluginsRT/ActivationReLUCeilingRT.h"
+#include "pluginsRT/ActivationMishRT.h"
#include "pluginsRT/ReorgRT.h"
#include "pluginsRT/RegionRT.h"
-//#include "pluginsRT/RouteRT.h"
+#include "pluginsRT/RouteRT.h"
#include "pluginsRT/ShortcutRT.h"
#include "pluginsRT/YoloRT.h"
#include "pluginsRT/UpsampleRT.h"
#include "pluginsRT/ResizeLayerRT.h"
-//#include "pluginsRT/Int8Calibrator.h"
#include "pluginsRT/DeformableConvRT.h"
+#include "pluginsRT/FlattenConcatRT.h"
+#include "pluginsRT/ReshapeRT.h"
+#include "pluginsRT/MaxPoolingFixedSizeRT.h"
class PluginFactory : IPluginFactory
{
@@ -52,12 +58,16 @@ public:
nvinfer1::IBuilder *builderRT;
nvinfer1::IRuntime *runtimeRT;
nvinfer1::INetworkDefinition *networkRT;
+#if NV_TENSORRT_MAJOR >= 6
+ nvinfer1::IBuilderConfig *configRT;
+#endif
nvinfer1::ICudaEngine *engineRT;
nvinfer1::IExecutionContext *contextRT;
const static int MAX_BUFFERS_RT = 10;
void* buffersRT[MAX_BUFFERS_RT];
+ dataDim_t buffersDIM[MAX_BUFFERS_RT];
int buf_input_idx, buf_output_idx;
dataDim_t input_dim, output_dim;
@@ -69,11 +79,25 @@ public:
NetworkRT(Network *net, const char *name);
virtual ~NetworkRT();
+ int getMaxBatchSize() {
+ if(engineRT != nullptr)
+ return engineRT->getMaxBatchSize();
+ else
+ return 0;
+ }
+
+ int getBuffersN() {
+ if(engineRT != nullptr)
+ return engineRT->getNbBindings();
+ else
+ return 0;
+ }
+
/**
- Do inferece
+ Do inference
*/
dnnType* infer(dataDim_t &dim, dnnType* data);
- void enqueue();
+ void enqueue(int batchSize = 1);
nvinfer1::ILayer* convert_layer(nvinfer1::ITensor *input, Layer *l);
nvinfer1::ILayer* convert_layer(nvinfer1::ITensor *input, Conv2d *l);
@@ -82,6 +106,8 @@ public:
nvinfer1::ILayer* convert_layer(nvinfer1::ITensor *input, Pooling *l);
nvinfer1::ILayer* convert_layer(nvinfer1::ITensor *input, Softmax *l);
nvinfer1::ILayer* convert_layer(nvinfer1::ITensor *input, Route *l);
+ nvinfer1::ILayer* convert_layer(nvinfer1::ITensor *input, Flatten *l);
+ nvinfer1::ILayer* convert_layer(nvinfer1::ITensor *input, Reshape *l);
nvinfer1::ILayer* convert_layer(nvinfer1::ITensor *input, Reorg *l);
nvinfer1::ILayer* convert_layer(nvinfer1::ITensor *input, Region *l);
nvinfer1::ILayer* convert_layer(nvinfer1::ITensor *input, Shortcut *l);
@@ -91,6 +117,9 @@ public:
bool serialize(const char *filename);
bool deserialize(const char *filename);
+
+
+
};
}}
diff --git a/include/tkDNN/NetworkViz.h b/include/tkDNN/NetworkViz.h
new file mode 100644
index 0000000..c8b1bea
--- /dev/null
+++ b/include/tkDNN/NetworkViz.h
@@ -0,0 +1,12 @@
+#pragma once
+#include
+#include
+#include "tkdnn.h"
+
+namespace tk { namespace dnn {
+
+cv::Mat vizFloat2colorMap(cv::Mat map);
+cv::Mat vizData2Mat(dnnType *dataInput, tk::dnn::dataDim_t dim, int imgdim);
+cv::Mat vizLayer2Mat(tk::dnn::Network *net, int layer, int imgdim = 1000);
+
+}}
diff --git a/include/tkDNN/Yolo3Detection.h b/include/tkDNN/Yolo3Detection.h
index 6c873bc..100a720 100644
--- a/include/tkDNN/Yolo3Detection.h
+++ b/include/tkDNN/Yolo3Detection.h
@@ -1,65 +1,36 @@
-#include
-#include
-#include /* srand, rand */
-#include
-#include
-#include "utils.h"
+#ifndef Yolo3Detection_H
+#define Yolo3Detection_H
+#include
+#include "opencv2/opencv.hpp"
-#include
-#include
-#include
+#include "DetectionNN.h"
-#include "tkdnn.h"
+namespace tk { namespace dnn {
-namespace tk { namespace dnn {
+class Yolo3Detection : public DetectionNN
+{
+private:
+ int num = 0;
+ int nMasks = 0;
+ int nDets = 0;
+ tk::dnn::Yolo::detection *dets = nullptr;
+ tk::dnn::Yolo* yolo[3];
-/**
- *
- * @author Francesco Gatti
- */
-class Yolo3Detection {
+ tk::dnn::Yolo* getYoloLayer(int n=0);
- private:
- tk::dnn::NetworkRT *netRT = nullptr;
- tk::dnn::Yolo* yolo[3];
- dnnType *input, *input_d;
-
- int ndets = 0;
- tk::dnn::Yolo::detection *dets = nullptr;
-
- cv::Mat imageF;
- cv::Mat bgr[3];
-
- public:
- int classes = 0;
- int num = 0;
- int n_masks = 0;
- float thresh = 0.3;
- cv::Scalar colors[256];
-
- // this is filled with results
- std::vector detected;
-
- Yolo3Detection() {}
-
- virtual ~Yolo3Detection() {}
-
- /**
- * Method used for inizialize the class
- *
- * @return Success of the initialization
- */
- bool init(std::string tensor_path);
-
- void update(cv::Mat &frame);
-
- tk::dnn::Yolo* getYoloLayer(int n=0) {
- if(n<3)
- return yolo[n];
- else
- return nullptr;
- }
+ cv::Mat bgr_h;
+
+public:
+ Yolo3Detection() {};
+ ~Yolo3Detection() {};
+ 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 postprocess(const int bi=0,const bool mAP=false);
};
-}}
+
+} // namespace dnn
+} // namespace tk
+
+#endif /* Yolo3Detection_H*/
diff --git a/include/tkDNN/baggageDetect.hpp b/include/tkDNN/baggageDetect.hpp
new file mode 100644
index 0000000..5a92d3b
--- /dev/null
+++ b/include/tkDNN/baggageDetect.hpp
@@ -0,0 +1,59 @@
+
+#ifdef OS_WIN
+ #pragma once
+
+ #ifdef LIB_EXPORTS
+ #define LIB_API __declspec(dllexport)
+ #else
+ #define LIB_API __declspec(dllimport)
+ #endif
+#endif
+
+#include
+
+
+#include
+#include
+
+
+#ifdef OPENCV
+#include
+#include
+using namespace cv;
+#endif
+
+
+using namespace std;
+
+struct baggagedetector {
+ int x,y,w,h,size;
+ char *label;
+ float prob;
+};
+
+#ifdef __cplusplus
+class baggageAI
+{
+ //std::shared_ptr detector_gpu_ptr;
+ public:
+ //static LIB_API image_t image_load(std::string image_filename);
+ #ifdef OS_WIN
+ LIB_API baggageAI();
+ //LIB_API ~baggageAI();
+ LIB_API baggagedetector * baggageDetections(char *input);
+ LIB_API baggagedetector * baggageDetections(unsigned char *input, int len, int antiLog, int gray);
+ #ifdef OPENCV
+ LIB_API baggagedetector * baggageDetections(Mat m);
+ #endif
+ #else
+ baggageAI();
+ //LIB_API ~baggageAI();
+ baggagedetector * baggageDetections(char *input);
+ baggagedetector * baggageDetections(unsigned char *input, int len,int antiLog, int gray);
+ #ifdef OPENCV
+ baggagedetector * baggageDetections(Mat m);
+ #endif
+ #endif
+};
+
+#endif
diff --git a/include/tkDNN/darknet.h b/include/tkDNN/darknet.h
new file mode 100644
index 0000000..fb97cdf
--- /dev/null
+++ b/include/tkDNN/darknet.h
@@ -0,0 +1,1032 @@
+#ifndef DARKNET_API
+#define DARKNET_API
+
+#if defined(_MSC_VER) && _MSC_VER < 1900
+#define inline __inline
+#endif
+
+#if defined(DEBUG) && !defined(_CRTDBG_MAP_ALLOC)
+#define _CRTDBG_MAP_ALLOC
+#endif
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#ifndef LIB_API
+#ifdef LIB_EXPORTS
+#if defined(_MSC_VER)
+#define LIB_API __declspec(dllexport)
+#else
+#define LIB_API __attribute__((visibility("default")))
+#endif
+#else
+#if defined(_MSC_VER)
+#define LIB_API
+#else
+#define LIB_API
+#endif
+#endif
+#endif
+
+#define SECRET_NUM -1234
+
+typedef enum { UNUSED_DEF_VAL } UNUSED_ENUM_TYPE;
+
+#ifdef GPU
+
+#include
+#include
+#include
+
+#ifdef CUDNN
+#include
+#endif // CUDNN
+#endif // GPU
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct network;
+typedef struct network network;
+
+struct network_state;
+typedef struct network_state network_state;
+
+struct layer;
+typedef struct layer layer;
+
+struct image;
+typedef struct image image;
+
+struct detection;
+typedef struct detection detection;
+
+struct load_args;
+typedef struct load_args load_args;
+
+struct data;
+typedef struct data data;
+
+struct metadata;
+typedef struct metadata metadata;
+
+struct tree;
+typedef struct tree tree;
+
+extern int gpu_index;
+
+// option_list.h
+typedef struct metadata {
+ int classes;
+ char **names;
+} metadata;
+
+
+// tree.h
+typedef struct tree {
+ int *leaf;
+ int n;
+ int *parent;
+ int *child;
+ int *group;
+ char **name;
+
+ int groups;
+ int *group_size;
+ int *group_offset;
+} tree;
+
+
+// activations.h
+typedef enum {
+ LOGISTIC, RELU, RELU6, RELIE, LINEAR, RAMP, TANH, PLSE, LEAKY, ELU, LOGGY, STAIR, HARDTAN, LHTAN, SELU, GELU, SWISH, MISH, NORM_CHAN, NORM_CHAN_SOFTMAX, NORM_CHAN_SOFTMAX_MAXVAL
+}ACTIVATION;
+
+// parser.h
+typedef enum {
+ IOU, GIOU, MSE, DIOU, CIOU
+} IOU_LOSS;
+
+// parser.h
+typedef enum {
+ DEFAULT_NMS, GREEDY_NMS, DIOU_NMS, CORNERS_NMS
+} NMS_KIND;
+
+// parser.h
+typedef enum {
+ YOLO_CENTER = 1 << 0, YOLO_LEFT_TOP = 1 << 1, YOLO_RIGHT_BOTTOM = 1 << 2
+} YOLO_POINT;
+
+// parser.h
+typedef enum {
+ NO_WEIGHTS, PER_FEATURE, PER_CHANNEL
+} WEIGHTS_TYPE_T;
+
+// parser.h
+typedef enum {
+ NO_NORMALIZATION, RELU_NORMALIZATION, SOFTMAX_NORMALIZATION
+} WEIGHTS_NORMALIZATION_T;
+
+// image.h
+typedef enum{
+ PNG, BMP, TGA, JPG
+} IMTYPE;
+
+// activations.h
+typedef enum{
+ MULT, ADD, SUB, DIV
+} BINARY_ACTIVATION;
+
+// layer.h
+typedef enum {
+ CONVOLUTIONAL,
+ DECONVOLUTIONAL,
+ CONNECTED,
+ MAXPOOL,
+ LOCAL_AVGPOOL,
+ SOFTMAX,
+ DETECTION,
+ DROPOUT,
+ CROP,
+ ROUTE,
+ COST,
+ NORMALIZATION,
+ AVGPOOL,
+ LOCAL,
+ SHORTCUT,
+ SCALE_CHANNELS,
+ SAM,
+ ACTIVE,
+ RNN,
+ GRU,
+ LSTM,
+ CONV_LSTM,
+ CRNN,
+ BATCHNORM,
+ NETWORK,
+ XNOR,
+ REGION,
+ YOLO,
+ GAUSSIAN_YOLO,
+ ISEG,
+ REORG,
+ REORG_OLD,
+ UPSAMPLE,
+ LOGXENT,
+ L2NORM,
+ EMPTY,
+ BLANK
+} LAYER_TYPE;
+
+// layer.h
+typedef enum{
+ SSE, MASKED, L1, SEG, SMOOTH,WGAN
+} COST_TYPE;
+
+// layer.h
+typedef struct update_args {
+ int batch;
+ float learning_rate;
+ float momentum;
+ float decay;
+ int adam;
+ float B1;
+ float B2;
+ float eps;
+ int t;
+} update_args;
+
+// layer.h
+struct layer {
+ LAYER_TYPE type;
+ ACTIVATION activation;
+ COST_TYPE cost_type;
+ void(*forward) (struct layer, struct network_state);
+ void(*backward) (struct layer, struct network_state);
+ void(*update) (struct layer, int, float, float, float);
+ void(*forward_gpu) (struct layer, struct network_state);
+ void(*backward_gpu) (struct layer, struct network_state);
+ void(*update_gpu) (struct layer, int, float, float, float, float);
+ layer *share_layer;
+ int train;
+ int avgpool;
+ int batch_normalize;
+ int shortcut;
+ int batch;
+ int dynamic_minibatch;
+ int forced;
+ int flipped;
+ int inputs;
+ int outputs;
+ float mean_alpha;
+ int nweights;
+ int nbiases;
+ int extra;
+ int truths;
+ int h, w, c;
+ int out_h, out_w, out_c;
+ int n;
+ int max_boxes;
+ int groups;
+ int group_id;
+ int size;
+ int side;
+ int stride;
+ int stride_x;
+ int stride_y;
+ int dilation;
+ int antialiasing;
+ int maxpool_depth;
+ int out_channels;
+ int reverse;
+ int flatten;
+ int spatial;
+ int pad;
+ int sqrt;
+ int flip;
+ int index;
+ int scale_wh;
+ int binary;
+ int xnor;
+ int peephole;
+ int use_bin_output;
+ int keep_delta_gpu;
+ int optimized_memory;
+ int steps;
+ int state_constrain;
+ int hidden;
+ int truth;
+ float smooth;
+ float dot;
+ int deform;
+ int sway;
+ int rotate;
+ int stretch;
+ int stretch_sway;
+ float angle;
+ float jitter;
+ float saturation;
+ float exposure;
+ float shift;
+ float ratio;
+ float learning_rate_scale;
+ float clip;
+ int focal_loss;
+ float *classes_multipliers;
+ float label_smooth_eps;
+ int noloss;
+ int softmax;
+ int classes;
+ int coords;
+ int background;
+ int rescore;
+ int objectness;
+ int does_cost;
+ int joint;
+ int noadjust;
+ int reorg;
+ int log;
+ int tanh;
+ int *mask;
+ int total;
+ float bflops;
+
+ int adam;
+ float B1;
+ float B2;
+ float eps;
+
+ int t;
+
+ float alpha;
+ float beta;
+ float kappa;
+
+ float coord_scale;
+ float object_scale;
+ float noobject_scale;
+ float mask_scale;
+ float class_scale;
+ int bias_match;
+ float random;
+ float ignore_thresh;
+ float truth_thresh;
+ float iou_thresh;
+ float thresh;
+ float focus;
+ int classfix;
+ int absolute;
+ int assisted_excitation;
+
+ int onlyforward;
+ int stopbackward;
+ int train_only_bn;
+ int dont_update;
+ int burnin_update;
+ int dontload;
+ int dontsave;
+ int dontloadscales;
+ int numload;
+
+ float temperature;
+ float probability;
+ float dropblock_size_rel;
+ int dropblock_size_abs;
+ int dropblock;
+ float scale;
+
+ int receptive_w;
+ int receptive_h;
+ int receptive_w_scale;
+ int receptive_h_scale;
+
+ char * cweights;
+ int * indexes;
+ int * input_layers;
+ int * input_sizes;
+ float **layers_output;
+ float **layers_delta;
+ WEIGHTS_TYPE_T weights_type;
+ WEIGHTS_NORMALIZATION_T weights_normalization;
+ int * map;
+ int * counts;
+ float ** sums;
+ float * rand;
+ float * cost;
+ float * state;
+ float * prev_state;
+ float * forgot_state;
+ float * forgot_delta;
+ float * state_delta;
+ float * combine_cpu;
+ float * combine_delta_cpu;
+
+ float *concat;
+ float *concat_delta;
+
+ float *binary_weights;
+
+ float *biases;
+ float *bias_updates;
+
+ float *scales;
+ float *scale_updates;
+
+ float *weights;
+ float *weight_updates;
+
+ float scale_x_y;
+ int objectness_smooth;
+ float max_delta;
+ float uc_normalizer;
+ float iou_normalizer;
+ float cls_normalizer;
+ IOU_LOSS iou_loss;
+ IOU_LOSS iou_thresh_kind;
+ NMS_KIND nms_kind;
+ float beta_nms;
+ YOLO_POINT yolo_point;
+
+ char *align_bit_weights_gpu;
+ float *mean_arr_gpu;
+ float *align_workspace_gpu;
+ float *transposed_align_workspace_gpu;
+ int align_workspace_size;
+
+ char *align_bit_weights;
+ float *mean_arr;
+ int align_bit_weights_size;
+ int lda_align;
+ int new_lda;
+ int bit_align;
+
+ float *col_image;
+ float * delta;
+ float * output;
+ float * activation_input;
+ int delta_pinned;
+ int output_pinned;
+ float * loss;
+ float * squared;
+ float * norms;
+
+ float * spatial_mean;
+ float * mean;
+ float * variance;
+
+ float * mean_delta;
+ float * variance_delta;
+
+ float * rolling_mean;
+ float * rolling_variance;
+
+ float * x;
+ float * x_norm;
+
+ float * m;
+ float * v;
+
+ float * bias_m;
+ float * bias_v;
+ float * scale_m;
+ float * scale_v;
+
+
+ float *z_cpu;
+ float *r_cpu;
+ float *h_cpu;
+ float *stored_h_cpu;
+ float * prev_state_cpu;
+
+ float *temp_cpu;
+ float *temp2_cpu;
+ float *temp3_cpu;
+
+ float *dh_cpu;
+ float *hh_cpu;
+ float *prev_cell_cpu;
+ float *cell_cpu;
+ float *f_cpu;
+ float *i_cpu;
+ float *g_cpu;
+ float *o_cpu;
+ float *c_cpu;
+ float *stored_c_cpu;
+ float *dc_cpu;
+
+ float *binary_input;
+ uint32_t *bin_re_packed_input;
+ char *t_bit_input;
+
+ struct layer *input_layer;
+ struct layer *self_layer;
+ struct layer *output_layer;
+
+ struct layer *reset_layer;
+ struct layer *update_layer;
+ struct layer *state_layer;
+
+ struct layer *input_gate_layer;
+ struct layer *state_gate_layer;
+ struct layer *input_save_layer;
+ struct layer *state_save_layer;
+ struct layer *input_state_layer;
+ struct layer *state_state_layer;
+
+ struct layer *input_z_layer;
+ struct layer *state_z_layer;
+
+ struct layer *input_r_layer;
+ struct layer *state_r_layer;
+
+ struct layer *input_h_layer;
+ struct layer *state_h_layer;
+
+ struct layer *wz;
+ struct layer *uz;
+ struct layer *wr;
+ struct layer *ur;
+ struct layer *wh;
+ struct layer *uh;
+ struct layer *uo;
+ struct layer *wo;
+ struct layer *vo;
+ struct layer *uf;
+ struct layer *wf;
+ struct layer *vf;
+ struct layer *ui;
+ struct layer *wi;
+ struct layer *vi;
+ struct layer *ug;
+ struct layer *wg;
+
+ tree *softmax_tree;
+
+ size_t workspace_size;
+
+//#ifdef GPU
+ int *indexes_gpu;
+
+ float *z_gpu;
+ float *r_gpu;
+ float *h_gpu;
+ float *stored_h_gpu;
+
+ float *temp_gpu;
+ float *temp2_gpu;
+ float *temp3_gpu;
+
+ float *dh_gpu;
+ float *hh_gpu;
+ float *prev_cell_gpu;
+ float *prev_state_gpu;
+ float *last_prev_state_gpu;
+ float *last_prev_cell_gpu;
+ float *cell_gpu;
+ float *f_gpu;
+ float *i_gpu;
+ float *g_gpu;
+ float *o_gpu;
+ float *c_gpu;
+ float *stored_c_gpu;
+ float *dc_gpu;
+
+ // adam
+ float *m_gpu;
+ float *v_gpu;
+ float *bias_m_gpu;
+ float *scale_m_gpu;
+ float *bias_v_gpu;
+ float *scale_v_gpu;
+
+ float * combine_gpu;
+ float * combine_delta_gpu;
+
+ float * forgot_state_gpu;
+ float * forgot_delta_gpu;
+ float * state_gpu;
+ float * state_delta_gpu;
+ float * gate_gpu;
+ float * gate_delta_gpu;
+ float * save_gpu;
+ float * save_delta_gpu;
+ float * concat_gpu;
+ float * concat_delta_gpu;
+
+ float *binary_input_gpu;
+ float *binary_weights_gpu;
+ float *bin_conv_shortcut_in_gpu;
+ float *bin_conv_shortcut_out_gpu;
+
+ float * mean_gpu;
+ float * variance_gpu;
+ float * m_cbn_avg_gpu;
+ float * v_cbn_avg_gpu;
+
+ float * rolling_mean_gpu;
+ float * rolling_variance_gpu;
+
+ float * variance_delta_gpu;
+ float * mean_delta_gpu;
+
+ float * col_image_gpu;
+
+ float * x_gpu;
+ float * x_norm_gpu;
+ float * weights_gpu;
+ float * weight_updates_gpu;
+ float * weight_deform_gpu;
+ float * weight_change_gpu;
+
+ float * weights_gpu16;
+ float * weight_updates_gpu16;
+
+ float * biases_gpu;
+ float * bias_updates_gpu;
+ float * bias_change_gpu;
+
+ float * scales_gpu;
+ float * scale_updates_gpu;
+ float * scale_change_gpu;
+
+ float * input_antialiasing_gpu;
+ float * output_gpu;
+ float * output_avg_gpu;
+ float * activation_input_gpu;
+ float * loss_gpu;
+ float * delta_gpu;
+ float * rand_gpu;
+ float * drop_blocks_scale;
+ float * drop_blocks_scale_gpu;
+ float * squared_gpu;
+ float * norms_gpu;
+
+ float *gt_gpu;
+ float *a_avg_gpu;
+
+ int *input_sizes_gpu;
+ float **layers_output_gpu;
+ float **layers_delta_gpu;
+#ifdef CUDNN
+ cudnnTensorDescriptor_t srcTensorDesc, dstTensorDesc;
+ cudnnTensorDescriptor_t srcTensorDesc16, dstTensorDesc16;
+ cudnnTensorDescriptor_t dsrcTensorDesc, ddstTensorDesc;
+ cudnnTensorDescriptor_t dsrcTensorDesc16, ddstTensorDesc16;
+ cudnnTensorDescriptor_t normTensorDesc, normDstTensorDesc, normDstTensorDescF16;
+ cudnnFilterDescriptor_t weightDesc, weightDesc16;
+ cudnnFilterDescriptor_t dweightDesc, dweightDesc16;
+ cudnnConvolutionDescriptor_t convDesc;
+ cudnnConvolutionFwdAlgo_t fw_algo, fw_algo16;
+ cudnnConvolutionBwdDataAlgo_t bd_algo, bd_algo16;
+ cudnnConvolutionBwdFilterAlgo_t bf_algo, bf_algo16;
+ cudnnPoolingDescriptor_t poolingDesc;
+#else // CUDNN
+ void* srcTensorDesc, *dstTensorDesc;
+ void* srcTensorDesc16, *dstTensorDesc16;
+ void* dsrcTensorDesc, *ddstTensorDesc;
+ void* dsrcTensorDesc16, *ddstTensorDesc16;
+ void* normTensorDesc, *normDstTensorDesc, *normDstTensorDescF16;
+ void* weightDesc, *weightDesc16;
+ void* dweightDesc, *dweightDesc16;
+ void* convDesc;
+ UNUSED_ENUM_TYPE fw_algo, fw_algo16;
+ UNUSED_ENUM_TYPE bd_algo, bd_algo16;
+ UNUSED_ENUM_TYPE bf_algo, bf_algo16;
+ void* poolingDesc;
+#endif // CUDNN
+//#endif // GPU
+};
+
+
+// network.h
+typedef enum {
+ CONSTANT, STEP, EXP, POLY, STEPS, SIG, RANDOM, SGDR
+} learning_rate_policy;
+
+// network.h
+typedef struct network {
+ int n;
+ int batch;
+ uint64_t *seen;
+ int *cur_iteration;
+ float loss_scale;
+ int *t;
+ float epoch;
+ int subdivisions;
+ layer *layers;
+ float *output;
+ learning_rate_policy policy;
+ int benchmark_layers;
+
+ float learning_rate;
+ float learning_rate_min;
+ float learning_rate_max;
+ int batches_per_cycle;
+ int batches_cycle_mult;
+ float momentum;
+ float decay;
+ float gamma;
+ float scale;
+ float power;
+ int time_steps;
+ int step;
+ int max_batches;
+ int num_boxes;
+ int train_images_num;
+ float *seq_scales;
+ float *scales;
+ int *steps;
+ int num_steps;
+ int burn_in;
+ int cudnn_half;
+
+ int adam;
+ float B1;
+ float B2;
+ float eps;
+
+ int inputs;
+ int outputs;
+ int truths;
+ int notruth;
+ int h, w, c;
+ int max_crop;
+ int min_crop;
+ float max_ratio;
+ float min_ratio;
+ int center;
+ int flip; // horizontal flip 50% probability augmentaiont for classifier training (default = 1)
+ int gaussian_noise;
+ int blur;
+ int mixup;
+ float label_smooth_eps;
+ int resize_step;
+ int attention;
+ int adversarial;
+ float adversarial_lr;
+ int letter_box;
+ float angle;
+ float aspect;
+ float exposure;
+ float saturation;
+ float hue;
+ int random;
+ int track;
+ int augment_speed;
+ int sequential_subdivisions;
+ int init_sequential_subdivisions;
+ int current_subdivision;
+ int try_fix_nan;
+
+ int gpu_index;
+ tree *hierarchy;
+
+ float *input;
+ float *truth;
+ float *delta;
+ float *workspace;
+ int train;
+ int index;
+ float *cost;
+ float clip;
+
+//#ifdef GPU
+ //float *input_gpu;
+ //float *truth_gpu;
+ float *delta_gpu;
+ float *output_gpu;
+
+ float *input_state_gpu;
+ float *input_pinned_cpu;
+ int input_pinned_cpu_flag;
+
+ float **input_gpu;
+ float **truth_gpu;
+ float **input16_gpu;
+ float **output16_gpu;
+ size_t *max_input16_size;
+ size_t *max_output16_size;
+ int wait_stream;
+
+ float *global_delta_gpu;
+ float *state_delta_gpu;
+ size_t max_delta_gpu_size;
+//#endif // GPU
+ int optimized_memory;
+ int dynamic_minibatch;
+ size_t workspace_size_limit;
+} network;
+
+// network.h
+typedef struct network_state {
+ float *truth;
+ float *input;
+ float *delta;
+ float *workspace;
+ int train;
+ int index;
+ network net;
+} network_state;
+
+//typedef struct {
+// int w;
+// int h;
+// float scale;
+// float rad;
+// float dx;
+// float dy;
+// float aspect;
+//} augment_args;
+
+// image.h
+typedef struct image {
+ int w;
+ int h;
+ int c;
+ float *data;
+} image;
+
+//typedef struct {
+// int w;
+// int h;
+// int c;
+// float *data;
+//} image;
+
+// box.h
+typedef struct box {
+ float x, y, w, h;
+} box;
+
+// box.h
+typedef struct boxabs {
+ float left, right, top, bot;
+} boxabs;
+
+// box.h
+typedef struct dxrep {
+ float dt, db, dl, dr;
+} dxrep;
+
+// box.h
+typedef struct ious {
+ float iou, giou, diou, ciou;
+ dxrep dx_iou;
+ dxrep dx_giou;
+} ious;
+
+
+// box.h
+typedef struct detection{
+ box bbox;
+ int classes;
+ float *prob;
+ float *mask;
+ float objectness;
+ int sort_class;
+ float *uc; // Gaussian_YOLOv3 - tx,ty,tw,th uncertainty
+ int points; // bit-0 - center, bit-1 - top-left-corner, bit-2 - bottom-right-corner
+} detection;
+
+// network.c -batch inference
+typedef struct det_num_pair {
+ int num;
+ detection *dets;
+} det_num_pair, *pdet_num_pair;
+
+// matrix.h
+typedef struct matrix {
+ int rows, cols;
+ float **vals;
+} matrix;
+
+// data.h
+typedef struct data {
+ int w, h;
+ matrix X;
+ matrix y;
+ int shallow;
+ int *num_boxes;
+ box **boxes;
+} data;
+
+// data.h
+typedef enum {
+ CLASSIFICATION_DATA, DETECTION_DATA, CAPTCHA_DATA, REGION_DATA, IMAGE_DATA, COMPARE_DATA, WRITING_DATA, SWAG_DATA, TAG_DATA, OLD_CLASSIFICATION_DATA, STUDY_DATA, DET_DATA, SUPER_DATA, LETTERBOX_DATA, REGRESSION_DATA, SEGMENTATION_DATA, INSTANCE_DATA, ISEG_DATA
+} data_type;
+
+// data.h
+typedef struct load_args {
+ int threads;
+ char **paths;
+ char *path;
+ int n;
+ int m;
+ char **labels;
+ int h;
+ int w;
+ int c; // color depth
+ int out_w;
+ int out_h;
+ int nh;
+ int nw;
+ int num_boxes;
+ int min, max, size;
+ int classes;
+ int background;
+ int scale;
+ int center;
+ int coords;
+ int mini_batch;
+ int track;
+ int augment_speed;
+ int letter_box;
+ int show_imgs;
+ int dontuse_opencv;
+ float jitter;
+ int flip;
+ int gaussian_noise;
+ int blur;
+ int mixup;
+ float label_smooth_eps;
+ float angle;
+ float aspect;
+ float saturation;
+ float exposure;
+ float hue;
+ data *d;
+ image *im;
+ image *resized;
+ data_type type;
+ tree *hierarchy;
+} load_args;
+
+// data.h
+typedef struct box_label {
+ int id;
+ float x, y, w, h;
+ float left, right, top, bottom;
+} box_label;
+
+// list.h
+//typedef struct node {
+// void *val;
+// struct node *next;
+// struct node *prev;
+//} node;
+
+// list.h
+//typedef struct list {
+// int size;
+// node *front;
+// node *back;
+//} list;
+
+// -----------------------------------------------------
+
+
+// parser.c
+LIB_API network *load_network(char *cfg, char *weights, int clear);
+LIB_API network *load_network_custom(char *cfg, char *weights, int clear, int batch);
+LIB_API network *load_network(char *cfg, char *weights, int clear);
+LIB_API void free_network(network net);
+
+// network.c
+LIB_API load_args get_base_args(network *net);
+
+// box.h
+LIB_API void do_nms_sort(detection *dets, int total, int classes, float thresh);
+LIB_API void do_nms_obj(detection *dets, int total, int classes, float thresh);
+LIB_API void diounms_sort(detection *dets, int total, int classes, float thresh, NMS_KIND nms_kind, float beta1);
+
+// network.h
+LIB_API float *network_predict(network net, float *input);
+LIB_API float *network_predict_ptr(network *net, float *input);
+LIB_API detection *get_network_boxes(network *net, int w, int h, float thresh, float hier, int *map, int relative, int *num, int letter);
+LIB_API det_num_pair* network_predict_batch(network *net, image im, int batch_size, int w, int h, float thresh, float hier, int *map, int relative, int letter);
+LIB_API void free_detections(detection *dets, int n);
+LIB_API void free_batch_detections(det_num_pair *det_num_pairs, int n);
+LIB_API void fuse_conv_batchnorm(network net);
+LIB_API void calculate_binary_weights(network net);
+LIB_API char *detection_to_json(detection *dets, int nboxes, int classes, char **names, long long int frame_id, char *filename);
+
+LIB_API layer* get_network_layer(network* net, int i);
+//LIB_API detection *get_network_boxes(network *net, int w, int h, float thresh, float hier, int *map, int relative, int *num, int letter);
+LIB_API detection *make_network_boxes(network *net, float thresh, int *num);
+LIB_API void reset_rnn(network *net);
+LIB_API float *network_predict_image(network *net, image im);
+LIB_API float *network_predict_image_letterbox(network *net, image im);
+LIB_API float validate_detector_map(char *datacfg, char *cfgfile, char *weightfile, float thresh_calc_avg_iou, const float iou_thresh, const int map_points, int letter_box, network *existing_net);
+LIB_API void train_detector(char *datacfg, char *cfgfile, char *weightfile, int *gpus, int ngpus, int clear, int dont_show, int calc_map, int mjpeg_port, int show_imgs, int benchmark_layers, char* chart_path);
+LIB_API void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filename, float thresh,
+ float hier_thresh, int dont_show, int ext_output, int save_labels, char *outfile, int letter_box, int benchmark_layers);
+LIB_API int network_width(network *net);
+LIB_API int network_height(network *net);
+LIB_API void optimize_picture(network *net, image orig, int max_layer, float scale, float rate, float thresh, int norm);
+
+// image.h
+LIB_API void make_image_red(image im);
+LIB_API image make_attention_image(int img_size, float *original_delta_cpu, float *original_input_cpu, int w, int h, int c);
+LIB_API image resize_image(image im, int w, int h);
+LIB_API void quantize_image(image im);
+LIB_API void copy_image_from_bytes(image im, char *pdata);
+LIB_API image letterbox_image(image im, int w, int h);
+LIB_API void rgbgr_image(image im);
+LIB_API image make_image(int w, int h, int c);
+LIB_API image load_image_color(char *filename, int w, int h);
+LIB_API void free_image(image m);
+LIB_API image crop_image(image im, int dx, int dy, int w, int h);
+LIB_API image resize_min(image im, int min);
+
+// layer.h
+LIB_API void free_layer_custom(layer l, int keep_cudnn_desc);
+LIB_API void free_layer(layer l);
+
+// data.c
+LIB_API void free_data(data d);
+LIB_API pthread_t load_data(load_args args);
+LIB_API void free_load_threads(void *ptr);
+LIB_API pthread_t load_data_in_thread(load_args args);
+LIB_API void *load_thread(void *ptr);
+
+// dark_cuda.h
+LIB_API void cuda_pull_array(float *x_gpu, float *x, size_t n);
+LIB_API void cuda_pull_array_async(float *x_gpu, float *x, size_t n);
+LIB_API void cuda_set_device(int n);
+LIB_API void *cuda_get_context();
+
+// utils.h
+LIB_API void free_ptrs(void **ptrs, int n);
+LIB_API void top_k(float *a, int n, int k, int *index);
+
+// tree.h
+LIB_API tree *read_tree(char *filename);
+
+// option_list.h
+LIB_API metadata get_metadata(char *file);
+
+
+// http_stream.h
+LIB_API void delete_json_sender();
+LIB_API void send_json_custom(char const* send_buf, int port, int timeout);
+LIB_API double get_time_point();
+void start_timer();
+void stop_timer();
+double get_time();
+void stop_timer_and_show();
+void stop_timer_and_show_name(char *name);
+void show_total_time();
+
+// gemm.h
+LIB_API void init_cpu();
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+#endif // DARKNET_API
+
diff --git a/include/tkDNN/dimensionless.h b/include/tkDNN/dimensionless.h
new file mode 100644
index 0000000..52eaa5e
--- /dev/null
+++ b/include/tkDNN/dimensionless.h
@@ -0,0 +1,852 @@
+#ifndef DIMENSIONLESS_API
+#define DIMENSIONLESS_API
+
+#if defined(_MSC_VER) && _MSC_VER < 1900
+#define inline __inline
+#endif
+
+#if defined(DEBUG) && !defined(_CRTDBG_MAP_ALLOC)
+#define _CRTDBG_MAP_ALLOC
+#endif
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#ifndef LIB_API
+#ifdef LIB_EXPORTS
+#if defined(_MSC_VER)
+#define LIB_API __declspec(dllexport)
+#else
+#define LIB_API __attribute__((visibility("default")))
+#endif
+#else
+#if defined(_MSC_VER)
+#define LIB_API
+#else
+#define LIB_API
+#endif
+#endif
+#endif
+
+#define SECRET_NUM -1234
+
+#ifdef GPU
+
+#include "cuda_runtime.h"
+#include "curand.h"
+#include "cublas_v2.h"
+
+#ifdef CUDNN
+#include "cudnn.h"
+#endif
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct network;
+typedef struct network network;
+
+struct network_state;
+typedef struct network_state network_state;
+
+struct layer;
+typedef struct layer layer;
+
+struct image;
+typedef struct image image;
+
+struct detection;
+typedef struct detection detection;
+
+struct load_args;
+typedef struct load_args load_args;
+
+struct data;
+typedef struct data data;
+
+struct metadata;
+typedef struct metadata metadata;
+
+struct tree;
+typedef struct tree tree;
+
+extern int gpu_index;
+
+// option_list.h
+typedef struct metadata {
+ int classes;
+ char **names;
+} metadata;
+
+
+// tree.h
+typedef struct tree {
+ int *leaf;
+ int n;
+ int *parent;
+ int *child;
+ int *group;
+ char **name;
+
+ int groups;
+ int *group_size;
+ int *group_offset;
+} tree;
+
+
+// activations.h
+typedef enum {
+ LOGISTIC, RELU, RELIE, LINEAR, RAMP, TANH, PLSE, LEAKY, ELU, LOGGY, STAIR, HARDTAN, LHTAN, SELU
+}ACTIVATION;
+
+// image.h
+typedef enum{
+ PNG, BMP, TGA, JPG
+} IMTYPE;
+
+// activations.h
+typedef enum{
+ MULT, ADD, SUB, DIV
+} BINARY_ACTIVATION;
+
+// layer.h
+typedef enum {
+ CONVOLUTIONAL,
+ DECONVOLUTIONAL,
+ CONNECTED,
+ MAXPOOL,
+ SOFTMAX,
+ DETECTION,
+ DROPOUT,
+ CROP,
+ ROUTE,
+ COST,
+ NORMALIZATION,
+ AVGPOOL,
+ LOCAL,
+ SHORTCUT,
+ ACTIVE,
+ RNN,
+ GRU,
+ LSTM,
+ CONV_LSTM,
+ CRNN,
+ BATCHNORM,
+ NETWORK,
+ XNOR,
+ REGION,
+ BAGGAGEAI,
+ ISEG,
+ REORG,
+ REORG_OLD,
+ UPSAMPLE,
+ LOGXENT,
+ L2NORM,
+ BLANK
+} LAYER_TYPE;
+
+// layer.h
+typedef enum{
+ SSE, MASKED, L1, SEG, SMOOTH,WGAN
+} COST_TYPE;
+
+// layer.h
+typedef struct update_args {
+ int batch;
+ float learning_rate;
+ float momentum;
+ float decay;
+ int adam;
+ float B1;
+ float B2;
+ float eps;
+ int t;
+} update_args;
+
+// layer.h
+struct layer {
+ LAYER_TYPE type;
+ ACTIVATION activation;
+ COST_TYPE cost_type;
+ void(*forward) (struct layer, struct network_state);
+ void(*backward) (struct layer, struct network_state);
+ void(*update) (struct layer, int, float, float, float);
+ void(*forward_gpu) (struct layer, struct network_state);
+ void(*backward_gpu) (struct layer, struct network_state);
+ void(*update_gpu) (struct layer, int, float, float, float);
+ int batch_normalize;
+ int shortcut;
+ int batch;
+ int forced;
+ int flipped;
+ int inputs;
+ int outputs;
+ int nweights;
+ int nbiases;
+ int extra;
+ int truths;
+ int h, w, c;
+ int out_h, out_w, out_c;
+ int n;
+ int max_boxes;
+ int groups;
+ int size;
+ int side;
+ int stride;
+ int reverse;
+ int flatten;
+ int spatial;
+ int pad;
+ int sqrt;
+ int flip;
+ int index;
+ int binary;
+ int xnor;
+ int peephole;
+ int use_bin_output;
+ int steps;
+ int state_constrain;
+ int hidden;
+ int truth;
+ float smooth;
+ float dot;
+ float angle;
+ float jitter;
+ float saturation;
+ float exposure;
+ float shift;
+ float ratio;
+ float learning_rate_scale;
+ float clip;
+ int focal_loss;
+ int noloss;
+ int softmax;
+ int classes;
+ int coords;
+ int background;
+ int rescore;
+ int objectness;
+ int does_cost;
+ int joint;
+ int noadjust;
+ int reorg;
+ int log;
+ int tanh;
+ int *mask;
+ int total;
+ float bflops;
+
+ int adam;
+ float B1;
+ float B2;
+ float eps;
+
+ int t;
+
+ float alpha;
+ float beta;
+ float kappa;
+
+ float coord_scale;
+ float object_scale;
+ float noobject_scale;
+ float mask_scale;
+ float class_scale;
+ int bias_match;
+ int random;
+ float ignore_thresh;
+ float truth_thresh;
+ float thresh;
+ float focus;
+ int classfix;
+ int absolute;
+
+ int onlyforward;
+ int stopbackward;
+ int dontload;
+ int dontsave;
+ int dontloadscales;
+ int numload;
+
+ float temperature;
+ float probability;
+ float scale;
+
+ char * cweights;
+ int * indexes;
+ int * input_layers;
+ int * input_sizes;
+ int * map;
+ int * counts;
+ float ** sums;
+ float * rand;
+ float * cost;
+ float * state;
+ float * prev_state;
+ float * forgot_state;
+ float * forgot_delta;
+ float * state_delta;
+ float * combine_cpu;
+ float * combine_delta_cpu;
+
+ float *concat;
+ float *concat_delta;
+
+ float *binary_weights;
+
+ float *biases;
+ float *bias_updates;
+
+ float *scales;
+ float *scale_updates;
+
+ float *weights;
+ float *weight_updates;
+
+ char *align_bit_weights_gpu;
+ float *mean_arr_gpu;
+ float *align_workspace_gpu;
+ float *transposed_align_workspace_gpu;
+ int align_workspace_size;
+
+ char *align_bit_weights;
+ float *mean_arr;
+ int align_bit_weights_size;
+ int lda_align;
+ int new_lda;
+ int bit_align;
+
+ float *col_image;
+ float * delta;
+ float * output;
+ int delta_pinned;
+ int output_pinned;
+ float * loss;
+ float * squared;
+ float * norms;
+
+ float * spatial_mean;
+ float * mean;
+ float * variance;
+
+ float * mean_delta;
+ float * variance_delta;
+
+ float * rolling_mean;
+ float * rolling_variance;
+
+ float * x;
+ float * x_norm;
+
+ float * m;
+ float * v;
+
+ float * bias_m;
+ float * bias_v;
+ float * scale_m;
+ float * scale_v;
+
+
+ float *z_cpu;
+ float *r_cpu;
+ float *h_cpu;
+ float *stored_h_cpu;
+ float * prev_state_cpu;
+
+ float *temp_cpu;
+ float *temp2_cpu;
+ float *temp3_cpu;
+
+ float *dh_cpu;
+ float *hh_cpu;
+ float *prev_cell_cpu;
+ float *cell_cpu;
+ float *f_cpu;
+ float *i_cpu;
+ float *g_cpu;
+ float *o_cpu;
+ float *c_cpu;
+ float *stored_c_cpu;
+ float *dc_cpu;
+
+ float *binary_input;
+ uint32_t *bin_re_packed_input;
+ char *t_bit_input;
+
+ struct layer *input_layer;
+ struct layer *self_layer;
+ struct layer *output_layer;
+
+ struct layer *reset_layer;
+ struct layer *update_layer;
+ struct layer *state_layer;
+
+ struct layer *input_gate_layer;
+ struct layer *state_gate_layer;
+ struct layer *input_save_layer;
+ struct layer *state_save_layer;
+ struct layer *input_state_layer;
+ struct layer *state_state_layer;
+
+ struct layer *input_z_layer;
+ struct layer *state_z_layer;
+
+ struct layer *input_r_layer;
+ struct layer *state_r_layer;
+
+ struct layer *input_h_layer;
+ struct layer *state_h_layer;
+
+ struct layer *wz;
+ struct layer *uz;
+ struct layer *wr;
+ struct layer *ur;
+ struct layer *wh;
+ struct layer *uh;
+ struct layer *uo;
+ struct layer *wo;
+ struct layer *vo;
+ struct layer *uf;
+ struct layer *wf;
+ struct layer *vf;
+ struct layer *ui;
+ struct layer *wi;
+ struct layer *vi;
+ struct layer *ug;
+ struct layer *wg;
+
+ tree *softmax_tree;
+
+ size_t workspace_size;
+
+#ifdef GPU
+ int *indexes_gpu;
+
+ float *z_gpu;
+ float *r_gpu;
+ float *h_gpu;
+ float *stored_h_gpu;
+
+ float *temp_gpu;
+ float *temp2_gpu;
+ float *temp3_gpu;
+
+ float *dh_gpu;
+ float *hh_gpu;
+ float *prev_cell_gpu;
+ float *prev_state_gpu;
+ float *last_prev_state_gpu;
+ float *last_prev_cell_gpu;
+ float *cell_gpu;
+ float *f_gpu;
+ float *i_gpu;
+ float *g_gpu;
+ float *o_gpu;
+ float *c_gpu;
+ float *stored_c_gpu;
+ float *dc_gpu;
+
+ // adam
+ float *m_gpu;
+ float *v_gpu;
+ float *bias_m_gpu;
+ float *scale_m_gpu;
+ float *bias_v_gpu;
+ float *scale_v_gpu;
+
+ float * combine_gpu;
+ float * combine_delta_gpu;
+
+ float * forgot_state_gpu;
+ float * forgot_delta_gpu;
+ float * state_gpu;
+ float * state_delta_gpu;
+ float * gate_gpu;
+ float * gate_delta_gpu;
+ float * save_gpu;
+ float * save_delta_gpu;
+ float * concat_gpu;
+ float * concat_delta_gpu;
+
+ float *binary_input_gpu;
+ float *binary_weights_gpu;
+ float *bin_conv_shortcut_in_gpu;
+ float *bin_conv_shortcut_out_gpu;
+
+ float * mean_gpu;
+ float * variance_gpu;
+
+ float * rolling_mean_gpu;
+ float * rolling_variance_gpu;
+
+ float * variance_delta_gpu;
+ float * mean_delta_gpu;
+
+ float * col_image_gpu;
+
+ float * x_gpu;
+ float * x_norm_gpu;
+ float * weights_gpu;
+ float * weight_updates_gpu;
+ float * weight_change_gpu;
+
+ float * weights_gpu16;
+ float * weight_updates_gpu16;
+
+ float * biases_gpu;
+ float * bias_updates_gpu;
+ float * bias_change_gpu;
+
+ float * scales_gpu;
+ float * scale_updates_gpu;
+ float * scale_change_gpu;
+
+ float * output_gpu;
+ float * loss_gpu;
+ float * delta_gpu;
+ float * rand_gpu;
+ float * squared_gpu;
+ float * norms_gpu;
+#ifdef CUDNN
+ cudnnTensorDescriptor_t srcTensorDesc, dstTensorDesc;
+ cudnnTensorDescriptor_t srcTensorDesc16, dstTensorDesc16;
+ cudnnTensorDescriptor_t dsrcTensorDesc, ddstTensorDesc;
+ cudnnTensorDescriptor_t dsrcTensorDesc16, ddstTensorDesc16;
+ cudnnTensorDescriptor_t normTensorDesc, normDstTensorDesc, normDstTensorDescF16;
+ cudnnFilterDescriptor_t weightDesc, weightDesc16;
+ cudnnFilterDescriptor_t dweightDesc, dweightDesc16;
+ cudnnConvolutionDescriptor_t convDesc;
+ cudnnConvolutionFwdAlgo_t fw_algo, fw_algo16;
+ cudnnConvolutionBwdDataAlgo_t bd_algo, bd_algo16;
+ cudnnConvolutionBwdFilterAlgo_t bf_algo, bf_algo16;
+ cudnnPoolingDescriptor_t poolingDesc;
+#endif // CUDNN
+#endif // GPU
+};
+
+
+// network.h
+typedef enum {
+ CONSTANT, STEP, EXP, POLY, STEPS, SIG, RANDOM, SGDR
+} learning_rate_policy;
+
+// network.h
+typedef struct network {
+ int n;
+ int batch;
+ uint64_t *seen;
+ int *t;
+ float epoch;
+ int subdivisions;
+ layer *layers;
+ float *output;
+ learning_rate_policy policy;
+
+ float learning_rate;
+ float learning_rate_min;
+ float learning_rate_max;
+ int batches_per_cycle;
+ int batches_cycle_mult;
+ float momentum;
+ float decay;
+ float gamma;
+ float scale;
+ float power;
+ int time_steps;
+ int step;
+ int max_batches;
+ float *seq_scales;
+ float *scales;
+ int *steps;
+ int num_steps;
+ int burn_in;
+ int cudnn_half;
+ float *pre_allocated_ptr;
+ int adam;
+ float B1;
+ float B2;
+ float eps;
+
+ int inputs;
+ int outputs;
+ int truths;
+ int notruth;
+ int h, w, c;
+ int max_crop;
+ int min_crop;
+ float max_ratio;
+ float min_ratio;
+ int center;
+ int flip; // horizontal flip 50% probability augmentaiont for classifier training (default = 1)
+ int blur;
+ float angle;
+ float aspect;
+ float exposure;
+ float saturation;
+ float hue;
+ int random;
+ int track;
+ int augment_speed;
+ int sequential_subdivisions;
+ int init_sequential_subdivisions;
+ int current_subdivision;
+ int try_fix_nan;
+
+ int gpu_index;
+ tree *hierarchy;
+
+ float *input;
+ float *truth;
+ float *delta;
+ float *workspace;
+ int train;
+ int index;
+ float *cost;
+ float clip;
+
+#ifdef GPU
+ //float *input_gpu;
+ //float *truth_gpu;
+ float *delta_gpu;
+ float *output_gpu;
+
+ float *input_state_gpu;
+ float *input_pinned_cpu;
+ int input_pinned_cpu_flag;
+
+ float **input_gpu;
+ float **truth_gpu;
+ float **input16_gpu;
+ float **output16_gpu;
+ size_t *max_input16_size;
+ size_t *max_output16_size;
+ int wait_stream;
+#endif
+} network;
+
+// network.h
+typedef struct network_state {
+ float *truth;
+ float *input;
+ float *delta;
+ float *workspace;
+ int train;
+ int index;
+ network net;
+} network_state;
+
+//typedef struct {
+// int w;
+// int h;
+// float scale;
+// float rad;
+// float dx;
+// float dy;
+// float aspect;
+//} augment_args;
+
+// image.h
+typedef struct image {
+ int w;
+ int h;
+ int c;
+ float *data;
+} image;
+
+//typedef struct {
+// int w;
+// int h;
+// int c;
+// float *data;
+//} image;
+
+// box.h
+typedef struct box {
+ float x, y, w, h;
+} box;
+
+// box.h
+typedef struct detection{
+ box bbox;
+ int classes;
+ float *prob;
+ float *mask;
+ float objectness;
+ int sort_class;
+} detection;
+
+// matrix.h
+typedef struct matrix {
+ int rows, cols;
+ float **vals;
+} matrix;
+
+// data.h
+typedef struct data {
+ int w, h;
+ matrix X;
+ matrix y;
+ int shallow;
+ int *num_boxes;
+ box **boxes;
+} data;
+
+// data.h
+typedef enum {
+ CLASSIFICATION_DATA, DETECTION_DATA, CAPTCHA_DATA, REGION_DATA, IMAGE_DATA, COMPARE_DATA, WRITING_DATA, SWAG_DATA, TAG_DATA, OLD_CLASSIFICATION_DATA, STUDY_DATA, DET_DATA, SUPER_DATA, LETTERBOX_DATA, REGRESSION_DATA, SEGMENTATION_DATA, INSTANCE_DATA, ISEG_DATA
+} data_type;
+
+// data.h
+typedef struct load_args {
+ int threads;
+ char **paths;
+ char *path;
+ int n;
+ int m;
+ char **labels;
+ int h;
+ int w;
+ int c; // color depth
+ int out_w;
+ int out_h;
+ int nh;
+ int nw;
+ int num_boxes;
+ int min, max, size;
+ int classes;
+ int background;
+ int scale;
+ int center;
+ int coords;
+ int mini_batch;
+ int track;
+ int augment_speed;
+ int show_imgs;
+ float jitter;
+ int flip;
+ int blur;
+ float angle;
+ float aspect;
+ float saturation;
+ float exposure;
+ float hue;
+ data *d;
+ image *im;
+ image *resized;
+ data_type type;
+ tree *hierarchy;
+} load_args;
+
+// data.h
+typedef struct box_label {
+ int id;
+ float x, y, w, h;
+ float left, right, top, bottom;
+} box_label;
+
+// list.h
+//typedef struct node {
+// void *val;
+// struct node *next;
+// struct node *prev;
+//} node;
+
+// list.h
+//typedef struct list {
+// int size;
+// node *front;
+// node *back;
+//} list;
+
+// -----------------------------------------------------
+
+
+// parser.c
+LIB_API network *load_network(char *cfg, char *weights, int clear);
+LIB_API network *load_network_custom(char *cfg, char *weights, int clear, int batch);
+LIB_API network *load_network(char *cfg, char *weights, int clear);
+
+// network.c
+LIB_API load_args get_base_args(network *net);
+
+// box.h
+LIB_API void do_nms_sort(detection *dets, int total, int classes, float thresh);
+LIB_API void do_nms_obj(detection *dets, int total, int classes, float thresh);
+
+// network.h
+LIB_API float *network_predict(network net, float *input);
+LIB_API float *network_predict_ptr(network *net, float *input);
+LIB_API detection *get_network_boxes(network *net, int w, int h, float thresh, float hier, int *map, int relative, int *num, int letter);
+LIB_API void free_detections(detection *dets, int n);
+LIB_API void fuse_conv_batchnorm(network net);
+LIB_API void calculate_binary_weights(network net);
+LIB_API char *detection_to_json(detection *dets, int nboxes, int classes, char **names, long long int frame_id, char *filename);
+
+LIB_API layer* get_network_layer(network* net, int i);
+//LIB_API detection *get_network_boxes(network *net, int w, int h, float thresh, float hier, int *map, int relative, int *num, int letter);
+LIB_API detection *make_network_boxes(network *net, float thresh, int *num);
+LIB_API void reset_rnn(network *net);
+LIB_API float *network_predict_image(network *net, image im);
+LIB_API float validate_detector_map(char *datacfg, char *cfgfile, char *weightfile, float thresh_calc_avg_iou, const float iou_thresh, const int map_points, network *existing_net);
+LIB_API void train_detector(char *datacfg, char *cfgfile, char *weightfile, int *gpus, int ngpus, int clear, int dont_show, int calc_map, int mjpeg_port, int show_imgs);
+LIB_API void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filename, float thresh,
+ float hier_thresh, int dont_show, int ext_output, int save_labels, char *outfile, int letter_box);
+LIB_API int network_width(network *net);
+LIB_API int network_height(network *net);
+LIB_API void optimize_picture(network *net, image orig, int max_layer, float scale, float rate, float thresh, int norm);
+
+// image.h
+LIB_API image resize_image(image im, int w, int h);
+LIB_API void copy_image_from_bytes(image im, char *pdata);
+LIB_API image letterbox_image(image im, int w, int h);
+LIB_API void rgbgr_image(image im);
+LIB_API image make_image(int w, int h, int c);
+LIB_API image load_image_color(char *filename, int w, int h);
+LIB_API void free_image(image m);
+
+// layer.h
+LIB_API void free_layer(layer);
+
+// data.c
+LIB_API void free_data(data d);
+LIB_API pthread_t load_data(load_args args);
+LIB_API pthread_t load_data_in_thread(load_args args);
+
+// dark_cuda.h
+LIB_API void cuda_pull_array(float *x_gpu, float *x, size_t n);
+LIB_API void cuda_pull_array_async(float *x_gpu, float *x, size_t n);
+LIB_API void cuda_set_device(int n);
+LIB_API void *cuda_get_context();
+
+// utils.h
+LIB_API void free_ptrs(void **ptrs, int n);
+LIB_API void top_k(float *a, int n, int k, int *index);
+
+// tree.h
+LIB_API tree *read_tree(char *filename);
+
+// option_list.h
+LIB_API metadata get_metadata(char *file);
+
+
+// http_stream.h
+LIB_API void delete_json_sender();
+LIB_API void send_json_custom(char const* send_buf, int port, int timeout);
+LIB_API double get_time_point();
+void start_timer();
+void stop_timer();
+double get_time();
+void stop_timer_and_show();
+void stop_timer_and_show_name(char *name);
+void show_total_time();
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+#endif // DIMENSIONLESS_API
diff --git a/include/tkDNN/evaluation.h b/include/tkDNN/evaluation.h
new file mode 100644
index 0000000..1614d6b
--- /dev/null
+++ b/include/tkDNN/evaluation.h
@@ -0,0 +1,120 @@
+#ifndef EVALUATION_H
+#define EVALUATION_H
+
+#include
+#include
+#include
+
+#include
+
+#include "tkdnn.h"
+#include "BoundingBox.h"
+
+namespace tk { namespace dnn {
+
+struct Frame
+{
+ std::string lFilename;
+ std::string iFilename;
+ std::vector gt;
+ std::vector det;
+
+ void print() const;
+};
+
+struct PR
+{
+ double precision = 0;
+ double recall = 0;
+ int tp = 0, fp = 0, fn = 0;
+
+ void print();
+};
+
+void readmAPParams( const char* config_filename, int& classes1,float& conf_thresh1
+ , int& classes2,float& conf_thresh2
+ , int& classes3,float& conf_thresh3
+ , int& classes4,float& conf_thresh4
+ , int& classes5,float& conf_thresh5
+ );
+
+/**
+ * This method computes the mean Average Precision for a set of detections and
+ * groundtruths. It returns the mAP for a given IoU threshold, and a given
+ * confidence threshold over all the classes.
+ *
+ * @param images collection of frames on which to compute the metrics
+ * @param classes number of classes of the considered dataset
+ * @param IoU_thresh threshold used to compute Intersection over Union
+ * @param conf_thresh threshold used to filter bounding boxes based on their
+ * confidence (or probability)
+ * @param map_points number of point used to compute the mAP. if 0 is given,
+ * all the recall levels are evaluated, otherwise only
+ * map_point recall levels are used. For COCO evaluation
+ * 101 points are used.
+ * @param verbose is set to true, prints on screen additional info
+ *
+ * @return mAP computed
+ */
+double computeMap( std::vector &images,const int classes,
+ const float IoU_thresh, const float conf_thresh=0.3,
+ const int map_points=101, const bool verbose=false);
+
+
+/**
+ * This method computes the mean Average Precision for a set of detections and
+ * groundtruths on several IoU thresholds. It is used to compute, for example,
+ * the most used metric in Object Detection, namely the mAP 0.5:0.95, which is
+ * the average among the mAP for IoU level from 0.5 to 0.95 with a step of 0.05.
+ *
+ * @param images collection of frames on which to compute the metrics
+ * @param classes number of classes of the considered dataset
+ * @param IoU_thresh starting threshold used to compute Intersection over Union
+ * @param conf_thresh threshold used to filter bounding boxes based on their
+ * confidence (or probability)
+ * @param map_points number of point used to compute the mAP. if 0 is given,
+ * all the recall levels are evaluated, otherwise only
+ * map_point recall levels are used. For COCO evaluation
+ * 101 points are used.
+ * @param map_step step used to increment IoU threshold
+ * @param map_levels number of IoU step to perform
+ * @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
+ * are written on file
+ * @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
+ * map_step=0.05 and map_levels=10)
+ */
+double computeMapNIoULevels(std::vector &images,const int classes,
+ const float i_IoU_thresh=0.5, const float conf_thresh=0.3,
+ const int map_points=101, const float map_step=0.05,
+ const int map_levels=10, const bool verbose=false,
+ const bool write_on_file = false, std::string net = "");
+/**
+ * This method computes the number of True Positive (TP), False Positive (FP),
+ * False Negative (FN), precision, recall and f1-score.
+ * Those values are computer over all the detections, over all the classes.
+ *
+ * @param images collection of frames on which to compute the metrics
+ * @param classes number of classes of the considered dataset
+ * @param IoU_thresh threshold used to compute Intersection over Union
+ * @param conf_thresh threshold used to filter bounding boxes based on their
+ * confidence (or probability)
+ * @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
+ * are written on file
+ * @param net name of the considered neural network
+ */
+void computeTPFPFN( std::vector &images,const int classes,
+ const float IoU_thresh=0.5, const float conf_thresh=0.3,
+ bool verbose=false, const bool write_on_file=false,
+ std::string net="");
+
+
+void printJsonCOCOFormat(std::ofstream *out_file, const std::string image_path, std::vector bbox, const int classes, const int w, const int h);
+
+}}
+#endif /*EVALUATION_H*/
+
+
diff --git a/include/tkDNN/handler.h b/include/tkDNN/handler.h
new file mode 100644
index 0000000..df91cd4
--- /dev/null
+++ b/include/tkDNN/handler.h
@@ -0,0 +1,28 @@
+#ifndef HANDLER_H
+#define HANDLER_H
+#include
+#include "stdafx.h"
+
+using namespace std;
+using namespace web;
+using namespace http;
+using namespace utility;
+using namespace http::experimental::listener;
+
+
+class handler
+{
+ public:
+ handler(utility::string_t url);
+
+ pplx::taskopen(){return m_listener.open();}
+ pplx::taskclose(){return m_listener.close();}
+ static void init_bag();
+ protected:
+
+ private:
+ void handle_post(http_request message);
+ http_listener m_listener;
+};
+
+#endif // HANDLER_H
diff --git a/include/tkDNN/image.h b/include/tkDNN/image.h
new file mode 100644
index 0000000..2cd9c3a
--- /dev/null
+++ b/include/tkDNN/image.h
@@ -0,0 +1,108 @@
+#ifndef IMAGE_H
+#define IMAGE_H
+#include "darknet.h"
+
+#include
+#include
+#include
+#include
+#include
+
+//#include "image_opencv.h"
+
+//#include "box.h"
+#ifdef __cplusplus
+extern "C" {
+#endif
+/*
+typedef struct {
+ int w;
+ int h;
+ int c;
+ float *data;
+} image;
+*/
+float get_color(int c, int x, int max);
+void flip_image(image a);
+void draw_box(image a, int x1, int y1, int x2, int y2, float r, float g, float b);
+void draw_box_width(image a, int x1, int y1, int x2, int y2, int w, float r, float g, float b);
+void draw_bbox(image a, box bbox, int w, float r, float g, float b);
+void draw_label(image a, int r, int c, image label, const float *rgb);
+void write_label(image a, int r, int c, image *characters, char *string, float *rgb);
+void draw_detections(image im, int num, float thresh, box *boxes, float **probs, char **names, image **labels, int classes);
+void draw_detections_v3(image im, detection *dets, int num, float thresh, char **names, image **alphabet, int classes, int ext_output);
+image image_distance(image a, image b);
+void scale_image(image m, float s);
+// image crop_image(image im, int dx, int dy, int w, int h);
+image random_crop_image(image im, int w, int h);
+image random_augment_image(image im, float angle, float aspect, int low, int high, int size);
+void random_distort_image(image im, float hue, float saturation, float exposure);
+//LIB_API image resize_image(image im, int w, int h);
+//LIB_API void copy_image_from_bytes(image im, char *pdata);
+void fill_image(image m, float s);
+void letterbox_image_into(image im, int w, int h, image boxed);
+//LIB_API image letterbox_image(image im, int w, int h);
+// image resize_min(image im, int min);
+image resize_max(image im, int max);
+void translate_image(image m, float s);
+void normalize_image(image p);
+image rotate_image(image m, float rad);
+void rotate_image_cw(image im, int times);
+void embed_image(image source, image dest, int dx, int dy);
+void saturate_image(image im, float sat);
+void exposure_image(image im, float sat);
+void distort_image(image im, float hue, float sat, float val);
+void saturate_exposure_image(image im, float sat, float exposure);
+void hsv_to_rgb(image im);
+//LIB_API void rgbgr_image(image im);
+void constrain_image(image im);
+void composite_3d(char *f1, char *f2, char *out, int delta);
+int best_3d_shift_r(image a, image b, int min, int max);
+
+image grayscale_image(image im);
+image threshold_image(image im, float thresh);
+
+image collapse_image_layers(image source, int border);
+image collapse_images_horz(image *ims, int n);
+image collapse_images_vert(image *ims, int n);
+
+void show_image(image p, const char *name);
+void show_image_normalized(image im, const char *name);
+void save_image_png(image im, const char *name);
+void save_image(image p, const char *name);
+void show_images(image *ims, int n, char *window);
+void show_image_layers(image p, char *name);
+void show_image_collapsed(image p, char *name);
+
+void print_image(image m);
+
+//LIB_API image make_image(int w, int h, int c);
+image make_random_image(int w, int h, int c);
+image make_empty_image(int w, int h, int c);
+image float_to_image_scaled(int w, int h, int c, float *data);
+image float_to_image(int w, int h, int c, float *data);
+image copy_image(image p);
+void copy_image_inplace(image src, image dst);
+image load_image(char *filename, int w, int h, int c);
+image load_image_stb_resize(char *filename, int w, int h, int c);
+image load_image_new(unsigned char *image_data, int len, int channels, int antiLog, int gray, int width, int height);
+image load_image_file(unsigned char *image_data, int channels, int antilog, int gray, int width, int height);
+//LIB_API image load_image_color(char *filename, int w, int h);
+image **load_alphabet();
+
+//float get_pixel(image m, int x, int y, int c);
+//float get_pixel_extend(image m, int x, int y, int c);
+//void set_pixel(image m, int x, int y, int c, float val);
+//void add_pixel(image m, int x, int y, int c, float val);
+float bilinear_interpolate(image im, float x, float y, int c);
+
+image get_image_layer(image m, int l);
+
+//LIB_API void free_image(image m);
+void test_resize(char *filename);
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/include/tkDNN/kernels.h b/include/tkDNN/kernels.h
index d7d5d05..5d673c8 100644
--- a/include/tkDNN/kernels.h
+++ b/include/tkDNN/kernels.h
@@ -3,42 +3,38 @@
#include "utils.h"
-void activationELUForward(dnnType* srcData, dnnType* dstData, int size, cudaStream_t stream = cudaStream_t(0));
-void activationLEAKYForward(dnnType* srcData, dnnType* dstData, int size, cudaStream_t stream = cudaStream_t(0));
-void activationLOGISTICForward(dnnType* srcData, dnnType* dstData, int size, cudaStream_t stream = cudaStream_t(0));
-void activationSIGMOIDForward(dnnType* srcData, dnnType* dstData, int size, cudaStream_t stream = cudaStream_t(0));
+void activationELUForward(dnnType *srcData, dnnType *dstData, int size, cudaStream_t stream = cudaStream_t(0));
+void activationLEAKYForward(dnnType *srcData, dnnType *dstData, int size, cudaStream_t stream = cudaStream_t(0));
+void activationReLUCeilingForward(dnnType *srcData, dnnType *dstData, int size, const float ceiling, cudaStream_t stream = cudaStream_t(0));
+void activationLOGISTICForward(dnnType *srcData, dnnType *dstData, int size, cudaStream_t stream = cudaStream_t(0));
+void activationSIGMOIDForward(dnnType *srcData, dnnType *dstData, int size, cudaStream_t stream = cudaStream_t(0));
+void activationMishForward(dnnType* srcData, dnnType* dstData, int size, cudaStream_t stream= cudaStream_t(0));
-void fill(dnnType* data, int size, dnnType val, cudaStream_t stream = cudaStream_t(0));
+void fill(dnnType *data, int size, dnnType val, cudaStream_t stream = cudaStream_t(0));
-void resizeForward( dnnType* srcData, dnnType* dstData, int n, int i_c, int i_h, int i_w,
- int o_c, int o_h, int o_w, cudaStream_t stream = cudaStream_t(0));
+void resizeForward(dnnType *srcData, dnnType *dstData, int n, int i_c, int i_h, int i_w,
+ int o_c, int o_h, int o_w, cudaStream_t stream = cudaStream_t(0));
-void reorgForward( dnnType* srcData, dnnType* dstData,
- int n, int c, int h, int w, int stride, cudaStream_t stream = cudaStream_t(0));
-void softmaxForward(float *input, int n, int batch, int batch_offset,
+void reorgForward(dnnType *srcData, dnnType *dstData,
+ int n, int c, int h, int w, int stride, cudaStream_t stream = cudaStream_t(0));
+
+void MaxPoolingForward(dnnType *srcData, dnnType *dstData, int n, int c, int h, int w, int stride_x, int stride_y, int size, int padding, cudaStream_t stream = cudaStream_t(0));
+
+void softmaxForward(float *input, int n, int batch, int batch_offset,
int groups, int group_offset, int stride, float temp, float *output, cudaStream_t stream = cudaStream_t(0));
-
-void shortcutForward(dnnType* srcData, dnnType* dstData, int n1, int c1, int h1, int w1, int s1,
- int n2, int c2, int h2, int w2, int s2,
+void shortcutForward(dnnType *srcData, dnnType *dstData, int n1, int c1, int h1, int w1, int s1,
+ int n2, int c2, int h2, int w2, int s2,
cudaStream_t stream = cudaStream_t(0));
-void upsampleForward(dnnType* srcData, dnnType* dstData,
- int n, int c, int h, int w, int s, int forward, float scale,
+void upsampleForward(dnnType *srcData, dnnType *dstData,
+ int n, int c, int h, int w, int s, int forward, float scale,
cudaStream_t stream = cudaStream_t(0));
-void float2half(float* srcData, __half* dstData, int size, const cudaStream_t stream = cudaStream_t(0));
+void float2half(float *srcData, __half *dstData, int size, const cudaStream_t stream = cudaStream_t(0));
-
-void modulated_deformable_im2col_cuda(cudaStream_t stream,
- const float *data_im, const float *data_offset, const float *data_mask,
- const int batch_size, const int channels, const int height_im, const int width_im,
- const int height_col, const int width_col, const int kernel_h, const int kenerl_w,
- const int pad_h, const int pad_w, const int stride_h, const int stride_w,
- const int dilation_h, const int dilation_w,
- const int deformable_group, float *data_col);
-
-void dcn_v2_cuda_forward(float *input, float *weight,
+void dcnV2CudaForward(cublasStatus_t stat, cublasHandle_t handle,
+ float *input, float *weight,
float *bias, float *ones,
float *offset, float *mask,
float *output, float *columns,
@@ -46,8 +42,10 @@ void dcn_v2_cuda_forward(float *input, float *weight,
const int stride_h, const int stride_w,
const int pad_h, const int pad_w,
const int dilation_h, const int dilation_w,
- const int deformable_group,
+ const int deformable_group, const int batch_id,
const int in_n, const int in_c, const int in_h, const int in_w,
const int out_n, const int out_c, const int out_h, const int out_w,
const int dst_dim, cudaStream_t stream = cudaStream_t(0));
+
+void scalAdd(dnnType* dstData, int size, float alpha, float beta, int inc, cudaStream_t stream = cudaStream_t(0));
#endif //KERNELS_H
diff --git a/include/tkDNN/kernelsThrust.h b/include/tkDNN/kernelsThrust.h
new file mode 100644
index 0000000..a7b32e9
--- /dev/null
+++ b/include/tkDNN/kernelsThrust.h
@@ -0,0 +1,39 @@
+#ifndef KERNELSTHRUST_H
+#define KERNELSTHRUST_H
+
+
+#include
+#include