Full text
id188365 SOFTWARE-LEVEL REDUNDANCY AND DIVERSITY FOR OBJECT DETECTION IN SAFETY-CRITICAL EMBEDDED SYSTEMS IVÁN SERRANO HERNÁNDEZ Thesis supervisor ENRICO MEZZETTI (Barcelona Supercomputing Center) Tutor: MIQUEL MORETÓ PLANAS (Department of Computer Architecture) Degree Bachelor's Degree in Informatics Engineering (Computing) Bachelor's thesis Facultat d'Informàtica de Barcelona (FIB) Universitat Politècnica de Catalunya (UPC) - BarcelonaTech 28/06/2024
iii Gracias en especial a Enrico Mezzetti, mi tutor, por acompañarme y guiarme durante estos meses de trabajo, por su paciencia y por aportarme la motivación necesaria para seguir adelante fuese cual fuese el obstáculo a superar. Gracias a mi familia, por su amor, su apoyo incondicional y por permanecer siempre a mi lado. Y por último, gracias también a mis compañeros en el BSC, por hacer de la oficina un entorno de trabajo agradable y ameno y por haberme tendido la mano siempre que lo he necesitado.
v Abstract Object detection modules are increasingly deployed to support various degrees of autonomous operation and decision-making in several safety-critical domains such as automotive, avionics, railways, and space. Failures in these systems can lead to severe consequences, ranging from economic and environmental disasters to endangering human life. Therefore, safety-critical systems must meet strict functionalsafety constraints before deployment and specific mechanisms and solutions must be deployed, at hardware and software level, in order to reduce the risk of failures and mitigate their consequences. This project focuses on the design and deployment of a dependable and reliable object detection solution that meets functional-safety requirements. By borrowing the concepts of redundancy and diversity from the hardware domain and applying them at the software level, we aim to mitigate the impact of hardware and software faults. The proposed solution leverages multiple instances of the YOLO object detection framework, implemented on an NVIDIA Orin System on Chip, a reference platform for industrial-quality AI-based embedded systems. The results of this work demonstrate that it is possible to deploy diverse and redundant instances of YOLO, using as middleware layer ROS2, in the NVIDIA Orin, achieving a performance-grade framerate, which was the main objective of this work. This achievement underscores the potential of the proposed solution in enhancing the reliability and safety of object detection systems in safety-critical applications, and it opens up new research directions for future work. Los sistemas de detección de objetos se utilizan cada vez más para apoyar diversos grados de funcionamiento autónomo y toma de decisiones en varios entornos críticos a nivel de seguridad, como la automoción, la aviónica, el ferrocarril o el espacio. Los fallos en estos sistemas pueden tener graves consecuencias, desde catástrofes económicas y medioambientales hasta poner en peligro vidas humanas. Por ello, los sistemas se seguridad críticos deben cumplir estrictos requisitos a nivel de seguridad funcional antes de su despliegue, y es preciso implantar mecanismos y soluciones específicos, a nivel de hardware y software, para reducir el riesgo de fallos y mitigar sus consecuencias. Este proyecto se centra en el diseño y despliegue de una solución de detección de objetos fiable que cumpla con los requisitos de seguridad funcional. Tomando
vi prestados del ámbito del hardware los conceptos de redundancia y diversidad y aplicándolos al nivel del software, pretendemos mitigar el impacto de los fallos tanto de hardware como de software en el sistema. La solución propuesta aprovecha múltiples instancias del framework de detección de objetos YoLo, implementado en un System on Chip NVIDIA Orin, una plataforma de referencia a nivel industrial para sistemas embebidos que empleen soluciones basadas en inteligencia artificial. Los resultados de este trabajo demuestran que es posible desplegar instancias diversas y redundantes de YoLo, utilizando ROS2 como capa de middleware, en la NVIDIA Orin, consiguiendo un framerate competitivo, que era el objetivo principal de este trabajo. Este logro subraya el potencial de la solución propuesta para mejorar la fiabilidad y seguridad de los sistemas de detección de objetos en aplicaciones de seguridad críticas, y abre nuevas vías de investigación para trabajos futuros. Els sistemes de detecció d’objectes s’utilitzen cada vegada més per secundar diversos graus de funcionament autònom i presa de decisions en diversos entorns crítics a nivell de seguretat, com l’automoció, l’aviònica, el ferrocarril o l’espai. Les fallades en aquests sistemes poden tenir greus conseqüències, des de catàstrofes econòmiques i mediambientals fins a posar en perill vides humanes. Per això, els sistemes se seguretat crítics han de complir estrictes requisits a nivell de seguretat funcional abans del seu desplegament, i cal implantar mecanismes i solucions específics, a nivell de hardware isoftware, per tal de reduir el risc de fallades i mitigar les seves conseqüències. Aquest projecte es centra en el disseny i desplegament d’una solució de detecció d’objectes fiable que compleixi amb els requisits de seguretat funcional. Manllevant de l’àmbit del hardware els conceptes de redundància i diversitat i aplicant-los al nivell del software, pretenem mitigar l’impacte de les fallades tant de hardware com de software en el sistema. La solució proposada aprofita múltiples instàncies del framework de detecció d’objectes YoLo, implementat en un System on Chip NVIDIA Orin, una plataforma de referència a nivell industrial per a sistemes embeguts que emprin solucions basades en intel·ligència artificial. Els resultats d’aquest treball demostren que és possible desplegar instàncies diverses i redundants de YoLo, utilitzant ROS2 com a capa de middleware, en la NVIDIA Orin, aconseguint un framerate competitiu, que era l’objectiu principal d’aquest treball. Aquest assoliment subratlla el potencial de la solució proposada per a millorar la fiabilitat i seguretat dels sistemes de detecció d’objectes en aplicacions de seguretat crítiques, i obre noves vies de recerca per a treballs futurs.
vii Contents 1 Scope definition and contextualization 1 1.1 Introduction and contextualization ..................... 1 1.1.1 Context ................................. 2 1.1.2 Key concepts ............................. 3 Artificial intelligence and AI - based object detection ...... 3 Embedded Systems .......................... 3 Safety-critical system ......................... 4 Explainability ............................. 4 Functional Safety (FuSa) ....................... 4 1.1.3 Actors involved ............................ 5 1.2 Justification .................................. 5 1.2.1 Current situation in this field .................... 6 1.2.2 Selections of Tools and Software .................. 6 Software ................................ 6 Hardware ............................... 7 1.3 Scope ...................................... 7 1.3.1 General objective ........................... 8 1.3.2 Specific objectives ........................... 8 1.3.3 Requirements ............................. 8 Functional Requirements ...................... 8 Non Functional Requirements ................... 9 1.3.4 Potential Obstacles and Risks .................... 9 1.4 Methodology ................................. 10 1.4.1 Progress Tracking ........................... 10 1.5 Legal concern and regulation ........................ 11 2 Time Planning 13 2.1 Required resources .............................. 13 2.1.1 Human Resources [R1] ........................ 13 2.1.2 Material Resources .......................... 14 2.2 Description of tasks .............................. 14 2.2.1 Project Management [T1] ....................... 14 Context and Scope [T1.1] ....................... 14 Time Planning [T1.2] ......................... 14 Budget [T1.3] .............................. 15
viii Sustainability report [T1.4] ...................... 15 Meetings [T1.5] ............................ 15 Project report [T1.6] .......................... 15 Presentation [T1.7] .......................... 15 2.2.2 Preparatory work [T2] ........................ 15 State-of-the-art study [T2.1] ..................... 15 Preparation of the working environment [T2.2] .......... 16 2.2.3 Project development [T3] ....................... 16 Reference object detection software [T3.1] ............. 16 Baseline redundancy [T3.2] ..................... 16 Middleware and containerization [T3.3] .............. 16 Diversity methods [T3.4] ....................... 16 Evaluation [T3.5] ........................... 17 Reporting [T3.6] ............................ 17 2.2.4 Overall time planning ........................ 17 2.3 Risks Management .............................. 18 2.3.1 Minor risks drivers .......................... 19 2.3.2 Major risks drivers .......................... 19 2.4 Changes from the original planning .................... 20 2.4.1 Reference object detection software [t3.1] ............. 20 2.4.2 Middleware and containerization [t3.3] .............. 20 3 Economic Management and Sustainability 21 3.1 Sustainability Report ............................. 21 3.1.1 Environmental dimension ...................... 21 3.1.2 Economic dimension ......................... 21 3.1.3 Social dimension ........................... 22 3.2 Budget ..................................... 22 3.2.1 Cost origins and estimation ..................... 22 Personnel costs ............................ 22 Generic costs ............................. 23 3.2.2 Costs associated with risks and contingencies .......... 24 Contingency costs .......................... 24 Risks associated costs ........................ 24 3.2.3 Final budget .............................. 25 3.3 Management control ............................. 25 4 Theoretical Foundations 27 4.1 How object detection works ......................... 27 4.1.1 Image processing ........................... 27 4.1.2 Model architecture .......................... 28 4.1.3 Evaluation metrics .......................... 28 4.2 YoLo framework ................................ 29
ix 4.2.1 Unified detection ........................... 30 4.2.2 YoLo v7 ................................ 30 4.3 GPU vs CPU based computing ....................... 33 4.3.1 Basic differences ........................... 33 4.3.2 GPUs for AI and Computer Vision ................. 33 5 Software-level diverse and redundant object detection 35 5.1 Familiarization with reference Object detection software ........ 35 5.1.1 Baseline software-level redundancy ................ 36 5.2 Software-level redundancy solution .................... 38 5.2.1 Porting and extending the redundancy mechanism on ROS2 . . 38 Basic architecture of the system ................... 39 Introduction of a reviewer node .................. 41 5.2.2 Containerization and Docker .................... 44 5.2.3 Addition of a third instance ..................... 45 5.2.4 Introducing a decision function ................... 48 5.3 Enforcing diversity among instances .................... 51 5.4 Final environment setup ........................... 52 6 Evaluation 55 6.1 Performance metrics ............................. 55 6.2 Scenarios to test ................................ 56 6.2.1 Target scenario ............................ 57 6.3 Reference results on the Server machine .................. 57 6.3.1 Single instance on CPU ....................... 57 6.3.2 Single instance on GPU ....................... 59 6.3.3 Two diverse instances on GPU ................... 61 6.3.4 Three diverse instances on GPU .................. 63 6.4 Baseline results on the Orin ......................... 64 6.4.1 Single instance on CPU ....................... 64 6.4.2 Single instance on GPU ....................... 65 6.5 One step beyond: tailoring the system for the board ........... 67 Accelerating the inference with TensorRT ............. 67 Downscaling the setup ........................ 68 6.5.1 Single instance on CPU ....................... 69 6.5.2 Single instance on GPU ....................... 70 6.5.3 Two diverse instances on GPU ................... 71 6.5.4 Three diverse instances on GPU .................. 73 7 Conclusions 75 7.1 Future work .................................. 76
1 Chapter 1 Scope definition and contextualization 1.1 Introduction and contextualization In the digital age in which we live, artificial intelligence (AI) systems have experienced exponential growth in their application and relevance in various aspects of our society. Among the many AI-enabled technological advances, object detection solutions exploiting deep learning algorithms have emerged as a fundamental tool in numerous applications in different technological domains such as manufacturing, health, and autonomous driving, just to name a few. The growing presence of AI- based solutions is sustained by the ability of these systems to process large volumes of data efficiently, as enabled by advanced high-performance computing devices, to obtain accurate and reliable results. The first applications of automatic image recognition date back to the 1960s, when rudimentary approaches based on manual feature extraction techniques were used. Those early methods required defining rules and thresholds for identifying objects in images. However, the technological landscape has abruptly changed with the emergence of the first machine learning algorithms at the end of the last century. Especially with the rapid advancement in the field of convolutional neural networks and in computing performances, modern and more reliable object detection systems have been developed. As a matter of fact, those systems are extensively considered to support autonomous operation and decision-making tasks in many aspects of our lives. FIGURE 1.1: Object detection for autonomous driving.
2Chapter 1. Scope definition and contextualization The good performance delivered by combining new cutting-edge object detection models and high-performance computing devices has made them emerge as potential candidates to constitute the core of real-time critical systems, such as the autonomous driving of cars or trains, among others. A failure in those systems may potentially lead to extremely severe consequences up to endangering human life. For this reason, safety critical systems are characterized by stringent constraints in their design, development, and verification processes in order to provide guarantees on the functional safety (FuSa) 1of the final systems. 1.1.1 Context Within the Bachelor’s Degree in Computer Engineering offered by the Universitat Politècnica de Catalunya at the Facultat d’Informàtica de Barcelona, up to five different specializations are studied. This work is located within the context of the mention in computing, and especially, at the intersection between the fields of artificial intelligence and computer vision. This activity will be focusing on the research topics addressed in the scope of the SAFEXPLAIN project (Europe, 2022), a European H2020 project coordinated by the Centro Nacional de Supercomputación (CNS) - Barcelona Supercomputing Center (BSC) whose objectives include the application of deep learning-based solutions in a way that they are explainable, with end-to-end traceability, and they meet functional safety requirements for critical AI-based autonomous systems, while preserving high performance. The project outcomes will include novel approaches to explain both data and model operation, assess the model reliability, and devise novel certification approaches tailored to different use of AI-based solutions in safetycritical systems. The use of AI-based solutions to perform object detection tasks in safety-critical environments is a relatively recent development. Reliability of the functionalities implemented by the AI module must be somehow guaranteed in order to abide by the requirements defined by certification standards (e.g., ISO2626 for automotive, DO-178C for avionics, etc.) and pass the scrutiny of authorities, which is a precondition for the actual deployment of those systems. However, no consolidated approach has been devised for supporting fully certifiable AI-based functionalities in safety-critical real-time systems. This project addresses the design and deployment of a reliable object detection solution for critical embedded systems that comply with the functional safety requirements established by domain specific certification and qualification standards. In particular, we will consider redundancy and diversity as well-known FuSa concepts to design and implement a reliable AI-based object detection solution. The concepts of redundancy and diversity at the software level will be used to mitigate the impact of possible errors in hardware and software and improve the system 1Functional Safety (FuSa): discipline focused on ensuring systems operate safely, protecting against hazards caused by malfunctioning or incorrect operation of equipment.
1.1. Introduction and contextualization 3 reliability. In particular, multiple diverse instances of the YoLo 2object detection framework will be deployed on top of an NVIDIA Orin SoC 3, an industrially representative high-performance embedded platform. The proposed solution will be also evaluated on an industrial use case leveraging object detection for railway surveillance cameras. 1.1.2 Key concepts Before proceeding with the work description, a number of key concepts are defined below in order to lay the foundation for all further development. Artificial intelligence and AI - based object detection Artificial Intelligence is a field of computer science that focuses on the development of systems and programs capable of performing tasks that normally require human intelligence and decision making skills. This includes solving problems of all kinds, making decisions, or recognizing patterns in text or images, among others, without the need for direct human intervention. On the other hand, object detection systems based on artificial intelligence use techniques typical of this field, such as convolutional neural networks, combined with computer vision methods in order to identify and locate specific objects within an image, as well as their respective classes, even in real-time systems. Examples of these systems can be found in the detection of pedestrians and vehicles that have driver assistance systems for modern vehicles, or security surveillance in urban or industrial environments, among many others. Embedded Systems An embedded system is a specialized computer system designed to be deployed on restricted operational scenarios or integrated into other larger devices or systems. Embedded systems typically have limited resources in terms of processing, memory, energy consumption, and storage capacity depending on their use case. These systems are often highly specialized and designed to meet the performance, power consumption, size, and cost requirements of their use case. Many of these systems are used to govern real-time control loops and are capable of interacting directly with the physical environment through sensors, as is the case in this project. In addition, embedded systems typically run software designed specifically for the task or function they perform, making them highly reliable agents for their intended application. 2You Only Look Once (YoLo) is a state of the art object detection framework. 3SoC stands for system on chip.
4Chapter 1. Scope definition and contextualization Safety-critical system A safety-critical system is a broad category including those systems where safe and reliable operation, in the sense of robustness against unexpected misbehavior, is essential to prevent situations that endanger human life or vital elements of its environment. These systems are used in environments where proper operation and safety are of paramount importance, and where any failure can result in catastrophic consequences. Examples that fall into this category include autonomous driving, health monitoring, satellite systems, railway systems, etc. A common aspect in these systems is that they normally deploy special features to guarantee their reliability and safety at operation, such as redundancy in critical hardware and software components, to support systems in case of malfunction of any component, or strict safety protocols. In addition, their design, development, implementation and maintenance are subject to rigorous regulations and standards to ensure their safety and proper operation. Explainability Explainability for AI systems is a recent research area that aims at defining a set of processes and methods that allows human users to understand and trust the results and outputs of AI engines. An AI system being explainable means that its decisions and outcomes can be understood and justified by a person. It must be possible to understand how the system arrives at the results, as well as why it produces certain outputs and not others. It should be noted in the context of this project that this is especially important in critical applications, which are intended to be as transparent as possible to regulators and users, and where it is necessary to understand the reasoning behind system decisions. Functional Safety (FuSa) The development of safety-critical systems follows strict certification or assessment processes according to generic and domain-specific security standards defined by national and international standards organizations (e.g., ISO 4). Functional safety (FuSa) is aiming at ensuring safety critical functions in the system, subsystem and software are properly analyzed and verified (and mitigations are put in place) against the system specification and safety requirements, including functional failure conditions and faults. In this context, functional safety (FuSa) is defined as part of the overall safety of a system that ensures freedom from unacceptable risk (as set out in IEC 2010), through safety functions integrated into programmable electronic systems. 4ISO is the International Organization for Standardization, which develops voluntary international standards to ensure quality and safety across industries.
1.2. Justification 5 1.1.3 Actors involved Me, the author, will be the main actor and contributor to this project. Nonetheless I will benefit from being exposed to most recent advances in the fields of AI-based safety-critical systems. The project will be implemented within the CAOS Research Group at the Barcelona Supercomputing Center, with a long track record of research publications and technological transfer awards in the field of critical systems, functional safety, and AI for real-time. I will also benefit from the outstanding collaborative network of the members in the BSC and CAOS group to gain access to instrumental resources. Particularly relevant for the scope of the project are the ongoing strict collaborations with Ikerlan of the Basque Country and the Swedish research center RISE with well-known expertise on FuSa solutions and explainable AI respectively. Also, we foresee the possibility of having access to a representative case study on the implementation of an object detection solution for surveillance cameras in a railway setup. 1.2 Justification As mentioned earlier in Section 1, the application of artificial intelligence to safetycritical (autonomous) systems has been only recently considered by industrial stakeholders. Although industrial-quality implementations are not yet deployed, these types of systems are currently assessed for governing several aspects of our lives. While several (academic and industrial) research efforts are being devoted to the design and deployment of reliable AI-based solutions, there is still a long way to go in this area before these solutions are safely deployed. Existing deep learning-based solutions running on top of complex hardware accelerators, typically used for image recognition tasks, do not comply with FuSa requirements. They do not exhibit sufficient explainability, traceability or robustness to provide the fault tolerance and security that is needed for the use of those solutions in safety-critical setups. On one side AI solutions are inherently less predictable and analyzable, for their behavior is less straightforward to understand and verify against expected inputs and reference results. On the other side, complex heterogeneous high-performance hardware platforms are used to sustain the unprecedented performance required to run those methods: those platforms also challenge the consolidated verification and validation processes that cannot scale properly to the augmented complexity of modeling this type of hardware. We identify a lack of adequate methodologies and tools to enable the deployment of certifiable and reliable AI-based solutions in safety-critical systems. In this project we focus on software-level solutions to improve system reliability and in particular to support FuSa-complaint AI methods for image-based object recognition, as used for collision avoidance in autonomous systems. In consideration of the particular scope of the project and the industrial relevance of the problem, we will consider
6Chapter 1. Scope definition and contextualization software-level solutions on industrially representative software and hardware setups. 1.2.1 Current situation in this field The application of AI-based autonomous systems for critical systems, specifically those that are deployed on embedded systems as is the case of this work, has only recently emerged. For this reason, it is difficult to find consolidated solutions from either the FuSa or AI domains that address the problem at hand. However, it is also true that both are now extremely hot topics with a wide range of applications from the automotive sector like autonomous driving (Salameh, Yao, and Goebel, 2021) to medicine and energy. We are observing a proliferation of fresh research results in the intersection between the two areas. In general, the works that follow a similar line to this one focus on two key points, which are the following. 1. Explainability of AI systems. The focus is on developing methods to have AI- based algorithms that are more transparent, and therefore more easily traceable end-to-end (Arrieta et al., 2019). 2. Functional Safety and reliability of AI systems. In this area, importance is mostly given to the validation and verification of AI-based systems and to the investigation of methods to make these algorithms robust to possible errors (Perez-Cerrolaza, Abella, Borg, et al., 2023). At the hardware level, which does not completely concern this work, there is also a proliferation of research in the field of functional safety, as reported by Perez- Cerrolaza, Abella, Kosmidis, et al., 2022. 1.2.2 Selections of Tools and Software For the development of this project, a set of various tools is needed at the software and hardware level. These tools have been chosen according to the current tooling standards and reference industrial quality solutions. Software The object detection system implemented in this project is deployed on the ROS2 platform, on top of a Linux system, concretely Ubuntu 22.04. ROS2 is an opensource platform designed for software development for robots, designed to improve scalability, robustness, and security. This platform is used because it offers a set of tools and libraries that facilitate the development of complex robotic applications, including communication between components, perception of the environment and much more, which is why it is a standard in the field of robotics.
1.3. Scope 7 In addition, as long as the application to be developed can run consistently both on the hardware that is going to be used for the use case and for possible tests on the server or locally, Docker is used so that the application works in isolation in a container. In this way, a more agile development is achieved and allows greater portability. Regarding the development IDE, Visual Studio Code will be use as the main one, as well VIM for all the on-server work. Hardware In addition to the machine on which the project is being developed, as well as a server on which tests are carried out prior to the deployment of the application, this work has the ultimate purpose of running on an NVIDIA Jetson Orin SoC, a highperformance and energy-efficient embedded system designed by NVIDIA for use in robots. autonomous vehicles and other intelligent machines. It’s based on NVIDIA’s Ampere architecture, the same one found in its RTX graphics cards. The architecture of the mentioned SoC is the following. FIGURE 1.2: NVIDIA’s Jetson Orin high-level Block diagram (Nvidia, 2024) 1.3 Scope This project deals with the design, implementation, and assessment of a softwarelevel solution for improved reliability of AI-based image recognition modules in safety-critical systems. Railway systems are extremely representative of FuSa requirements and practice in safety-critical embedded systems. The regulatory standards share several commonalities with other domains with the main difference that trains work on a restricted scenario and the systems admits a safe state (the train stopping), which does not necessarily happen for avionics and automotive. The path towards full autonomy in the railway domain is simpler than in other domains. This is especially true in the underground train systems where more than
8Chapter 1. Scope definition and contextualization 2300 kilometers of fully automated metro lines are expected to be operative within 2025. Autonomous trains still need to cope with issues arising from the interaction with the environment, such as the presence of obstacles on the track like cars, vegetation,animals, or even people. 1.3.1 General objective In this project we will focus on a specific use case of image recognition that deals with object detection (and collision avoidance) in autonomous railway systems. We will address the scenario where two surveillance cameras are used to patrol the train tracks and surrounding area to detect the presence of obstacles and, in case, to issue a stop command to enter in a safe state. In order to meet FuSa requirements and improve on system reliability, we aim at enforcing redundancy and diversity in the image recognition components by deploying multiple and diverse instances. We will consider different solutions for diversity including varying input data size, input quality, algorithm, etc. 1.3.2 Specific objectives The specific objectives of this project can be chronologically unfolded as follows: 1. Familiarize with image open source recognition software frameworks (e.g., YoLo). 2. Design a redundant software module for image recognition. The main objective is to have two redundant instances of YoLo working in parallel and communicating in order to compare results on frame’s objects detection. 3. Differentiate the redundant instances to provide diversity. Testing various diversity methods on the redundant instances in order to alter the general state of the nodes. 4. Profile performance and of the proposed variants under different deployment configurations (e.g., CPU, GPU) 5. Deploy on representative setup and hardware device (NVIDIA Orin). 6. Possibly integrate on representative industrial case study, concretely in a railway surveillance cameras. 1.3.3 Requirements Functional Requirements 1. YoLo instance redundancy: It is expected that the project will be able to deploy at least two instances of the YoLo object detection framework on the NVIDIA Jetson Orin SoC.
1.3. Scope 9 2. Application of diversity techniques: Instances of the YoLo object detection framework are expected to apply diversity techniques to ensure that their states are always different. This indicates an important consideration to ensure the robustness and reliability of the system. 3. Detection of dangerous objects: It is expected that the system will be able to detect objects that may pose a danger to the use case to be studied. This requirement is critical to the security and performance of the system. 4. Accuracy and robustness: Object detection, both in location and class, is expected to be accurate and robust to software and hardware errors. This requirement highlights the importance of system accuracy and reliability, even in adverse situations. Non Functional Requirements 1. Performance: The system must be able to process real-time object detection without compromising its performance. 2. Regulatory compliance: The system must comply with existing security standards for its use case in order to aspire to be homologated. 3. Maintainability: The system should be designed with a modular, easily understandable, and well-documented architecture for easy maintenance and future upgrades. 1.3.4 Potential Obstacles and Risks When it comes to potential risks, I find it sensible to categorize them into two primary groups: minor and major risk drivers. The first hurdle to consider in the minor risks drivers group is the lack of experience in working with embedded systems. One of the biggest envisioned challenges for me consists in getting familiar with the NVIDIA Orin and its architecture, for a hardware-aware deployment of the object detection system that will have been previously implemented on a commodity laptop and, later on a high-performance server. Another important obstacle in this same group is the lack of knowledge of functional safety methods, since the application of techniques to improve the safety of the AI system that is developed in this work is a challenge for me. In addition, the fact of working together with a team of people is a significant limitation in access to computational resources, especially with the SoC with which the project is going to be developed, since in the team of which I am part at the BSC there are limited units. Therefore, this is going to be a considerable obstacle when it comes to time management and project organization.
16 Chapter 2. Time Planning Preparation of the working environment [T2.2] The first phase of development will be simple, and will only require the preparation of the development environment, as well as other tools such as Github and Gitlab for version control, and email, Rocket Chat and Skype for internal communications with the team in the company, among other bureaucratic procedures typical of my incorporation into the BSC staff. 2.2.3 Project development [T3] Following the incremental methodology that was chosen for the development of this project, the development stages will grow in complexity, and will be dependent on the previous one at all times. The project development phase starts with the ending of the project management phase. Reference object detection software [T3.1] This stage is focused on the development of what will be the core of the final project, an object detection software. Thanks to the research carried out in the previous work, we chose to use the existing YoLo framework, but we did not use just any library, but rather a complete implementation based on Tensor Flow in order to have total control over all its functionalities and configurations to be able to modify them in future stages of the project. This software will be developed to be capable of image and video detections, and will be tested both locally on the work laptop and on the server. It is important to mention that this first phase will be designed to run on CPUs. Baseline redundancy [T3.2] The goal of this phase is to run two identical instances of the previous stage software in parallel in order to see how they perform on CPUs, and to establish a solid foundation for subsequent phases. Another objective of this phase is to test some method of communication between the two instances in order to guarantee the correctness of the detections. Middleware and containerization [T3.3] The objective of this phase is to package the entire application developed up to this point in a container using Docker, adding an abstraction layer to the project and thus providing greater consistency for its execution on different machines. In addition, according to the software used for the final use case of this project, the application will also be implemented on top of the ROS2 robotics platform. This phase will require the adaptation of everything developed up to this point to the new architecture of the platform. Given the proximity to the final product, it will be used to adapt the configuration of the application as well as some points of the source code to be able to run it on GPUs. Diversity methods [T3.4] In this final phase of the project, different diversity techniques will be implemented for the two instances of the object detection framework with the aim of improving the functional security of the application. Once this point has been developed, we will move on to the testing of the application within the framework of the aforementioned safety use case in railways.
2.2. Description of tasks 17 Evaluation [T3.5] During the evaluation phase, the performance and functionality of the developed software components will be comprehensively assessed. This includes evaluating the effectiveness and accuracy of the object detection software, assessing the performance, and examining the efficacy of diversity methods implemented to enhance functional security. Evaluation metrics will encompass detection accuracy, processing speed and resource utilization. Testing will be conducted on CPUs and GPUs to ensure compatibility and optimal performance. Reporting [T3.6] Following the evaluation, a detailed report will be compiled. This report will cover an analysis of evaluation results including quantitative metrics and qualitative observations, discussion of encountered issues and proposed solutions or improvements and lastly recommendations for further development or refinement. 2.2.4 Overall time planning The following table specifies the time planning for each and every of the development phases mentioned above.
18 Chapter 2. Time Planning Task Code Task Name Estimated time in hours Task dependencies Tasks resources T1 Project Management 115 - - T1.1 Context and Scope 25 - {R1,R2} T1.2 Time Planning 15 {T1.1} {R1,R2} T1.3 Budget 10 {T1.2} {R1,R2} T1.4 Sustainability Report 5 {T1.3} {R1,R2} T1.5 Meetings 30 - {R1} T1.6 Project Report 20 {T1.4} {R1,R2} T1.7 Presentation 10 {T3.6} {R2} T2 Preparatory Work 80 - - T2.1 State of the art study 60 - {R1,R2} T2.2 Preparation of the working environment 20 {T2.1} {R1,R2} T3 Project development 360 - - T3.1 Reference Object detection software 90 {T2.2} {R1,R2} T3.2 Baseline Redundancy 20 {T3.1} {R1,R2} T3.3 Middleware and containerization 90 {T3.2} {R1,R2, R3} T3.4 Diversity Methods 110 {T3.3} {R1,R2, R3,R4} T3.5 Evaluation 30 {T3.4} {R1,R2, R3,R4} T3.6 Reporting 20 {T3.5} {R1,R2, R3,R4} TABLE 2.1: Overall planning The Gantt diagram showing the time planning for every task can be found in the Appendix A. 2.3 Risks Management Up to this point, the planning that will be followed for the development of this final degree project has been described, but it must be borne in mind that there are various risks that can alter this planning. It is therefore necessary to have mechanisms that allow us to adapt to
2.3. Risks Management 19 these risks, and that, without wasting a great deal of time, allow us to take alternative routes that do not modify what will be the final product of the work. Taken into account the potential obstacles and risks mentioned in the first chapter (see 1.3.4), the various risks management procedures will go as follows. 2.3.1 Minor risks drivers On the one hand, we have the small setbacks that may arise on a day-to-day basis, or even over the course of several days. These can be related to the learning necessary for the development of the project, and have as a quick solution the guidance of the tutor, either through weekly meetings or through sporadic consultations in the office. I can also count on co-workers from the CAOS group to solve problems of this type, although this will not be a recurring thing. 2.3.2 Major risks drivers In the event that major inconveniences appear, such as the theft of the work laptop, or the cessation of operation of the server of the CAOS group, ample planning has already been carried out at a temporal level so that recovering from an incident of this type is not a problem. In addition, the use of version control software means that at no time will more than the work of part of one of the development stages be lost, so the time spent overcoming obstacles of this caliber will never be dangerous or compromise the viability of the project at any time.
20 Chapter 2. Time Planning 2.4 Changes from the original planning This section aims to anticipate the changes from the initial planning that have been made, which will be assessed in more detail in the following chapters. The substantial changes in the planning are related to the development of the project [T3], specifically to the Reference object detection software [T3.1] and to Middleware and containerization [T3.3]. 2.4.1 Reference object detection software [t3.1] During the initial development phase of the project, while tests were being carried out to evaluate the performance of the developed primary system, it was observed that the initial version of YoLo that was used, version 4, did not reach the expected 30 fps. Consequently, the decision was made to migrate to a more up-to-date version. For this reason, version 7 of the same framework was chosen, which was released two years after v4. This new version satisfactorily met the requirements of the project. The change of version of the framework did not represent a significant deviation in the planning, since a generous margin of time had been foreseen for this phase, considering the possibility of changes such as this. 2.4.2 Middleware and containerization [t3.3] The delay in this phase has been caused by the step of making the leap to NVIDIA Orin. The team inside which I am at the BSC had a board with Jetson16.0, which was where the developed system was planned to be tested, but a series of issues like lack of memory and incompatibilities at the software level made this step impossible. For this reason, it was necessary to use another board with an older Jetson version that was not fully suited for the software used in the project, and which slightly delayed the development of the project. However, the time that had to be dedicated to this task was commuted with the time spent on documentation so as not to be delayed more than necessary with respect to the initial planning. Another substantial change has been the merge of the evaluation and reporting stages into a single one, just evaluation. In addition, the new Gantt updates the delivery date of the project, which was not known at the beginning of the project. A new, slightly modified and updated Gantt chart has been added to Appendix Breflecting all the changes mentioned. 1Jetson refers to the software stack provided by NVIDIA for their Jetson family of embedded computing boards.
21 Chapter 3 Economic Management and Sustainability 3.1 Sustainability Report In this project, I consider it essential to carry out a sustainability analysis that encompasses three key dimensions: economic, environmental and social. Along these lines, I have carried out a self-assessment of my sustainability competence and subsequently examined these three dimensions within the framework of my research. As far as self-assessment is concerned, I should point out that, although I am up-to-date on sustainability, the questionnaire has revealed that my knowledge is far from complete to undertake a comprehensive study on larger projects, such as those developed in large companies. I recognize that the social and environmental dimensions of a project do not receive the attention they deserve from me, possibly because we tend to focus only on the economic dimension. On the other hand, I believe that the environmental dimension is becoming more and more important in today’s society, thanks to the increase in environmental awareness. Therefore, I consider it vitally important to pay due attention to this area, as neglecting it can lead to rejection of the project by the community. The same goes for the social dimension; I believe that a project will hardly be successful if it does not contribute to improving people’s quality of life, and I believe that this work is directly oriented towards that objective. 3.1.1 Environmental dimension Due to the nature of this project, the environmental impact it has is minimal beyond the electrical energy needed to keep the hardware to be used running. In addition, this project is being carried out in a city like Barcelona, which in the spring season uses between 40 and 50 percent clean energy in its electricity grid. However, it is always possible to reduce the environmental impact. A simple way would be to increase the use of clean energy, such as by using solar panels or other renewable energy sources to power the devices to be used. However, given the scale of this project, this solution seems unrealistic when we consider the cost of such a move. 3.1.2 Economic dimension As far as the cost of the project is concerned, this has been estimated in detail and with a certain margin, and I believe that it is a more than adequate budget considering the people
22 Chapter 3. Economic Management and Sustainability involved and the resources that are going to be used. The fact of using existing resources that are shared with other users, such as servers, makes the cost of the project very reasonable considering the means that will be available. The current state of play in this field ranges from fairly inexpensive software solutions to high-cost hardware systems such as the multi-core lockstep (Perez-Cerrolaza, Abella, Borg, et al., 2023). From an economic point of view, this project aims to develop a reliable solution for a specific use case without resorting to prohibitively expensive hardware and using software-based security techniques, which are more affordable. 3.1.3 Social dimension The social dimension of this project is by far the most prominent of the three already mentioned. The purpose of this work is solely and exclusively to improve people’s lives, developing a system that is capable of guaranteeing their safety in a use case in which they still rely mostly on human criteria, which is clearly less safe. Personally, this job will provide me with a whole series of knowledge about artificial intelligence, computer architecture, and functional security techniques, as well as the enormous feeling of accomplishment of working on a product focused on improving people’s lives. 3.2 Budget In this section, the economic factors involved in the development of this project will be analysed in an approximate way, specifying various categories such as contingency costs, personal costs, or costs associated with activities, among others. 3.2.1 Cost origins and estimation Personnel costs Personnel costs are understood to be all expenses associated with employing workers in a company, including salaries, taxes, and benefits, among others. Given that this is a final degree project that is carried out within a company, it is necessary to distinguish a minimum of three profiles that are essential for the realization of the project. 1. Developer : A computer engineer in charge of the development of the project in question. 2. Project manager: A person in charge of the control and management of the project, in order to guarantee a good evolution throughout its development. He is also in charge of the presentation of the project. 3. Human resources person: In charge of hiring staff and guiding the developer in the first steps in the company in which this work is framed. The role of project manager in the context of this work is shared between the author himself, me, and the tutor of the work and the co-director on the part of the faculty, while the developer is solely and exclusively the author of the project. On the other hand, the person in charge of human resources is considered only in the first stage of the project.
3.2. Budget 23 Below are the hourly salaries of the profiles mentioned above. Profile Net salary Taxes Gross salary Human Resources 15€5.46€20.46€ Project Leader 25,20€10,06€40€ Developer (Junior)9,6€2,4€12€ TABLE 3.1: Estimated salaries according to other similar positions in Barcelona In addition to the tasks already mentioned in Chapter 2, recruitment and on-boarding by the human resources person are therefore added. Taking into account the totality of the tasks and the different hourly costs of each profile, the costs associated with personnel broken down are as follows. Task Code Task Name Profile Total time (hours) Total gross cost (€)Project manager Developer Human Resources T1 Project management 40 115 T1.1 Context and Scope 25 25 300 T1.2 Time planning 15 15 180 T1.3 Budget 10 10 120 T1.4 Sustainability report 5 5 60 T1.5 Meetings 30 30 60 1560 T1.6 Project report 5 20 25 500 T1.7 Presentation 5 10 15 320 T2 Preparatory work 4 80 15 T2.0 Recruiting and onboarding 15 15 306,9 T2.1 State of the art study 2 60 62 800 T2.2 Preparation of the working environment 2 20 22 320 T3 Project development 28 360 T3.1 Reference Object detection software 4 90 94 1240 T3.2 Baseline redundancy 2 20 22 320 T3.3 Middleware and containerization 5 90 95 1280 T3.4 Diversity Methods 8 110 118 1640 T3.5 Evaluation 5 30 35 560 T3.6 Reporting 4 20 24 400 TOTAL 9906,9€ TABLE 3.2: Summary of costs for every task of the project. Generic costs Below are the different costs associated with different project factors. •Workspace: This is the physical space in which the project is going to take place. This space will be the work area on the 4th floor of the Til·lers building, within the
24 Chapter 3. Economic Management and Sustainability Barcelona Supercomputing Center premises. Cleaning and maintenance are understood as expenses associated with the workspace, so for a team of two to three people (depending on the stage), this will be reduced. •Power consumption: The power consumption will come mostly from the cost of keeping the laptop running with which this work is carried out. The operation of the server and the NVIDIA Orin must also be taken into account, although the use of these represents a very small part of the working time (it is considered reasonable that this part is 5% of the time). •Internet use: The cost of the internet bill is estimated at about 40 euros per month. •Software: The software used is free of charge, so there is no cost involved. •Hardware: The only hardware that has been explicitly acquired for the development of this project is the laptop, with an approximate cost of 1500 euros. The table below summarizes the generic expenses. Factor Expected cost for 5 months (euros) Workspace 400 Power consumption (laptop) 30 Power consumption (server) 15 Internet usage 200 Software 0 Hardware 1500 TOTAL 2145€ TABLE 3.3: Generic expenses. 3.2.2 Costs associated with risks and contingencies Contingency costs As indicated in the planning section, this project considers the possibility of facing obstacles and contingencies that could affect its development. These eventualities can not only delay progress temporarily, but also lead to additional costs. Therefore, it is crucial to assess its impact on the project budget.For this reason, it has been considered reasonable to add 20% of the budget associated with generic costs. Considering this, the contingency cost is 2574€(or 429€over the baseline budget). Risks associated costs According to the possible eventualities detailed in the planning chapter, a budget of the costs of each of the possible risks is detailed below, calculated as the base cost multiplied by the probability of their happening. All risks associated to hardware have been grouped as "Hardware malfunction", and its costs is computed as the same percentage of the risk driver happening regarding to the total number of hours of the project, since I consider that the main cost of a issue of this kind is the time that ends up costing to the developer.
3.3. Management control 25 Risk driver Probability Cost Loss of the equipment 5% 75€ Hardware malfunction 10% 640,4€ TOTAL 715,4€ TABLE 3.4: Cost associated to risk drivers. 3.2.3 Final budget All of the different budgets listed for the various categories listed above are listed together below. Cost source Partial Cost Personnel Cost 9906,9€ Generic Costs 2154€ Contingency associated costs 429€ Costs associated to risk drivers 714,4€ TOTAL 13203,94€ TABLE 3.5: Summary of the final budget. 3.3 Management control During the development of this project, periodic reviews of the costs will be carried out in order to ensure the greatest possible follow-up of the economic management plan initially detailed. It is considered advisable that this management control be carried out simultaneously with the follow-up meetings, since in this way a follow-up can be carried out twice, on the one hand by the author of the work and on the other by the tutor. As this is a project that is not of business caliber, it is considered sufficient that the hours detailed in the initial plan are reviewed weekly and compared with those dedicated during that week, in order to detect possible deviations, and if detected, to be able to readjust the planning. To carry out this task, two simple descriptors are defined, one for the economic cost and the other for the cost at the level of hours, in order to be able to make the monitoring quantifiable for the completion of the project. Costdeviation = (RC −EC)∗RH (3.1) Timedeviation = (EW −RW)∗EC (3.2) Where: •EC: Expected costs in euros. •RC: Real costs in euros. •EW: Expected Workload in hours. •RW: Real Workload in hours. Following equations (1.1) and (1.2), the cost deviation reflects the impact of cost deviation in terms of labor hours, and vice versa for the time deviation.
32 Chapter 4. Theoretical Foundations reference frameworks. For one, in terms of speed, it can process images at a rate of 155 frames per second, much faster than other state-of-the-art object detection algorithms. It should be noted that the original YoLo model was capable of processing at a maximum speed of 45 frames per second. FIGURE 4.7: YoLo benchmark on frames per second. Then, in terms of accuracy, YoLo v7 performs well compared to other object detection algorithms. It achieves an average accuracy of 37.2% at an IoU threshold of 0.5 in the aforementioned COCO image set, which is comparable to other reference object detection algorithms today. The quantitative comparison of performance is shown figure 4.8. FIGURE 4.8: YoLo benchmark on precision. However, it is important to note that YoLo v7 is less accurate than two-stage detectors such as Faster R-CNN and Mask R-CNN, which although slower and with worse inference times, tend to achieve higher accuracy. With all this in mind, it is more than reasonable to have chosen YoLo v7 to form the core of this project.
4.3. GPU vs CPU based computing 33 4.3 GPU vs CPU based computing When we think of a computer, we usually refer to the CPU (Central Processing Unit) as its brain, but the GPU today has become its heart. GPUs (Graphical Processing Units) have become a major player in the modern world of supercomputing, and are largely responsible for initiating the current boom in artificial intelligence. Let’s see why below. 4.3.1 Basic differences At the architectural level, a CPU is composed of only a few cores plus one or more cache levels capable of supporting a few processing threads running simultaneously. On the other hand, a graphics card is composed of several hundred cores capable of processing thousands of threads at once, raising the level of parallelism to levels unattainable by any CPU. FIGURE 4.9: CPU vs GPU architecture. The table below summarizes the main differences between these two processing units. CPU GPU Several cores Many cores (hundreds or thousands) Low latency High throughput Suitable for serial processing Good for parallel computing Handful of operations at once Thousands of operations at once 4.3.2 GPUs for AI and Computer Vision The design of modern GPUs, with thousands of cores with less compute capacity than CPUs but more numerous and efficient, offers an ideal level of parallelism for processing large volumes of data ideal for artificial intelligence or computer vision applications. Specifically, its architecture is ideal for matrix and vector operations, which is very common in the field of computer vision and deep learning. For example, in a convolutional neural network (CNN), which is frequently used for image object classification, each convolutional layer can process hundreds or thousands of convolution operations simultaneously. Since those are independent calculations, performing these in parallel can significantly reduce the time required to process these large volumes of data. Moreover, this deep learning capability is accelerated even more in NVIDIA GPUs thanks to the inclusion of dedicated Tensor Cores, which accelerate large matrix operations and perform mixed-precision matrix multiply-and-accumulate calculations in a single operation. For instance, Tensor Cores can operate on half-precision (16-bit) and single-precision (32-bit) floating-point numbers simultaneously, which significantly reduces memory bandwidth and speeds up computation without sacrificing performance.
34 Chapter 4. Theoretical Foundations To put the icing on the cake, most of the frameworks that exist today for artificial intelligence applications are optimized for use on graphics cards, such as TensorFlow or PyTorch. It is for all the reasons mentioned above that the system that is developed for this project will be implemented in such a way that it is optimized to run on GPU, since being an object detection system we want to achieve the maximum possible performance in order to achieve a higher frame rate.
35 Chapter 5 Software-level diverse and redundant object detection The main objective of this project consisted in the design and deployment of an object detection application with SW-level redundancy and diversity mechanisms for collision avoidance in an autonomous driving framework and embedded critical systems in general. In this chapter we present the core contribution of the project and provide details on all the stages of design and development of the proposed solutions, from the first steps at the local level to the last phase on the NVIDIA Orin and on the server of the CAOS group. 5.1 Familiarization with reference Object detection software In this first stage of development, we approached YoLo (Redmon et al., 2015) as a reference object detection module for autonomous and advance assistance driving frameworks. As a first step, we focused on retrieving an implementation of YoLo, in Python with an AI framework optimized for GPUs. Subsequently, we adapted it to a scenario in which it would be used as a real-time object detector, and carried out a first battery of tests at a local level (native setup on mainstream laptop), using only the CPU, as a way to confirm the functional correctness of the detection algorithm. Following the work of some of the colleagues in the CAOS research group, version 4 of YoLo was initially chosen for the preliminary familiarization activities, specifically we opted for a version implemented with the frameworks TensorFlow and Keras. The only change that was applied to the original code, besides fixing minor bugs when porting the repository to another setup, was to adapt the code to video processing since it was only focused on object detection in images. To this purpose, the OpenCV library was preferred over other alternatives such as MoviePy or FFmpeg, since the target system in this project is designed to work in real time and OpenCV stands out precisely for its timing accuracy and efficiency. In addition, the opencv:VideoCapture object through which the video is read offers great flexibility in terms of reading video either from files, external video channels, or the machine’s own webcam, if available. In addition to this, and taking into account the real-time nature of the system to be implemented, we slightly modified the way predictions are computed in order to improve the stability of the system, introducing the well-known known technique of frame averaging (Kim et al., 2023). This technique smooths out fluctuations between consecutive frames, which is especially useful in scenarios where objects are moving quickly, and also increases robustness against possible sudden changes in lighting conditions or injection of noise in the cameras.
36 Chapter 5. Software-level diverse and redundant object detection FIGURE 5.1: Prediction for current frame is computed as the current one and the last two seen. To this purpose, we deployed a FILO (First In Last Out) data structure to keep the predictions over the last 3 frames. For the first three frames of the video, the predictions are computed without the need to perform non-maximum suppression, and the results are added to the stack containing the frame stream. Once the stack is filled, the average of the three predictions is computed, and the non-maximum suppression is applied to the mean to result in the final prediction. For the rest of the video, the oldest prediction is removed and the current frame prediction is added to the FILO structure before repeating the whole decision process. The first practical approach with the algorithm was made locally, using images of 320x320 pixels resolution and using only the CPU. Then, the same implementation has been tested on higher resolution images, to assess whether performance were preserved even in more realistic input scenarios. Resolution 320x320px 320x320px (no I/O) 608x608px (no I/O) Framerate 3.290 3.788 1.324 TABLE 5.1: Baseline implementation framerate on CPU, under different image resolutions. As can be observed in Table 5.1, the results are exceptionally bad, reaching a derisory frame rate of around 3 fps with 320x320 images, and even worse reaching 1.324 fps with a resolution of 608x608. We derived two main conclusions from this first experiment: (i) the resolution obviously affects performances, as could have been easily anticipated, and (ii) the input and output operations greatly affect performance, as we observed up to a ˜ 15% difference for the simple fact of not showing the images at each frame. Input and output operations such as showing an image on screen take a long time due to the significant difference in speeds between the CPU and I/O devices, as well as the latency added by communication, synchronization, and data transfer. To this we must add that parallelism of any kind is not being used, all I/O operations are sequential, and therefore the time that the CPU spends on the I/O is not dedicated to the processing of the next frame. 5.1.1 Baseline software-level redundancy The next step in the development of the project was to develop one of the main functional requirements of the project: software-level redundancy for the object detection module. In practice, this translates into the implementation of two (or more) instances of the module that are executed in parallel on different cores in order to avoid reciprocal interference and
5.1. Familiarization with reference Object detection software 37 maximize the isolation between the two instances at the level of consumed hardware resources. The software architecture that was followed for this phase is as follows. FIGURE 5.2: Redundancy diagram To achieve the aforementioned redundancy, when executing the script that launches the project, two new child processes are created using the spawn() function of Python’s multiprocessing library, and for each of these two processes an unnamed pipe is opened to have a bidirectional but independent communication from both processes. Regarding the communication, the flow of data though the pipes works as follows. FIGURE 5.3: Communication between parent and child process The fork() method could also have been used to create the child processes, but we want to achieve as much independence as possible at the resource level between the two instances. fork() creates a new duplicate process from the parent that inherits its address space, variables, and state, whereas with spawn nothing is inherited from the parent and therefore its state is not shared with it. This communication is not only important so that the parent process can know the number of detections of each of the instances for each frame, but also to ensure synchronization. In a real-time system such as the one we want to implement, it is essential that at all times the different instances that have been deployed of the object detection framework work at the same time, processing the same frame each time. As the evaluation of the intermediate versions of the system implemented in this project is not vital, we will limit ourselves to commenting only on the frame rate per second with results, in order to have an approximate idea of the performance of the system with different resolutions. The results obtained are as follows. Resolution 320x320px (no E/S) 608x608px (no E/S) Framerate 3.453 1.25
38 Chapter 5. Software-level diverse and redundant object detection It may seem in the results that the addition of parallelism has practically not harmed the frames per second. Keep in mind that using such a rigid synchronization policy hurts performance, but this ensures that both instances are processing the same frame at all times. In any case, the observed performances confirmed that the specific version of YoLo considered in the preliminary phase (i.e., v4) was not enough efficient, even more if multiple instances in parallel are considered. This led us to the decision of switching to a more recent version of YoLo, specifically v7 as already mentioned in Chapter 4. Similarly to v4, the considered YoLo v7 implementation is leveraging PyTorch framework and not TensorFlow. Therefore, we applied very similar changes to the original repository, as even v7 was originally designed for offline image detection and therefore had to be adapted to the use case of this work (in addition to applying the optimizations already mentioned of frame averaging). 5.2 Software-level redundancy solution In this section, we provide a description of the main steps and aspects covered for the definition of the final software-level redundancy solution. Starting from the slightly tailored instance of YoLo v7, we focused on the design and implementation of the solution on top of ROS2 (Macenski et al., 2022) as a reference middleware solution for autonomous applications. ROS2 functionalities and semantics are at the core of well-known autonomous driving frameworks, such as Apollo (Alcón et al., 2021) and Autoware (Kato et al., 2018). The consolidated solutions is also meant to be easily ported to diverse targets, including the Orin as per project objectives. For this reason, we opted for a containerization solution, to easy deployment across diverse hardware targets. 5.2.1 Porting and extending the redundancy mechanism on ROS2 In the following we detail on how a new ROS2 layer was added to the YoLo-based solution, including the configuration of the project’s codebase that was necessary to benefit from GPU execution. ROS (Robot Operating System) (Quigley et al., 2009) is a software framework widely used in the development of complex robotic systems, such as autonomous driving systems. Although it is not an operating system as such, ROS (and specifically for this project version two of ROS) offers a wide collection of tools for the creation and efficient management of processing nodes, making it ideal for the context distributed control and real-time systems. One of the reasons why ROS was chosen for this project is because of its highly representative of autonomous driving applications (where object detection solutions are largely applied) and because of its modular architecture, which allows efficient communication between nodes as well as the execution of services and actions both synchronously and asynchronously. With regard to communications, there are two main types. •Publisher-subscriber communication: This is an asynchronous communication method in which nodes can post messages to specific topics (a topic is a communication channel that allows nodes to exchange messages asynchronously), and other nodes can subscribe to these topics to receive the messages. •Communication in the form of a service: They allow synchronous communication between nodes through a request and a response. ROS2 allows the parallel execution of different nodes, so each one that is launched will end up on a different core of the machine where the system is running. In addition, within
5.2. Software-level redundancy solution 39 each node ROS2 uses multiple processing threads to concurrently manage the receipt and sending of messages. Therefore, ROS2 adds an extra layer of abstraction that allows efficient and coordinated management of communications between processes, as well as the development of easily scalable systems. Basic architecture of the system Once we have seen what ROS2 is and how it works internally in a basic way, we move on to see what was the architecture of the first version of the system that incorporated this new layer of abstraction. The objective was to emulate the system explained above (Figure 5.4) but using ROS2 instead of the already seen calls to system functions and communication through pipes. The first thing was to change the structure of the repository to one of ROS2’s. This operating system uses a workspace structure managed by colcon, the default build tool. An outline of the basic structure that such an environment should follow would be as follows. FIGURE 5.4: Basic repo structure with ROS2 A repository can contain several packages, each of which is the largest organizational unit that this system has, since nodes are included within each package. For this first version, only one package with three different nodes was used; one for the publisher and one for each of the two instances in charge of processing the images. All three nodes follow the same structure. 1import rclpy 2from rclpy . node import Node 3 4class Node_i ( Node ): 5// node code 6 7def main(args=None): 8# initialize ROS2 communications 9rclpy . init ( args = args ) 10 11 # create node and spin 12 publisher = Node_i () 13 14 rclpy . spin ( publisher ) 15 16 # explicitly destroy the node
40 Chapter 5. Software-level diverse and redundant object detection 17 publisher . destroy_node () 18 rclpy . shutdown () 19 20 if __name__ == ’ __main__ ’: 21 main () First, a class is defined that inherits from the Node base class provided by the ROS2 rclpy library. This class will represent a node in ROS2, and within it will include all the methods of the functionality that the node fulfills, as well as configuration of communications with other processes. Then the main function defines the entry point of the program, and starts by always initializing the IPC 1. The node object is then created and launched using the rclpy:spin() function, a blocking call that in addition to launching the node makes it visible to other nodes in order to listen and process incoming messages, services, or other events. Until an outage signal or a shutdown request is received from another node, it will not stop. Finally, once the function performed by the node is finished, it is explicitly destroyed in order to free up all the resources it has used. The implementation of each of the nodes is explained in more detail below. •Publisher node The publisher node is the one that initiates the system pipeline. It defines a topic for communication with the other two nodes, thus employing an asynchronous communication with the instances that then subscribe to it. This node is responsible for pacing the reading of images thanks to a timer that can be adjusted based on the desired framerate. By managing the timer interruption, every (1/framerate) seconds the subscribers will receive the signal thought their shared topic to read a new frame from their respective camera channels. In this way, the communication that this node establishes with the other two is completely decoupled. •Subscriber nodes The subscriber nodes are responsible for capturing the signal from the publisher, reading the same frame and processing it. The first thing these nodes do when they are launched is to load the YoLo model, and then subscribe to the topic previously created by the publisher. The processing of frames is handled in a similar way to how frames are published, through interruptions. With each frame that is captured, an interruption is triggered for which a specific callback has been designed, and it is in this callback that the frame is processed. The subscriber code follows the following structure. 1... 2class Receiver ( Node ): 3def __init__ ( self ): 4// name the node 5super (). __init__ (" image subscriber ") 6 7// Load the model 1Inter-process communication (IPC) refers to the mechanisms and techniques used by processes to communicate and coordinate with each other.
5.2. Software-level redundancy solution 41 8self . model = YoLov7 (...) 9... 10 11 // create subscription 12 self . subscription = self . create_subscription( 13 Image, 14 ’video_frames’, 15 self.listener_callback , 16 1) 17 ... 18 def listener_callback (self , msg ): 19 20 current_frame = self .br. imgmsg_to_cv2 (msg ) 21 22 if self . frame_counter < 3: 23 // fill the batch 24 ... 25 else: 26 // perform detections normally 27 ... With the capture of each frame, depending on whether the frame batch is empty, the subscriber fills it with partial detections (without Non Max Suppression, as seen in the section 5.1) or performs the detection normally using the whole batch of three frames. The last parameter of rclpy:create_subscription() defines the maximum buffer length allowed for the subscriber. For the purpose of this project, which is to develop a realtime object detection system, a maximum size of one is used, because despite the fact that it is very strict, it is not desired to have a delay in the processing of the frames at any time. In any case, the framerate will be lowered if subscribers can’t keep up with the publishing rate. Introduction of a reviewer node The next logical step in the development of this object detection system was to implement some kind of control and review mechanism on the detections that were calculated in each frame. To do this, and taking advantage of the modularity offered by ROS2, a new node was added as follows. FIGURE 5.5: Node scheme with the reviewer node. For this new node, a different type of communication was used than for the publisher, because if for the other case a decoupled communication made sense, the reviewer must
48 Chapter 5. Software-level diverse and redundant object detection The idea is similar to that of the previous algorithm, but by multiplying the number of cases to be considered, since one instance has been added. There is a difference between two cases, if the frame that is received is the one that is going to be processed or not. In case it is, we look to see if we already have the other two frames of the other two instances, and if so, we do the review of the three messages. Otherwise, we add the data from the received frame to its respective queue to be processed later. In case of receiving a frame ahead of the current one, it is simply saved in the queue of the process that has sent the data. 5.2.4 Introducing a decision function Now that we have the complete architecture as it is going to be used for the final version of the project, it makes sense to analyze the algorithm of the reviewer node for the revision of the outputs of the three instances. The reviewer node essentially implements a decision function that, based on the inputs received from the redundant instances, elaborates a final outcome on which an action is typically taken. This algorithm has been implemented as an extra in this work, since its objective is to develop a functional system with redundancy and diversity at the software level, not to design an optimal reviewing algorithm for the outputs of the different instances. However, a simple algorithm has been implemented to demonstrate that at runtime it is possible to perform a non-trivial review without slowing down the system. The algorithm works as follows.
5.2. Software-level redundancy solution 49 Algorithm 3 performReview def performReview(instance1, instance2, instance3): numObj1 = len(instance1.classes) numObj2 = len(instance2.classes) numObj3 = len(instance3.classes) if numObj1 == numObj2: results = [] pos1 = array([(x,y) for x,y in zip(instance1.x_coord, instance1.y_coord)]) pos2 = array([(x,y) for x,y in zip(instance2.x_coord, instance2.y_coord)]) tree = cKDTree(pos2) _, indices = tree.query(pos1) for i, (pos_i, index_i) in zip(pos1, indices): if instance1.classes[i] == instance2.classes[index_i]: conf_i = (instance1.classes_confidence[i] + instance2.classes_confidence[index_i]) / 2.0 results.append([instance1.classes[i], conf_i, pos_i]) else: if instance1.classes_confidence[i] > instance2.classes_confidence[index_i]: results.append([instance2.classes[index_i], instance2.classes_confidence[index_i], pos2[index_i]]) else: results.append([instance1.classes[i], instance1.classes_confidence[i], pos_i]) write the results else: if len(instance1.classes) != len(instance3.classes) and len(instance2.classes) != len(instance3.classes): move to fail safe state else: objects detected thanks to majority voting with the tiebreaker The algorithm of the performReview() method has the function of reviewing the outputs of the three instances, and has the following possible outcomes. 1. outcome 1: Provide more accurate detections in case the first two instances detect the same number of objects, putting together the predictions of both in a particular way. 2. outcome 2: Perform majority voting with the tiebreaker node in case of having a different number of detections in the first two instances. 3. outcome 3: Trigger a fail-safe state in case the 3 instances detect a different number of objects. For the first outcome, it is necessary to compare the predictions of both instances in pairs, where each pair represents an object of the same frame.
50 Chapter 5. Software-level diverse and redundant object detection The problem for this is that the model’s predictions are not ordered, and therefore there is no way to know from two outputs of two instances which detections belong at a semantic level to the same object. To solve this problem, a K-dimensional tree is constructed from the centroids of the bounding boxes of the detections of each of the nodes. The KD tree is a very useful data structure for organizing points in multidimensional spaces (although in this case it is limited to two dimensions), allowing very efficient searches of nearby neighbors. The reason why this tree is used is because the way to match detections that belong to the same object will be done from the minimum distance between centroids. So a p_i prediction of the main instance will be associated with a p_j prediction of trail one if and only if the p_j centroid is the closest to the p_i centroid of all the predictions in the second instance. This KD tree is constructed recursively by dividing space into orthogonal hyperplanes, alternating axes at each step, and dividing space into two groups based on a specific threshold for that dimension. The division process is carried out iteratively until a maximum depth is reached or a limit of preset points is reached. FIGURE 5.7: KD Tree for two dimensions In this way, we can have the pairs of detections that belong to the same object, and with them we do the following. • If the detections are of the same class, the confidence of that object is recalculated as the average of the two trusts of the two instances. • If the detections are of different classes, the one with the highest class confidence is selected. The construction of the tree has a complexity of O(n*logn), where n is the number of points, and for the search for close neighbors O(logn + k), where k is the number of neighbors that are searched. For my algorithm, in which only one neighbor is searched for each of the npoints in the tree, the complexity of the algorithm in its entirety is O(n*logn). Moving to the other outcomes, when the number of detections from the two main instances is different, the tiebreaker node is used to see if majority voting can be performed. If the tiebreaker node has made a different number of predictions, it is understood that there has been an error at some point and therefore it must go to a fail-safe state. In case this node has made the same number of predictions as one of the other two, the predictions made by the majority are trusted. As an addition to all this, once the system architecture was complete and was not going to be modified anymore, a new package was added to the repository with a launch file to configure each node and launch them in the desired order.
5.3. Enforcing diversity among instances 51 5.3 Enforcing diversity among instances This was the last point to be completed to meet the functional requirements of the project, since redundancy had been covered and at that time only diversity remained. Diversity has been covered as last aspect in the project as it naturally applies on top of an already redundant system. At this stage of the project, we can count on three instances of the object detection module. The idea of software-level diversity is to devise software-level differentiation so that each of the instances is working on a slightly different input when performing the inference. To this end, the following solutions were considered and deployed. We provide the following distinctive features for each object detection node. •Main subscriber This is the reference instance. The network weights used for inference are encoded in FP32 format, and the input images to that network are in RGB format. It should be noted that both for this instance and for the other three the resolution of the images will be the same, by the simple principle of Garbage In Garbage Out. •Trail subscriber For the next node, diversity is achieved by modifying the data type of the network weights. Instead of using fp32, the last 16 bits of the mantissa are left and fp16 is used instead, resulting in a less accurate representation. The idea behind this is to slightly modify the weights so that they differ slightly but remain semantically equivalent as long as the inference still leads to the same detections as with the original network. FIGURE 5.8: Bit level representation for fp32 and fp16. From left to right, there is the sign (blue), the exponent (green) and lastly the mantissa (red) This allows to use exactly the same software as with the first instance, preserving its performance, and even reducing the cost of this node due to the smaller space occupied by the network. Other operations similar to this could be performed, for example dropping a different number of bits of the mantissa to achieve greater or lesser precision. However, fp16 is used as PyTorch has built-in functionality by default to reduce the accuracy of the model’s weights to this particular data type. •Tiebreaker subscriber For the tiebreaker, a logic very similar to that of the previous node has been used. The idea is that in the inference process there is some slight variation in the propagation through the network as long as there are differences but not sufficiently significant semantically. To do this, the input data has been modified, adding a little brightness to the image (1 point evenly for each channel), and an increase of 1% in the image contrast thanks to
52 Chapter 5. Software-level diverse and redundant object detection opencv:cv2.convertScaleAbs(). It is not desired to add too much brightness nor contrast so as not to alter the intensity of edges, contrasts and textures, and end up losing details that can mismatch the features extracted during the training phase of the model, but enough so that the propagation through the network is different to the other instances. 5.4 Final environment setup Before reporting on the evaluation and assessment of the proposed solutions, we discuss the different platform setups considered in the scope of the project and comment on the diverse features and related challenges. In the first familiarization phase we conducted most of our activity on the mainstream laptop, with no dedicated GPU support. For the implementation phase, we moved to a highend server machine with dedicated GPU support. Finally, we moved to the NVIDIA AGX Orin as the representative embedded device for the final assessment. Below are the main hardware-level (computational) differences between the server and the Orin board. Specs\Machine Nvidia Jetson Orin AGX CAOS22 Server CPU 12 Core ARM Cortex-A78AE v8.2 (64 bits), 6 MB of L2 Cache, 4 MB of L3 Cache 16 Core AMD Zen 3 Ryzen 9 5950X (64 bits), 6 MB of L2, 64 MB of L3 Cache GPU Nvidia Ampere Architecture, 2048 CUDA Cores, 64 Tensor Cores, 5.3 TFLOPs Nvidia Ampere Architecture, Nvidia RTX 3090, 10496 CUDA Cores, 328 Tensor Cores, 36 TFLOPs Memory 32 GB LPDDR5 128 GB LPDDR5 Power consumption 15 - 65W ∼700W Storage 64 GB eMMC multiple disks: 2 TB nvme SSD, 6 TB nvme SSD, 256GB nvme SSD TABLE 5.2: Comparison between NVIDIA Orin and the CAOS22 Server on the hardware level. Other important differences between board and server are at the software level, such as with the operating system. The operating system of the NVIDIA Orin is Linux for Tegra (L4T), an Ubuntu-based Linux distribution that is specially adapted for embedded systems of the Jetson family. The kernel of this OS, as well as drivers and libraries are adapted to the board, and therefore are not necessarily up to date nor compatible with conventional packages found in latest Ubuntu releases. The boards of the Jetson family come incorporated with an SDK 2of NVIDIA’s own called Jetpack, in which the following is included in its most basic configuration. 2SDK, or Software Development Kit, is a set of tools for developers designed to be able to configure and create applications for a specific environment
5.4. Final environment setup 53 • CUDA Toolkit: it is the platform offered by NVIDIA to be able to take advantage of the GPU for parallel execution. • cuDNN (CUDA Deep Neural Network Library): Optimized library for deep neural networks on NVIDIA GPUs. • TensorRT: platform for optimizing inference with deep learning. • VisionWorks and OpenCV: computer vision libraries. • Support for containers with Docker and NVIDIA GPU Cloud, although of these two only Docker is used in this project. The two main impediments in the migration from the server to the Orin board were differences at the architecture and operating system level. To address these problems, it was decided to use Docker to create a consistent and easily portable development environment to other boards in the same family, just as was done on the server. This decision was made because, being developer kits, the kernel versions of the boards change frequently, leading to compatibility issues, particularly with packages related to the GPU. As for Docker, it was necessary to use a different configuration than the server, as the NVIDIA:cuda image that was used was not compatible with the architecture of the board, and a specially designed L4T image had to be used instead. Specifically, an image was used that had all machine learning Python packages installed such as torch or torchvision specific to the board, thus avoiding having to manually configure them. A problem derived from using Docker was the lack of space on the board, since Docker already occupies several GB, and the image that was used weighed around 13GB. In addition, it must be taken into account that the space of the board was not available in its entirety, as its resources are distributed among the different members of the CAOS group. For this reason, it was necessary to look for a compatible SSD and expand the storage (a 2TB MVMe expansion has been finally procured). The last problem in the migration to the board had to do with ROS2. The version used for this project is ROS:Humble, but this is only compatible on Debian systems with Ubuntu Focal (22.04), and the board in question has an older Kernel version that uses Ubuntu 20.04. For this reason, it was necessary to find a Docker image that installed from source ROS Humble in order to sort this drawback.
55 Chapter 6 Evaluation This section outlines the test design for evaluating the performance of the designed object detection system and reports the observed results. The primary objectives of the evaluation are to measure various aspects of processing time and communication latency, and to assess the system’s behavior under different configurations and input resolutions. 6.1 Performance metrics Evaluation is focused on a set of performance-related metrics that serve to assess the achievement of timing constraints on the object detection function. The performance metrics that are going to be considered are the following. •Elapsed processing time: This metric measures the total time taken from the moment a frame is published to when it is reviewed. It encompasses all stages of the pipeline. •Frame processing time: This measures the time taken to process each frame individually across all three different instances. •Communication time: The purpose of this metric is to provide insights on the time lost due to the different types of communications used in the pipeline. •Frame rate: Provides a general understanding of the performance of the system. FIGURE 6.1: Stages where metrics are retrieved.
56 Chapter 6. Evaluation Green area represents the section of the pipeline where included in the elapsed processing time. The sum of orange areas represent the parts computed in the communication time, and lastly the frame processing time is compressed in the blue area (scale is not representative). 6.2 Scenarios to test The tests are designed to evaluate the system under various scenarios to understand its performance under different loads and deployment configurations. Deployment configurations (i.e. where object detection functions are executed) is a relevant aspect to consider in heterogeneous architecture where multiple and diverse computing elements and accelerators are available. A system designer is interested in determining the optimal configuration, given that minimal performance requirements are met. The explored scenarios include: •Single Instance on CPU Running just one instance of the object detection framework on the CPU. The goal of this scenario is to evaluate the most primitive version of this system possible, running only a single node that processes the images that are received from the publisher. Since only one node is running, there is no reason to use the reviewer, so in total with this set up there will only be two active nodes. This comparison will highlight the contrast between the two processing platforms and provide a deeper understanding of the limitations inherent in running the system exclusively on one CPU. Since the project will be implemented on the NVIDIA Orin, it is critical to understand how using the accelerators available on the GPU can significantly improve the performance and efficiency of the system. This comparison will also serve to justify and support the choice to use the GPU in the final deployment of the project, demonstrating the tangible benefits of leveraging the available acceleration resources. •Single Instance on GPU: Running just one instance of the object detection framework on the GPU. This second scenario is the natural evolution of the first. Only a single node is used to process images, and as in the first scenario, there is no need to use the reviewer node, so only two nodes will be active. The only difference is that the subscriber node will execute some of its code on the graphics card, which should result in a substantial improvement in system performance. •Two Instances on GPU: Running two instances of the object detection framework simultaneously on the GPU. This is the target scenario, it represents the first point at which the functional requirements established for this work are met, because we have achieved both redundancy (two instances that make predictions working in parallel) and diversity (both instances differ slightly at the software level). Getting this scenario to perform well would in itself fulfill the objective of this work, but at a functional level it has a drawback, and that is that the only alternative it would have to react to an error would be to repeat the prediction, as it would require another instance to be able to carry out majority voting.
6.3. Reference results on the Server machine 57 •Three Instances on GPU (Extra Scenario): Running three instances of the object detection framework simultaneously on the GPU. This is an extra scenario for this work, and it represent the most complete among those considered in the project, because in addition to covering the functional requirements established at the beginning of this work, it provides an extra layer of functional safety by introducing an additional instance of the object detection function, which ultimately allows to carry out majority voting in the event of suffering an error of any kind, and therefore have some room for manoeuvre in a compromised situation. The tests will be conducted under two main experimental setups (see Section 5.4). In the first setup, the entire battery of tests scenarios will be carried out on the more powerful server machine, testing all the scenarios. The second setup will aim at performing the same tests on the NVIDIA Orin board, trying to get as close as possible to the results obtained on the server setup but taking into account the lower computational power of Orin. 6.2.1 Target scenario The ideal target scenario comprises a system performing object detection that meets the requirements for redundancy and diversity with two (ideally with three) instances running in parallel, and that operates smoothly enough in terms of frames per second. The latter is a critical aspect, especially when moving away from powerful (and power consuming) high-end platforms as the considered server machine. The ability of the human eye to perceive movement is a complex issue, and transferring the concept of framerate from the world of computer vision to anatomy is not easy, but it is possible to make an approximation to it. On the one hand there is the perception of continuous movement, for a person to perceive continuity there must be at least between 12 and 16 frames per second. Then, from 23 to 30 frames per second, most people begin to perceive motion as smooth and fluid (Ozgur, Yue, and Ali, 2006), which is why most video standards in the world of film and television move in this same interval (conversion, 2024). Although there is evidence that the human eye is sensitive to higher frame rates, the above interval is the goal to be achieved for the objective scenario of this work. Performance is heavily affected by the input size as the more details included in an image the more the time required to perform the inference. As far as resolution is concerned, the goal is to achieve the 30 frames per second rate with the highest possible resolution, which for YoLo v.7 is 640x640 pixels, so that to achieve the maximum accuracy. 6.3 Reference results on the Server machine In the following we report the results gathered on the served setup for all the defined deployment scenarios. As declared in the previous Section, YoLo has been configure to process 640x640 pixels images at 30 frames per second. 6.3.1 Single instance on CPU This is the first of the experiments on the server. To carry it out, the project launcher file has been edited to only run the publisher node and the main subscriber. The main subscriber is using the model encoded with fp32.
64 Chapter 6. Evaluation FIGURE 6.9: Left to right, frame processing time for main, trail and tiebreaker instance. The processing time of each frame for each instance is maintained, although somewhat higher than the same levels observed in the previous GPU experiments, being on average 0.0205s for the main subscriber, 0.0202s for the trail and finally 0.0208s for the tiebreaker. This is showing again how the introduction of diversity does not influence performance. This is a considerable worsening compared to scenario 1 for example, where the average was 0.0119s (72.26% decrease), or 0.0181s in scenario 2 (13.2% decrease) for the same main instance. It is normal, however, for the individual performance of each instance to deteriorate as the number of active instances increases, for example by limitations such as the bandwidth of the memory communication bus (derived from simultaneous access of all instances to it) or overheads from task planning and waiting, among other reasons. The important thing is that the system continues to work well with three instances, maintaining the requirements for diversity and redundancy and with an acceptable frame rate. FIGURE 6.10: Left to right, elapsed communication times for main, trail and tiebreaker instances In the three graphs above it can be noticed how despite working with three instances, the total time lost due to communications is practically negligible. 6.4 Baseline results on the Orin Despite the big difference in resources between the CAOS22 server and the NVIDIA Orin, for the tests on the board we will initially use exactly the same configuration in terms of resolution and framerate as on the server, that is 640x640 pixel images at 30 frames per second. 6.4.1 Single instance on CPU The configuration for this first scenario is exactly the same as the one explained in Section 6.3.1, with the main and only subscriber using the fp32 version of the model. The results obtained are as follows.
6.4. Baseline results on the Orin 65 FIGURE 6.11: On the left, elapsed time for end to end processing (blue) relative to 30 fps (orange). On the right the end to end elapsed time stats. As expected, there is the same problem as with scenario 1 on the server, and that is that the subscriber is not able to keep up with the publisher. Specifically, in this case the problem is much greater, because on the server the subscriber was able to process up to 70 frames, delaying a maximum of 7.54 seconds, while in the Orin only 14 frames are processed, with a delay at the end of the video of 12.40 seconds. Note also how initially it starts with 3.59 seconds with respect to the publisher, despite using a warm up method in the publisher to take the subscriber to the processing rhythm that the framerate dictates progressively. Reviewing the processing time of each frame we get the following. FIGURE 6.12: Frame processing time for the main instance As the previous plot revealed, the main subscriber processes the frames at a much lower rate than the framerate should limit, around the one second mark, when in the same scenario on the server the average was around 0.150 seconds. These results were to be expected, however, as the board has much less memory, in addition to having a processor with ARM architecture that has 4 cores and less and much lower power consumption, just as shown in Table 5.2. 6.4.2 Single instance on GPU Using exactly the same setup as in the previous section, the results obtained are as follows.
66 Chapter 6. Evaluation FIGURE 6.13: Elapsed end to end processing time (blue) relative to the framerate (orange) Here for the first time we see a very relevant change in terms of performance, and that is that on the server a single instance worked comfortably, but we see that the board is not able to keep up with the pace set by the publisher. Seeing the time it takes for the subscriber to process each frame, it is noticeable how at all times it is behind the framerate. FIGURE 6.14: On the left, elapsed frame processing time (blue) relative to framerate (orange). On the right the elapsed frame processing time stats. Compared to the same scenario on the server, in terms of average processing time the board achieves 0.036315 seconds, a 286.84% increase, which is an absolute failure. The fact that a single instance does not work within the established test margins completely invalidates the next two scenarios to be tested, as of course they would be a failure in terms of performance. The only possible solution at this point is to modify the environment that is being used on the board in order to make it faster, and also less demanding in terms of resources, and for that it is necessary to use more relaxed operating margins than those chosen for the server. We explore the necessary changes and their respective evaluation in the next section.
6.5. One step beyond: tailoring the system for the board 67 6.5 One step beyond: tailoring the system for the board This last step forward in the development of the board is aimed at increasing the performance of the system that has been developed up to this point. We aim at achieving a satisfactory framerate, bringing the performance on the Orin as close as possible to those obtained on the server. To achieve this, two paths will be followed. • Speed up the inference: Reduce the time it takes for each instance to compute predictions in order to increase the throughput and lower the latency. • Use a lighter setup: To reduce the amount of resources needed by the system, since the board is much more limited at the hardware level than the server. Accelerating the inference with TensorRT When deploying AI models, several techniques can optimize runtime for deployment, including (1) designing and adjusting model architecture concerning size, depth, and width, (2) applying pruning techniques to remove neurons, neuron groups, or filters with minimal impact on output, and (3) using quantization to change the numerical representation of data and network weights (Staacker et al., 2022). Since general deep learning frameworks like TensorFlow and PyTorch are not specifically optimized for inference, we focus on (1) and (2) to enhance system performance, acknowledging that these techniques typically involve a trade-off between runtime and accuracy. Quantization it is not an option for this work since we already have two different instances that use fp32 and fp16, and applying it would lead us to make the leap to int8 to one of the diverse instances, something that would surely end up introducing too much variation in the results from one instance to the other. To achieve these improvements, we will utilize NVIDIA’s TensorRT deep learning framework, a high-performance inference engine designed to enhance throughput and efficiency. TensorRT implements various optimization strategies to reduce the latency of deep learning models (Zhou and Yang, 2022), such as: • Layer and tensor fusion: Optimizes GPU memory and bandwidth usage by fusing nodes in a kernel vertically or horizontally (or both), reducing the overhead and cost of reading and writing tensor data for each layer. • Kernel auto-tuning: Provides kernel-specific optimization by selecting the best layers, algorithms, and optimal batch size based on the target GPU platform. • Dynamic tensor memory: Improves memory reuse by allocating memory to the tensor only for the duration of its use, reducing memory consumption and avoiding allocation overhead for efficient execution. • Multi-stream execution: Processes multiple input streams in parallel.
68 Chapter 6. Evaluation Three main steps have been followed in order to build and use the TensorRT inference engine (Zhou and Yang, 2023). 1. Export of the PyTorch model to ONNX 1 In this initial step, we use the built in export method from the PyTorch library to export the PyTorch model to ONNX files. This function takes an input tensor to trace the original PyTorch model’s execution and then exports the traced model to an ONNX file. 2. Build of the TensorRT engine We build the TensorRT engine using an ONNX model with the TensorRT Python API. The process involves several steps. First of all a network definition is created, this step involves defining the structure of the neural network that TensorRT will use. Then, the ONNX parser is used to import the model with the common format build in the previous step. And lastly, the TensorRT model is build using a builder to compile and optimize the network definition into a TensorRT engine. It is at this point that it is indicated what type of data is going to be used for the model, whether floating point 16 or 32, in addition to the resolution of the model’s input images. 3. TensorRT engine deployment This last step is carried out at runtime, and requires the following tasks. Specifically, tasks (a) (b) and (c) are executed in the first stage of the warm up explained in the section 6.3.2, intended as mentioned above to load the model. (a) Create an Inference Execution Context: Set up the environment needed to execute the model. (b) Allocate Memory on the CUDA Device: Reserve space for both input and output data on the GPU. (c) Transfer Input Data to the CUDA Device: Move the input data from the host (CPU) to the allocated memory on the GPU. (d) Execute the TensorRT Engine Inference: Run the model inference using TensorRT’s asynchronous execution API, which allows the GPU to perform computations without waiting for the CPU. (e) Transfer Output Data Back to the Host: Move the results from the GPU memory back to the CPU. (f) Synchronize the Stream: Ensure all data transfers and inference operations are completed by synchronizing the stream used for these tasks. This guarantees that all steps are finished before proceeding. Downscaling the setup To try to reduce the amount of resources needed to run the system, two different approaches have been used. 1Open Neural Network Exchange (ONNX), is an open source AI ecosystem designed to maximize interoperability between different frameworks thanks to the establishment of a common file format.
6.5. One step beyond: tailoring the system for the board 69 The first has consisted of using a lighter version, or tiny as it is usually called, of the model’s weights. To build these tiny versions, different techniques are used, such as reducing the number of layers or their width, or also what is known as pruning (Lianga et al., 2021), which involves eliminating neurons, groups of neurons or filters that have little or no contribution to the final result. FIGURE 6.15: Pruning technique to reduce the model’s complexity The model weights employ then a simplified architecture with fewer parameters, and thus result in significantly lighter weight files, decreasing the amount of RAM and VRAM required to load and run the model. In addition, the simplified architecture and the use of fewer parameters contribute to a faster inference. The second improvement has been simpler; using images with lower resolution. For all the tests up to this point in the work, 640x640 pixel images have been used, but for this last point it will be changed to 320x320 instead. FIGURE 6.16: 640x640 resolution vs 320x320 This change means that at the time of inference, 4 times less data is introduced into the network. Once we have seen the modifications that have been made to better adapt the system to the board, we proceed with the tests. 6.5.1 Single instance on CPU This scenario has not been feasible, as TensorRT is not designed to run on CPU. This framework is exclusively designed and optimized for NVIDIA graphics cards.
70 Chapter 6. Evaluation 6.5.2 Single instance on GPU For this scenario, we have used exactly the same configuration as in the two previous tests considering a single instance running on GPUs (on Server and Orin), but changing the subscriber code to incorporate the optimizations mentioned above. As before, the subscriber is using a fp32 version of the model. The results obtained are reported in Figure 6.17 below. FIGURE 6.17: On the left, elapsed time for end to end processing (blue) relative to 30 fps framerate (orange). On the right the end to end elapsed time stats. We see how, except for the warm-up phase, the time elapsed from one end of the pipeline to the other is maintained consistently and with a wide margin below the threshold defined by the framerate. This is positively reminiscent of the results obtained for this same scenario on the server, although the average elapsed time is 62.26% higher in comparison. Let’s consider below in Figure 6.18 the processing time of each frame. FIGURE 6.18: On the left, frame processing time (blue) relative to 30 fps framerate (orange). On the right the frame processing time stats. We see how the processing time of each frame is consistent except for the warm-up interval. Once stabilized, it stays far from the framerate threshold. Compared to the same scenario on the server, it is 42.18% slower, and compared to the old configuration on the board it has improved by 212.92% both in terms of average processing time.
6.5. One step beyond: tailoring the system for the board 71 6.5.3 Two diverse instances on GPU This is the key target scenario in the scope of this work, since supporting a system working correctly with two diverse and redundant instances on the Orin meet all the objectives established for the project. The same setup is used as in the other two scenarios already analyzed above with the same configuration, but adding the optimizations mentioned at the beginning of this section. Redundancy is covered since we have two instances, and diversity too because of the different data type used for the model; main instance is using fp32 and the trail instance fp16. The results obtained for the time elapsed from one end of the pipeline to the other are as follows. FIGURE 6.19: On the left, elapsed time for end to end processing (blue) relative to the framerate (orange). On the right the end to end elapsed time stats. In this case, we see how the time elapsed from one end of the pipeline to the other is always below the framerate limit, except for the warm-up phase and two small spikes between frames 50 and 60, which we can still qualify as successful. In this case the margin is not at all wide, and we could say that we are already at the limits of this system, since a higher framerate or a higher resolution would already compromise the system. It should be noted from here how the average elapsed time has worsened compared to the previous scenario, 17% slower specifically, and nearly doubles the standard deviation, possibly due to the variability introduced by the competition for resources of the two instances. Let’s look at the processing times of each frame for the two instances.
72 Chapter 6. Evaluation FIGURE 6.20: On the left, frame processing time (blue) related to framerate (orange) for the main instance. On the right, frame processing time (blue) related to framerate (orange) for the trail instance. FIGURE 6.21: On the left, frame processing time stats for the main instance. On the right, frame processing time stats for the trail instance. We have frame processing time very close to the framerate threshold. In the case of the main subscriber, the average processing time of each frame has worsened by 24.52% compared to the same instance in the previous scenario, a considerable deterioration considering that only one more instance has been added. FIGURE 6.22: On the left, communication overhead the main instance. On the right, communication overhead for the trail instance. On the other hand, the overhead introduced by communication is once again negligible. With this experiment it has been possible to replicate the target scenario that had already been tested on the board, having redundant and diverse instances working in parallel with some logic implemented in the review of the output of each instance, and equally important, with a frame rate good enough to work if necessary in a real time scenario.
6.5. One step beyond: tailoring the system for the board 73 6.5.4 Three diverse instances on GPU Despite the two-instances scenario was already hitting the limits of the Orin in terms of computation and supported framerate, we wanted to test the extra scenario with three redundant instances. Redundancy is clearly covered, and regarding diversity the main subscriber uses the model with fp32, while the trail subscriber uses fp16. In the three instance scenario, with the addition of the tiebreaker, which slightly modifies the input image, the diversity aspect is even more evident. Results are reported in Figure 6.23 below. FIGURE 6.23: End to end elapsed time (blue) related to framerate (orange). Looking at the graph of elapsed time from one end of the pipeline to the other, it is seen that the experiment is a failure. However, despite never being below the framerate threshold, you can see how the observed time is pretty close to it an is not increasing, which indicates that the delay occurs only at the beginning. This could possibly be corrected by using a gentler warm-up phase, giving all three instances more time to pick up the pace. FIGURE 6.24: Left to right, frame processing time for main, trail and tiebreaker instance. The processing times per frame for all three instances, shown in Figure 6.24, exhibit average times very similar to those of previous experiments, although they occasionally exceed the framerate threshold. However, the observed behavior can be misleading. It is possible to obtain reasonable processing times in all three instances without significantly benefiting from parallelism. This may be due, for example, to high competition for resources, which limits the effectiveness of parallelism despite apparent average times. The important thing to take away from this experiment is that although it has not been successful, it shows that using three instances simultaneously on the board would still be possible by slightly
81 Appendix B Updated time planning appendix B.1 Updated Gantt Diagram The following image displays the updated Gantt diagram with the time planning for all the involved tasks in the project. Notice how every group of tasks appears in different colors. FIGURE B.1: Updated Gantt Chart
83 Appendix C Codebase of the project The codebase of the project can be found in the following GitHub repository: https://github.com/ivanserrano-hernandez/Bachelor-Thesis . This repository is divided in five different branches. •main It contains a basic implementation of the object detection system, with no redundancy or diversity, nor the ROS2 layer, nor is it GPU-ready. •ros2-build This branch contains a more advanced implementation, already with the ROS2 layer and two different instances. •server-build Final project implementation designed for the CAOS22 server. •jetson-orin-pytorch Final project implementation designed for NVIDIA Orin, with the object detection framework using PyTorch. •jetson-orin-trt Final project implementation designed for NVIDIA Orin, with TensorRT optimization.
85 Bibliography Alcón, Miguel et al. (2021). “Enabling Unit Testing of Already-Integrated AI Software Systems: The Case of Apollo for Autonomous Driving”. In: URL:https: //upcommons.upc.edu/bitstream/handle/2117/353609/2021121176.pdf? sequence=1. Arrieta, Alejandro Barredo et al. (2019). “Explainable Artificial Intelligence (XAI): Concepts, Taxonomies, Opportunities and Challenges toward Responsible AI”. In: URL:https://arxiv.org/abs/1910.10045. Caro, Martí, Jordi Fornt, and Jaume Abella (2023). “Efficient Diverse Redundant DNNs for Autonomous Driving”. In: URL:https://www.researchgate.net/ publication/372864152_Efficient_Diverse_Redundant_DNNs_for_Autonomous_ Driving/citation/download. conversion, Television standards (2024). Wikipedia.URL:https://en.wikipedia. org/wiki/Television_standards_conversion. Elharroussa, Omar et al. (2022). “Backbones-Review: Feature Extraction Networks for Deep Learning and Deep Reinforcement Learning Approaches”. In: URL: https://arxiv.org/pdf/2206.08016. Europe, European Union’s Horizon (2022). Safexplain home page.URL:https : / / safexplain.eu/. Girshick, Joss et al. (2014). “Rich feature hierarchies for accurate object detection and semantic segmentation”. In: URL:https://arxiv.org/pdf/1311.2524v5. Kato, Shinpei et al. (2018). “Autoware on Board: Enabling Autonomous Vehicles with Embedded Systems”. In: URL:https://www.researchgate.net/publication/ 327198306_Autoware_on_Board_Enabling_Autonomous_Vehicles_with_Embedded_ Systems. Kim, Sanmin et al. (2023). “Predict to Detect: Prediction-guided Object Detection using Sequential Images”. In: URL:https://openaccess.thecvf.com/content/ ICCV2023/papers/Kim_Predict_to_Detect_Prediction-guided_3D_Object_ Detection_using_Sequential_Images_ICCV_2023_paper.pdf. Li, Renjie et al. (2022). “A comprehensive review on deep supervision: Theories and applications”. In: URL:https://arxiv.org/pdf/2207.02376. Lianga, Tailin et al. (2021). “Pruning and Quantization for Deep Neural Network Acceleration: A Survey”. In: URL:https://arxiv.org/pdf/2101.09671. Macenski, Steve et al. (2022). “Robot Operating System 2: Design, Architecture, and Uses In The Wild”. In: URL:https://arxiv.org/abs/2211.07752.
86 Bibliography Nvidia (2024). Nvidia Orin.URL:https : / / www . nvidia . com / content / dam / en - zz/Solutions/gtcf21/jetson-orin/nvidia-jetson-agx-orin-technical- brief.pdf. Ozgur, Ferhat, Tao Yue, and Shaukat Ali (2006). “Kristin Koch and Judith McLean and Ronen Segev and Michael A. Freed and Michael J Berry and Vijay Balasubramanian and Peter Sterling”. In: URL:https://retina.anatomy.upenn.edu/ pdfiles/6728.pdf. Perez-Cerrolaza, Jon, Jaume Abella, Markus Borg, et al. (2023). “Artificial Intelligence for Safety-Critical Systems in Industrial and Transportation Domains: A Survey”. In: URL:https://dl.acm.org/doi/pdf/10.1145/3626314. Perez-Cerrolaza, Jon, Jaume Abella, Leonidas Kosmidis, et al. (2022). “GPU Devices for Safety-Critical Systems: A Survey”. In: URL:https://www.researchgate. net/publication/362138939_GPU_Devices_for_Safety-Critical_Systems_A_ Survey. Quigley, Morgan et al. (2009). “ROS: an open-source Robot Operating System”. In: URL:http://robotics.stanford.edu/~ang/papers/icraoss09-ROS.pdf. Redmon, Joseph et al. (2015). “You Only Look Once: Unified, Real-Time Object Detection”. In: URL:https://arxiv.org/pdf/1506.02640. Salameh, Shahin Atakishiyev andMohammad, Hengshuai Yao, and Randy Goebel (2021). “Towards Safe, Explainable, and Regulated Autonomous Driving”. In: URL:https://arxiv.org/abs/2111.10518. Staacker, Lukas et al. (2022). “Deployment of Deep Neural Networks for Object Detection on Edge AI Devices with Runtime Optimization”. In: URL:https : //openaccess .thecvf .com /content/ ICCV2021W/ ERCVAD/papers/Stacker _ Deployment_of_Deep_Neural_Networks_for_Object_Detection_on_Edge_ ICCVW_2021_paper.pdf. Zhou, Yuxiao and Kecheng Yang (2022). “Exploring TensorRT to Improve Real-Time Inference for Deep Learning”. In: URL:https://userweb.cs.txstate.edu/~k_ y47/webpage/pubs/icess22.pdf. — (2023). “Improved Real-Time Deep Learning Inference by Exploiting TensorRT”. In: URL:https://shorturl.at/FL784.