Full text
Bachelor’s degree in Mathematics Bachelor’s degree in Data Science and Engineering Computer vision techniques to improve micromobility safety Pau Fabregat Fabregat Supervised by Josep Ramon Morros Rubió Co-directed by Laia Pagès Giralt CARNET Barcelona February, 2023
ii
Abstract [en] The use of micromobility vehicles, namely electric scooters or bicycles, has experienced an upsurge in metropolitan areas. These vehicles share the lane with pedestrians, cars, and other users. Safety is a must for all of them. Computer vision techniques such as object detection, object tracking, and lane-type classification can make a huge difference and prevent crashes. This project proposes a multitask neural network integrating the state-of-the-art models YOLOv5, YOLOv7, and Strong- SORT, trained to detect and track road objects and classify the lane type in real-time. The device in charge of these predictions is a mobile phone attached to the vehicle; therefore, the model is quantized and pruned to reduce computation requirements. [ca] L’ús de vehicles de micromobilitat, concretament de patinets elèctrics o bicicletes, ha experimentat un auge a les àrees metropolitanes. Aquests vehicles comparteixen el carril amb vianants, cotxes i altres usuaris. La seguretat és imprescindible per a tots ells. Les tècniques de visió per computador com la detecció d’objectes, el seguiment d’objectes i la classificació del tipus de carril poden marcar una gran diferència i prevenir accidents. Aquest projecte proposa una xarxa neuronal multitasca que integra els models d’última generació YOLOv5, YOLOv7 i StrongSORT, entrenada per detectar i fer el seguiment d’objectes de la carretera i classificar el tipus de carril en temps real. L’aparell encarregat d’aquestes prediccions és un telèfon mòbil acoblat al vehicle; per tant, el model es quantifica i es poda per reduir els requisits de càlcul. [es] El uso de vehículos de micromovilidad, concretamente patinetes eléctricos o bicicletas, ha experimentado un auge en las áreas metropolitanas. Estos vehículos comparten el carril con peatones, automóviles y otros usuarios. La seguridad es imprescindible para todos ellos. Las técnicas de visión por computadora, como la detección de objetos, el seguimiento de objetos y la clasificación del tipo de carril, pueden marcar una gran diferencia y evitar accidentes. Este proyecto propone una red neuronal multitarea que integra los modelos de última generación YOLOv5, YOLOv7 y StrongSORT, entrenada para detectar y rastrear objetos en la carretera y clasificar el tipo de carril en tiempo real. El dispositivo encargado de estas predicciones es un teléfono móvil acoplado al vehículo; por lo tanto, el modelo se cuantifica y se poda para reducir los requisitos de cálculo. Keywords: [en] micromobility, multitask neural networks, object detection, object tracking, image recognition, int8 quantization [ca] micromobilitat, xarxes neuronals multitasca, detecció d’objectes, seguiment d’objectes, reconeixement d’imatges, quantificació int8 [es] micromovilidad, redes neuronales multitarea, detección de objetos, seguimiento de objetos, reconocimiento de imágenes, cuantificación int8 Mathematics Subject Classification. 68T45. iii
iv
Contents 1. Introduction 1 1.1. Requirements and specifications . . . . . . . . . . . . . . . . . . . . . 2 1.2. Methods and procedures . . . . . . . . . . . . . . . . . . . . . . . . . 2 2. State of the Art 5 2.1. MultiTask Neural Networks . . . . . . . . . . . . . . . . . . . . . . . 6 2.2. ObjectDetection ............................. 7 2.2.1. R-CNN, Fast R-CNN, and Faster R-CNN . . . . . . . . . . . . 9 2.2.2. YOLO ............................... 11 2.2.3. YOLOv5 and multitasking approaches . . . . . . . . . . . . . 13 2.2.4. YOLOv7.............................. 15 2.3. Lane-type classification . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2.4. Objecttracking.............................. 19 2.4.1. SORT ............................... 22 2.4.2. DeepSORT............................. 23 2.4.3. StrongSORT............................ 24 3. Methodology 27 3.1. Objectdetection ............................. 27 3.2. Lane-type classification . . . . . . . . . . . . . . . . . . . . . . . . . . 28 3.2.1. Dataset............................... 28 3.2.2. YOLOv5 classification heads . . . . . . . . . . . . . . . . . . . 29 3.2.3. YOLOv7 classification heads . . . . . . . . . . . . . . . . . . . 31 3.3. Tracking.................................. 33 3.4. Quantization................................ 33 3.4.1. PyTorch quantization modes . . . . . . . . . . . . . . . . . . . 35 3.5. Trainingphase............................... 37 4. Results 41 4.1. Image classification results . . . . . . . . . . . . . . . . . . . . . . . . 41 4.2. Quantization savings . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 4.3. Inference examples and weak spots . . . . . . . . . . . . . . . . . . . 46 5. Conclusions and future development 49 v
vi
Introduction 1 1. Introduction As cities develop and grow, their inhabitants’ necessities suffer substantial changes. The way citizens move across cities is changing its pattern. One of the newest relevant actors is the electric scooter. These vehicles provide clean and cheap transport with low maintenance requirements. In the metropolitan area of Barcelona, the number of journeys by micromobility vehicles, including bicycles, has increased, between 2018 and 2021, at an average annual rate of 8.4% [1]. 2 019 2 020 2 021 −40 −30 −20 −10 0 10 20 30 Year Variation (%) Walking Micromobility Public transport Car Motorbike Figure 1: Interannual variation (%) of journeys in the Barcelona metropolitan area. As micromobility vehicles have to coexist with pedestrians and other means of transport and offer less protection to the driver, safety is an increasing concern. In Spain, 13 people died in 2021 in accidents involving electric scooters [2], more than doubling the six deaths in 2020. A total of 385 accidents were reported the same year, 83 of them severe. Out of the 13 deaths in 2021, falls caused 5 (traumatic brain injuries), collisions with other vehicles caused 5, and 3 were pedestrians run over by scooter drivers. Also, a study [3] conducted by in Barcelona showed that 38% of the users had ignored zebra crossings, and 35% had not respected traffic lights. Furthermore, in bike lanes, 35% had driven the wrong direction, and more than 90% had exceeded the speed limit at some point. Moreover, as no driving license is required to drive these vehicles, 40% of the users admitted not knowing the latest driving norm, and 13% admitted having been fined. Summing up, we must take driver’s security into account. This project proposes a multitask neural network capable of detecting possible hazards during driving (other vehicles, pedestrians, etc.) and informing the driver on whether its behavior (speed, lane type being used, etc.) is correct. This lightweight model runs on a mobile phone, and as architecture requirements have been optimized, this safety measure is available to anyone.
2 1.1 Requirements and specifications 1.1. Requirements and specifications This project has been developed inside CARNET Barcelona, a research hub participating in the RideSafeUM project by the EIT Urban Mobility, an initiative of the European Institute of Innovation and Technology, and co-funded by the European Union. The RideSafeUM project has developed a mobile app with multiple driving safety features (warnings on speeds or access bans and even accident identification). The model designed in this project can help widen and enhance these features. Previous theses conceived at CARNET have researched different but related topics on micromobility, such as using computer vision to analyze pavement damages [4] [5] or traffic signs [6], or investigating ways to assemble a multitask network [7]. The newest theses provided algorithms to detect the lane type from a smartphone camera [8] [9]. For this project, it was required to go further by creating a multitasking network with the following features: (i) Object detection. Detect pedestrians, different kinds of vehicles, and other items such as signs or traffic lights. Spotting entities close to the camera has higher priority than investing resources in detecting far objects from the background. (ii) Object tracking. Following nearby objects’ trajectories is crucial to avoid crashes. (iii) Lane-type classification. Different lanes mean different rules: knowing through which lane type we are driving provides us information to warn the driver about scooter driving bans and speed limits. (iv) Low resources requirements. The multitask network has to be designed and trained to be, in further stages, deployed on a mobile phone. As we try to reach the largest possible audience, the computation requirements of the model must fit in an average smartphone. 1.2. Methods and procedures The primary programming language used is Python (versions ≥3.8), with intense use of the open-source Torch machine learning library and its frameworks PyTorch and PyTorch Lightning, being the latest quite suitable for organizing the model training and test code in a structured and intuitive way. The YOLOv5 and YOLOv7 object detectors used for (i) are implemented using PyTorch, like the StrongSORT tracker for (ii). PyTorch also supports multiple types of quantization methods: dynamic, static, static-quantization-aware, and a new technique (still a prototype) named FX Graph Mode quantization. These methods will be pretty valuable for the aforementioned
Introduction 3 (iv) goal. A dataset created in the spring of 2022 will be used for training the models. This dataset contains almost 1500 labeled videos at 60 FPS with a recorded length of approx 10.5 hours. Each video belongs to a single class of these possible five: unidirectional bike lane, bidirectional bike lane, road, shared, and sidewalk. For simplicity, both bike lane types will be merged while training. The development of this thesis would not have been possible without the services provided by CALCULA Computing Services, a Slurm-managed server offered by the Universitat Politècnica de Catalunya.
10 2.2 Object Detection Fast R-CNN [27] was presented in 2015 by Ross Girshick, who was part of the team behind R-CNN. The main novelty of this upgrade is that, instead of forwarding each RoI through the ConvNet, the convolutional network (which admits several architectures) is fed with the whole image. Then the output is used to predict the candidate regions. As features are calculated just once, the speedup is noticeable: if we ignore the region proposal step, Fast R-CNN can process images almost in real-time [28]. This new version uses fully-connected layers with softmax function to predict objects’ classes instead of SVMs. A new issue is that, after the ConvNet, the feature map from which we propose regions has a smaller resolution than the original image due to max-pooling layers. As we have to pair boxes from before and after the ConvNet, the resulting bounding boxes can be slightly misaligned. Figure 7: Fast R-CNN architecture. Source: [26]. Faster R-CNN [28] addresses the slowness issue due to the region proposal phase, which is Fast R-CNN’s Achilles heel as it prevents any real-time inference. Ren et al. proposed a Region Proposal Network (RPN). One of its main characteristics is that n(tunable parameter) bounding boxes with different sizes and aspect ratios are suggested for each feature in the feature map. These kinds of bounding boxes are called anchor boxes. Figure 8: Different anchor boxes layouts. Source: [29].
State of the Art 11 After the RPN, Faster R-CNN uses RoI pooling and bounding box regression as its predecessor. The overall increase in both test and inference speed is notable: summing up all the detection phases, Faster R-CNN runs at 5 FPS on a K40 GPU. Figure 9: Faster R-CNN architecture. Source: [28]. 2.2.2. YOLO You Only Look Once (YOLO) [30] is a one-stage object detector released in 2015 by Redmon et al. and inspired by the GoogLeNet model. YOLO uses a single neural network to predict both the bounding boxes and the classes of the objects contained in an image. First, the input image is resized and divided into a S×Slattice. Then, for each cell, YOLO does the following: (i) Propose B(fixed number) bounding boxes candidates and compute the confidence for each one of these boxes. The authors define this confidence as Pr(Object)·IoUtruth pred . Notice that, during training, we know the annotated ground truth; in the test step, YOLO already knows many bounding boxes for each object class and uses this information to approximate their location. Hence, IoU is a helpful metric as the network output might differ slightly from this ‘ground truth’. (ii) Compute the object class probabilities Pr(Classi|Object), that is, the chances of each class having one of its objects in the cell, conditioned on actually framing an object (resulting in the class probability map from Figure 10). This conditioning implies that the loss functions will not penalize a wrong class prediction if there is no object in the cell. For instance, when authors evaluate YOLO on PASCAL VOC, S= 7 and B= 2 are used.
12 2.2 Object Detection When YOLO was released, it outperformed well-established models like R-CNN, but it did not achieve state-of-the-art accuracy in object detection. The main YOLO’s strength was its speed: 45 FPS and 63.4% mAP vs. Faster R-CNN’s 7 FPS and 73.2% (both computed on a Titan X GPU and on PASCAL VOC 2007). Figure 10: YOLOv1 model outline. Source: [30]. YOLOv2 (2016) [31], also called YOLO9000 because it can detect over 9000 object classes, presented some improvements to YOLOv1, such as implementing batch normalization or using Faster R-CNN’s notion of anchor boxes. Batch normalization (BN) [32] is a technique that makes neural networks’ training more robust, stable, and faster. The idea behind BN is to normalize each mini-batch’s values (by using its mean and variance) just before the activation functions. This way, we make minibatches less ‘different’ between them, reducing what is called the Internal Covariate Shift. Lastly, notice that the BN output values are of the form yi=γˆxi+β, where xiis the normalized value, and γand βare learnable scale and shift parameters. Figure 11: Batch normalization applied to an activation x. Source: [32]. YOLOv3 (2018) [33] and YOLOv4 (2020) [34] introduced new features and upgrades: multi-scale predictions, data augmentation, and changes in the architecture to make use of Spatial Pyramid Pooling (SPP) and better backbones.
State of the Art 13 2.2.3. YOLOv5 and multitasking approaches YOLOv5 [35] (2020) has become one of the most used object detection models. It’s implemented using PyTorch, and recent versions provide support for classification and image segmentation (in a single-task way). Furthermore, multiple pretrained model weights with various sizes are provided. The nano version uses just 1.9 million parameters, making it an excellent choice for edge devices and low resources gadgets. Previous YOLO versions did not offer such nano [33] versions. SizeF P 16 (MB) mAPval 50−90 mAPval 50 Params (M) GFLOPs YOLOv5n 4 28.0 45.7 1.9 4.5 YOLOv5s 14 37.4 56.8 7.2 16.5 YOLOv5m 41 45.4 64.1 21.2 49.0 YOLOv5l 89 49.0 67.3 46.5 109.1 YOLOv5x 166 50.7 68.9 86.7 205.7 Table 1: YOLOv5 pre-trained checkpoints summary, using images with a resolution of 640 ×640 px. Source: [35]. YOLOv5 achieved state-of-the-art performance on the MS COCO dataset. The Microsoft Common Objects in Context (MS COCO) [36] is a widely used dataset with more than 200 K labeled images and with almost a hundred object categories. Figure 12: The 91 object categories included in the COCO dataset. Source: [36]. Built upon YOLOv4 and YOLOv5, the first multitasking approaches using these object detection models are proposed, among which we can highlight YOLOP [37] and YOLOv5DS [38], both created explicitly for autonomous driving purposes. YOLO for Panoptic Perception (YOLOP) is a multitasking model capable of doing simultaneously, and in real-time, the following tasks: (i) Drivable area segmentation. (ii) Lane line detection. It uses the same architecture as (i). (iii) Object detection. The authors remark on the benefits of the single-stage gridbased approach and provide proof that it is more related and yields better results on the other two tasks than region-based approaches.
14 2.2 Object Detection YOLOP uses the same encoder for the three tasks. This hard parameter sharing structure makes the model faster and lighter: YOLOP can run at 23 FPS on a Jetson TX2. The encoder can be split up into a backbone (CSP-Darknet from YOLOv4) and a neck, being the Spatial Pyramid Pooling (SPP) a key part of the latter. The SPP [39] is a layer that bypasses the issue of a necessary fixed size input in CNNs, concretely the fully-connected layers. SPP gives a fixed-length representation of any feature map by pooling it in three different ways, each one with different sizes (thus, we can think of it visually as a ‘pyramid’): 1, 4, and 16. Then, these values, represented as d-dimensional arrays (dis the input depth), are concatenated, creating an (1 + 4 + 16) ×darray that feeds the fully-connected layers. Figure 13: YOLOP architecture. Source: [37]. Regarding the loss function for training, the authors selected a weighted sum of each task loss: Lall =γ1Ldet +γ2Lda−seg +γ3Lll−seg Where Ldet is the object detection loss (which is, at the same time, a weighted sum of losses), Lda−seg is the drivable area segmentation loss, and Lll−seg is the lane line segmentation loss. A critical component of the last two is the Cross-Entropy Loss, widely used for the image classification task. The authors compared every single task performance against the whole multi-task model performance. Results showed that using the joint model produced minimal decreases of just 0.4% AP in object detection, 0.5% mIoU (IoU for segmentation) in drivable area seg., and 1.7% IoU in lane line seg. The best part: the multi-task model did the three tasks in almost half the time it had taken if done separately, showing the usefulness of the shared backbone.
State of the Art 15 YOLOv5DS [38] works on a similar base, but using YOLOv5 for object detection instead of YOLOv4. Figure 14: YOLOv5DS architecture. Source: [38]. 2.2.4. YOLOv7 YOLOv7 [40] [41] was proposed in July 2022 by the same team who created YOLOv4. This new iteration introduces an improved architecture and efficient training methods that make this object detector achieve state-of-the-art performance. In addition, a total of seven model sizes are provided, being the lightest one the YOLOv7-tiny, built to be deployed in edge devices. Resolution mAPval 50−90 mAPtest 50 Params (M) GFLOPs YOLOv7-tiny 640 38.7 56.7 6.2 13.8 YOLOv7 640 51.2 69.7 36.9 104.7 YOLOv7-X 640 52.9 71.2 71.3 189.9 YOLOv7-W6 1280 54.6 72.6 70.4 360.0 YOLOv7-E6 1280 55.9 73.5 97.2 515.2 YOLOv7-D6 1280 56.3 74.0 154.7 806.8 YOLOv7-E6E 1280 56.8 74.4 151.7 843.2 Table 2: YOLOv7 versions summary. Resolutions for square images. Source: [40]. The standard YOLOv7 model is intended for normal GPU inference, while the W6 model is designed for cloud GPUs. Using compound scaling techniques, YOLOv7-X is obtained from vanilla YOLOv7, and the E6 and D6 models from YOLOv7-W6. Furthermore, using extended ELAN layers, YOLOv7-E6 becomes YOLOv7-E6E. The tiny version uses leaky ReLU as its activation function, while the others use SiLU (like YOLOv5).
16 2.2 Object Detection The goal of model scaling is to, starting from a raw model, develop new versions of it that fulfill different requisites. For instance, with model scaling, we can modify its width (channels number) or the number of layers (and their attributes) [42]. The authors propose a ‘compound model scaling’ to preserve the original model’s goodness and optimalities. Figure 15: Depth scaling can change the output width. YOLOv7 is prepared to handle issues like this thanks to the compound model scaling. Source: [40]. The Efficient Layer Aggregation Network (ELAN) and its extended version (E- ELAN) are key pieces of YOLOv7’s architecture. The authors use the nomenclature α-βELAN [41]: the core idea behind ELANs is to perform βconvolutional steps, and every αsteps send the result to the output. The results are then concatenated along with the original input. These computational blocks are widely used in all YOLOv7 versions: vanilla uses 2-4 ELANs (like the one in Figure 16) and 1-4 ELANs, while the tiny version only uses 1-2 ELANs. The extended E-ELAN layers are only used in YOLOv7-E6E. Figure 16: 2-4 Efficient Layer Aggregation Network (left) and the proposed E-ELAN (right). Source: [40]. YOLOv7 is also prepared for instance segmentation and human pose estimation. Both are trained on the respective MS COCO datasets, can run in real-time, and achieve almost state-of-the-art results.
State of the Art 17 Many of the improvements in this YOLO iteration come from exploiting its bag- of-freebies. This expression was first used in the YOLOv4 paper [34], and refers to various techniques that only enhance the training phase and thus provide increased accuracy models without extra time detection drawbacks. A quintessential example is data augmentation: increase the amount of the training data by diversifying it, that is, create new images by applying geometric distortions (rotating, zooming, flipping, cropping, etc.) and photometric distortions (de-texturizing, de-colorizing, edge enhancing, grayscaling, altering hue and contrast, etc.). Figure 17: Data augmentation example. Source: [43]. The YOLOv4 bag-of-freebies mainly includes data augmentation, techniques to address unbalanced classes, and a new loss function based on the IoU metric, replacing the regression method that computed the mean square error (MSE) of the height, width, and center of the predicted bounding boxes. YOLOv7 adds new features, such as auxiliary heads in the middle layers for deep supervision. As said, YOLOv7 achieves state-of-the-art accuracy and speed in the object detection task, outperforming other detectors in the YOLO family, such as YOLOX, YOLOR, and PPYOLO. Regarding the fifth version, YOLOv7-tiny (6.2 M params) beats YOLOv5s (7.2 params): 38.7% vs. 37.4% mAPval 50−90 resp., and 286 vs. 156 FPS resp. As for larger versions, YOLOv7-X (71.3 M params) and YOLOv5x (86.7 M params) achieve 52.9% vs. 50.7% mAPval 50−90 resp., and 114 vs. 83 FPS resp. on a GPU V100. 2.3. Lane-type classification The lane-type classification can be understood as a supervised image classification problem: we want to assign a single label to the whole image. Convolutional neural networks (CNN) have become the feature extractor par excellence for this task and are widely used in renowned models, namely AlexNet [25], VGGNet [44], GoogLeNet [45], or ResNet [46].
18 2.3 Lane-type classification Figure 18: Basic CNN concept. Source: [47]. Regarding models built for edge devices, some of the most prominent networks are the MobileNets family [48], ShuffleNet [49], and EfficientNet [50]. Some YOLO versions propose classification heads designed specifically for their architecture. It is the case with YOLOv5. Its classification head consists of the following layers: a 2D convolution with 1280 output channels (EfficientNet-b0 output size [50]) that preserves widths and heights (kernel-size=1, stride=1, padding=0), an Adaptive Average Pooling, which is basically a pooling layer in which we set the output size (1×1in this case) and the kernel-size and stride are automatically selected, and finally a fully connected layer. Figure 19: YOLOv5 classification head. Self-created diagram of the architecture described in: [35]. The YOLOv5 classification models are created by just locating the classification head at the end of the same backbone used for object detection. The authors trained these models along with ResNets and EfficientNets on the ImageNet dataset. Top1 Acc (%) Top5 Acc (%) Params (M) GFLOPs YOLOv5n-cls 64.6 85.4 2.5 0.5 YOLOv5s-cls 71.5 90.2 5.4 1.4 ResNet18 70.3 89.5 11.7 3.7 EfficientNet-b0 75.1 92.4 5.3 1.0 Table 3: Classification models comparison, using images with a resolution of 224 × 224 px. Only the lightest models are shown. Source: [35].
State of the Art 19 YOLOv5-cls does not achieve state-of-the-art results, although the small version overperforms ResNet18 with less than half of its parameters and GFLOPs. Notice that the YOLO classifier has not been designed deliberately for image classification but for object detection. EfficientNet-b0 beats YOLOv5s-cls by 3.6 and 2.2 points in top1 and top5 accuracy resp. despite being the latter slightly bigger. Remind that the top1 accuracy metric counts the percentage of correct predictions of the model, being the predicted label the one with the most probability. Contrastingly, top5 accuracy refers to the proportion of predictions in which the true label is among the five with higher probabilities. The classification head from YOLOv5 is also implemented in YOLOv7. Thus, it’s fully compatible, but no performance results on how the new architecture might improve accuracy are given in the YOLOv7 paper. A previous thesis [8], developed within the framework of the RideSafeUM EIT project, trained multiple lightweight image classifiers for the lane-type classification task using a dataset with four classes (bike lane, road, shared lane, and sidewalk). The model that achieved the best performance was ShuffleNet1, with 93.2% test accuracy and approximately 2 million parameters. 2.4. Object tracking Object detection algorithms can be used in video sequences by forwarding each frame through the model. We can further refine its results and provide new features using object tracking methods. Among its goals, we can highlight the following [51]: (i) Assign a unique identifier to each object. If the same item appears in multiple frames, it must have the same ID. (ii) Predict the future position of an object from its previous information. (iii) Address the issues of occlusions and interactions between objects, especially those quite similar in appearance. Limited image resolution, non-linear motion, or poor illumination must also be tackled. (iv) [For online trackers] Perform the previous tasks without heavily increasing the computational cost, as real-time inference is required. If the input video is running at a decent amount of FPS, it is common to skip some of these to improve the inference celerity. Object tracking models can be built upon either specifically designed backbones or well-known object detection backbones (e.g., from Faster R-CNN or YOLO). We will focus on two-dimensional Multiple Object Tracking (MOT) because Single Object Tracking (SOT) is designed to follow a unique target whose shape or aspect is generally known a priori [52].
26 2.4 Object tracking
Methodology 27 3. Methodology The designed multi-task model uses a hard-parameter sharing architecture with a common backbone for the different tasks. Through this chapter, we will look into the implementation details for each head: the object detection head (section 3.1.), the lane-type classification head (section 3.2.), and the tracker (section 3.3.), which strictly speaking is not a head but uses the same backbone for extracting features. Afterward, almost the entire model is quantized (section 3.4.). Figure 26: Designed multi-task model architecture. 3.1. Object detection The selected object detection models are YOLOv5 and YOLOv7. The main advantages of the first one are that its smaller version (YOLOv5n) has relatively fewer parameters than YOLOv7-tiny, concretely 1.9 M vs. 6.2 M. Also, the last layer of the classification head that we will use is the one proposed by YOLOv5, and although it is fully compatible with YOLOv7, the first version may provide better results. The leading reason for also choosing YOLOv7 is straightforward: it is the current state-of-the-art object detector.
28 3.2 Lane-type classification The authors trained the models using only the MS COCO dataset to obtain the pre-trained weights checkpoints. As seen in Figure 12, out of the 91 included object categories, we can consider 10 of them from 3 different groups as convenient for our purposes: person, vehicles (bicycle, car, motorbike, bus, train, and truck), and outdoor objects (traffic lights, street sign, and stop sign). We could also consider animals such as dogs or cats, but for the sake of simplicity, we do not take them into account. Thanks to the nano and tiny lightweights versions and the benefits of COCO-trained checkpoints, we can approach the multi-task challenge in the following manner: as backbone and object detection head, use (i) the ones from YOLOv5 or (ii) the ones from YOLOv7, both with their respective pre-trained weights. This way, the backbone is frozen for training the multi-task model, and only the classification head needs to be trained. Therefore, the training phase does not require a customlabeled dataset for object detection (which would need a certain amount of work to be created), or using images from COCO, or having to deal with a weighted sum of losses. Furthermore, the necessary resources for training, including time, are significantly reduced. 3.2. Lane-type classification The lane-type classification head is created using sequences of layers from the architectures of YOLOv5 and YOLOv7. The authors have chosen these modules for their models to fulfill the requirements of efficiency and remarkable performance. The final phase of the head is the classification layer proposed by YOLOv5 (see Figure 19). For instance, YOLOv5’s backbone uses a repeated sequence of C3+Conv modules. An example of a classification head would be a copy of these C3+Conv layers with their weights not initialized and with the classification layer at the end of this network. This thesis proposes and compares several classification heads for each object detector. 3.2.1. Dataset For training the classification head, a video dataset created in spring 2022 in the framework of the EIT RideSafeUM project [8] [9] is used. The videos were recorded in Barcelona using a smartphone’s camera tied to an electric scooter. The location information of each sequence was also stored. The original filming resolution and frequency are 1080 ×1920 px and 60 frames per second. Afterward, the videos were cropped into shorter sequences of approx 30 seconds and labeled into five different classes: unidirectional bike lane, bidirectional bike lane, road, sidewalk, and shared. For simplicity, both bike lanes are merged during the annotation phase into a single class called ‘bike lane’. Figure 27 shows a frame example for each category.
Methodology 29 Figure 27: From left to right: unidirectional bike lane, bidirectional bike lane, road, sidewalk, and shared lane. Regarding the balance between classes, their ratios are 35.1% bike lane, 16.8% road, 34.5% sidewalk, and 13.6% shared lane. The dataset is slightly unbalanced, but not enough to raise concerns. The multi-task model is fed with frames, not video files. The frames are obtained by sampling each video at 30 FPS. Each class has its own folder, which contains as many folders as videos, with all the frames for the same video in the same folder. Notice that each video represents one and only one class. If we lower the camera recording resolution from the mobile phone in which we deploy the model, we can prevent fast battery drains. Thus, the dataset images are also resized to a 320 ×640 px resolution. However, in-depth energy analyses are left for future development. 3.2.2. YOLOv5 classification heads YOLOv5 is prepared to use part of its architecture to perform the image classification task instead of object detection. This is done by simply removing the neck and heads and adding the classification layer at the end of the backbone. We propose three different classification heads: (i) The first head, v5/h1 (to be distinguished from the ones we use for YOLOv7), consists of two sequential Conv+C3 modules followed by the classification module. The convolutional layers use kernel-size=1, stride=1, and padding=0. These Convs are used in both the neck and the C3 modules. (ii) The second head, v5/h2, mirrors the same pattern as v5/h1. Instead, it uses Conv layers with kernel-size=3, stride=2, and padding=1. Thus, they gather more spatial information from the inputs than the ones used in v5/h1. These Convs are precisely the ones used in the backbone. (iii) The third head, v5/h3, adapts v5/h2 by adding or removing Conv+C3 depending on the input size to obtain a 20 ×20 ×1024 output, which is the default size for the classification layer. Before this last layer, an SPPF is included.
30 3.2 Lane-type classification Figure 28: YOLOv5x architecture. Notice that each model size of YOLOv5 has the same architecture. It is not the case for YOLOv7. Source: [61]. Each head is tested by taking different layers’ outputs from the backbone or the neck as inputs. Concretely, four locations are studied: after the first, second, third, and fifth C3 modules. The deeper we go, the more we use features pre-trained for object detection. YOLOv5 has a wrapper called AutoShape, which allows the model to be fed with various image sizes (dimensions must be divisible by 32). The proposed heads are trained with the 256×512 px (width×height) images. The model is also trained with resized 256 ×256 px square images to see whether there is a significant performance decrease.
Methodology 31 Figure 29: Proposed heads for the YOLOv5 architecture. Notice that v5/h3 depends on the input layer. 3.2.3. YOLOv7 classification heads The YOLOv7 object detector does not provide a custom classification module. Instead, the one from YOLOv5 is left as an option for implementing the image classifier. Figure 30 shows a general outline of YOLOv7’s vanilla version architecture. Compared to the tiny version, the latter uses only 1-2 ELANs and the backbone B2 blocks are replaced by MaxPool layers [41]. As with YOLOv5, the design of the proposed heads is closely related to the backbone structure. The suggested classification heads are the following: (i) Head v7/h1: a pair of MaxPools with 1-2 ELAN layers. (ii) Head v7/h2: the same as v5/h2. This allows us to compare the performance of the Conv+C3 blocks against MaxPool+ELAN. (iii) Head v7/h3: with similar purposes as v5/h3, and unlike v7/h1 and v7/h2, this head varies depending on which layer is attached to. The possible fork points are after the first, second, or third ELAN (see Figure 31). Notice that YOLOv7-tiny is way larger than the YOLOv5 nano version (1.9 M vs. 6.2 M params), and thus some of the proposed classification heads might be slightly heavier for being deployed in edge devices such as a mobile phone.
32 3.2 Lane-type classification Figure 30: YOLOv7 architecture (standard version). B3 block is equivalent to a 1-4 ELAN, while the raw ELAN block is the regular 2-4 ELAN. Source: [62]. Figure 31: Proposed heads for the YOLOv7 architecture. Notice that v7/h3 depends on the input layer: from left to right, 1st, 2nd, and 3rd ELAN.
Methodology 33 3.3. Tracking DeepSORT and StrongSORT are the selected trackers to be implemented in the multitasking model. Previous theses [7] developed in CARNET explored the possibilities of using YOLOv5 as the feature extractor of DeepSORT. The results were satisfactory, so we have built the YOLOv7 extractor and assembled StrongSORT upon the previously developed code. The backbone and the tracker are connected at the end of the SPPF layer (v5) or the CSPSPP layer (v7). The appearance-free link model (AFLink) and the Gaussian-smoothed interpolation (GSI) are intended for offline tracking. Anyway, both techniques have been included in the project code (and are set off by default). They require MOTChallenge [53] input formatting; that is, for each frame, each tracked object is represented as a 10-value array: <frame>, <id>, <bb_left>, <bb_top>, <bb_width>, <bb_height>, <conf>, <x>, <y>, <z> where bb stands for bounding box, conf is the detection confidence (for object detection datasets), and the x,y,z coordinates are used for 3D boxes. Hence, the last four elements in the array are set to −1(N/A value). 3.4. Quantization Quantization refers to the different techniques used to convert a certain numerical data type into a representation with less precision and fewer memory requirements. These conversions usually take single-precision floating-point values (FP32, also called float32), which occupy 32 bites, and transform them into 8-bit integers (int8). Figure 32: FP32 to (unsigned) int8 quantization example. Source: [63]. The main benefits of quantizing a model are the followings: (i) Size reduction. By converting FP32 into int8, the necessary memory resources can be reduced by up to 75%. (ii) Inference speedup. Using lower-precision representations can lead to a significant speedup depending on the hardware and its architecture. (iii) Power savings. For instance, in mobile phones, as less intensive computations are required, quantization can prevent fast battery drains.
34 3.4 Quantization All these points are crucial when developing a model that will be deployed in an edge device. The principal drawback is the precision lost. We get slightly away from the training output as we round the values. This issue is especially noticeable when there is a wide dynamic range, i.e., when the difference between the maximum and minimum value is large. Let xinput be a float-point value. Its int8 quantized value Qis: Q= min max roundxinput s+z, −128,127 where sand zare the scale and zero-point parameters. Remind that int8 values fall into the [−128,127] interval. If we want to de-quantize Q, we obtain xoutput with: xoutput = (Q−z)·s Notice that xinput and xoutput may not be the same. Quantization can be performed in a symmetrical or asymmetrical (affine) way. The first takes the zero value as the center of the input domain. Thus, applying this approach to non-zero-centered values can lead to undesirable results (see Figure 33). Affine quantization avoids this problem but is more computationally expensive during the inference step. Figure 33: Example of affine and symmetric quantization. Notice that most of the range on the right is not used as no values are <1. Source: [64]. Let Xbe the set of values we want to quantize. Let xmin and xmax be the minimum and maximum values in X. The scale sand zero-point zparameters for affine quantization are defined as [65]: s=xmax −xmin 255 z=−128 −round(xmin s)
Methodology 35 For symmetric quantization, we simply have: s=2·max(|xmin|,|xmax|) 255 z= 0 where we have assumed float-point to int8 quantization. To quantize the multi-task model, we use the Torch library, concretely the PyTorch framework. By using xmin and xmax as previously defined, we are implementing the ‘MinMax observer’, which is the one used by default. PyTorch also supports the ‘Histogram observer’ [65], which computes the optimal xmin and xmax (in the sense of reducing the quantization error) by taking into account the histogram of the values to be transformed. PyTorch allows quantizing a whole tensor or, instead, each one of its channels. The second way ensures that outliers will only affect the channel in which they are located and will not contaminate the rest of the tensor. Figure 34: Per-channel and per-tensor quantization. Source: [64]. The main PyTorch configurations (fbgemm and qnnpack) use histogram per-tensor affine quantization for activation functions and MinMax per-channel (qnnpack uses per-tensor) symmetric quantization for weights. 3.4.1. PyTorch quantization modes There are three quantization modes supported by PyTorch: (i) Post Training Dynamic Quantization (PTQ-dynamic). It is the simplest available mode. Weights are quantized and then stored, while activations are saved in FP32 and quantized during the inference step (that is why we call it ‘dynamic’). The main advantage is that the activations quantization range is adapted for each input, which leads to slightly better accuracy. The drawbacks are that the dynamic phase adds a little overhead to the process and, above all, that this method does not support the quantization of the widely used convolutional layers.
42 4.1 Image classification results There is a noticeable difference in the volume of parameters. While YOLOv5-nano’s average is ∼3.5 M, YOLOv7-tiny’s average is ∼11 M. This is due to the first being smaller than the second (1.9 M vs. 6.2 M), which also leads to smaller feature maps being used. The results from training the multi-task model with 256 ×256 images are the following: Validation accuracy (%) Resolution: 256×256 Backbone Layer Head type h1 h2 h3 YOLOv5 nano 3 85.3 84.7 89.1 5 86.1 86.0 88.0 7 89.0 89.0 90.2 14 85.8 86.3 86.2 YOLOv7 tiny 8 84.7 83.1 90.2 15 91.6 87.6 91.7 22 90.3 87.5 90.4 Table 7: Validation accuracy from each head, trained with 256 ×256 px images. Performance ratio Resolution: 256×256 Backbone Layer Head type h1 h2 h3 YOLOv5 nano 3 2.52 2.14 2.94 5 2.35 2.07 2.58 7 2.14 1.64 3.40 14 1.38 1.15 2.07 YOLOv7 tiny 8 0.66 0.42 0.94 15 1.26 0.78 1.08 22 0.62 0.39 1.01 Table 8: Performance ratio from each head, trained with 256 ×256 px images.
Results 43 The best head for YOLOv5 is h3 plugged at the end of the 7th layer. This layer corresponds to the third C3 module (see figure 28). The h3 heads are the ones that preserve most of the native architecture of the backbone. In terms of the accuracy-parameters ratio, all h3 heads used in YOLOv5 outperform their h1 and h2 opponents. In this aspect, the use of the Spatial Pyramid Pooling layer seems to be critical. Moreover, the fact that obtaining features from the 7th layer gives better results than from the 3rd or 5th layers shows us that the pre-trained checkpoints for object detection can really extract valuable features for the image classification task. Nevertheless, YOLOv5 tends to show better ratios for earlier layers. Regarding YOLOv7, the configuration with the best ratio is head h1 located at the 15th layer, which is the second ELAN (see figure 30). It achieves a 91.6% validation accuracy, surpassing the 90.2% of the best YOLOv5 head. The drawback is that the former uses three times more parameters. As the multi-task model is designed to work correctly on edge devices, using 3 M parameters instead of 9 M is a huge difference. Although YOLOv7-tiny surpasses YOLOv5n as object detectors, part of this improvement is due to its better ability to discover background objects. As stated in the project requirements, foreground items have a higher priority. The results from training the multi-task model with 256 ×512 images (w×h) are the followings: Validation accuracy (%) Resolution: 256×512 Backbone Layer Head type h1 h2 h3 YOLOv5 nano 3 77.9 87.1 92.1 5 86.3 86.6 90.7 7 89.2 88.0 89.6 14 85.9 85.9 87.2 YOLOv7 tiny 8 88.8 86.7 92.3 15 89.7 89.4 91.6 22 90.0 89.2 90.5 Table 9: Validation accuracy from each head, trained with 256 ×512 px images.
44 4.1 Image classification results Performance ratio Resolution: 256×512 Backbone Layer Head type h1 h2 h3 YOLOv5 nano 3 -1.0 3.23 3.89 5 2.42 2.28 3.45 7 2.19 1.45 3.21 14 1.40 1.07 2.40 YOLOv7 tiny 8 1.24 0.92 1.13 15 1.05 0.96 1.07 22 0.60 0.47 1.02 Table 10: Performance ratio from each head, trained with 256 ×512 px images. In this case, the best configuration is h3/l3 (connected after layer 3, i.e., after the first C3 block) for YOLOv5. Compared with the case with lower resolution, both show the effectiveness of the h3 heads, although obtaining features from earlier layers provides the best results in this case. This is the winning configuration if we average the ratios from both resolutions; hence, it is the proposed solution for YOLOv5. Once the model has been selected, we can test it on the separate test dataset (256×512 px). The v5/h3/l3 model achieves 92.3% accuracy, slightly outperforming the 92.1% validation accuracy. This fact is very positive as it shows that the model generalizes properly. The confusion matrix for the tested model is the following: Predicted label Bike Road Sidewalk Shared Ground truth Bike 28.9 0.8 0.4 0.6 Road 0.8 22.5 0.3 2.6 Sidewalk 0.3 0.1 27.0 0.6 Shared 0.1 0.3 0.8 13.9 Table 11: Test confusion matrix of the multi-task model with YOLOv5 and head h3/l3, trained on 256 ×512 px images. The most frequent error is to predict lanes as shared when, in fact, they are roads. These two classes may be the ones that are more similar to each other. The second
Results 45 kind of error, with <1%, is misleading bike and road. For YOLOv7, head h1 after the 8th layer (after the first ELAN, as these networks are defined piecewise) seems slightly better than the other combinations, but it is closely followed by h1/l15 and h3/l15. Generally, compared with the 256×256 case, the model tends to be benefited from training at higher resolutions. The h3 heads provide high validation accuracies, and despite using relatively many parameters, the trade-off is beneficial for them. We can also notice that the ELAN-based h1 heads work better than the C3-based h2. Comparing both resolutions, we have that h3/l15 is the most balanced one, as it is the only head configuration reaching the podium in both cases, and thus the final chosen head. As with the YOLOv5 model, we can test it on the separate test dataset (256 ×512 px). The v7/h3/l15 model achieves 92.0% accuracy, surpassing by 0.4 p.p. the precision in the validation phase. The confusion matrix for the tested model is the following: Predicted label Bike Road Sidewalk Shared Ground truth Bike 29.0 1.2 0.1 0.5 Road 0.7 23.0 0.1 2.3 Sidewalk 0.9 0.2 25.7 1.2 Shared 0.1 0.5 0.3 14.2 Table 12: Test confusion matrix of the multi-task model with YOLOv7 and head h3/l15, trained on 256 ×512 px images. Again, the most common error is predicting share lanes as roads, and also as sidewalks. 4.2. Quantization savings The multi-task model is calibrated using a 5% random subset of the validation dataset. Fewer samples can be used, but we want the quantized version to achieve the best possible accuracy. About 100 mini-batches are said to be enough [64]. Using a relatively large dataset for calibrating is helpful for obtaining a more representative distribution of the values to be quantized. Suppose the quantization and dequantization are done for each layer. In that case, the extra overhead due to these two operations raises the necessary inference time up to 400%, which makes the model impossible to run into an edge device.
46 4.3 Inference examples and weak spots Thus, in both YOLOv5 and YOLOv7, the input is quantized once it enters the first layer and is dequantized during the detection and classification layers. In the case of YOLOv5, the SiLU activation function is not prepared for PyTorch quantization, so it has to be properly managed by dequantizing the input tensor and requantizing at the end. With no extra configurations, the int8 quantized versions of the selected YOLOv5 and YOLOv7 models run just 2.3% and 7.1% faster on average than their float-point versions. Take into account that some computers are optimized for working with FP32 and FP64, so the real speed-up of the quantized models needs to be tested on mobile phones in future developments. Better results can be obtained by fusing the Conv and BatchNorm layers. This way, they are treated as just one. Each model has dozens of these combinations. By applying this technique, quantized YOLOv5 and YOLOv7 run 9.8% and 17.0% faster than their float-point versions. Quantized models suffer a ∼12% accuracy reduction when running on the test dataset (notice that the calibration has not been done with this dataset). YOLOv5 falls to 79.9% and YOLOv7 falls to 81.1%. One of the most noticeable advantages of quantization is the reduction of the size model. The original multi-task with YOLOv5 occupies 22.0 MB; its quantized version, 3.5 MB. Float-point YOLOv7 occupies 76.0 MB, while its int8 just 10.8 MB. That represents only 16% and 14% of the original size, respectively. This coincides with the expected ×8reduction from FP64 to int8. 4.3. Inference examples and weak spots The multi-task model runs in real-time with any GPU configuration of the employed computing servers. However, it is essential to note that it is necessary to test the models on edge devices in future developments. Precise analysis on the MOTChallenge tracking metrics MOTA, HOTA, and IDF1 has not been performed due to time restrictions and efforts being focused on other parts of the project. Notwithstanding, by direct observation, we can notice that StrongSORT tends to outperform DeepSORT. For instance, in figure 38, despite being the person an easy target to be detected, DeepSORT ignores it, while Strong- SORT does effectively track it. The vehicle movement makes the mobile phone oscillate; thus, the recorded images can be quite blurred. Even though the lane-type classification remains somewhat robust thanks to the Gaussian noise used in data augmentation, the object detection task clearly suffers from this blur. Excessive blurring can sometimes lead to no item being detected, as seen in figure 39.
Results 47 Figure 38: Predicted objects using YOLOv5 nano with DeepSORT (left) and Strong- SORT (right). Figure 39: The excess of blur can ruin the object detections. Figure 40: Relatively distant objects can be difficult for YOLOv5 nano to be detected, as for example the traffic lights.
48 4.3 Inference examples and weak spots
Conclusions and future development 49 5. Conclusions and future development The main four requirements have been fulfilled. We have designed a multi-task model capable of performing both object detection and image classification tasks. The best configuration for the YOLOv5 backbone achieves a 92.3% test accuracy with 3.1 M parameters, while the best for the YOLOv7 backbone assesses 92.0% with 10.8 M parameters. Furthermore, the tracker helps refine the results from the object detection task, and the int8 quantization of the model reduces its size by almost eight times. As for future developments, the multi-task model can start to be proven in mobile phones. The model checkpoint must be adapted to be deployed, which can be done with PyTorch. The use of the model in edge devices can raise concerns about battery usage. This is a crucial aspect because the safety measures delivered by the app are intended to be available for the broad majority of smartphones. Thus, the impact of the number of parameters and FLOPs will need to be analyzed. In this thesis, we have seen the storage improvement of using quantized models. Still, as long as the tests have been done in computers with quite more resources than a mobile phone and optimized for float-point values, the speed-up of int8 models must be adequately tested on final devices. The quantization mode used is Post-Training Static. Although the results are decent, further modifications can be done in the code to correctly implement Quantization Aware Training (QAT) or even the FX Graph Mode prototype. QAT is promising since it is supposed to close the gap between float-point and int8 accuracies. As seen in figure 39, the blur produced by the vehicle motion can be a challenge for the object detector. The image classifier is more robust, partially due to using Gaussian noise as a data augmentation technique. The blur issue can be addressed in various ways, one of them a camera calibration, but considering that all image pre-processing must not be computationally expensive. During the development of this thesis, new YOLO versions have been published. The most relevant may be YOLOv8 [71], proposed in January 2023 by the same authors who created YOLOv5. Regarding this 5th iteration, the v6.2 release is the one used in this project, but the new v7.0 release is now available. YOLOv8 also has a nano version with approx 3 M parameters, so it is entirely suitable for the multitasking model.
50 Although a variety of classification heads has been studied, new ones can be proposed using modules or layers that do not necessarily belong to the object detector architecture. Moreover, the potential use of YOLOv8 should lead to the suggestion of new heads.
REFERENCES 51 References [1] Autoritat del Transport Metropolità (TMB). “Enquesta de Mobilitat en Dia Feiner (EMEF).” atm.cat. https://www.atm.cat/comunicacio/ publicacions/emef (accessed Jan. 17, 2023). [2] Fundación MAPFRE. “Patinetes eléctricos. Buenas prácticas y últimos datos de siniestralidad.” fundacionmapfre.org. https://documentacion. fundacionmapfre.org/documentacion/publico/es/media/group/1116513. do (accessed Oct. 3, 2022). [3] RACC. “El comportament dels usuaris dels vehicles de mobilitat personal (VMP) a Barcelona (2021).” racc.cat. https://saladepremsa.racc. cat/wp-content/uploads/2021/09/Dossier-VMP-2021.pdf (accessed Oct. 3, 2022). [4] J. Prats, “Micromobility safety applications using AI,” B.S. Thesis, Universitat Politècnica de Catalunya, Barcelona, 2021. [Online]. Available: https: //upcommons.upc.edu/handle/2117/357583. [5] M. Torrecilla, “Lane condition analysis for micro-mobility applications,” B.S. Thesis, Universitat Politècnica de Catalunya, Barcelona, 2021. [Online]. Available: https://upcommons.upc.edu/handle/2117/357604. [6] E. Bayó, “Traffic sign detection for micromobility,” M.S. Thesis, Universitat Politècnica de Catalunya, Barcelona, 2021. [Online]. Available: https: //upcommons.upc.edu/handle/2117/350044. [7] E. Valls, “Multitask newtorks for micromobility vision applications,” M.S. Thesis, Universitat Politècnica de Catalunya, Barcelona, 2021. [Online]. Available: https://upcommons.upc.edu/handle/2117/360064. [8] A. Mateo, “Lane type classification using efficient networks,” M.S. Thesis, Universitat Politècnica de Catalunya, Barcelona, 2022. [Online]. Available: https://upcommons.upc.edu/handle/2117/379857. [9] J. Puig, “Visual determination of lane type for micromobility,” B.S. Thesis, Universitat Politècnica de Catalunya, Barcelona, 2022. [Online]. Available: https://upcommons.upc.edu/handle/2117/373754. [10] Taxonomy and Definitions for Terms Related to Driving Automation Systems for On-Road Motor Vehicles, J3016-202104, SAE International, Apr. 2021. [Online]. Available: https://www.sae.org/standards/content/j3016_202104/. [11] National Highway Traffic Safety Administration (NHTSA). “Automated Vehicles for Safety.” nhtsa.gov. https://www.nhtsa.gov/ technology-innovation/automated-vehicles-safety (accessed Oct. 7, 2022). [12] Taxonomy and definitions for terms related to driving automation systems for on-road motor vehicles, ISO/SAE PAS 22736:2021, ISO, Aug. 2021. [Online]. Available: https://www.iso.org/standard/73766.html.