Full text
I MDSAA Mestrado em Métodos Analíticos Avançados Master Program in Data Science and Advanced Analytics Threat Detection with Computer Vision Internship at Everis UK Gabriel Azenha Cardoso Internship report presented as a requirement to be awarded the master’s degree in Data Science and Advanced Analytics
II NOVA Information Management School Instituto Superior de Estatística e Gestão de Informação Universidade Nova de Lisboa Threat Detection with Computer Vision by Gabriel Azenha Cardoso Internship report presented as a requirement to be awarded the master’s degree in Data Science and Advanced Analytics Advisor: Professor Doutor Mauro Castelli February 2023
III ACKNOWLEDGEMENTS I must express my gratitude to my family, especially my mother who encouraged me to take this master course and gave the support and conditions I needed to fulfill this goal. I am also thankful to my friends from back home and all the new friendships I made along the way by helping me going through some hard moments that only a few could understand. I also must thank Everis UK for the opportunity, and in particular to the Innovation team for receiving me with arms wide open and being extremely patient to answer all my questions and appeals for assistance. A special thanks to Mauricio for guiding me through my first professional experience in information technology and being always kind and supportive and Wen for teaching me everything she knew on computer vision and deep learning. My final acknowledgement goes to Professor Mauro Castelli, for all the advice and suggestions to this paper.
IV ABSTRACT This document describes the work conducted during an internship experience at the AI Innovation Department of Everis UK (now NTT Data). It reports what was done, learned, and developed with the sole objective of having a commercial product solution for the company's clients. The primary goal was to implement a solution in retail stores, to help assist the security team with threat detection. To do so, the solution consists in deploying trained deep learning models into hardware connected to the CCTV security cameras and detecting in that live feed any potential threats. By the time I started working on this project, was at an advanced stage so I had to study all the work previously done to understand what was needed and properly integrate the team fully. My contribution was focused on the model training process, where I had to create and structure a dataset and train a model capable of detecting the targeted classes quickly and accurately. KEYWORDS computer vision; deep learning; inference; security
V INDEX LIST OF FIGURES ............................................................................................................. VII LIST OF TABLES .............................................................................................................. VIII LIST OF ABREVIATIONS AND ACRONYMS ....................................................................... IX 1. INTRODUCTION ........................................................................................................... 1 1.1. IDEA DESCRIPTION ............................................................................................... 2 1.2. BUSINESS OBJECTIVES .......................................................................................... 3 1.3. SITUATION ASSESSMENT ..................................................................................... 3 1.3.1. Resources ...................................................................................................... 3 1.3.2. Challenges and Benefits ................................................................................ 3 1.3.3. Value Proposition .......................................................................................... 3 1.3.4. Business Model ............................................................................................. 4 2. THEORETHICAL FRAMEWORK ..................................................................................... 5 2.1. DEEP LEARNING ................................................................................................... 5 2.2. DEEP LEARNING APPLICATIONS IN COMPUTER VISION ....................................... 5 2.2.1. Computer Vision Introduction ...................................................................... 5 2.2.2. Neural Networks ........................................................................................... 5 2.2.3. Convolutional Neural Networks .................................................................... 7 2.2.4. TensorFlow .................................................................................................... 9 2.3. NVIDIA DEEPSTREAM ......................................................................................... 11 2.3.2. Deepstream Graph Architecture ................................................................. 12 2.3.3. Key Features ................................................................................................ 13 3. SOFTWARES AND TOOLS ........................................................................................... 15 3.1. COMPUTER VISION ANNOTATION TOOL ............................................................ 15 3.1.1. Introduction ................................................................................................ 15 3.1.2. CVAT Setup Basics ...................................................................................... 15 3.2. AZURE VIRTUAL MACHINE ................................................................................. 16 3.3. NVIDIA JETSON NANO ........................................................................................ 16 3.4. NVIDIA TRANSFER LEARNING TOOLKIT .............................................................. 17 3.4.1. Overview ..................................................................................................... 17 3.4.2. Pre-trained Models ..................................................................................... 18 3.5. PYTHON .............................................................................................................. 19 3.6. MOBAXTERM ..................................................................................................... 19 3.7. DOCKER .............................................................................................................. 20
VI 4. MODELLING ............................................................................................................... 22 4.1. STATUS OF THE PROJECT .................................................................................... 22 4.1.1. Overview ..................................................................................................... 22 4.1.2. Scripts .......................................................................................................... 23 4.1.3. Model Train Step Guide .............................................................................. 28 4.1.4. Limitations ................................................................................................... 30 4.2. TRANSFER LEARNING TOOLKIT DEMO ............................................................... 31 4.3. DATA PREPARATION .......................................................................................... 41 4.3.1. KITTI Conversion ......................................................................................... 41 4.3.2. Annotations and Folder Structure ............................................................... 43 4.4. TRAINING ........................................................................................................... 44 5. RESULTS DISCUSSION ................................................................................................ 48 6. CONCLUSIONS ............................................................................................................ 50 7. REFERENCES .............................................................................................................. 52
VII LIST OF FIGURES FIGURE 1 – MAIN ARCHITECTURE COMPONENTS ................................................................................................... 2 FIGURE 2 – MODEL DEVELOPMENT COMPONENTS ................................................................................................ 2 FIGURE 3 - NTT DATA VALUE PROPOSITION CANVAS ............................................................................................. 3 FIGURE 4 - BUSINESS MODEL CANVAS .................................................................................................................... 4 FIGURE 5 – BIOLOGICAL AND ARTIFICIAL NEURONS [5] .......................................................................................... 6 FIGURE 6 – ACTIVATION FUNCTIONS PLOTS ........................................................................................................... 7 FIGURE 7 – CNN REPRESENTATION ......................................................................................................................... 8 FIGURE 8 – DIAGRAM OF TENSORFLOW ARCHITECTURE ........................................................................................ 9 FIGURE 9 – A SIMPLIFIED GRAPH CORRESPONDING TO A MODEL [6] .................................................................. 10 FIGURE 10 – NVIDIA METROPOLIS ........................................................................................................................ 11 FIGURE 11 – FULL DEEPSTREAM ARCHITECTURE .................................................................................................. 12 FIGURE 12 – INFERENCE WORKFLOW ................................................................................................................... 14 FIGURE 13 – TAO TOOLKIT INTEGRATION ............................................................................................................. 14 FIGURE 14 – TLT PRE-TRAINED MODEL’S OVERVIEW ............................................................................................ 18 FIGURE 15 – PERFORMANCE OF PRE-TRAINED MODELS ..................................................................................... 19 FIGURE 16 – OBJECT DETECTION WORKFLOW ...................................................................................................... 22 FIGURE 17 – TRAIN_SSD.PY RUNNING LOG ........................................................................................................... 30 FIGURE 18 – TLT PAGE ON THE NGC CATALOG FOR VIDEO STREAMING .............................................................. 31 FIGURE 19 – DATA TREE FOR NVIDIA DEMO ......................................................................................................... 33 FIGURE 20 – TLT INFERENCE WITH MASK/NO MASK DEMO MODEL .................................................................... 40 FIGURE 21 – CVAT ANNOTATION EXAMPLE .......................................................................................................... 43 FIGURE 22 – TLT RUNNING LOG ............................................................................................................................ 45 FIGURE 23 – TRAINED MODEL 2 CLASS PRECISION ............................................................................................... 46 FIGURE 24 – TLT INFERENCE TEST ......................................................................................................................... 47
VIII LIST OF TABLES TABLE 1 – UK STORES INCIDENT REGISTRATION ..................................................................................................... 1 TABLE 2 – THE TRAIN_SSD.PY ARGUMENTS .......................................................................................................... 24 TABLE 3 – EVAL_SSD.PY ARGUMENTS ................................................................................................................... 27 TABLE 4 - RUN_SSD_EXAMPLE.PY ARGUMENTS ................................................................................................... 28
IX LIST OF ABREVIATIONS AND ACRONYMS AI Artificial Intelligence API Application Programming Interface CCTV Closed-Circuit Television CLI Command Line Interface CNN Convolutional Neural Networks CPU Central Processing Unit CSI Camera Serial Interface CUDA Compute Unified Device Architecture CVAT Computer Vision Annotation Tool DLA Deep Learning Accelerator GPU Graphics Processing Unit HPC High Performance Computing HR Human Resources IT Information Technology IVA Intelligent Virtual Agent ML Machine Learning MVP Minimum Viable Product NGC NVIDIA GPU Cloud NN Neural Networks NVDEC NVIDIA Video Decoding NVENC NVIDIA Video Encoding OEM Original Equipment Manufacturer RTSP Real Time Stream Protocol SASL Simple Authentication and Security Layer SDK Software Development Kit SVM Support-vector machine TLS Transport Layer Security UI User Interface UK United Kingdom USB Universal Serial Bus VGG Visual Geometry Group
6 multiple layers together, a neural network can learn complex patterns in data and perform a wide range of tasks, such as image classification, speech recognition, and natural language processing. Figure 5 – Biological and artificial neurons [5] The sum of the inputs is weighted, so each input is scaled depending on its corresponding weight. Together with the neuron’s bias, they are the main parameters that we can adjust during the training phase to optimize the final results. Formalizing the process mathematically for one neuron that takes two inputs x0 and x1, weighted by a factor w0 and w1, respectively, (with an optional bias) we can express the input values as a horizontal vector, the weights as vertical vector and multiply them resulting in the following equation: So, we can represent a simple artificial neuron in a network as it follows. Here, z is the output of the neuron, x is the input vector, w is the weight vector, and b is the bias. The weight vector determines the strength of the connections between the input and the output, and the bias determines the threshold of the activation function.
7 The equation represents the dot product between the input vector and the weight vector, with the addition of the bias term. This dot product captures the weighted sum of the inputs, and the bias term shifts the activation function to the left or right, which affects the range of outputs that can be produced by the neuron. Before the neuron outputs, the signal has to pass a key component of the original perceptron, the activation function, which with linear inputs takes a binary form, returning 1 or a 0 (usually with t = 0). In non-linearity cases (more complex behaviors) and continuous differentiability the most common functions are: ● The sigmoid function, (with 𝑒 "the exponential function) ● The hyperbolic tangent, ● The Rectified Linear Unit (ReLU), To visualize the difference between each function, plots in the following figure: Figure 6 – Activation functions plots [5] With this logic in mind, we modeled a simple artificial neuron, that can receive a signal, process it and out a value that can be forwarded to other neurons, building a network [5]. 2.2.3. Convolutional Neural Networks Knowing what Neural Networks are, we go a step deeper into the concept and went on the understanding what convolutional neural networks (CNNs) are and how these modern methods are trained to further improve their robustness. CNNs were introduced to solve some of the shortcomings of the original neural networks. The two main drawbacks of basic networks when dealing with images are the explosive number of parameters and the lack of spatial reasoning.
8 Images are very complex structures with a large number of values (H x W x D values with H indicating the image’s height, W width, and D the depth). Even small single-channel images can have input vectors of size (e.g.) 28 x 28 x 1 = 784 values each and these numbers simply explode when considering larger RGB images or deeper networks. Also, because their neurons receive all the values from the previous layer without any distinction (they are fully connected), these neural networks do not have the concepts of distance or spatiality. Spatial relations in the data are lost. Multidimensional data (e.g. images) could also be anything from column vectors to dense layers because their operations do not take into account the data dimensionality nor the positions of input values, more precisely this means that the idea of proximity between pixels is lost to fully connected (FC) layers, as all pixel values are combined by the layers without considering their original positions. As it does not change the behavior of dense layers, to simplify, it flattens multidimensional inputs before passing them to these layers (reshapes them into column vectors). Neural layers would be smarter if they could consider the spatial information, meaning that some input values belong to the same pixel (channel values) or the same image region (neighbor pixels). CNNs offers simple solutions to these shortcomings while working in the same way as the networks previously presented. First, CNNs can handle multidimensional data. For images, it takes as input the same three-dimensional data (H x W x D) and has its neurons arranged in a similar volume, and this leads to the second improvement of CNNs that unlike fully connected networks each neuron only has access to some elements in the neighboring region of the previous layer. This region is called the receptive field of the neurons: Figure 7 – CNN representation [7] By linking neurons only to their neighboring ones in the previous layer, CNNs not only drastically reduce the number of parameters to train, but also preserve the localization of image features [7].
9 Now that we know the basic concept and logic of CNNs we can understand why they lay the robust training and optimization foundations of the models used for computer vision projects and used for the development of our solution. 2.2.4. TensorFlow TensorFlow is an open-source library developed by Google primarily to simplify the deployment of machine learning solutions on various platforms. TensorFlow’s architecture is composed of a C++ layer, a python low-level API that wraps C++ sources, so when calling a python method in TensorFlow, it usually invokes C++ code behind the scenes but since python is considered to be easier to use this wrapper allows users to work more quickly. At the top layer is the high-level API made from two components, Keras and the Estimator API. The Estimator API contains pre-made components that allow you to build machine learning models more easily, very similar to building blocks or templates. Keras is a user-friendly, modular, and extensible wrapper for TensorFlow that at first was designed as an interface to enable fast experimentation with neural networks. Figure 8 – Diagram of TensorFlow architecture [6] In this project, we used TensorFlow 2 which was released with some new features and concepts. One of those core concepts is the tensors, which can be described as N-dimensional arrays that could take the form of a scalar, a vector, a 3D matrix, or an N-dimensional matrix. This component is used to store mathematical values which can be fixed values created using tf.constant or changing values created using tf.variable. TensorFlow uses tensors as inputs and as outputs, and a component that transforms one into the other is called an operation, therefore a computer vision model is composed of multiple operations. These operations are represented using what is called a directed acyclic graph (DAC), also referred to as a TensorFlow graph.
10 Figure 9 – A simplified graph corresponding to a model [6] Each node is composed of smaller operations such as matrix multiplications and additions and while very simple this graph represents the different layers of a simple model in the form of multiple operations. By relying on graphs, TensorFlow can run part of the operations on the CPU and another part on the GPU, run different parts of the graph on different machines in case of a distributed model, and optimize the graph to avoid unnecessary operations, lending to better computational performance. Another useful concept is backpropagating errors using gradient tape. In short, TensorFlow computes the results of an operation instead of storing the operation, with no information on the operation and its inputs it would be impossible to automatically differentiate the loss operation. That is where the gradient tape makes a difference, by running our loss computation in the context of tf.gradienttape, TensorFlow will automatically record all operations and allow us to replay them backward afterward. def train_step(): with tf.GradientTape() as tape: loss = tf.math.abs(A * X - B) dX = tape.gradient(loss, X) print('X = {:.2f}, dX = {:2f}'.format(X.numpy(), dX)) X.assign(X - dX) for i in range(7): train_step() The code above defines one training step. Every time train_step is called, the loss is computed in the context of the gradient tape, then the context is used to compute the gradient. The X variable is then updated, and we can see it converging toward the value that solves the equation: X = 20.00, dX = 3.000000 X = 17.00, dX = 3.000000 X = 14.00, dX = 3.000000 X = 11.00, dX = 3.000000 So, for innovative models or when experimenting, the gradient tape is a powerful tool that allows automatic differentiation without much effort [6].
11 2.3. NVIDIA DEEPSTREAM 2.3.1. What is NVIDIA Deepstream? “NVIDIA’s Deepstream SDK is a complete streaming analytics toolkit based on GStreamer for AI-based multi-sensor processing, video, audio, and image understanding. It’s ideal for vision AI developers, software partners, startups, and OEMs building IVA apps and services” [8]. With this toolkit, developers can construct stream processing pipelines that include neural networks and other advanced processing tasks, such as tracking, video encoding/decoding, and video rendering. These pipelines enable real-time analysis on video, image, and sensor data, facilitating timely insights and analytics. Figure 10 – NVIDIA Metropolis [8] Deepstream takes the streaming data as input – from a USB/CSI camera, video from a file, or streams over RTSP (which is the available stream format for us) and uses “AI and computer vision to generate insights from pixels for a better understanding of the environment” [9]. This toolkit has the potential to serve as a fundamental building block for various video analytic applications, such as safety monitoring, retail self-checkout, and our specific focus, object detection. DeepStream supports application development in C/C++ and Python, offering Python bindings for extra ease of use. The toolkit includes pre-built reference applications in C/C++ and Python to simplify the development process. The core SDK includes hardware accelerator plugins that leverage accelerators such as VIC, GPU, DLA, NVDEC, and NVENC, enabling compute-intensive tasks to be offloaded to dedicated accelerators for optimal performance in video analytics applications.
12 A notable feature of DeepStream is its secure bi-directional communication between edge and cloud environments. The toolkit includes built-in security protocols such as SASL/Plain authentication using username/password and 2-way TLS authentication to ensure data security. DeepStream uses various NVIDIA libraries from the CUDA-X stack, including CUDA, TensorRT, NVIDIA Triton Inference server, and multimedia libraries. TensorRT accelerates AI inference on NVIDIA GPUs, and DeepStream abstracts these libraries into plugins, simplifying the development of video analytic pipelines without the need to learn each library. DeepStream is optimized for NVIDIA GPUs and can integrate on embedded edge devices running the Jetson platform, as well as data center GPUs like T4. DeepStream applications can be containerized using NVIDIA container Runtime and are available on NGC, the NVIDIA GPU cloud registry [9]. 2.3.2. Deepstream Graph Architecture “Deepstream is an optimized graph architecture built using the open-source GStreamer framework. The graph below shows a typical video analytic application starting from input video to outputting insights. All the individual blocks are various plugins that are used. At the bottom are the different hardware engines that are utilized throughout the application. Optimum memory management with zero-memory copy between plugins and the use of various accelerators ensure the highest performance” [9]. Figure 11 – Full Deepstream Architecture [9] DeepStream provides a comprehensive suite of GStreamer plugins that serve as foundational building blocks for constructing efficient video analytics pipelines. These plugins are specifically designed to harness hardware acceleration capabilities and optimize performance in various video processing tasks: • The streaming data can be captured from diverse sources such as RTSP, local file systems, or cameras and processed using the CPU. • Optionally, image pre-processing can be applied after decoding, including image dewarping for correcting distortions from FishEye lenses or color space conversion.
13 • Frames are then batched for optimal inference performance using the gst-nvstreammux plugin. • Inference can be performed using TensorRT, NVIDIA's inference accelerator runtime, or native frameworks such as TensorFlow or PyTorch with the Triton inference server. GPU or DLA (Deep Learning Accelerator) can be utilized for inference on Jetson AGX Xavier and Xavier NX. • Object tracking can be performed after inference using built-in reference trackers in the SDK. • Visualization artifacts such as bounding boxes, segmentation masks, and labels can be created. DeepStream offers various options for outputting the results, such as rendering the output with bounding boxes on the screen, saving the output to a local disk, streaming out over RTSP, or sending metadata to the cloud. Built-in broker protocols such as Kafka, MQTT, AMQP, and Azure IoT are available, and custom broker adapters can be created to suit specific requirements [9]. 2.3.3. Key Features DeepStream provides comprehensive support for AI models, specifically for object detection and segmentation, encompassing cutting-edge models such as SSD, YOLO, FasterRCNN, and MaskRCNN. Moreover, DeepStream facilitates the integration of custom functions and libraries, catering to unique requirements. The versatility of DeepStream spans from rapid prototyping to full-scale production-level solutions, affording the flexibility to choose the most suitable inference path. The platform seamlessly integrates with the NVIDIA Triton™ Inference Server, allowing for the deployment of models in native frameworks such as PyTorch and TensorFlow for inference. Additionally, DeepStream leverages the NVIDIA TensorRT™ to enable high-throughput inference with support for multi-GPU, multi-stream, and batching, leading to optimal performance. In addition to supporting native inference, DeepStream's capabilities extend to communication with independent/remote instances of the Triton Inference Server via gRPC, enabling the implementation of distributed inference solutions. This empowers efficient and scalable deployment of AI models in distributed environments, ensuring robustness and scalability of the inference process.
14 Figure 12 – Inference workflow [8] Furthermore, DeepStream facilitates seamless integration with the Transfer Learning Toolkit (TAO Toolkit) within the NVIDIA Metropolis ecosystem, enabling accelerated development and enhanced real-time performance of vision AI systems. The TAO Toolkit enables developers to adapt and optimize production-quality vision AI models, including SSD, MaskRCNN, YOLOv4, RetinaNet, and other state- of-the-art models, while DeepStream offers turnkey integration of these models for deployment.This integrated approach empowers the use of pre-trained models and transfer learning techniques, resulting in a streamlined workflow for building end-to-end vision AI applications. By leveraging the TAO Toolkit in conjunction with DeepStream, developers can achieve faster development cycles and superior performance in real-time scenarios, making it a valuable tool for academic research and development in the field of vision-based AI [9]. Figure 13 – TAO Toolkit integration [11]
15 3. SOFTWARES AND TOOLS 3.1. COMPUTER VISION ANNOTATION TOOL 3.1.1. Introduction CVAT is a free and open-source interactive video and image annotation tool for computer vision. It was designed to provide users with a set of convenient instruments for annotating digital images and videos since data scientists need lots of annotated data to train (in our case) the CNNs at the core of AI workflows and obtain that data with the necessary quality is a huge and time-consuming challenge. CVAT supports supervised machine learning tasks pertaining to object detection, image classification, image segmentation, and 3D data annotation. It allows users to annotate images with multiple tools (boxes, polygons, cuboids, circles, skeletons, etc). 3.1.2. CVAT Setup basics In our particular case, we used machines with Windows 10 and for that, we needed to install a few other tools for further use: • Install WSL2 (Windows Subsystem for Linux); • Download and install Docker Desktop; • Download and install git for Windows; • Download and install Google Chrome, it is the only browser that supports CVAT; Open the Git Bash application and clone the CVAT source code from the GitHub repository with the following command. git clone https://github.com/opencv/cvat cd cvat Then we must run docker containers. It will take some time to download the latest CVAT release and other required images like Postgres, Redis, etc. from DockerHub and create containers. docker-compose up -d After this, we create a superuser. A superuser can use an admin panel to assign correct groups to other users. # enter docker image first Docker exec -it cvat_server /bin/bash # then run
22 4. MODELLING 4.1. STATUS OF THE PROJECT 4.1.1. Overview By the time I got assigned to this project, there was already a system designed and tested. This system was based on the work that an Nvidia developer that goes by the name of dusty-nv in GitHub. On his GitHub, there is a repository with a shared work (https://github.com/dusty-nv/pytorchssd/tree/8ed842a408f8c4a8812f430cf8063e0b93a56803) that consists of the implementation of an SSD (Single Shot Detector) for object detection with PyTorch and using MobilleNet architecture. In this git repository, we have all the necessary scripts (written in python) for the training, evaluation, and export of the trained model, we must prepare the input with our labeled data and run the scripts with our specifications. Figure 16 – Object Detection Workflow To start the process, we have to get a usable input, meaning we have to label data with the classes we want to detect (e.g. knife, face mask…), which will be explained in more detail ahead. Having the correct input, we call directly the split_traintest.py to separate our data into two datasets, one for training and the other for testing later. Then we run the train_ssd.py script, with the selected pre-trained model and subsequent specifications. When the training concludes we check the detection accuracy of our model for each class by calling the eval_ssd.py. With the output, we evaluate if the model is ready to be exported and tested or if we need to retrain it with more data labeled with a specific class or even with a different pre-trained model, the accuracy benchmark is 70% for each class detection. Finally, if the accuracy is over our minimum benchmark, we call the onnx_export.py, which will give us a .onnx file containing the model ready to be tested with the run_ssd_example.py, where we confirm if our model detects anything in a set of random images. After we confirm detections, the model is stored in our VM and sent to the Jetson Nano, to run on the live CCTV feed connected to that machine.
23 4.1.2. Scripts As mentioned above, in the training process with PyTorch we use 5 scripts: • split_traintest.py • train_ssd.py • eval_ssd.py • onnx_export.py • run_ssd_example.py The first is the split_traintest.py, which is a Python script that splits annotated images into training, validation, and test datasets. The script uses the ArgumentParser module to allow the user to input the path to the annotations directory and the images split text output directory. The Path() object is used to format the input paths according to the operating system being used. The os module's listdir function is used to get a list of all the files in the annotations directory. The names of the files are then extracted, split into training and test datasets using the ‘train_test_split’ function from scikit-learn, and written to separate text files in the images split txt output directory. ### split the whole dataset to train and test: 8:2 from sklearn.model_selection import train_test_split X_train, X_test = train_test_split(name_list, test_size=0.20, random_state= 1) ### write the names to sperate txt files: train_val and test train_list = open(train_filename,'w') for element in X_train: train_list.write(element) train_list.write('\n') train_list.close() test_list = open(test_filename,'w') for element in X_test: test_list.write(element) test_list.write('\n') test_list.close() With the input data for the train_ssd.py script, the train can begin. This is a script for training and evaluating a single-shot multi-box detection model using the PyTorch deep learning framework. It supports several base architectures (VGG-16, MobileNet-V1, MobileNet-V2) and allows for training on different datasets (PASCAL VOC, OpenImages). The script covers the following steps: 1. Setting up logging and command line argument parsing. 2. Loading datasets and defining data loaders. 3. Defining the base architecture and customizing it with the desired parameters. 4. Setting up the loss function and optimizer. 5. Initializing the model and running training and evaluation. 6. Logging training statistics using TensorBoard. This script uses several libraries such as argparse, torch, and torchvision. The argparse module is used to define command-line arguments for various hyperparameters and settings, and once these hyperparameters and settings are defined, the script will train the detector according to those specifications.
24 Table 2 – The train_ssd.py arguments The ‘train()’ is the function that trains a deep learning model on an object detection task. The input includes a data loader, a network model, a loss criterion, an optimizer, and a device (GPU in this case is). During each iteration, the gradients of the model parameters are computed and updated using the optimizer. The running loss, regression loss, and classification loss are computed and logged every "debug_steps" iterations. The TensorBoard scalar values for the average loss, average regression loss, and average classification loss are also recorded. Additionally, the network graph is added to TensorBoard after the training is completed. def train(loader, net, criterion, optimizer, device, debug_steps=100, epoch =-1): net.train(True) running_loss = 0.0 running_regression_loss = 0.0 running_classification_loss = 0.0 for i, data in enumerate(loader): images, boxes, labels = data images = images.to(device) boxes = boxes.to(device) labels = labels.to(device) optimizer.zero_grad() confidence, locations = net(images) regression_loss, classification_loss = criterion(confidence, locati ons, labels, boxes) # TODO CHANGE BOXES loss = regression_loss + classification_loss loss.backward() optimizer.step() running_loss += loss.item() running_regression_loss += regression_loss.item() running_classification_loss += classification_loss.item() if i and i % debug_steps == 0: avg_loss = running_loss / debug_steps avg_reg_loss = running_regression_loss / debug_steps avg_clf_loss = running_classification_loss / debug_steps logging.info( f"Epoch: {epoch}, Step: {i}/{len(loader)}, " + f"Avg Loss: {avg_loss:.4f}, " + f"Avg Regression Loss {avg_reg_loss:.4f}, " + f"Avg Classification Loss: {avg_clf_loss:.4f}" )
25 running_loss = 0.0 running_regression_loss = 0.0 running_classification_loss = 0.0 tb.add_scalar('Train_Loss', avg_loss, epoch) tb.add_scalar('Train_Regression_Loss', avg_reg_loss, epoch) tb.add_scalar('Train_Classification_Loss', avg_clf_loss, epoch) tb.add_graph(net, images) Then the ‘test()’ function is used to evaluate the performance of the object detection model. It sets the network to evaluation mode by calling ‘net.eval()’, and then calculates the loss on the validation dataset. The function loops over the validation data and calculates the loss, regression loss and classification loss. The loss is calculated by calling the ‘criterion’ function and passing it the network's output, ‘confidence’ and ‘locations’, along with the ground truth ‘labels ‘and ‘boxes.’ The loss is accumulated for each batch and divided by the number of batches to obtain the average loss for the entire validation dataset. def test(loader, net, criterion, device): net.eval() running_loss = 0.0 running_regression_loss = 0.0 running_classification_loss = 0.0 num = 0 for _, data in enumerate(loader): images, boxes, labels = data images = images.to(device) boxes = boxes.to(device) labels = labels.to(device) num += 1 with torch.no_grad(): confidence, locations = net(images) regression_loss, classification_loss = criterion(confidence, lo cations, labels, boxes) loss = regression_loss + classification_loss running_loss += loss.item() running_regression_loss += regression_loss.item() running_classification_loss += classification_loss.item() return running_loss / num, running_regression_loss / num, running_class ification_loss / num At the end of the function, it returns the average of the total loss, average regression loss, and average classification loss. The next step is to evaluate the model’s precision with the eval_ssd.py script. It has two functions, the first one is the ‘group_annotation_by_class()’, which is the function that groups the annotations in the dataset, loops over all of those annotations and extracts information such as the ground-truth bounding boxes, the class labels, and whether the annotation is considered difficult or not. The extracted information is then stored in three dictionaries: ‘true_case_stat’, ‘all_gt_boxes’, and ‘all_difficult_cases’. The ‘true_case_stat’ dictionary stores the number of true (i.e.,
26 non-difficult) cases for each class. The ‘all_gt_boxes’ dictionary stores the ground-truth bounding boxes for each image and class, and the ‘all_difficult_cases’ dictionary stores the difficulty status for each annotation for each class and image. Finally, the function converts the lists of bounding boxes and difficulties into tensors and returns the three dictionaries. Then it runs the second function on this script, the compute_average_precision_per_class(), which is the function that computes the average precision of object detection. The input arguments include: • ‘num_true_cases’: a dictionary with class index as key and number of true positive cases for that class as value. • ‘gt_boxes’: a dictionary with class index as key and for each class, a dictionary of image IDs and their corresponding ground truth bounding boxes. • ‘difficult_cases’: a dictionary with class index as key and for each class, a dictionary of image IDs and the corresponding ground truth "difficulty" labels. • ‘prediction_file’: a file containing the model predictions, with each line having the format ‘image_id\tscore\tbox_coordinates’. • ‘iou_threshold’: the Intersection over Union (IoU) threshold used to determine a true positive match between a prediction and ground truth. • ‘use_2007_metric’: a flag indicating whether to use the 11-point interpolation method (VOC 2007) or not. The function first reads the prediction file and stores the image IDs, boxes, and scores in separate lists, sorted by score in descending order. Then, for each prediction, it finds the corresponding ground truth box (if there is one) and computes its IoU with the prediction. If the IoU is above the threshold, the prediction is considered a true positive, unless the ground truth is marked as "difficult". The true and false positive counts are accumulated as the loop progresses and are used to compute precision and recall. Finally, the average precision is computed using either the VOC 2007 method (if ‘use_2007_metric’ is set) or the standard method. def compute_average_precision_per_class(num_true_cases,gt_boxes, difficult_cases, prediction_file, iou_threshold, use_2007_metric): with open(prediction_file) as f: image_ids = [] boxes = [] scores = [] for line in f: t = line.rstrip().split("\t") image_ids.append(t[0]) scores.append(float(t[1])) box = torch.tensor([float(v) for v in t[2:]]).unsqueeze(0) box -= 1.0 boxes.append(box) scores = np.array(scores) sorted_indexes = np.argsort(-scores) boxes = [boxes[i] for i in sorted_indexes] image_ids = [image_ids[i] for i in sorted_indexes] true_positive = np.zeros(len(image_ids))
27 false_positive = np.zeros(len(image_ids)) matched = set() for i, image_id in enumerate(image_ids): box = boxes[i] if image_id not in gt_boxes: false_positive[i] = 1 continue gt_box = gt_boxes[image_id] ious = box_utils.iou_of(box, gt_box) max_iou = torch.max(ious).item() max_arg = torch.argmax(ious).item() if max_iou > iou_threshold: if difficult_cases[image_id][max_arg] == 0: if (image_id, max_arg) not in matched: true_positive[i] = 1 matched.add((image_id, max_arg)) else: false_positive[i] = 1 else: false_positive[i] = 1 true_positive = true_positive.cumsum() false_positive = false_positive.cumsum() precision = true_positive / (true_positive + false_positive) recall = true_positive / num_true_cases if use_2007_metric: return measurements.compute_voc2007_average_precision(precision, re call) # 11 point interpolation for average precision else: return measurements.compute_average_precision(precision, recall) The argsparse input hyperparameters and settings for this script. Table 3 – eval_ssd.py arguments If the precision across all classes is over 70%, the model is ready to be exported, tested, and sent to the team that will test the inference in the store’s CCTV live feed with the Jetson Nano. To export the file there is the onnx_export.py script. This script converts the trained PyTorch object detection model to ONNX format. It uses the ‘torch.onnx’ module for the conversion and ‘argparse’ for parsing the command-line arguments of network architecture, input and output paths, labels file, input dimensions, and batch size. The script sets the device to use CUDA if available and specified by the user, otherwise it uses the CPU.
28 The script supports multiple network architectures, including VGG16, MobileNet v1, MobileNet v1 Lite, SqueezeNet Lite, and MobileNet v2 Lite. It formats the input model paths and automatically selects the checkpoint with the lowest loss if an input path is not specified, determines the number of classes by counting the lines in the labels file, constructs the network architecture based on the specified architecture argument, then loads the PyTorch model checkpoint, converts it to ONNX format, and saves it to the specified output path. Table 4 – onnx_export.py arguments The last script of this model train workflow is the run_ssd_example.py, which is the inference test of the object detection model. The script loads the input images and the label file and creates a list of image paths. After that, it chooses the network architecture based on the provided "--net" argument and creates the corresponding SSD network, then it loads the trained model weights and runs object detection on each image in the ‘images_paths’ list. The output of the detection is the images with the bounding boxes around the detected objects, which are saved in the specified ‘output_images_dir’. Table 5 - run_ssd_example.py arguments 4.1.3. Model train step guide The whole model train workflow with PyTorch can be resumed to a few steps. Before running the scripts and assuming that there already is a VOC PASCAL annotations dataset, we start by accessing the GPU machine (Azure virtual machine with 4 GPUs) with MobaXterm. ssh everisai@**.***.***.** password: *********
29 Next we activate the ‘opencv’ environment with a conda command. It allows to use a specific version of the library in isolation from the rest of our system. After executing this command, we should be able to run the scripts that use OpenCV. conda activate opencv Then we run a command to start a PyTorch Docker container using the Nvidia GPU acceleration and map the host directory, where we have stored the annotations dataset and the scripts, to the container directory. sudo nvidia-docker run --ipc=host --gpus all -it --rm -v /home/everisai/pyt hon/:/python nvcr.io/nvidia/pytorch:21.05-py3 The ‘--ipc=host’ flag is used to share the host inter-process communication namespace with the container, allowing it to access the host's GPU devices, the ‘--gpus all’ flag specifies that all available GPUs should be used, the ‘-it’ starts the container in interactive mode and the ‘—rm’ automatically removes the container when it exits. The ‘nvcr.io/nvidia/pytorch:21.05-py3’ is the image name for the PyTorch environment with the CUDA version. The next step is to install the libraries that we need and are missing from the container. pip install torch==1.7.0+cu110 torchvision==0.8.1+cu110 torchaudio===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html The command will install (outdated versions used by the time of this project) PyTorch version 1.9.0, torchvision 0.8.1 and torchaudio 0.7.0. The ‘+cu110’ indicates that these packages are built with CUDA 11.0 support, which requires an Nvidia GPU. The ‘-f’ option allows you to specify the official PyTorch repository for stable releases URL from which to download the package. Then we set the directory to the scripts folder and start to run them. cd /python/training/detection/model_v1.0 Inside the container we start by running the train_ssd.py script. The split_traintest.py is ran in our local machines and then the separated data is imported into the container. python3 train_ssd.py --net=vgg16-ssd --dataset-type=voc --pretrained-ssd=mo dels/vgg16-ssd-mp-0_7726.pth --data=data/ --model-dir=models/vgg16/ --batch -size=30 --workers 1 --learning-rate=0.001 --base-net-lr=0.001 --epochs 100
30 The command runs the training script for the object detection model using the architecture with the VGG16 backbone. The model is set to use a batch size of 30, a learning rate of 0.001, and is trained for 100 epochs. I specified the use of a single worker for training with the ‘--workers 1’. This argument is used to specify the number of worker threads to use for data loading, which can help speed up the training process by loading data in parallel with the training process. The next step is the evaluation of the object detection model with the eval_ssd.py script. The evaluation script will use the specified SSD architecture (vgg16-ssd), the trained model and the dataset to evaluate the model's precision across all classes. python3 eval_ssd.py --net vgg16-ssd --dataset data/ --trained_model models/ vgg16/vgg16-ssd-Epoch-93-Loss-2.5332502018321645.pth --label_file models/ l abels.txt If the model has an acceptable precision, it is exported with the onnx_export.py script. python3 onnx_export.py --model-dir=models/vgg16 Then we run the trial implementation with the run_ssd_example.py script. python3 run_ssd_example_WY.py vgg16-ssd models/vgg16/vgg16-ssd-Epoch-93-Los s-2.5332502018321645.pth models/vgg16/labels.txt data/JPEGImages If there is confirmation of correct detections in the test images, the model moves to the inference process. 4.1.4. Limitations This solution works and has positive results, but it also has limitations that can become liabilities for this project. The main problem here was that the time it takes an immense amount of time to fully run the train_ssd.py script. Each train attempt with a dataset of approximately 30 thousand annotations took between 15 and 16 hours. Figure 17 – train_ssd.py running log
31 That time was not ideal since each hour of VM usage has its associated cost, and those costs were over the budget, which raised a financial liability. With this code, we were only able to train our model with one CUDA card at a time, but since our VM machine has four available GPU cards there is a possibility of using multiple cards to run the same script. My challenge here is to change the workflow and enable the multi-GPU model training. That will be accomplished with the NVIDIA Transfer Learning Toolkit since it is compatible with our hardware, has a lot of architectural frameworks flexibility, and has a multi-GPU selection feature which in theory will accelerate the whole process. 4.2. TRANSFER LEARNING TOOLKIT DEMO The first step to implement the NVIDIA Transfer Learning Toolkit is to install and configure an NGC Catalog account (NVIDIA GPU Cloud). This catalog is a curated set of GPU-optimized software for AI, HPC and Visualization. NGC offers a diverse collection of containers, including deep learning frameworks, that bundle software applications, libraries, dependencies, and run-time compilers in a self-contained environment for seamless deployment across different computing environments, facilitating software portability and enabling easy scaling of applications across the cloud, data center, and edge environments with a single command [16]. Then I had to create an NGC account in https://catalog.ngc.nvidia.com/ and get an API $KEY that it can be generated in the account options. Having the previous step concluded, I am able to fetch and start any NGC container. In the TLT collection, there’s a detailed overview that goes through of what it is, how it works, where to get started. After studying the TLT available options, I settled for the Transfer Learning Toolkits For Streaming Video Analytics container. The next step was to fetch the container from NGC onto the GPU instance, and that is done by running a provided docker command on the VM terminal. Figure 18 – TLT page on the NGC catalog for video streaming [16]
38 bbox_rasterizer_config { target_class_config { key: " balaclava " value { cov_center_x: 0.5 cov_center_y: 0.5 cov_radius_x: 0.40000000596 cov_radius_y: 0.40000000596 bbox_min_radius: 1.0 } } target_class_config { key: " knife " value { cov_center_x: 0.5 cov_center_y: 0.5 cov_radius_x: 1.0 cov_radius_y: 1.0 bbox_min_radius: 1.0 } } Having these changes listed and understood, everything was ready to run the tlt-train feature. tlt-train detectnet_v2 -e $SPECS_DIR/detectnet_v2_train_resnet18_kitti.txt \ -r model_unpruned \ -k $KEY \ -n resnet18_detector \ --gpus $NUM_GPUS After the train is completed, I can evaluate the model’s accuracy on each class. tlt-evaluate detectnet_v2 -e $SPECS_DIR/detectnet_v2_train_resnet18_kitti.t xt\ -m model_unpruned/weights/resnet18_detector.tlt \ -k $KEY The tlt-evaluate detectnet_v2 command is used to evaluate a trained model using the detectnet_v2 architecture. The -e flag is specifying the path to the evaluation configuration file, is the same used for the training process, the -m flag is specifying the path to the trained model, and the -k flag is the access key which has to be the same used for the train process. As of this step, I have a trained model and its detection accuracy. It already can be exported for testing purposes, but before that, there is the optional step of prune the model. Model pruning is the process of removing unnecessary parameters from a trained model in order to reduce its size and computational requirements. Pruning a model with TLT is done using the prune command, but first I must create a new directory to store the pruned model: mkdir -p model_pruned
39 And now the TLT model prune command: tlt-prune -m $USER_EXPERIMENT_DIR/model_unpruned/weights/resnet18_detector. tlt \ -o $USER_EXPERIMENT_DIR/model_pruned/resnet18_nopool_bn_detectne t_v2_pruned.tlt \ -eq union \ -pth 0.8 \ -k $KEY Here, the -eq flag is specifying the pruning method: in this case, it is 'union', a method that removes the weights with the lowest absolute. The -pth flag is specifying the pruning threshold: in this case the suggestion is to use 0.8, which means that only the weights that are below 0.8 will be pruned but later I can adjust for accuracy and model size trade off. A higher pth gives higher inference speed but worse accuracy. Now, the pruned model must be retrained. tlt-train detectnet_v2 -e $SPECS_DIR/detectnet_v2_retrain_resnet18_kitti.tx t \ -r $USER_EXPERIMENT_DIR/model_retrain \ -k $KEY \ -n resnet18_detector_pruned \ --gpus $NUM_GPUS This command is like the previous one, but to run the retrain there’s the need to specify a different specifications file, which is very similar to the train file. The --gpus and -k input must be the same used in the train process. When the retrain process is finished, I can re-evaluate the model. tlt-evaluate detectnet_v2 e $SPECS_DIR/detectnet_v2_retrain_resnet18_kitti. txt \ -m $USER_EXPERIMENT_DIR/model_retrain/weights/re snet18_detector_pruned.tlt \ -k $KEY After concluding these steps, I have a .tlt file, and to test if it properly detects the intended classes I can run the TLT inference feature in a data sample with at least 8 images and see if there is any detection. tlt-infer detectnet_v2 -e $SPECS_DIR/detectnet_v2_inference_kitti_tlt.txt \ -o $USER_EXPERIMENT_DIR/tlt_infer_testing \ -i $DATA_DOWNLOAD_DIR/test_images \ -k $KEY
40 This command will perform inference on a trained model using the .tlt file on the input images located in the directory specified by the -i flag and save the inference output to the directory specified by the -o flag. Same as before, the specifications file is already set to work with this data and these classes, but looking at it I could identify that besides the class names I also will have to change the inference dimensions to match what the model was trained for. # Inference dimensions. image_width: 960 image_height: 544 Looking into the tlt_infer_testing files, I confirmed that the model was detecting both classes properly. Figure 20 – TLT inference with mask/no mask demo model [18] Finally the next and last step is to export the file to .etlt format. In summary, the .tlt format is used to store the model's architecture, weights, and other metadata and it can be used for both training and inference while the .etlt format is an optimized format for deployment and inference and it can be used only for inference. tlt-export detectnet_v2 \ -m experiment_dir_retrain/weights/resnet18_detector_pruned.tlt \ -o experiment_dir_final_pruned/resnet18_detector_pruned.etlt \ -k $KEY
41 Now the model is ready for deployment, and I can move on to the next phase and apply these TLT features with our data and detect a different set of classes. 4.3. DATA PREPARATION 4.3.1. KITTI Conversion This is the final step to fully integrate our data with the TLT features. The TLT train process only works if the input data is in KITTI format, which is not possible to export directly from CVAT, so I need to export the data in VOC PASCAL which gives me the annotations files in .xml, and then convert to KITTI with a script. To fulfill this task, I cloned a github repository ( https://github.com/krustnic/xml2kitti ) with that same purpose and created some extra features to customize the code according to our necessities. Another TLT train specification is that all images in the dataset have to be the same size, so if in the configuration file I set the width to 960 and the height to 544, all images must have that exact same dimensions. path = r'…/JPEGImages' c=0 for file in os.listdir(path): f_img = f+"/"+file img = Image.open(f_img) img = img.resize((height,width)) img.save(f_img) c+=1 print(f'{c} resized images') This code uses the Python imaging library (PIL) to resize the set of images located in a directory. The first line assigns the path of the directory containing the images to the variable ‘path’ then it initializes a variable ‘c’ to zero, which will be used to keep track of the number of resized images. In the for loop, the ‘os.listdir(path)’ function is used to list all the files in the directory specified by the ’path’ variable. The loop iterates through each file in the directory. For each iteration, the code opens the file using the PIL's ‘Image.open()’ function and assigns it to the variable 'img'. Then it uses the ‘.resize()’ method on the 'img' variable to resize the image to the given 'height' and 'width' size. Then it saves the resized image to the same file using the ‘.save()’ method. Finally, the 'c' variable is incremented by 1 for each iteration of the loop, to keep track of the number of resized images. At the end of the loop, the code prints the total number of resized images. The xml2kitti.py successfully converted most of the files. The output was sent into the same folder of the input and there were some conversion exceptions, raising the issue of having more images than KITTI annotations, which must be the same number. To solve this problem first I added a file moving
42 function to move the output to another directory ('.../Annotations_kitti') and a file remover function to remove the images without a corresponding KITTI annotation. dest_dir = '.../Annotations_kitti' for file in glob.glob('.../Annotations/*.txt'): shutil.move(file, dest_dir) In this code snippet I use the python 'glob' and 'shutil' libraries to move a set of files from one directory to another. The first line assigns the path of the destination directory to the variable 'dest_dir'. The for loop uses the 'glob' library function 'glob.glob()' to search for all the files in the directory '.../Annotations/' that have the '.txt' extension and then it iterates through each file found. For each file, the code uses the 'shutil' library function 'shutil.move()' to move the file from its current location to the destination directory specified by the 'dest_dir' variable. kitti_list=[] c=0 for file2 in os.listdir(".../Annotations_kitti"): name2 = file2.rsplit('.',1)[0] kitti_list.append(name2) for file in os.listdir(".../JPEGImages"): name1 = file.rsplit('.',1)[0] filename = ".../JPEGImages/"+file if name1 not in kitti_list: os.remove(filename) c+=1 print(f'Removed-------{file}') print(f'Removed {c} files') Here I use python's os library to remove a set of files from a directory based on a comparison with the files in another directory. The variable 'c' will be used to keep track of the number of removed files, and the 'kitti_list' will have the names of all the KITTI files, which are added in the first loop using the ‘os.listdir()’ function to list all the files in ".../Annotations_kitti" and iterates through each file in the directory. For each file, I apply the ‘.rsplit()’ function to remove the file extension and append the name to the variable 'kitti_list'. The second for loop uses the ‘os.listdir()’ function to list all the files in the image directory (".../JPEGImages") and iterates through each file in the directory. For each file, I again apply the ‘.rsplit()’ function to remove the file extension and assign the name of the file to the 'name1' variable to then compare it to the names in the ‘kitti_list’, if is not found I apply the ‘os.remove()’ to delete the image file and increment the ‘c’ variable by 1. By the end, to apply these changes I just need to run the following in the prompt. python3 xml2kitti.py .../Annotations
43 4.3.2. Annotations and Folder Structure The first step of this segment is the labeling process in CVAT. We start by running the docker CVAT image and access through the http://localhost:8080/ on google chrome. Next I have to create a new task, name it, add the labels that will be the classes in the exported annotations, upload the images to be labeled and manually select in the image the objects associated to the labels. Figure 21 – CVAT Annotation example After finishing the label process in all images there is an export option to dump all the annotations in PASCAL VOC format into a folder. That folder will be the one used to convert the files to KITTI and import the data for the model training, but there are some necessary changes to have the folder in the right structure. The dumped folder is composed by the following: • Labels ‘.txt’ file • ‘Annotations’ folder • ‘ImageSets’ folder For the desired structure I must do these changes: • Insert the images folder with the name ‘JPEGImages’. • Rename the labels file to ‘labels’. • In the labels file, delete everything except the classes names and I also need to make sure that there are not any empty lines. • Delete the ‘ImageSets’ folder. • Create an empty folder named ‘Annotations_kitti’. By the end of these changes the desired folder structure should look like this.
44 |---Annotations | image_name.xml | ........... | ........... | |---Annotations_kitti | (empty) | |---JPEGImages | image_name.jpeg | ........... | ........... | |---labels.txt 4.4. TRAINING With the annotations in KITTI format I finally can use the TLT features. The first data batch is composed of close to 30000 annotations of two classes, balaclava, and knife. The main goal here is to apply the train feature and guarantee a lower training time with the multiple gpus option and still maintain an acceptable precision (>70%). Before the whole process, download the tlt_specs folder from the NVIDIA demo to my local machine and adjust the configuration files as listed above. The docker image directory name will be "train_tlt", so the data sources change must be according to that, set the target classes names to “balaclava” and “knife”, select the output image width and height to 1280 and 720 respectively (the resolution of the input images) and to reduce the train time I can set number of training epochs to 100. Having done these changes on all files I can start the process steps according to the NVIDIA demo. First, pull the docker TLT container. docker pull nvcr.io/nvidia/tlt-streamanalytics:v2.0_py3 Run the docker image with the name “train_tlt”. docker run --gpus all -it -v "/path/to/dir/on/host/":"train_tlt" \ -p 8888:8888 nvcr.io/nvidia/tlt-streamanalytics:v2.0_py3 /bin/bash The path on host we should apply is the one where the TLT specifications files and the annotations are. For this first run I am going to select the same architecture framework used in the demo, the Detectnet_v2 and the pretrained model will be the Resnet18. Later, when the process is fully working, I can test another frameworks and models and tune it to optimize the detection.
45 With the docker image created and the necessary data there, I must convert the tf records from the KITTI annotations. tlt-dataset-convert -d tlt_specs/detectnet_v2_tfrecords_kitti_trainval.txt - o /train_tlt/tfrecords/kitti_trainval/ After confirming that the records are in the output directory, I need to create a target destination folder and download the pretrained model. mkdir pretrained_resnet18 ngc registry model download-version nvidia/tlt_pretrained_detectnet_v2:resn et18 \ --dest pretrained_resnet18 Next, open the detectnet_v2_train_resnet18_kitti.txt to confirm that everything is correctly set to run the TLT train feature. After guarantee that the specifications are correct, I can train the model with my data. First, I am going to use 2 gpus and compare the total training time with the performance I got using just 1. The previous train time was around 15h-16h. tlt-train detectnet_v2 -e tlt_specs/detectnet_v2_train_resnet18_kitti.txt \ -r model_unpruned \ -k $KEY \ -n resnet18_detector \ --gpus 2 Figure 22 – TLT running log As observed in the figure above, the time it took to complete the model training was 5 hours and 22 minutes, which reduces by 10 hours the model train time and fulfills the main goal of this implementation. Now I will directly prune and retrain the model and after that evaluate and try to test the inference on some test images. I will create a different directory for the pruned model and then run the tlt-prune feature. mkdir model_pruned tlt-prune -m model_unpruned/weights/resnet18_detector.tlt \ -o model_pruned/resnet18_nopool_bn_detectnet_v2_pruned.tlt \ -eq union \ -pth 0.01 \ -k $KEY
46 After the model prune the model must be retrained. tlt-train detectnet_v2 -e tlt_specs/detectnet_v2_retrain_resnet18_kitti.txt \ -r model_retrain \ -k $KEY \ -n resnet18_detector_pruned \ --gpus 2 Again, the time of retrain is around the 5 hours mark. Now I run the evaluation and check the model’s detection quality. tlt-evaluate detectnet_v2 -e tlt_specs/detectnet_v2_retrain_resnet18_kitti. txt \ -m model_retrain/weights/resnet18_detector_pruned.tlt \ -k $KEY Figure 23 – Trained model 2 class precision The results are very promising, we can observe that the balaclava classes detection precision is very good and well above the 70%, which is not the case for the knife detection which is quite understandable since a knife is much more difficult to detect. Although the knife precision is not ideal, is very close to the minimum necessary and the precision across all classes meets the requirements, so I can proceed to the inference test phase and depending on the results I decide if this model will be exported and tested in loco or if it needs to be improved immediately. With this thought, I will run the inference command to generate detections on some random images that I have put together and imported to the docker image. tlt-infer detectnet_v2 -e train_tlt/detectnet_v2_inference_kitti_tlt.txt \ -o tlt_infer_testing \ -i test_images \ -k $KEY Looking to the output, I confirm that the results are satisfactory and in fact detection is running accordingly the expectations.
47 Figure 24 – Tlt inference test Has observed the values associated to the detections are according to the tlt-evaluation results. Since these results demonstrate that the model can in fact detect I will export and share with the local team to test it in the client’s premises. To do so, I apply the export command. mkdir -p model_final_pruned tlt-export detectnet_v2 \ -m model_retrain/weights/resnet18_detector_pruned.tlt \ -o model_final_pruned/resnet18_detector_pruned.etlt \ -k $KEY The .etlt file is the final product of the whole process and is what I will share with the inference team.
54