scieee AI-readable full text Open interactive document viewer

Developing a support for FPGAs in the Controller parallel programming model

Rodríguez Canal, Gabriel

Abstract

Grado en Ingeniería Informática

Full text

Universidad de Valladolid ESCUELA DE INGENIERÍA INFORMÁTICA GRADO EN INGENIERÍA INFORMÁTICA MENCIÓN EN COMPUTACIÓN Developing a support for FPGAs in the Controller parallel programming model Student: Mr. Gabriel Rodríguez Canal Advisors: Dr. Yuri Torres de la Sierra Dr. Arturo González Escribano To my family. I II ACKNOWLEDGEMENTS Acknowledgements I want to thank the Trasgo research group for giving me the opportunity to work with them and initiate my research career. I want to especially thank my advisors, Arturo and Yuri, for their implication in my work and all their advise that have made of this work a fruitful, enjoyable experience. Their guidelines have been utterly valuable to grasp the research methodology. I would also like to show my appreciation to my colleagues at the research group, who welcomed me and helped me with their experience. I would also like to outline the invaluable help of the professor Darío Suárez Gracia, from the University of Zaragoza. Thank you for answering all my questions and sharing your research resources with us. I want to mention my family as well, who have supported me emotionally during this journey, happy most of the time yet hard and stressful at some moments. This research has been partially supported by MICINN (Spain), the ERDF program of the European Union and Junta de Castilla y León: PCAS project (TIN2017-88614-R), FEDER Grant VA082P17 (PROPHET project), CAPAP-H6 and MECD (Beca de Colaboración, Spain). III ACKNOWLEDGEMENTS IV RESUMEN Resumen La computación heterogénea se presenta como la solución para conseguir supercomputadores cada vez más rápidos capaces de resolver problemas más grandes y complejos en diferentes áreas de conocimiento. Para ello, integra aceleradores con distintas arquitecturas capaces de explotar las características de los problemas desde distintos enfoques obteniendo, de este modo, un mayor rendimiento. Las FPGAs son hardware recongurable, i.e., es posible modicarlas después de su fabricación. Esto permite una gran exibilidad y una máxima adaptación al problema en cuestión. Además, tienen un consumo energético muy bajo. Todas estas ventajas tienen el gran inconveniente de una más difícil programación mediante los propensos a errores HDLs (Hardware Description Language), tales como Verilog o VHDL, y requisitos de conocimientos avanzados de electrónica digital. En los últimos años los principales fabricantes de FPGAs han enfocado sus esfuerzos en desarrollar herramientas HLS (High Level Synthesis) que permiten programarlas a través de lenguajes de programación de alto nivel estilo C. Esto ha favorecido su adopción por la comunidad HPC y su integración en los nuevos supercomputadores. Sin embargo, el programador aún tiene que ocuparse de aspectos como la gestión de colas de comandos, parámetros de lanzamiento o transferencias de datos. El modelo Controller es una librería que facilita la gestión de la coordinación, comunicación y los detalles de lanzamiento de los kernels en aceleradores hardware. Explota de forma transparente sus modelos de programación nativos, en concreto OpenCL y CUDA, y, por tanto, consigue un alto rendimiento independientemente del compilador. Permite al programador utilizar los distintos recursos hardware disponibles de forma combinada en entornos heterogéneos. Este trabajo extiende el modelo Controller mediante el desarrollo de un backend que permite la integración de FPGAs, manteniendo los cambios sobre la interfaz de usuario al mínimo. A través de los resultados experimentales se comprueba que se consigue una disminución del esfuerzo de programación signicativa en comparación con la implementación nativa en OpenCL. Del mismo modo, se consigue un elevado solapamiento entre computación y comunicación y un sobrecoste por el uso de la librería despreciable. V RESUMEN VI ABSTRACT Abstract Heterogeneous computing appears to be the solution to achieve ever faster computers capable of solving bigger and more complex problems in dierent elds of knowledge. To that end, it integrates accelerators with dierent architectures capable of exploiting the features of problems from dierent perspectives thus achieving higher performance. FPGAs are recongurable hardware, i.e., it is possible to modify them after manufacture. This allows great exibility and maximum adaptability to the given problem. In addition, they have low power consumption. All these advantages have the great objection of more dicult programming with the errorprone HDLs (Hardware Description Language), such as Verilog or VHDL, and the requirement of advanced knowledge of digital electronics. The main FPGA vendors have concentrated on developing HLS (High Level Synthesis) tools that allow to program them with C-like high level programming languages. This favoured their adoption by the HPC community and their integration in new supercomputers. However, the programmer still has to take care of aspects such as management of command queues, launching parameters or data transfers. The Controller model is a library to easily manage the coordination, communication and kernel launching details on hardware accelerators. It transparently exploits their native or vendor specic programming models, namely OpenCL and CUDA, thus enabling the potential performance obtained by using them in a compiler agnostic way. It is intended to enable the programmer to make use of the dierent available hardware resources in combination in heterogeneous environments. This work extends the Controller model through the development of a backend that allows the integration of FPGAs, keeping the changes over the user-facing interface to the minimum. The experimental results validate that a signicant decrease in programming eort compared to the native OpenCL implementation is achieved. Similarly, high overlap of computation and communication and a negligible overhead due to the use of the library are attained. VII LIST OF FIGURES 3.8 Management of incongruent grid sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 3.9 Pinned memory in OpenCL (Nvidia's implementation). . . . . . . . . . . . . . . . . . . . . 33 4.1 Initialisation code removed from runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 4.2 Arbitration logic for two dierent ways of passing structs . . . . . . . . . . . . . . . . . . . 46 4.3 Generation of function signature from CTRL_KERNEL . . . . . . . . . . . . . . . . . . . 47 5.1 Experimentation results with Hotspot and Matrix Power (size) . . . . . . . . . . . . . . . 55 5.2 Experimentation results with Hotspot, Matrix Power and Sobel Filter (iterations) . . . . . 56 XIV LIST OF TABLES List of Tables 1.1 Summary of the most relevant features and costs of OpenCL compatible FPGAs. . . . . . 4 1.2 Costsofsoftwarelicenses. .................................... 4 1.3 Estimations of the time invested by two roles involved in the work for its development. . . 5 2.1 Evolution of DRAM size over years . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 4.1 Load store units latencies in the experiment kernels . . . . . . . . . . . . . . . . . . . . . . 46 5.3 Frequencies of the experimentation kernels in native and Controllers versions. . . . . . . . 56 5.1 Average exectution times, overlap and overhead with AOC v19.3 . . . . . . . . . . . . . . 58 5.2 Average exectution times, overlap and overhead with AOC v20.1 . . . . . . . . . . . . . . 59 5.4 Developmenteortmetrics ................................... 59 XV LIST OF TABLES XVI CHAPTER 1. INTRODUCTION Chapter 1 Introduction On this chapter the following aspects are introduced: • The context and motivation for the work. • Problem statement. • The structure of the document. 1.1 Context The increase in the operating frequency of processors has been the recipe for progress in computing performance during decades, but this is no longer possible due to heat emission. The power dissipated by a processor is proportional to the squared voltage and the frequency. Frequency grows linearly with voltage, so the case for the power is even worse, as it turns out to be proportional to the cubed voltage [49]. This raised the need for other strategies, both software and hardware based, to bypass this limitation. The traditional sequential approach in which a single CPU core executed one instruction after another evolved to the concurrent and parallel programming paradigms, which seek the execution of tasks at the same time. This premise can be virtually achieved in concurrent programming with a single core by interleaving small windows of time for the dierent tasks, creating the illusion of multitasking . Parallel computing, on the other hand, achieves true simultaneous execution of tasks by relying on multicore processors. These comprise several independent compute units capable of executing one thread each simultaneously. It is common nowadays to nd microprocessors with 4 or 8 cores in commodity systems. However, a CPU with N cores will not be able to achieve a speedup of N in a given application, due to data dependencies, serial parts and synchronization costs, partially explained by Amdahl's Law [32]. CPU vendors have worked in the renement of this approach, creating new architectures and developing new technologies such as hyperthreading [27], capable of increasing the number of virtual cores by scheduling several threads in a given core that are to use a disjoint set of resources. Following this trend, GPUs (Graphical Processing Unit), another microprogrammed architecture initially designed to support the complex calculations of graphical computing, turned out to outperform multicore CPUs thanks to their huge number of simpler compute units, which gives them the name of manycore . This ability to better exploit inherent parallelism fostered the development of heterogeneous systems, in which a CPU plays the role of host and the computation is ooaded to a co-processor or accelerator . This way it is posible to dissect problems and schedule every piece to the most suitable accelerator. Tipically, sequential parts will be solved faster by CPUs, while massively parallel problems t GPUs better. Despite all the performance 1 1.2. MOTIVATION benets of GPUs they come at the cost of high energy consumption. This could be minimised by the use of ASICs (Application Specic Integrated Circuit), that featured just the resources required for a given problem, thus limiting the working die area. This is not a practical solution, since the development of ASICs has cumbersome design costs. Fortunately, recongurable hardware gathers both the capability of implementing solutions to dierent problems of GPUs through programming and the specity of a circuit adapted to a given problem of ASICs. FPGAs (Field Programmable Gate Array) are the example of recongurable hardware device most used in industry [10, 38]. They have been around since the 80s, when they were used to diminish the cost of prototyping new ASIC designs. They were not capable of holding really complex designs back then, what made them unsuitable for computing. This has changed thanks to the improvements in integration, which has lead to an increase in the density of their logic fabric. They have suered from heavy and error-prone programming with HDLs (Hardware Description Language) such as Verilog [29] or VHDL [8] in the past, which, on top of that, required deep knowledge of electronics, which hindered their adoption by the HPC 1 community. This has changed in the recent years thanks to the development of HLS (High Level Synthesis) languages and frameworks such as the Intel FPGA SDK for OpenCL by Intel [23] or SDAccel by Xilinx [48], both based on OpenCL, thus improving programmability by replacing HDLs by C-like languages. 1.2 Motivation The development of HLS tools has eased the integration of FPGAs in heterogenous systems. However, several challenges regarding programmability remain that have to be faced by the programmer. He still has to take care of aspects such as command queue management, kernel launching parameters or data transfers. This results in a cumbersome boilerplate code that severely impacts portability. The main goal of heterogeneous systems is the exploitation of the particular features of every architecture available to achieve higher performance. This is usually achieved by leveraging the vendor specic tools for every given architecture and having in-depth knowledge of their details. Controllers removes these restriction by providing a uniform user-facing interface to the programmer that enables the use of CPUs and GPUs as accelerators by leveraging the vendor specic frameworks under the hood, thus achieving optimal performance. It also takes care of dependencies, thus easing ecient programmability and allows seamless overlapping of data transfers and computation thanks to its asynchronous policy. 1.3 Problem statement The aim of this work is to expand the Controllers model by giving support to FPGAs, thus allowing their integration in heterogeneous systems that use the library. Controllers already supported the simultaneous use of CPUs and GPUs. In order to preseve this compatibility, this work should intend for a modular approach. FPGAs are very dierent from the traditional microprogrammed architectures. Their ability to adapt to the given problem instead of the other way around and their recongurability opens a world of possibilities. However, the particularities of their architecture poses new challenges in the form of dierent 1 HPC (High Performance Computing) deals with big scale scientic and engineering problems, such as weather forecasting or simulation of uid dynamics, seeking a reduction in the time needed to nd their solution and giving support to ever increasing input sizes. For that, it involves a combination of research in areas such as compilers, runtime systems, parallel programming and cutting-edge hardware. The last trend for performance are heterogeneous systems, which form the basis of modern supercomputers appearing in the world class list TOP500 [1]. 2 CHAPTER 1. INTRODUCTION ways of programming at the algorithmic level, a broader set of congurable parameters and compilation times that can last for hours. Despite the huge improvement in programmability achieved by the HLS frameworks, these dierences require a further eort to ease their use in a heterogeneous environment. On top of that, memory management is even more critical for these devices due to their slower types of ochip memory. For this reason, a library like Controllers that takes care of data transfers and data dependencies is a must for the proper integration of these devices in heterogeneous systems. 1.3.1 Objectives The objectives of this work are as follows: • Study and comprehend the existent works. • Study the Hitmap [15] and Controllers [30] libraries that lay the foundations of this work. • Design and implement a prototype of the proposed model. • Design, implement and execute experimentation cases that enable the validation of the model. • Obtain results and reach conclusions from the experimentation performed. • Validate the proposed model. 1.3.2 Budget and planication This work is the rst attempt of the Trasgo research group to include FPGAs in their workow. As a consequence, some resources have to be acquired before the work starts. In these situations it is necessary to account for the costs of new hardware, software licenses and the time invested in training the involved personnel. This section presents a rough inital planication and several budget options to get some insight into the costs of this work. Table 1.1 shows the most relevant OpenCL compatible FPGAs in the market at the moment. Many features can be taken into account to choose an option. However, only the most relevant for our purposes have been listed. Features such as the operating temperature or power consumption account for price variability, but they are not that determinant for an initial budget. Finally, the features that made it into the list are: 1. Memory: maximum ochip memory that can be installed on the FPGA board. From fastest to slowest, the three available types are HBM2, DDR4 and DDR3. 2. PCIe: the type of connectivity bus featured by the FPGA board. The highest memory bandwidth will be achieved by x16. 3. LUTs: lookup-tables. This gure expresses the number of congurable logic gates in the FPGA. The higher this number the biggest the design that can be held. Refer to 2.1.1 for more information. Xilinx Alveo U50 is a cost eective solution that could serve our research purposes, specially compared to the outdated Intel Stratix V. However, since this project will probably lead to further research an Intel Stratix 10 outperforms its competitors because of its 10.2 million of LUTs. FPGAs need specialised software that performs all the steps related to the process of circuits synthesis. The cost of this software is non negligible and has to be added to the budget. Table 1.2 summaries the 3 1.3. PROBLEM STATEMENT FPGA model Memory (max) PCIe LUTs Cost Intel Stratix V [40] 8 GB DDR3 x8 622K $6250 Intel Stratix 10 [39] 8 GB DDR4 x16 10.2M $10,880 Intel Arria 10 [41] 16 GB DDR4 x8 1.15M $5520 Xilinx Alveo U50 [12] 8 GB HBM2 x16 872K 2604.72 e Xilinx Alveo U200 [11] 64 GB DDR4 x16 892K 4382.41 e Table 1.1: Summary of the most relevant features and costs of OpenCL compatible FPGAs. Software Cost Quartus Prime Pro (xed) [21] $3995 Quartus Prime Pro (oating) $4995 Xilinx Vivado HL System Edition (xed) [47] $3495 Xilinx Vivado HL System Edition (oating) $4295 Table 1.2: Costs of software licenses. costs of the Intel's and Xilinx's suites, both in xed and oating license versions. Floating license should be the preferred option, since more than one person might be working on FPGA projects in the future. Intel oers an alternative to this on-premise solution called Intel Devcloud [3]: 6 months of free access to their HPC cluster featuring Intel Arria 10 FPGAs. More details on the available hardware at 5.5. It oers an adequate experimental environment with homogeneous computing nodes. However, the developer is subject to any change that the Intel team may consider applying to their cluster. For that reason, a local installation is likely in the future. Table 1.3 shows a tentative coarse task decomposition of the work during the development of this project based on a discussion with the advisors about a possible path to follow and the diculty of every step. In order for the time estimations to be accurate the prole of every role has to be taken into account, i.e., previous knowledge and abilities. Since both advisors have successfully managed several honours project in the past the times shown in the table are based on previous experience. In the case of the student, it has to be taken into account that this is his rst contact with parallel computing, although he has undertaken some projects on its own regarding low level programming and electronics. For this reason, the learning OpenCL - FPGA task, which includes traning in the parallel computing paradigm at a conceptual level, is estimated to last 80 hours. Reading is one of the pillars of research. Given that this is the rst contact of the student with research in general and heterogeneous computing and parallel programming in particular, a high proportion of the time allocated for this work will be spent on this task. Controllers and Hitmap lay the foundations of this work. They are two quite complex tools. However, this work seeks to result in an expansion of Controllers and Hitmap is just an auxiliary tool, from which only a few features are required. This implies that it is requiered to have deep knowledge about the inners of Controllers, but there is no need to reach the same level of comprehension for Hitmap. Knowing the user-facing interface and some implementation details of this library suce. The process of implementation can be quite time consuming due to the use of preprocessor macros and the conceptual diculty associated to metaprogramming. The programmer must be aware of the pieces of code that will be actually expanded in the actual program. Conditional compilation and limited aid from the compiler when debugging turn this into a complicated task, which justify an initial estimation of 100 hours of development. Experimentation should be a straightforward task once FPGAs are properly integrated in Controllers 4 CHAPTER 1. INTRODUCTION thanks to the new backend. Since this is the rst contact of the student with a project of this kind 30 hours might be a resonable estimate. Writing this document should be a straightforward task as well, provided that all the results obtained during the work have been properly annotated. Experience shows, however, that students have a hard time writing their rst research document, so 40 hours is the prior estimate. Finally, a certain degree of freedom is advisable in projects management to account for unexpected events. This can be accounted by inating the estimates of every task. However, since this work is based on research, having some extra time for other side related tasks, e.g. learning some Verilog or CUDA, makes more sense and has been recorded as Others . Role Task Time (hours) Student Learning OpenCL - FPGA 80 Reading 100 Understanding Controllers 60 Understanding Hitmap 5 Backend implementation 100 Experimentation 30 Writing document 40 Others 40 Advisor Meetings 60 Corrections to the draft 20 Table 1.3: Estimations of the time invested by two roles involved in the work for its development. All in all, tables 1.1, 1.2 and 1.3 provide the necessary information to estimate the overall cost of the project. For the reasons exposed, the FPGA model chosen for this work is Intel Stratix 10 and a oating license of Quartus is preferred. Regarding the cost of the time invested by the two roles considered a cost of 25 e /h for the student and and 50 e /h for the advisors is assigned. As a consequence, the total cost of the project, applying an exchange rate of $1.13 = 1 e , would be 9628.32 e (FPGA) + 4420.35 e (Quartus) + 11375.00 e (student) + 4000.00 e (advisors) = 29423.67 e . 1.4 Document structure The rest of document is organised as follows: chapter 2 introduces some basic concepts about FPGA architecture and the related work. Chapter 3 describes the nal prototype and the previous exploration of FPGA parameters that inuenced the decisions taken. Chapter 4 shows the iterative process of implementation of the model. Chapter 5 explains the experimentation conducted over the chosen case studies to validate the proposed model. Finally, chapter 6 discusses the conclusions reached and the possible future research lines. 5 1.4. DOCUMENT STRUCTURE 6 CHAPTER 2. PREVIOUS CONCEPTS AND STATE OF THE ART Chapter 2 Previous concepts and State of the Art This chapter introduces the following aspects: • The FPGA architecture and the OpenCL programming model. • Related work about optimisation of parallel applications. • The Hitmap and Controllers libraries, developed by Trasgo research group. 2.1 FPGA architecture An FPGA (Field Programmable Gate Array) is an integrated circuit that can be recongured after manufacturing [46, 37]. The most basic models consist of just programmable logic gates and interconnects and I/O ports, which turn them into recongurable hardware, as depicted in gure 2.1. It is not uncommon, however, that they also feature other digital components such as digital signal processors (DSPs), dynamic RAM (DRAM) or even microprocessors. These are known as hard IP and serve the dual purpose of extending the FPGA capabilities with tested electronics that may otherwise be dicult to implement and saving FPGA surface for other custom non-standard functionality desired by the hardware designer. All of them could be implemented by leveraging the FPGA logic elements, provided that the FPGA is large enough. However, it is often not worth it reinventing the wheel knowing circuits design can be a low productivity and error-prone task. In the same fashion, emulating software libraries, there exists soft IP , i.e. HDL (Hardware Description Languages, such as VHDL or Verilog) les usually sold by manufacturers that describe a hardware component that can be instantiated with the FPGA programmable resources. These are not necessarily xed and allow a certain degree of freedom by exposing congurable parameters, as does the Nios II processor [9]. FPGAs can be manufactured with either fuse/antifuse or SRAM technology. Only the latter is recongurable and interesting from the point of view of HPC, so from now on only this kind is considered in this work. This makes FPGAs particularly suitable for applications when data paths are complex and poses a restriction on the utilised surface, since only the targeted elements are needed. This way, it is possible to save energy by leaving the rest of the die idle, as opposed to microprogrammed accelerators, such as GPUs [7]. 7 2.2. RELATED WORK Data matrix Min. shift register Extra shift register M N Figure 2.9: Shift register pattern applied to bidimensional data. ... ... Figure 2.10: First and nal step of an iteration of a stencil calculation. 2.2 Related work This section gives an overview of the related work. First, some insight is be given into the previous work developed by the Trasgo research group that has been leveraged in this work. After that, the basics of the OpenCL model are explained to enable the comprehension of the rest of this document. Finally, Controllers is compared with other heterogenous programming models. 2.2.1 Hitmap The Hitmap library [15] oers automatic techniques of partitioning and mapping of data, in an ecient and congurable way, in run time. This library denes an abstraction interface and a plug-in system that encapsulates regular and irregular techniques, helping to generate code independent from the chosen mapping function. Hitmap supports partitioning ( tiling ) of sparse or compact array distributions. This partitioning enables the implementation of data and tasks parallelism according to the SPMD (Single Program Multiple Data) model. This library oers functionalities to create, manipulate, distribute and communicate these partitions ( tiles ) and hierarchy of partitions. The Hitmap library introduces the following concepts: Signature : A signature S is dened as a tuple of three integer elements representing a subspace of 14 CHAPTER 2. PREVIOUS CONCEPTS AND STATE OF THE ART array indices in a one-dimensional domain. It resembles the classical Fortran or MATLAB notation for array-index selections. The cardinality of the signature is the number of dierent indices in the domain S∈ Signature = (begin : end : stride) Card (s∈ Signature ) = b (s.end - s.begin)/s.stride c. Shapes . We dene a Shape h as a n -tuple of signatures. It represents a selection of subspace of array indices in a multidimensional domain (multidimensional parallelotope). The cardinality of the shape is the number of dierent index combinations in the domain h∈ Shape = (S0, S1, S2, . . . , Sn−1) Card(h∈ Shape ) = n−1 Y i=0 Card (Si). Tiles . We dene a Tile as an n -dimensional array. Its domain is dened by a shape, and it has a number of elements of a given type, depending on the programming language chosen Tile h∈ Shape :S0×S1×S2×. . . ×Sn−1−→ <type>. Figure 2.11: Tiling creation from an original array. Extracted from [15]. Hitmap supports three sets of functionalities: • Tiling functions . Denition and manipulation of arrays and tiles, in a tile-by-tile basis. These functions can be used independently of the others, to improve locality in sequential code as well as to generate data distributions manually for parallel execution. • Mapping functions . Data distribution and layout functions to automatically partition array domains into tiles, depending on the virtual topology selected. These functions are oriented to data and task distribution on parallel environments. The input needed at this point are the virtual topology and layout functions to be used, and the data structure to be distributed. These functions return i) the ranges of the tiles that need to be created (using the tiling functions), ii) the mapping between tiles and virtual processors, and iii) the neighbour information, encapsulated in a single structure. 15 2.2. RELATED WORK • Communication functions . Creation of reusable communication patterns for distributed hierarchical tiles. These functions are an abstraction of a message-passing model to communicate tiles among virtual processors, and may be used with the mapping information (mapped tiles, neighbourhood information, and virtual topology), to create mapping-dependent communication patterns. They return a handler that can be used to repeatedly communicate tiles among processors. Figure 2.12: UML diagram of the Hitmap library architecture. Extracted from [15]. 2.2.2 Controllers The controller model [30] introduces a simplied way to program application that can exploit heterogeneous computational platforms including accelerators or/and multi-core CPUs. Its architecture is represented in gure 2.13. The device controllers coordinate the execution of series of kernels. These kernels are declared as functions, that are managed by the controller entities. Controllers automatically manages the two main concepts used in a program that exploits accelerators. 1. Kernel management , including the kernel launching and conguration. The controller manages the deployment/execution of sequences of kernel functions in the computational device associated to the controller. The controllers can include policies to exploit concurrent kernel execution techniques, interleave computations with communications or reorder the sequence of kernels. The kernel conguration is the selection of specic conguration parameters for the kernel launching that can be associated to a particular kernel and computational platform. 2. Data management , including the data transfers carried out across the memory hierarchies of the host and the accelerators and the abstraction used to access data elements independently of the target device, the threads indices space or the data layout. 16 CHAPTER 2. PREVIOUS CONCEPTS AND STATE OF THE ART Figure 2.13: Diagram of the controller model architecture. The kernel-launching requests can be enqueued. The controller entity manages the execution of enqueued kernels, and for bound variables, the data transfers between memory spaces. In the gure, the host variable A is not bound to the controller. Variable B is a bound variable, with a duplicated image for the data in the device memory. Variable C is an internal variable of the controller, dened in the host, but allocated only in the device. Extracted from [30]. Rules for asynchronous execution The rules applied at run-time to decide which operations should wait to be ready for execution, and which ones can be started, executed asynchronously, and potentially be overlapped with previous or subsequent operations are based on data dependencies. The decisions of which kernels should be or not be executed concurrently to improve the overall performance of the application is a problem orthogonal to the overlapping of data transfers with kernel or host-task execution, and it is beyond the scope of this work. In this proposal, the order of the execution of kernels is strictly preserved. Similarly, requests for the execution of host-tasks are also executed in order, although they can be overlapped with kernels if dependencies allow it. Data transfers can be overlapped with the execution of both kernels and host-tasks. The internal rules that decide when a request can be safely started have been designed by studying the dependencies between the dierent types of requests and between the input/output role of their parameters. Allocate/deallocate and wait operations have simple rules due to the synchronisations required by their semantics. Each data structure can have two memory images, one in the host and one in the device. The kernel, host-task and data transfer requests have been analysed considering them as a multiple-reader/multiple-writer problem. The dependencies generated by this scheme are depicted in 2.14. Queue management policy Controllers implements two policy modules: synchronous and asynchronous execution. The asynchronous policy module pops tasks from the queue, but it delegates to the backend the application of the rules depicted in 2.14. Thus, dierent mechanisms can be exploited on dierent backends, using the particular primitives and resources provided by the specic programming model. The backend methods use the information provided in the request parameters, and in the associated tiles, to evaluate the rules and transform the request into calls to the particular programming model for the specic device. The synchronous policy works with the same model, but always introducing a dependency with the previously 17 2.2. RELATED WORK Figure 2.14: Dependencies between request types. Rounded boxes identify request types, using the x data structure as parameter. We distinguish between K or H requests that use x with an input or output role. For clarity, the Wait and Alloc/Free operations are skipped in the gure. Inside each box we represent in small boxes whether the request reads or writes in the host or device memory image of x . Arrows express dependencies between request types implied by the use (read or write) of the memory images of x . Requests that are not linked with arrows can be executed concurrently. Remind that this model does not consider the case of several concurrent host-tasks. evaluated request to sequentialise them. In the Controllers model a kernel is declared using two primitives. The rst is CTRL_KERNEL_PROTO , that declares a prototype for all the implementations of a given kernel. See lines 1-5 in gure 2.2. It declares the number of implementations available and for which backend or devices are those implementations designed. This is used by the Controller to locate, at run-time, the best available implementation of a kernel for the chosen device. In the example, there is only one implementation declared. The GENERIC keyword indicates that it is usable on any backend. Other keyword names are associated to the specic types of backend or device. The rest of the prototype is the description of the kernel parameters, including their input/output roles, types and names. INVAL indicates a value parameter. IN, OUT, or IO (in/out) indicate the role of a HitTile received as reference. Each kernel implementation is declared by using the primitive CTRL_KERNEL . See lines 7-17 in gure 2.2. The rst parameters are the kernel name, and the type of implementation. After the declaration of the kernel parameters, the code is included in a structured block. This particular example computes a saxpy operation, fused with the application of the square root on each element of the result. The implementation is a generic ne-grain data-parallel specication, that can be automatically coarsened and adapted by the Controller to the proper task granularity of dierent types of devices, such as GPU, or sets of CPU cores. 1 CTRL_KERNEL_PROTO ( saxpy_sqrt , 1 , GENERIC , 2 3, 3 IVAL , int , alpha , 4 IN , HitTile_float , matrix_x , 5 IO , HitTile_float , matrix_y ) ; 6 7 CTRL_KERNEL ( saxpy_sqrt , GENERIC , 8 int alpha , 9 KHitTile_float matrix_x , 10 KHitTile_float matrix_y , 11 { 12 const int row = threadId . x ; 13 const int col = threadId . y ; 18 CHAPTER 2. PREVIOUS CONCEPTS AND STATE OF THE ART 14 hit ( matrix_y , row , col ) = sqrt ( 15 alpha * hit ( matrix_x , row , col ) + 16 hit ( matrix_y , row , col ) ) ; 17 } ); Listing 2.2: Example of a kernel prototype and its implementation, using the Controller library 1 int main(int argc, char *argv[]) { 2 3 Ctrl_Thread threads; 4 Ctrl_ThreadInit(threads , SIZE , SIZE); 5 6 __ctrl_block__(1) 7 { 8 PCtrl ctrl = Ctrl_Create(CTRL_TYPE_FPGA , CTRL_POLICY_ASYNC , DEVICE , &PLATFORM); 9 10 HitTile_float matrix_a = Ctrl_Alloc(ctrl , float, hitNewShapeSize(SIZE , SIZE) ); 11 HitTile_float matrix_b = Ctrl_Alloc(ctrl , float, hitNewShapeSize(SIZE , SIZE) ); 12 HitTile_float matrix_c = Ctrl_Alloc(ctrl , float, hitNewShapeSize(SIZE , SIZE) ); 13 14 HitTile_float matrix_tmp = hitNewTile(float, hitNewShapeSize(SIZE, SIZE)); 15 16 Ctrl_HostTask(ctrl , Init_Tiles , matrix_a , matrix_b , matrix_c); 17 18 Ctrl_Launch(ctrl , Mult, threads , matrix_c , matrix_a , matrix_b , SIZE, SIZE); 19 20 21 Ctrl_HostTask(ctrl , Init_Tiles , matrix_a , matrix_b , matrix_c); 22 23 // Matrix Mult: Main loop 24 // Clock: Synchronise and start measuring 25 Ctrl_MoveTo(ctrl , matrix_a , matrix_b , matrix_c); 26 27 for (int i = 0; i < N_ITER; i++) { 28 if ((i % 2) == 0) { 29 Ctrl_Launch(ctrl , Mult , threads , matrix_c , matrix_a , matrix_b , SIZE , SIZE); 30 Ctrl_MoveFrom(ctrl , matrix_c); 31 Ctrl_HostTask(ctrl , Host_Compute , i, p_sum , p_res , matrix_c , matrix_tmp ); 32 }else { 33 Ctrl_Launch(ctrl , Mult , threads , matrix_b , matrix_a , matrix_c , SIZE , SIZE); 34 Ctrl_MoveFrom(ctrl , matrix_b); 35 Ctrl_HostTask(ctrl , Host_Compute , i, p_sum , p_res , matrix_b , matrix_tmp ); 36 } 37 } 38 39 Ctrl_GlobalSync(ctrl); 40 // Clock: synchronise and stop measuring 41 42 Ctrl_Free(ctrl , matrix_a , matrix_b , matrix_c); 43 hit_tileFree(matrix_tmp); 44 45 Ctrl_Destroy(ctrl); 46 } 47 48 ... 49 } Listing 2.3: Snippet of the main code of a Matrix Multiplication programmed using the Controller library (asynchronous) 19 2.2. RELATED WORK 2.2.3 OpenCL OpenCL (Open Computing Language) [16] is an open royalty-free standard for general purpose parallel programming across CPUs, GPUs and other processors, giving software developers portable and ecient access to the power of these heterogeneous processing platforms. As such, it does not provide an implementation for the dierent architectures, but they are developed by the vendors who decide to give OpenCL support to their devices, as in the case of Intel with their Intel FPGA SDK for OpenCL. Platform model The platform model of OpenCL consists of a host that is connected to one or several accelerators (devices in OpenCL terminology). Devices are formed by compute units and compute units, at the same time, by processing elements. Once again, it is up to the vendors how to map this concepts to their architecture. In the case of FPGAs compute units and processing elements tend to be considered the same, since a compute unit is always mapped to a pipeline. The role of the host in this model is that of submitting commands to the devices that will be used to perform computations. Figure 2.15: Depiction of the OpenCL platform model. Extracted from [26]. Execution model OpenCL applications comprise two parts: host program and kernels . The host program is executed by the host and contains the entry point of the application. It takes care of orchestrating all the devices and performing tasks such as managing data transfers between host and devices, submitting commands to the accelerators or processing the events they generate. On the other hand, the kernel is the function that is executed on one or more accelerators and conveys the computational load of the program. The core feature of kernel execution in OpenCL is the index space . A given instance of a kernel, named work-item , is associated to a point in that index space with its own global ID, equivalent to the so named thread in other models such as CUDA. Although every work-item executes the same code, frequently they operate on dierent data and can even follow dierent execution pathways, leading to a concept known in parallel programming as branch divergence . Work-items are organised into work-groups , which are a more coarse-grained decomposition of the index space and have their own ID. Work-items are assigned a unique local ID within the work-group as 20 CHAPTER 2. PREVIOUS CONCEPTS AND STATE OF THE ART well. This makes possible to identify work-items either by their global ID or by a combination of their work-group ID and their local ID. According to the OpenCL specication every work-item runs on a single processing element, whilst every work-group is mapped to only a compute unit. Since FPGAs are not microprogrammed, PEs and CUs are equivalent concepts when working with these devices, i.e, work-groups run, indeed, on a single pipeline (compute unit), but their work-items will execute through all stages of the pipeline, instead of sequentially executing all the instructions of the kernel code as they would on a CUDA core of a Nvidia GPU (processing element). Figure 2.16: Depiction of the OpenCL execution model. Extracted from [26] The execution of kernels takes place on a given context, which gives access to the host to the following resources: • Devices : the collection of accelerators used by the host. • Kernels : the OpenCL functions that run on OpenCL devices. • Program objects : the program source and executable that implements the kernels. • Memory objects : a set of memory objects visible to the host and the OpenCL devices. Memory model OpenCL denes four memory address spaces that can be accessed by the work-items: • Global memory : accessible for every work-item in every work-group. It is usually the slowest type of memory and tends to be o-chip (o-chip DRAM in FPGAs). • Constant memory : this is a special region of global memory that remains constant during the execution of the kernel, acting as a sort of caché. • Local memory : shared among work-items in the same work-groups. It is usually implemented in faster memory than global memory (on-chip SRAM in FPGAs). • Private memory : accessible only by a given work-item. It is frequently the fastest type of memory and is usually mapped to registers. 21 2.3. CONCLUSIONS Programming model OpenCL supports the data parallel programming model and the task parallel programming model. The rst one distributes computation among a set of work-items organised as has been explained in the execution model. This type of kernels are called ND-Range kernels. The second model relies on a single work-item to perform the computations, which gives place to the so called Task kernels. The programming model of OpenCL denes two domains of synchronisation: work-items in a single work-group and commands enqueued to command queues in a single context. The rst is performed using a work-group barrier, whilst the second relies on command-queue barriers and events, the approach leveraged in Controllers. 2.2.4 Other programming models There are several projects that intend to develop heterogeneous programming models seeking the same goals than Controllers, such as EngineCL [31], the University of Thessally's [33], OmpSs@FPGA [5] or FPM [45]. EngineCL and the University of Thessally's model improve programmability in heterogeneous systems by leveraging OpenCL under the hood for every supported architecture. This can lead to higher overheads than using the vendor specic tools such as CUDA for Nvidia GPUs. On top of that, EngineCL depends on C++ fancy features such as variadic templates, initialiser lists or rvalue references, thus denying to the programmer the possibility of integrating the tool with applications coded in the C language. Besides, the geometry for kernel execution must be manually specied by the programmer with the University of Thessally's model through the workers() and groups() classes. OmpSs@FPGA and FPM do have vendor specic backends for every supported architecture, thus avoiding the performance issues suered by the previous models. They rely on non-standard directives to express parallelism and dependencies and a source-to-source compiler that translates them into runtime system API calls, a common feature with the University of Thessally's model. Forcing the programmer to include a source-to-source compiler in his software stack might cause trouble when the model is to be included in an environment that implements another compiler specic syntax. Controllers decreases programming eort while keeping the overhead resultant from the use of the library to the minimum. To that end, it features vendor specic tools. It is designed to be compatible with the C99 standard by avoiding the use of the aforementioned C++ features, which are replaced by preprocessor macros, thus allowing the generation of portable code in both languages and keeping the model compiler agnostic. Finally, the geometry for kernel execution can be automatically adjusted by Controllers in run time thanks to the characterisation of the kernel. 2.3 Conclusions The rst part of this chapter introduced the FPGA architecture. It gave some insight into the complexity of this type of accelerators and explained the inner mechanisms that allow recongurability. Some details about memories featured by FPGAs and how to overcome their limitations were also given. In the second part the related work was presented. A brief description of the previous work of Trasgo research group relevant to this work, namely Controllers and Hitmap, was given to ease the comprehension of the rest of the document. Finally, an analysis of several state of the art heterogeneous models was made in order to establish a comparison with Controllers. 22 CHAPTER 3. DESCRIPTION OF THE SOLUTION Chapter 3 Description of the solution This chapter introduces the following aspects: • The congurable parameters in FPGAs that are to be supported by the Controllers model. • An extension of the Controllers model that allows the execution of kernels in FPGAs with automatic overlapping of communication and computation operations. 3.1 Approach to the solution So far HPC has been based on the exploitation of microprogrammed architectures such as CPUs and GPUs, which have something in common: they are xed by the manufacturer. Recongurable computing has broken this paradigm by allowing the programmer to design his own architecture. Although this has the benet of adapting the hardware to the problem, resulting in an increase in performance in certain applications and signicant savings in power [4] it comes at the cost of more dicult programming. Although this has been alleviated by HLS languages, mainly OpenCL, in the recent times, leading to an increase in productivity, there are still plenty of tunable parameters. Since the success of a given FPGA implementation relies on these parameters, a previous exploration must be conducted in order to nd how we can give support for them in our model. Take into account that all the work shown in this document has been undertaken using an Intel FPGA, so this section will reect the possibilities oered by the software stack of this manufacturer. Xilinx FPGAs are programmed in OpenCL as well, so no major changes would have to done to integrate them apart from the syntax to congure these parameters. This section shows the proposal of a new backend for the Controller library that gives support to FPGAs. This solution reduces the programming eort, allows automatic management of dependencies and seamless overlapping of data transfers and computations thanks to its asynchronous policy. It keeps the changes to the user-facing interface to the minimum while adding support for the studied parameters that are most relevant for performance. 3.2 Congurable parameters There are two types of congurable parameters: compiler parameters and kernel parameters. Compiler parameters must be xed by the programmer prior to the kernel compilation. Otherwise, the default value will be used. On the other hand, kernel parameters may not be congured by the programmer and the compiler will adapt its value depending on the data access patterns. 23 3.4. INTEGRATION OF FPGA AS ACCELERATOR IN CONTROLLERS 3.4 Integration of FPGA as accelerator in Controllers FPGAs can be programmed in the OpenCL programming model. This a standard for heterogeneous computing that allows the programmer to leverage the capabilities of dierent types of accelerators: CPUs, GPUs and FPGAs. The Trasgo research group had previously integrated GPUs, both Nvidia's and AMD's, in their model. There is a specic backend for Nvidia cards that was implemented in CUDA and a generic one implemented in OpenCL. The last one was used as a base to develop the backend for FPGAs. Thanks to the transparency for dierent architectures of OpenCL, integrating the FPGA for the execution of kernels was straightforward. Most of the work was dedicated towards exploiting specic characteristics of FPGAs that were not considered in the GPU backend. They are listed as follows: 3.4.1 Single work item kernels Due to the inherent parallel nature of GPUs, kernels were executed in ND-Range fashion (refer to 2.2.3 for more information). Although this kernel launch model is supported by FPGAs, the single work item model adapts better to the pipeline architecture in the general case (there are some exceptions, such as the Matrix Power algorithm studied at 5). For this reason the Controller library is extended to support both models when targetting FPGAs that can be selected thanks to a parameter in the kernel characterisation, namely NDRANGE and TASK . Since there is no restriction on the execution model for a given problem (provided that the kernel code does not include explicit constraints) it is up to the programmer to choose the most adequate to achieve maximum performance. 3.4.2 Format of kernel name It is now clear there are plenty of congurable parameters in FPGA kernels. Some of them have to be statically specied in the kernel code, as in the case of the pipeline conguration. The number of SIMD lines additionally requires to x the workgroup dimensions. This is why the FPGA kernel binaries nomenclature had to be carefully chosen: kname{ _SIMD- N - X x Y x Z}{ _CU- M}{ _proling / emu }_version .aocx Optional parts appear inside brackets in the kernel name denition. Parts in bold letter are mandatory, whilst the rest of the denition are variables: • kname: name of the kernel as it will be called in the host code. • N: number of SIMD lanes. • X, Y, Z: dimensions X, Y and Z, respectively of workgroups. • M: number of CU replicates. • version: either Ctrl or Ref, standing for Controllers and native. This simple solution allows the execution of instances of the same kernel with dierent compile-time parameterisations and prevents valuable information from being lost after the compilation process that can be useful for the programmer to use the kernel binary in other contexts dierent from that of the Controller library. 30 CHAPTER 3. DESCRIPTION OF THE SOLUTION 3.4.3 Expansion of kernel signature The pipeline conguration is a decision with great impact on performance. For that reason, the kernel signature for FPGAs has been extended with a new parameter called PIPELINE . The purpose of this new parameter is to allow the programmer to set the number of SIMD lines and/or compute units and choose between the ND-Range or Task model of execution. This new directive must always appear in kernel signatures for FPGAs. It supports multiple parameters in order to enable sophisticated congurations of the pipeline. Caution is needed here, as some parameters clash between them because of their opposite semantics (as would happen in a raw native implementation). The possible parameters that PIPELINE can receive are: • TASK: the kernel will be executed as a SWI (Single Work Item) kernel. • NDRANGE: the kernel will be executed as an ND-Range kernel. • SIMD( M, wgx, wgy, wgz ): the characterised kernel will execute in a pipeline with M lanes and workgroup dimensions ( wgx, wgy, wgz ). • CU( N ): the kernel will execute in a pipeline replicated N times. As the reader might have guessed TASK and NDRANGE cannot be used together in the same signature. The oine compilation of kernels required by FPGAs imposes new restrictions on the manipulation of strings for the generation of the kernel code that is to be compiled, since many of those were performed at runtime with the OpenCL backend. To keep the changes of the CTRL_KERNEL primitive to the minimum the roles of the kernel arguments are added nested in the PARAMS macro and the kernel body is no longer a parameter but a block of code following the signature in a C function fashion. 1 CTRL_KERNEL(Mult , FPGA , PIPELINE( NDRANGE , 2 SIMD( 4, 64, 64, 1) ), 3 PARAMS( OUT, IN, IN, INVAL , INVAL ), 4 KHitTile_float C, KHitTile_float A, 5 KHitTile_float B, 6 int A_width , int B_width) Listing 3.2: Example of the new kernel signature 3.4.4 Kernel declaration Controllers was initially thought as a unied host plus device programming model, leveraging the online compilation capability supported by the integrated architectures. However, FPGAs are an exception to this rule, since they can only operate with oine compilation. Kernels must be compiled separately from host code and the resulting kernel binaries must be provided to the host application. For this reason the code must be split into host and kernel les. In order to work around this limitation and preserve the transparency property of Controllers some eort was dedicated to hide it from the programmer. Some code was moved to a header le included by both the host and the kernel le to minimise the changes to be made by the programmer to adapt his Controller code to work with FPGAs. These common parts were the denition of types used by Hitmap tiles, Ctrl_NewType , and any type alias made to allow the use of qualied types, such as unsigned char , in specialised HitTiles . In addition, the kernel execution mode (either ND-Range or Task) was added to the kernel characterisation as a parameter, which should match the one specied in CTRL_KERNEL . 31 3.4. INTEGRATION OF FPGA AS ACCELERATOR IN CONTROLLERS Ctrl_NewType conveys dierent information depending on which le includes it. Hence, it is necessary for the preprocessor to distinguish between host code and kernel code in order to perform the appropriate macro expansions in every case. The less invasive way of achieving this result is the annotation of the kernel le with the empty macro CTRL_FPGA_KERNEL_FILE . 3.4.5 Managing incongruent grid sizes Sometimes, computation is issued for a grid size that is not multiple of any of the block dimensions. As a result, the last block in that given dimension will have some of its work-items idle, since otherwise unallocated memory positions would be accessed. The OpenCL backend deals with this issue by checking that the index of the current work-item is between the grid borders specied in the structure Ctrl_Thread by the user with the function Ctrl_ThreadInit. This leads to a branch divergence i.e. work-items that meet the condition will perform the computation, whilst those that do not will return. Although this solution works for GPUs, FPGAs cannot cope with branch divergence in SIMD pipelines, since it is not synthesisable. An alternative approach, which might lead to minor performance improvements, and can be extended to every architecture supported by Controllers with minor eort is the use of padding. As has been already mentioned, the problems with vectorisation come from checking the work-item indices belong to the index space, which prevents going out of bounds when accessing memory. The adopted solution comes through deleting the need for testing such condition. This is achieved by allocating enough memory for a big block size. The chosen size is 256 in every working dimension, since these are the default dimensions assumed by AOC for a SIMD kernel with a synchronisation point when they are not specied by the user. The user will not perceive any alteration in the memory he requested, since the HitShape created will be preserved. To this end, the new memory size the backend will work with will be stored at the tile members acumCard and origAcumCard[0] . This way, some trash computations will be performed, as they will be out of bounds according to the dimensions chosen by the user, and they will not be visible because they exceed the boundaries specied in the requested shape initially. 3.4.6 Replacing pinned memory by aligned memory In order for DMA transfers to take place in the CUDA programming model memory has to be pinned [18]. The term pinned memory refers to memory pages in the host address space that will not be moved to swap storage during the execution of the program. This way it is guaranteed that the page will be available when the DMA controller initiates a transference between host and device. In case the programmer does not explicitly allocate memory as pinned, the runtime will create a temporary pinned copy of the page to be transferred, aecting performance. On the other hand, memory is a scarce resource and pinning abuse may also lead to performance decrease. There is no way to guarantee the allocation of pinned memory in OpenCL, however, as the Nvidia OpenCL Best Practices Guide states it is possible to give a hint to the runtime to act this way. The process for host to device transfers, depicted in gure 3.9, is as follows (the opposite device to host is analogous): • Create data buer for transfers. • Create auxiliary buer to indicate OpenCL the corresponding mapped host memory will not be swapped out. • Map auxiliary buer to host memory. 32 CHAPTER 3. DESCRIPTION OF THE SOLUTION Pipeline Device Workgroup Ctrl_MoveTo Padded data Host Hitmap Figure 3.8: The gure shows a case in which the user allocates a 6 × 4 matrix. For the sake of simplicity and to keep the gure clear, the Task model of execution is supposed, hence, a single work-group is launched, and the default work-group size for padding has been reduced from 256x256 to 16x16. Although the user requests a 6 × 4 matrix, it is padded until the data ts into 16x16 work-groups. In this case a high percentage of the allocated memory is just due to padding because the matrix is extremely small. This will not happen in real applications. The device computes the kernel with the padded data, but the programmer only sees the data he requested, keeping this process transparent data pinned_data device_data Device Host Figure 3.9: Pinned memory in OpenCL (Nvidia's implementation). The dashed arrow indicates mapped memory, whilst the continuous one stands for the direction of the memory transfer This construct has no interest when programming for FPGAs, however, as it is not mentioned in any of the Intel guides nor in the scientic literature and none of the author tests point in the opposite direction. Rather, it just contributes to the occupancy of the global memory of the device. Intel FPGAs, on the other hand, benet from aligned memory to to achieve higher transfer rates thanks to DMA. The memory bus of these device is 64 bytes wide, i.e, data is transferred in that size bursts. Thus, memory buers are aligned to 64 bytes in this solution to take advantage of this feature. More information on memory alignment in chapter 2. 33 3.5. CONCLUSIONS 3.5 Conclusions This chapter was a summary of the congurable parameters of Intel FPGA SDK for OpenCL and showed a brief study that justies the inclusion of support for vectorisation and compute unit replication in Controllers. Finally, the specication of the new backend was detailed. 34 CHAPTER 4. IMPLEMENTATION Chapter 4 Implementation This chapter introduces the following aspects: • Description of the approaches to the nal implementation of the FPGA backend of the Controllers model. • Removal of initialisation operations from runtime code sections. • Enabling proling and emulation of kernels. 4.1 Naïve approach to the solution The rst milestone of the problem solved in this work was getting the Controllers model to execute FPGA kernels. Since FPGAs can be programmed in OpenCL, this was achieved by modifying the existing OpenCL backend for GPU. As a consequence, this was quite straightforward, although this solution just gave partial support to the Controllers instrumentation i.e. management of queues with asynchronous and synchronous policies and data transfers, but did not leverage the Hitmap library nor eased the seamless denition of kernels. 4.1.1 Changes made to the GPU backend In this section the changes applied to the OpenCL backend in order to serve as a draft for this work are detailed. To start with, the OpenCL backend for GPUs was copied and every function, macro or variable referring to the previous backend nomenclature was renamed to prevent collisions between both backends when they are running at the same time to support GPUs and FPGAs. Oine compilation Before this work, Controllers dealt with kernels as strings in order to perform online compilation. FP- GAs do not support this compilation mode and need to load a kernel binary compiled previously with a specic compiler (AOC - Altera Oine Compiler in the case of Intel FPGAs) in a process known as oine compilation. In order for the new FPGA backend to support this feature it was only necessary to read the precompiled kernel binary, whose path was hardcoded, and feed it to the function clCreateProgramWithBinary instead of clCreateProgramWithSource , which takes a kernel string as 35 4.1. NAÏVE APPROACH TO THE SOLUTION argument. The online compilation takes place when the function clCreateKernel is called. In the case of oine compilation it is turned into a dummy function that still has to be called to adjust to the OpenCL standard and only serves the purpose of returning an OpenCL kernel object built from the binary. Constraints on passing structures Controllers wraps data into a simplication of Hitmap tiles known as KHitTiles in order to allow data partitioning. This cannot be done straightforwardly, since the OpenCL standard states that structs with pointer members cannot be passed as kernel arguments (section 6.8.d) [16]. The OpenCL backend for GPU works around this by unfolding the tile arguments into coordinates and the pointer to data. The tile coordinates are saved into a KHitTile wrapper and the data is passed by reference. The Intel FPGA SDK for OpenCL has an extra limitation in old versions of the compiler on passing data structures: they cannot be passed by value. Instead, struct arguments must be converted into pointers to struct [22]. As host pointers are meaningless for the device, pointers to struct must be passed through an OpenCL buer. All this manipulation was suspected to incur in some serious overhead and seemed too much eort for a naïve approximation of the solution which only looked for a functional implementation. Instead, the KHitTile struct was fully unfolded and every member was passed individually as a parameter. This implied kernels had to be adapted to receive all these dummy (recall they are intended to leverage the Hitmap library, which will not be used yet) arguments. Since this limitation is resolved in new versions of the compiler, there is no point in including support for this in the backend, so it was overlooked in the development of the denitive solution. ND-Range kernels and Tasks support The only dierence in host code between launching an ND-Range kernel or a Task is calling the function clEnqueueNDRangeKernel or clEnqueueTask , respectively. Additionally, clEnqueueNDRange needs the grid and workgroup dimensions. Both functions calls were typed in the FPGA backend and every time a kernel of one kind was to be launched the call of the opposite kind was commented out. 4.1.2 Changes made to the experimentation code The advantage of using Controllers over other heterogeneous programming models is highlighted by the minimal changes that have to be made in the experimentation host codes to launch kernels on FPGA. In fact, only the used device had to be changed to FPGA. Some other changes had to be performed, but they are totally unrelated to the Controllers model, and are only due to the kernels being dierent from the GPU version. Although the GPU kernels can be executed on FPGA it is not recommended, since it is an entirely dierent architecture and the performance achieved will be poor in most cases. For this reason, sometimes the arguments passed to the FPGA kernels vary in number or type with respect their GPU counterparts, which has to be reected in the kernel prototype. In the case of the native version of experimentation host codes the oine compilation and ND-Range kernels and Tasks support explained in the previous point had to be added. 36 CHAPTER 4. IMPLEMENTATION 4.2 Approaches considered before denitive solution It is clear that some of the decisions took in the naïve approximation can be considered bad practice and are not acceptable in a nal product. It serves its exploratory purpose as a prototype well, nonetheless. During the development of this work several approaches were tried in order to satisfy the goal of integrating FPGAs in Controllers in an iterative manner. In this section every approach and the reasons why it was not the most appropriate alongside some thoughts on the knowledge gained from each of them, which inuenced the following approach, are presented in this section. 4.2.1 First steps towards generalisation The naïve approach requires programmer intervention in the FPGA backend to change the kernel used and specify its launching mode (ND-Range or Task). This is unacceptable and should be moved to the Controllers frontend. Choosing the desired kernel to launch Both the pipeline conguration and the device for execution (actual hardware or FPGA emulator), alongside proling mode or normal mode are decisions that have to be made prior to the kernel compilation. For this reason, these are static features of the kernel binary and a dierent conguration of these parameters requires a new compilation. Given that kernel compilation is an expensive process that can take up to several hours it is advisory to save these binaries. There is no simple way of retrieving all this parameters from the compiled binary apart from consulting the HTML report generated during compilation, which is not easy to automate. A plausible solution which helps getting all the binaries organised is naming them according to the nomenclature explained in 3.4.2. It has also the advantage of allowing the mapping of the kernel characterisation detailed in 3.4.3 to the appropriate kernel binary by the manipulation of the string of the kernel path. Specifying the kernel launching mode Launching a kernel as ND-Range or as a Task not only implies how many workitems will execute it but prior work of adaptation of the whole kernel has had to be made in order to adapt to one of them. Although every kernel can be launched in both modes (unless an explicit restriction is expressed in the kernel le) this adaptation work is necessary to achieve high performance. Therefore, it seems reasonable to consider this decision part of the characterisation of the kernel, specically of the conguration of the pipeline. The concrete parameters were explained in 3.4.3. The annotation __attribute__((max_global_work_dim(0))) in the kernel le restricts its execution to Task mode and encourages AOC to try to optimise the pipeline in this direction. This has been exploited in Controllers by the creation of a series of new macros which will ultimately expand to the attribute conditioned to the denition of CTRL_FPGA_KERNEL_FILE . The mechanism used to achieve this has been the concatenation of the parameter passed to KERNEL_PIPELINE with the token EXTRACT with the operator ##. This way, when the concatenation result is CTRL_EXTRACT_KERNEL_TASK , a macro dened in the backend, the preprocessor will expand it to the given denition, which in this case is the said attribute. This mechanism has been used for the rest of the arguments. 37 4.2. APPROACHES CONSIDERED BEFORE DEFINITIVE SOLUTION 4.2.2 First approach: Unied host+device programs As has been discussed in the previous chapter the use of OpenCL on FPGAs requires host code and kernel code to be split in two dierent les, so that oine compilation is possible. This clashes with the transparency property of Controllers, i.e., the programmer faces the same programming interface regardless of the device he intends to use. The way to achieve this is by shifting the task of splitting the Controllers code from the programmer to another preprocessing step. Lex The tool chosen to achieve this result was Lex (specically the GNU avour Flex). Lex is a tool for generating scanners, also known as lexers: programs which recognise lexical patterns in text. It is based on the recognition of patterns by leveraging regular expressions. Unlike sed, Lex is designed to work over whole les. Moreover, it allows intermingling C code, which makes Lex a more versatile tool. Structure of a kernel le The code snippet 4.1 shows how a kernel le prepared for oine compilation should look. It is worth noticing every construct shown here is also necessary for the compilation of the host code. For this reason, the annotation CTRL_FPGA_KERNEL_FILE is necessary to allow the preprocessor to distinguish between the backend implementation targeted to the host and to the device. 1 #define CTRL_FPGA_KERNEL_FILE 2 #include "Ctrl.h" 3 4 Ctrl_NewType( float ); 5 6 CTRL_KERNEL_CHAR(Mult , MANUAL , LOCAL_SIZE_0 , LOCAL_SIZE_1 , KERNEL_PIPELINE(KERNEL_SIMD( 4, 64, 64, 1))); 7 8 CTRL_KERNEL_PROTO( Mult, 9 1, FPGA , 5, 10 OUT, HitTile_float, C, 11 IN, HitTile_float, A, 12 IN, HitTile_float, B, 13 INVAL, int, A_width , 14 INVAL, int, B_width 15 ); 16 17 CTRL_KERNEL(Mult, FPGA, KHitTile_float C, KHitTile_float A, KHitTile_float B, int A_width , int B_width , 18 ( 19 ... 20 )); Listing 4.1: Structure of a kernel le after preprocessing step Extraction of kernel constructs from unied code The Lex program created for the extraction of kernel constructs from unied code is shown in code snippet 4.2. Specically, it extracts CTRL_KERNEL , Ctrl_NewType , CTRL_KERNEL_CHAR and CTRL_KERNEL_PROTO . Since the input le is scanned sequentially three buers have to be dened to allow the recognition of the constructs in no particular order, i.e, assuming they are indenpendent of 38 CHAPTER 4. IMPLEMENTATION each other. Some regular expresions, such as those referring to macro arguments or the kernel prototype, have been given an alias based on semantics to improve readability. Scanning the kernel body in CTRL_KERNEL and the primitive CTRL_KERNEL_CHAR was done by declaring two start conditions that drive the automaton to the states that deal with the problem of matching parentheses. The rest of the code is self explanatory. 1 %{ 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 6 #define CTRL_KERNEL_BUF 100000 7 #define CTRL_KERNEL_PROTO_BUF 1000 8 9 int unmatched_parens = 0; 10 char ctrl_kernel_buf[CTRL_KERNEL_BUF]; 11 char ctrl_kernel_proto_buf[CTRL_KERNEL_PROTO_BUF]; 12 char ctrl_kernel_char_buf[CTRL_KERNEL_PROTO_BUF]; 13 %} 14 15 %option noyywrap 16 17 spaces [\t\n ] 18 sep ; 19 arg [ A-Za-z0-9_*-]+{spaces}* 20 new_t Ctrl_NewType{spaces}*"("([^\)]|{spaces}])*")"{spaces}*{sep}*{spaces}* 21 k_char_1 CTRL_KERNEL_CHAR{spaces}*"("({arg},{spaces}*)+KERNEL_PIPELINE"(" 22 k_proto CTRL_KERNEL_PROTO{spaces}*"("(({arg}|,){spaces}*)+")"{spaces}*{sep}*{spaces}* 23 ctrl_k_signature CTRL_KERNEL{spaces}*"("{spaces}*({arg},)+[\t\n ]"(" 24 25 26 /* extracts argument inside parenthesis */ 27 %x kernel_body k_char_args 28 %% 29 {new_t} { 30 strcat(ctrl_kernel_char_buf , yytext); 31 } 32 {k_char_1} { 33 strcat(ctrl_kernel_char_buf , yytext); 34 unmatched_parens = 1; 35 BEGIN k_char_args; 36 } 37 {k_proto} { 38 strcat(ctrl_kernel_proto_buf , yytext); 39 } 40 {ctrl_k_signature} { 41 strcat(ctrl_kernel_buf , yytext); 42 unmatched_parens = 1; 43 BEGIN kernel_body; 44 } 45 46 47 .|\n ; 48 49 <kernel_body >{spaces}*[^\(^\)]+"(" { 50 unmatched_parens++; 51 strcat(ctrl_kernel_buf , yytext); 52 } 53 <kernel_body >[^\(^\)]*")"{spaces}*{sep}*{spaces}* { 54 strcat(ctrl_kernel_buf , yytext); 55 56 if (!unmatched_parens) 57 BEGIN INITIAL; 39 4.3. DEFINITIVE APPROACH: RETURNING TO THE KTILE WRAPPER Figure 4.2: Arbitration logic in struct_without_pointer (left) and struct_with_pointer kernels (right) struct_with_pointer struct_without_pointer LD 129 26 ST 3 2 Table 4.1: Load store units latencies in the experiment kernels 4.3 Denitive approach: returning to the ktile wrapper As it has already been discussed, there is a performance penalty on using pointers to struct as kernel arguments. Given its magnitude there is no other workaround for passing the ktiles to the kernel than returning to the approach taken in the OpenCL backend. It could be easily adapted to FPGA by typing data pointers as void * (Recall the only information referring to the datatype of the data pointer is the HitTile type, which is of the form HitTile_<type> ) had it not been because this is done in CTRL_KERNEL_PROTO , which, as every C statement, has to be followed by ; . Since the kernel signature is followed by the kernel body and nothing can stay in between, the ; would have to be removed. It could be argued that Controllers would stop being a C based model, so this is not an acceptable workaround. Moreover, the kernel prototype was initially thought as an independent statement and generating the kernel signature from it would keep it xed before CTRL_KERNEL . Instead, it will be expanded from CTRL_KERNEL . The same applies for kernel attributes, that were expanded from CTRL_KERNEL_CHAR in the unied version. 4.3.1 Expanding the kernel signature from CTRL_KERNEL In order to generate the kernel signature it is necessary to have the roles of each argument, since ktiles have to be separated in the ktile wrapper and the data pointer and INVALs must be kept as they are. This information is not available in CTRL_KERNEL , but in CTRL_KERNEL_PROTO . It has to be 46 CHAPTER 4. IMPLEMENTATION duplicated in order to make this distinction between arguments. Take into account that CTRL_KERNEL is supposed to be seen as the kernel signature for the user of Controllers and the roles are just qualiers to the arguments. In order to minimise the impact of including them here they will be surrounded by the macro CTRL_KERNEL_FPGA_ROLES . The name of the arguments cannot be extracted leveraging the preprocessor, since it is preceded by its type and a white space. The concatenation operator cannot alter any of the characters of the token, but it is able to attach text to its sides. This allows the modication of the type and the name of the argument. On top of that, it is possible to assign an alias to a pointer with typedef . With these tools, the strategy is as shown in gure 4.3: now there will be a ktile wrapper structure for every type instantiated in the host code, so that it can be instantiated by attaching fpga_wrapper_ to the beginning of the token. In order to type the data pointer as void * this datatype, alongside the keyword restrict, are aliased with typedef in the creation of ktiles of a given type, as well. A token will be concatenated to them, _wrapper and _data , respectively, in order to be distinguishable from the rest of the arguments. KHitTile_<type> K fpga_wrapper_KHitTile_<type> K_wrapper data_KHitTile_<type> K_data __global void * restrict typedef KHitTile_<type> K ## (assembled in kernel body) coords data* coords data* data* coords Figure 4.3: The concatenation operator and typedef are leveraged to generate the function signature from CTRL_KERNEL . Special attention should be paid to the semantics of the address qualier for the denition of the pointer alias. Dening the alias as typedef void* restrict data_KHitTile_<type> will result in the oine compiler giving the error parameter may not be qualied with an address space . In order to understand what is going on it is necessary to analyse the steps taken by the compiler. Since no address space is specied, the pointer points to the private address space. Hence __global data_KHitTile_<type> is indicating that the pointer itself resides in the global address space, so the compiler is understanding the opposite of what we want to convey: the pointer should reside in the private address space and should be pointing to the global address space. For that, the solution comes through including the address qualier in the denition of the alias, so the compiler understands it refers to the memory pointed by the pointer, as in gure 4.3. 1 // Host code file 2 CTRL_KERNEL_CHAR(Mult , MANUAL , NDRANGE , LOCAL_SIZE_0 , LOCAL_SIZE_1); 3 4 CTRL_KERNEL_PROTO( Mult, 5 1, FPGA , 5, 47 4.3. DEFINITIVE APPROACH: RETURNING TO THE KTILE WRAPPER 6 OUT, HitTile_float, C, 7 IN, HitTile_float, A, 8 IN, HitTile_float, B, 9 INVAL, int, A_width , 10 INVAL, int, B_width 11 ); 12 13 // Kernel code file 14 CTRL_KERNEL(Mult , FPGA , PIPELINE( NDRANGE , SIMD( 4, 64, 64, 1) ), PARAMS( OUT , IN, IN, INVAL , INVAL ), 15 KHitTile_float C, KHitTile_float A, KHitTile_float B, int A_width , int B_width) 16 { 17 CTRL_INIT_KTILE(A, float); 18 CTRL_INIT_KTILE(B, float); 19 CTRL_INIT_KTILE(C, float); 20 // Kernel body 21 } Listing 4.8: Example of the denitive version of the Controllers interface modied macros Expanding the kernel signature from CTRL_KERNEL , an alternative approach Since the names of the arguments must be available for the generation of the kernel signature and leveraging the preprocessor to hide this requirement from the user by the last approach was unsuccessful, there is no other option than requesting the programmer to do so. To serve this purpose, the macro KTILE( type, name ) is created, which only takes the type of the data pointer and the name of the argument as parameters. The roles are not needed anymore, since they were just used to dierentiate between invals and ktiles and this is solved by the use of the new macro. The pipeline specication is also moved from CTRL_KERNEL_CHAR to CTRL_KERNEL , but the launching mode has to be preserved in both macros. It will be used to determine the launching model in the kernel characterisation macro and to generate the associated attributes in CTRL_KERNEL . A code excerpt involving the modied macros is given in 4.9, where it is clearly stated which belong to either the host or the kernel le. 1 // Host code file 2 CTRL_KERNEL_CHAR(Mult , MANUAL , NDRANGE , LOCAL_SIZE_0 , LOCAL_SIZE_1); 3 4 CTRL_KERNEL_PROTO( Mult, 5 1, FPGA , 5, 6 OUT, HitTile_float, C, 7 IN, HitTile_float, A, 8 IN, HitTile_float, B, 9 INVAL, int, A_width , 10 INVAL, int, B_width 11 ); 12 13 // Kernel code file 14 CTRL_KERNEL(Mult , FPGA , PIPELINE( NDRANGE , SIMD( 4, 64, 64, 1) ), KTILE(float, C), KTILE(float, A), KTILE(float, B), int A_width , int B_width) 15 { 16 CTRL_INIT_KTILE(A, float); 17 CTRL_INIT_KTILE(B, float); 18 CTRL_INIT_KTILE(C, float); 19 // Kernel body 20 } Listing 4.9: Example of an alternative version of the Controllers interface modied macros 48 CHAPTER 4. IMPLEMENTATION 4.3.2 Proling and emulation Thanks to the kernel name format described in 3.4.2 the user is able to perform proling or run a kernel on an emulated device just by enabling the corresponding option in the CMake le that compiles the Controllers project. Since this is a decision that conceptually aects how a kernels is executed but not its functionality or its eventual mapping on the device it seems more appropriate to keep these options outside the Controllers code. To enable proling the option FPGA_PROFILING must be set, whilst for emulation the same must be done with the option FPGA_EMULATION . As they are incompatible, when they are activated at the same time emulation will be chosen by default. What is happening behind the scenes is that the kernel path string is modied by inserting the word proling or emu , depending on the enabled option, as specied by the kernel name format. 4.4 Conclusions This chapter described the solution developed for the integration of FPGAs in the Controllers library. It enhances programmability, while allowing transparent dependency and data management and asynchronous execution, which leads to performance gains thanks to to the ability to overlap data transfers and computation. This was achieved at the cost of minor changes to the user-facing interface of Controllers when programming FPGAs in the denitive approach. They could be minimised even more in the future thanks to the second approach, which does not work at the moment due to the current behaviour of the Intel compiler. All the discarded approaches are functional, so the rst approach could be leveraged in the future to remove any divergence the programmer can perceive in Controllers due to the use of this backend, provided the independence from external tools is not a concern anymore. The initalisation operations related to kernels launching were removed from the runtime, as this became a need for the second approach. This might, in addition, lead to a potential improvement in time measurements that compare Controllers with other reference models. Finally, proling and emulation were eased for the programmer by requiring just the activation of a ag. 49 4.4. CONCLUSIONS 50 CHAPTER 5. EXPERIMENTATION Chapter 5 Experimentation This chapter introduces the following aspects: • The objectives of the experimentation performed. • The chosen case studies:  Hotspot  Matrix Power  Sobel Filter • Performance study that validates our proposal. • Study of software metrics on the generated code. • The results obtained from the experimentation and the conclusions reached. 5.1 Objectives of experimentation This section introduces the objectives of the experimentation for the proposed model. This objectives are as follows: 1. The performance improvement due to overlap depends on the workload of the communication and computation tasks and the dependencies between them. 2. The solution proposed over the Controllers library oers a code implementation with less complexity over other existing technologies. 3. The overhead of this abstraction, due to the implemented prototype and the internal control structures, has a minimal eect over performance in parallel executions compared to solutions over other exising technologies. 5.2 Case study: Hotspot The base program is an adaptation of that of the Rodinia suite of benchmarks by Zohouri et al. [50, 51, 35, 53]. It computes the stability point of the Poisson's Partial Dierential Equation (PDE) for heat 51 5.3. CASE STUDY: MATRIX POWER diusion. It uses a Jacobi iterative method on a 2-dimensional discrete space. It is a 4-point stencil program that executes a xed number of time iterations. The kernel exploits the shift register pattern for both spatial and temporal locality (refer to 2.1.6 for further information). The program is tested with 400 iterations. The result matrix is transferred to the host after each kernel launching operation, saving it in a dierent host buer using a host-task. Thus, the results could be used to check partial results or create an animation of the computation evolution. Matrices with input sizes from 1024 × 1024 to 4096 × 4096 are considered in order to achieve a memory-bound scenario. Algorithm 1 Hotspot 1: function Copy ( A, B ) 2: Data: x, y: column and row indices, respectively 3: B[x][y]←A[x][y] 4: end function 5: function HotspotIteration ( P, A, B ) 6: Data: x, y: column and row indices, respectively 7: B[y][x]←P[y][x]+(A[y−1][x] + A[y+ 1][x]−2A[y][x])/Rx+ (A[y][x−1] + A[y][x+ 1] −2A[y][x])/Ry+ (T−A[y][x])/Rz 8: end function 9: function main 10: Data: n: number of iterations, P: power matrix, A: original temp. matrix, B: temp. matrix copy 11: for i←1, n do 12: HotspotIteration (P, A, B) 13: MoveFrom (B) 14: Copy (B,A) 15: end for 16: end function 5.3 Case study: Matrix Power This program is an evolution of the 2mm and 3mm programs in the PolyBench Benchmarks [36] to generate a chain of matrix multiplications of arbitrary length. It computes the normalisation of the matrices Ci=Ai:i∈[1 : n] . It iteratively computes in the device the multiplication of the original matrix by the partial result of the previous step: ck=Ck−1×A:k∈[1 : n] where C0=A . The kernel to multiply matrices is obtained from the Intel FPGA Support Resources. This optimised kernel uses local memory, loop unrolling and SIMD to take advantage of the FPGA resources. Each partial result Ci is transferred to the host. A host-task computes the normalistion of the matrix and saves it in another buer. The matrix normalisation consists of the following phases: (a) Determining the minimum and maximum values in the matrix; (b) substracting the minimum from each element of the matrix, and dividing each element by the maximum; (c) computing the elements norm as the square root of the sum of each element power 2; and (d) dividing each matrix element by the elements norm . The program is tested with n = 30 iterations and input sizes from 1024 × 1024 to 4096 × 4096 to reach a memory-bound scenario. 52 CHAPTER 5. EXPERIMENTATION 5.4 Case study: Sobel The Sobel Operator is described in 2. For this experimental study an implementation that iteratively processes frames from a video in YUV format has been chosen. The kernel was adapted from that of the Intel FPGA Support Resources, which received as input RGB images and transformed every pixel to a single channel on the y. Instead, this transformation was removed, since the tested program reads an input video stream from a le, frame by frame and each frame has three components that are communicated to the device. Then, the Sobel lter is applied to each component launching the same kernel, once for each component. The resulting image is transferred back to the host to store it in an output video le. Each component of a frame is read, written, computed, or transferred separately. The input/output images are read from and written to les. The computation of the Sobel lter is a very fast operation. Thus, this study case is very demanding in terms of concurrency exploitation and asynchronous data-transfer executions. The program is tested with 120, 240, 300 and 360 frames of a high-denition video (Full HD images of 1920 × 1080 pixels) so the performance gained from computation and communication overlap could be perceived. Algorithm 2 Sobel 1: function SobelOperation ( A, B, threshold ) 2: Data: x, y: column and row indices, respectively 3: h← −A[y−1][x−1] −2A[y−1][x]− A[y−1][x+ 1] + A[y+ 1][x−1] + 2A[y+ 1][x] + A[y+ 1][x] 4: v← −A[y−1][x−1] + A[y−1][x+ 1] − 2A[y][x−1] + 2A[y][x+ 1] − A[y+ 1][x−1] + A[y+ 1][x+ 1] 5: temp ←p(h2+v2) 6: if temp > threshold then 7: B[x][y]←255 8: else 9: B[x][y]←0 10: end if 11: end function 12: function main 13: Data: n: number of frames, A[3]: input video matrix, B[3]: output video matrix 14: for i←1, n do 15: for j←1,3 do 16: MoveTo (A[j]) 17: SobelOperation (A[j], B[j]) 18: MoveFrom (B[j]) 19: LoadFrame (A[0], A[1], A[2]) . Reads frame from source video and loads it in input matrices 20: PutFrame (B[0], B[1], B[2]) . Writes output matrices in destination video 21: end for 22: end for 23: end function 53 5.5. EXPERIMENTAL ENVIRONMENT 5.5 Experimental environment In this experimental study the nal prototype of the Controller library is compared against the reference programs in OpenCL with the synchronous and asynchronous implementations. The choice between synchronous and asynchronous policy can be done at run-time. The kernel codes are surrounded by the primitive CTRL_KERNEL and the accesses to global memory are rewritten with the Hitmap's hit() access macro. The experimentation was conducted on nodes of the Intel DevCloud platform featuring FPGAs. Each of these nodes comprises an Intel(R) Xeon(R) Gold 6128 CPU @ 3.40GHz with 192 GB of RAM equipped with an Intel Arria 10. The O.S. is an Ubuntu 18.04 Linux distribution. All programs are compiled with GCC v7.4 using the Intel FPGA SDK for OpenCL. The performance experiments measure the clock time from the start of the rst data transfer to the end of the last host-task. This includes data transfers, computation times, and system overheads. 5.6 Performance study Figure 5.1 shows the performance results obtained for the dierent versions of the Hotspot and Matrix Power case studies. The plots represent the total execution times in the y-axis and dierent input data sizes in the x-axis. Figure 5.2 shows the performance of Hotspot, Matrix Power and Sobel lter when the number of iterations increases to enable a comparison with the latter, since input size is not a parameter. During the development of this work AOC was upgraded in Intel DevCloud, leading to some behavioural changes in the oine compiler and, as a result, some changes in the overhead of the Controllers library that are worth studying. For that reason, plots for the 19.3 and 20.1 version of the compiler are included. The same information is conveyed by tables 5.1 and 5.2 to ease the discussion of the results with numerical values. From these results it is clear that the asynchronous policy of Controllers works specially well with FPGAs, with almost non existent overhead and, in some cases, even negative overhead. This can be explained through the treatment of events by Controllers, which processes them in batches, opposed to the reference programs, which do so once they are issued. The Controllers way reduces the number of requests to the device driver, hence leading to minor gains in time that could explain this counterintuitive results. The dierences between the compiler versions are particularly noticeable in the Matrix Power and Sobel Filter kernels. It can be seen that for the 19.3 version the Matrix Power the Controller implementation achieves lower times than its counterpart, while the opposite happens when it is compiled with the 20.1 version of AOC. On the other hand, the opposite happens to the Sobel lter kernel, whose Controllers version performs better with the 20.1 compiler (notice that the dierence lies in the asynchronous policy version, whilst for the synchronous one Controllers outperforms the native implementation regardless of the compiler). Recall that, although functionally the same, the code of Controllers kernels is not exactly the same once CTRL_KERNEL is expanded and hence the synthesised circuits dier. Table 5.3 gathers the operating frequencies of the synthesised kernels for both versions. They match the previous observations: the Matrix Power kernel achieves a frequency of 258.33 Hz in the Controllers implementation and 255.95 Hz in the reference one with the 19.3 version of AOC, whilst it was stated that the Controllers version ouperformed its counterpart with this compiler version. The opposite happens with the 20.1. The same reasoning can be applied to the Sobel lter kernel. However, the Controllers implementation always achieves lower times with the Hotspot benchmark regardless of the compiler, although according to 5.3 this sould only occur 54 CHAPTER 5. EXPERIMENTATION 0 5 10 15 20 25 30 35 1000 1500 2000 2500 3000 3500 4000 4500 Exec. time (s) Size (NxN) Ctrl Sync Ref Sync Ctrl Async Ref Async (a) Hotspot 400 iterations (v19.3) 0 1 2 3 4 5 6 7 8 9 10 600 800 1000 1200 1400 1600 1800 2000 2200 2400 2600 Exec. time (s) Size (NxN) Ctrl Sync Ref Sync Ctrl Async Ref Async (b) Matrix power 30 iterations (v19.3) 0 5 10 15 20 25 30 35 1000 1500 2000 2500 3000 3500 4000 4500 Exec. time (s) Size (NxN) Ctrl Sync Ref Sync Ctrl Async Ref Async (c) Hotspot 400 iterations (v20.1) 0 1 2 3 4 5 6 7 8 9 10 600 800 1000 1200 1400 1600 1800 2000 2200 2400 2600 Exec. time (s) Size (NxN) Ctrl Sync Ref Sync Ctrl Async Ref Async (d) Matrix power 30 iterations (v20.1) Figure 5.1: Experimentation results with Hotspot and Matrix Power benchmarks for dierent matrix sizes. AOC v19.3 results are at the top, whilst v20.1 are at the bottom. with the 20.1 version and not in the 19.3 or, at least, it should not be that signicant with this one. This suggests that other factors might be involved in this phenomenon. Unfortunately, proling is of no help in this case, since the frequencies of the studied kernels change due to the instrumentation and the order relations between them changes (see, for example, how the Matrix Power kernel achieves higher frequency in the reference implementation with the 19.3 version of the compiler when it is compiled from proling). Future work will include xing the operating frequency of the kernel with the workaround described in [52], since the Intel FPGA SDK for OpenCL does not provide any native mechanism, to nd out the underlying cause of this behaviour. 55 6.2. FUTURE WORK 6.2 Future work The development of this work has opened multiple research lines that might be the source of future works. In chapter 5 it was found that the use of Controllers leads to lower execution times than OpenCL in several scenarios. This could be partially explained by the dierence in operating frequency between Controllers and reference kernels. This explanation had some holes, however, so more rened tools such as the workaround for xing kernel frequency mentioned in [52] or the advanced proling method detailed in [43] will probably be used to dig into the problem. FPGAs allow more advanced techniques that are out the scope of this work and could potentially increase performance. This is the case of partial reconguration , which allows the modication of some parts of the synthesised circuit while the rest are runnning. Since programming time range from milliseconds to a second, there is a chance for overlapping them with computation or data transfers, leading to performance improvements. Combining this technique with the ideas for partial recongurable kernels in OpenCL in [42] could turn Controllers into an attractive option for shared heterogeneous environments in which context switches are frequent, such as cloud platforms. HLS languages have the benet of improving programmability and this has been the main focus of this work. However, the programmer might lose control over the synthesised circuit, relying on the design inferred by the compiler. This can be problematic for advanced use cases, as the one in 4.2.3. Fortunately, it is possible to integrate HDL modules with the Intel FPGA SDK for OpenCL, reaching full control over the nal design. 6.3 Personal assessment This work has been my rst contact with research and the beginning of a career focused on research in HPC. Its development did not only allow me to learn new technologies but also introduced me to the research methodology. As a result, now I am capable of looking up the information I need to support my arguments more eciently and I have become a better learner, which are valuable skills in every job. I came from a data science background, so I had to learn many new concepts and tools to undertake this project successfully. It has been an exciting journey that has opened my mind and has given me the opportunity to work with FPGAs and expand my knowledge about electronics and the details of the low level layers of computers. Had it not been for this I would have never made a serious project with FPGAs and I would have not discovered all the learning oportunities it oers to electronics enthusiasts like me thanks to their recongurability. All in all, this has been an enriching experience that rearms my motivation to pursuit a PhD and a career based on research. 62 APPENDIX A. CONTENTS OF THE CD-ROM Appendix A Contents of the CD-ROM The code of the backend elaborated in this work, as well as the case studies adapted for the experimentation, can be accessed upon request. For that, contact the members in charge at the Trasgo research group ( https://trasgo.infor.uva.es/ ) for this work: • Arturo González Escribano : [email protected]a.es • Yuri Torres de la Sierra : [email protected]a.es 63 64 BIBLIOGRAPHY Bibliography [1] TOP500. https://www.top500.org/ . [Online; accessed 8-June-2020]. [2] ISO/IEC 9899:201x; Programming languages  C. " http://port70.net/~nsz/c/c11/n1570.html# 6.10.9 ", 2011. [Online; accessed 7-May-2020]. [3] A development sandbox for data center to edge workloads. https://software.intel.com/content/ www/us/en/develop/tools/devcloud.html , 2020. [Online; accessed 15-June-2020]. [4] BertenDSP. GPU vs FPGA performance comparison. In Proceedings of the 2017 ACM/SIGDA International Symposium on Field-Programmable Gate Arrays-FPGA'17 , 2016. [5] Jaume Bosch, Xubin Tan, Antonio Filgueras, Miquel Vidal, Marc Mateu, Daniel Jiménez-González, Carlos Álvarez, Xavier Martorell, Eduard Ayguadé, and Jesus Labarta. Application Acceleration on FPGAs with OmpSs@ FPGA. In 2018 International Conference on Field-Programmable Technology (FPT) , pages 7077. IEEE, 2018. [6] Randal E Bryant, O'Hallaron David Richard, and O'Hallaron David Richard. Computer systems: a programmer's perspective , volume 2. Prentice Hall Upper Saddle River, 2003. [7] Cosmin Cernazanu-Glavan, Stefan Fedeac, Alexandru Amaricai-Boncalo, and Marius Marcu. Energy proling of FPGA designs. In 2014 IEEE International Symposium on Robotic and Sensors Environments (ROSE) Proceedings , pages 118123, October 2014. [8] IEEE Design Automation Standards Committee et al. Std 10762008, ieee standard vhdl language reference manual. IEEE, New York, NY, USA , 2008. [9] Altera Corporation. Nios II Classic Processor Reference Guide. page 282. [10] Altera Corporation. FPGA architecture (White Paper). 2006. [11] Digi-Key. A-U200-P64G-PQ-G. https://www.digikey.es/product-detail/es/xilinx-inc/ A-U200-P64G-PQ-G/122-2250-ND/9645681 . [Online; accessed 13-June-2020]. [12] Digi-Key. A-U50DD-P00G-ES3-G. https://www.digikey.es/products/es?keywords=xilinx% 20alveo%20u50 . [Online; accessed 13-June-2020]. [13] Ulrich Drepper. What every programmer should know about memory. Red Hat, Inc , 11:7, 2007. [14] Tony Gaddis. Digital Fundamentals, Global Edition . Pearson Education Limited, 2014. [15] Arturo Gonzalez-Escribano, Yuri Torres, Javier Fresno, and Diego R Llanos. An extensible system for multilevel automatic data partition and mapping. IEEE Transactions on Parallel and Distributed Systems , 25(5):11451154, 2013. [16] Khronos OpenCL Working Group et al. The OpenCL Specication, version 1.0. 29, 8 December 2008. 65 BIBLIOGRAPHY [17] Maurice Howard Halstead et al. Elements of software science , volume 7. Elsevier New York, 1977. [18] Mark Harris. How to optimize data transfers in CUDA C/C++. NVIDIA Developer Zone , 2012. [19] Mark Harris. An ecient matrix transpose in CUDA C/C++. Retrieved July , 26, 2013. [20] Hynix. 64Mb Synchronous DRAM based on 1M x 4Bank x16 I/O, 2007. [21] Intel. Intel R  Quartus R  Prime Pro Edition Software. https://www.intel.com/content/www/us/ en/programmable/buy/design-software.html . [Online; accessed 13-June-2020]. [22] Intel. Intel FPGA SDK for OpenCL Programming Guide . 2016. [23] Intel. Intel FPGA SDK for OpenCL Programming Guide . 2019. [24] Intel. Intel FPGA SDK for OpenCL Best Practices Guide . 2020. [25] Qi Jia and Huiyang Zhou. Tuning stencil codes in OpenCL for FPGAs. In 2016 IEEE 34th International Conference on Computer Design (ICCD) , pages 249256. IEEE, 2016. [26] David R Kaeli, Perhaad Mistry, Dana Schaa, and Dong Ping Zhang. Heterogeneous computing with OpenCL 2.0 . Morgan Kaufmann, 2015. [27] Deborah T Marr, Frank Binns, David L Hill, Glenn Hinton, David A Koufaty, J Alan Miller, and Michael Upton. Hyper-Threading Technology Architecture and Microarchitecture. Intel Technology Journal , 6(1), 2002. [28] Thomas J McCabe. A complexity measure. IEEE Transactions on software Engineering , (4):308320, 1976. [29] Michael McNamara. IEEE Standard Verilog Hardware Description Language. https://www. verilog.com/IEEEVerilog.html , 2008. [Online; accessed 9-June-2020]. [30] Ana Moreton-Fernandez, Hector Ortega-Arranz, and Arturo Gonzalez-Escribano. Controllers: An abstraction to ease the use of hardware accelerators. The International Journal of High Performance Computing Applications , 32(6):838853, 2018. [31] Raúl Nozal, Jose Luis Bosque, and Ramón Beivide. Enginecl: Usability and performance in heterogeneous computing. Future Generation Computer Systems , 107:522537, 2020. [32] David Padua. Encyclopedia of parallel computing . Springer Science & Business Media, 2011. [33] Ioannis Parnassos, Nikolaos Bellas, Nikolaos Katsaros, Nikolaos Patsiatzis, Athanasios Gkaras, Konstantinos Kanellis, Christos D Antonopoulos, Michalis Spyrou, and Manolis Maroudas. A programming model and runtime system for approximation-aware heterogeneous computing. In 2017 27th International Conference on Field Programmable Logic and Applications (FPL) , pages 14. IEEE, 2017. [34] David A Patterson and John L Hennessy. Computer Organization and Design ARM Edition: The Hardware Software Interface . Morgan kaufmann, 2016. [35] Artur Podobas, Hamid Reza Zohouri, Naoya Maruyama, and Satoshi Matsuoka. Evaluating high-level design strategies on FPGAs for high-performance computing. In 2017 27th International Conference on Field Programmable Logic and Applications (FPL) , pages 14. IEEE, 2017. [36] Louis-Noël Pouchet and Scott Grauer-Gray. Polybench: The polyhedral benchmark suite (2011). URL http://www-roc. inria. fr/ pouchet/software/polybench , 2015. 66 BIBLIOGRAPHY [37] Arifur Rahman. FPGA based design and applications . Springer Publishing Company, Incorporated, 2008. [38] Prasanna Sundararajan. High performance computing using FPGAs. Technical report, 2010. [39] TerasIC. DE10-Pro. https://www.terasic.com.tw/cgi-bin/page/archive.pl?Language= English&CategoryNo=248&No=1144 . [Online; accessed 13-June-2020]. [40] TerasIC. DE5-Net FPGA Development Kit. https://www.terasic.com.tw/cgi-bin/page/ archive.pl?Language=English&CategoryNo=158&No=526&PartNo=1 . [Online; accessed 13-June- 2020]. [41] TerasIC. DE5a-Net-DDR4. https://www.terasic.com.tw/cgi-bin/page/archive.pl?Language= English&CategoryNo=228&No=1108&PartNo=1 . [Online; accessed 13-June-2020]. [42] Anuj Vaishnav, Khoa Dang Pham, Dirk Koch, and James Garside. Resource Elastic Virtualization for FPGAs Using OpenCL. In 2018 28th International Conference on Field Programmable Logic and Applications (FPL) , pages 1111117, Dublin, Ireland, August 2018. IEEE. [43] Anshuman Verma, Huiyang Zhou, Skip Booth, Robbie King, James Coole, Andy Keep, John Marshall, and Wu-chun Feng. Developing dynamic proling and debugging support in OpenCL for FPGAs. In Proceedings of the 54th Annual Design Automation Conference 2017 , pages 16, 2017. [44] Hasitha Muthumala Waidyasooriya, Masanori Hariyama, and Kunio Uchiyama. Design of FPGA- based computing systems with OpenCL . Springer, 2018. [45] Chao Wang, Xi Li, Junneng Zhang, Peng Chen, Xiaojing Feng, and Xuehai Zhou. FPM: A Flexible Programming Model for MPSoC on FPGA. In 2012 IEEE 26th International Parallel and Distributed Processing Symposium Workshops PhD Forum , pages 477484, May 2012. [46] Wayne Wolf. FPGA-based system design . Pearson education, 2004. [47] Xilinx. Vivado Design Suite - HLx Editions. https://www.xilinx.com/products/design-tools/ vivado.html#buy . [Online; accessed 13-June-2020]. [48] Xilinx. SDAccel Programmers Guide . 2019. [49] Victoria Zhislina. Why has CPU frequency ceased to grow? Intel. Retrieved October , 14, 2015. [50] Hamid Reza Zohouri. High performance computing with FPGAs and OpenCL. arXiv preprint arXiv:1810.09773 , 2018. [51] Hamid Reza Zohouri, Naoya Maruyama, Aaron Smith, Motohiko Matsuda, and Satoshi Matsuoka. Evaluating and optimizing OpenCL kernels for high performance computing with FPGAs. In SC'16: Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis , pages 409420. IEEE, 2016. [52] Hamid Reza Zohouri and Satoshi Matsuoka. The Memory Controller Wall: Benchmarking the Intel FPGA SDK for OpenCL Memory Interface. In 2019 IEEE/ACM International Workshop on Heterogeneous High-performance Recongurable Computing (H2RC) , pages 1118. IEEE, 2019. [53] Hamid Reza Zohouri, Artur Podobas, and Satoshi Matsuoka. Combined spatial and temporal blocking for high-performance stencil computation on FPGAs using OpenCL. In Proceedings of the 2018 ACM/SIGDA International Symposium on Field-Programmable Gate Arrays , pages 153162, 2018. 67