Deep learning compiler optimization methods specifically for CNN accelerators
By using operator fusion, memory optimization and quantization strategies on the CNN-specific accelerator, the problem of complex network structure and limited quantization methods is solved, and efficient memory management and computing performance improvement are achieved.
Patent Information
- Application Number
- CN202210638258.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2022-06-07
- Publication Date
- 2024-08-23
- Estimated Expiration
- 2042-06-07
AI Technical Summary
It is difficult for existing technology to efficiently process complex network structures and flexibly support different quantization methods on CNN-specific accelerators, resulting in frequent memory access, waste of computing resources, and loss of accuracy.
It adopts operator fusion, memory allocation address superposition, convolution offset and offset fusion, variable bit width quantization, loop tiling and rearrangement strategies to reduce memory access through compiler optimization, improve operation accuracy, and perform on fixed hardware A variety of quantification methods are implemented.
It effectively reduces the accelerator's memory access and storage space waste, improves calculation accuracy, and achieves a nearly 2x acceleration ratio of INT8 quantization without increasing DSP resources.
Smart Images

Figure CN114995822B
Abstract
Description
Technical Field
[0001] The present invention relates to the field of compiler optimization, and in particular to a deep learning compiler optimization method dedicated to a CNN accelerator. Background Art
[0002] With the development of deep learning algorithms, convolutional neural network models have gradually migrated from the cloud to the edge. At the same time, the scale of the model continues to grow, resulting in a sharp increase in the number of parameters and computation. General processing platforms such as CPUs and GPUs have shortcomings such as insufficient performance and high power consumption. Therefore, related research has begun to customize high-performance and energy-efficient CNN dedicated accelerators through FPGAs or ASICs. However, due to the lack of flexibility of dedicated accelerators, software tools such as deep learning compilers need to be designed for use with them.
[0003] Faced with the complex network structure, the deep learning compiler needs to simplify it and finally turn it into various Concat and Split branch structures. For dedicated accelerators, such operations require re-reading the previous calculation results into the cache, and then writing them back to the cache after related operations. Frequent memory access will cause high memory latency and high energy consumption, and will also increase the cost of on-chip resources.
[0004] In addition, because floating-point calculations are more complicated to process in accelerators such as FPGA, the compiler also needs to quantize the model into fixed-point integers. Quantization is divided into symmetric quantization and asymmetric quantization. Symmetric quantization is simple to implement, but it will cause excessive precision loss when the positive and negative data are unevenly distributed, while asymmetric quantization with lower precision loss will increase the computational complexity of the accelerator. At the same time, DSP is used in FPGA to perform multiplication and accumulation operations, but the DSP module is customized and cannot reflect the computing performance advantages of low-bit-width quantized data. Therefore, the compiler's choice of quantization method for the model will be limited by hardware. Summary of the invention
[0005] The present invention aims to at least solve the technical problems existing in the prior art, and in particular innovatively proposes a deep learning compiler optimization method specifically for CNN accelerators.
[0006] In order to achieve the above-mentioned object of the present invention, the present invention provides a deep learning compiler optimization method dedicated to CNN accelerator, comprising the following steps:
[0007] S1, through the optimization methods of operator fusion and / or bn fusion, reduce the accelerator's access to memory and the waste of storage space, and use the memory allocation address superposition method to avoid data overlap between tensors;
[0008] S2 adopts multiple model quantization deployment schemes under fixed hardware. By integrating the offset and convolution bias of asymmetric quantization, the hardware can support asymmetric quantization without additional computing modules, thereby improving the calculation accuracy without changing the hardware. At the same time, through the coordinated optimization of the compiler and accelerator, the input data of the DSP is configured as the shift addition of two numbers, so that two multiplication operations can be performed simultaneously in one DSP, finally realizing the compiler's support for variable bit width quantization.
[0009] Further, the S2 comprises the following steps:
[0010] S2-1, run the calibration set to obtain the dynamic distribution range of the feature map;
[0011] S2-2, detects the quantization bit width option and determines whether it is INT8 or INT16. If it is INT8, input shift-addition or weight shift-addition is used; thus, the calculation speed of INT8 is twice that of INT16.
[0012] S2-3, traverse the computation graph and determine whether there is a jump connection relationship between feature graphs. If so, unify the scaling factor and offset;
[0013] S2-4, detect the quantization compilation form option, calculate the scaling factor scale and zero offset according to the selection of INT8 or INT16 in the previous step, and if it is asymmetric quantization, merge the bias and offset.
[0014] Further, the fusion of the bias and the offset includes:
[0015] For asymmetric quantization, the quantization formula of the convolution calculation process is:
[0016]
[0017] where q 1 ,q 2 ,q 3 , respectively represent input fixed-point numbers, weight fixed-point numbers, and output fixed-point numbers;
[0018] S 1 , S 2 , S 3 They are the input scaling factor, weight scaling factor, and output scaling factor respectively;
[0019] Z 1 , Z 2 , Z 3 They are the input offset, weight offset and output offset respectively;
[0020] 2 -n Indicates right shift n bits operation;
[0021] M 0 is an integer;
[0022] ∑ represents convolution summation;
[0023] B′ represents the new bias;
[0024] round(·) means rounding to the nearest integer;
[0025] Bias means bias.
[0026] Further, the input shift addition comprises:
[0027] Adjacent input shift addition: The input value at the same position corresponding to the next adjacent output point is shifted and added before being sent to the processing engine PE. The calculated result will correspond to two adjacent output points on the output feature map after splitting; the step length of the next group of outputs is 2, and the step length of the corresponding input feature map is also 2;
[0028] Or half-input shift addition: the output feature map is evenly divided up and down, and the input data corresponding to the lower half of the output feature map will be read in a leapfrog manner, while the distance between the upper and lower input points is fixed. At this time, the input offset step is 1, and the number of rows OH in the loop is halved;
[0029] The weight shift addition includes: the weights at the same position on two adjacent convolution kernels are shifted and added and then sent to the weight channel of PE. The result after calculation is split into two adjacent channel values corresponding to the same position of the output feature map. The calculation process of a single convolution kernel remains unchanged. At this time, the number of convolution kernels OC is halved.
[0030] Furthermore, the weighted shift addition also includes: when performing shift addition of signed numbers, the output result of the PE is evenly split into high-order data and low-order data according to the number of bits, and the high-order data needs to be added with the sign bit of the low-order data.
[0031] Furthermore, it also includes:
[0032] In the systolic array, each PE unit accumulates the output result of a PE, and then sends it to the next PE unit for further accumulation, adding an overflow bit to accommodate the carry of data accumulation. This is used to ensure consistency with the INT16 quantization calculation process and that the carry generated by the low-order result in the accumulation process in the INT8 quantization mode will not overwrite the content of the high-order data and the high-order result will not overflow.
[0033] Furthermore, it also includes: using a scheduling strategy that optimizes convolution loop tiling and loop rearrangement to improve the performance of the accelerator. First, the outer loop sequence is enumerated, and the loop tiling size space is explored between different outer loops in the form of multi-threading. The loop tiling size is also enumerated to obtain the block data size corresponding to each cache, and then the clock cycle consumed by this method is calculated according to the information of the FPGA hardware. Finally, the loop scheduling solution that consumes the least clock cycle is adopted through comparison.
[0034] Furthermore, the specific steps of the loop tiling are as follows:
[0035] S100, external circulation:
[0036] S100-1, if h is less than OH, continue the first outer cycle, and h increases by 1 each time;
[0037] S100-2, if c is less than OW, continue the second outer loop, and w = w + ow for each loop;
[0038] S100-3, if oc is less than OC, continue the third outer loop, and oc=oc+To for each loop;
[0039] S100-4, if ic is less than IC, continue the fourth outer loop, and ic=ic+Ti every time the loop is repeated;
[0040] S200, loading data into cache;
[0041] S300, internal circulation:
[0042] S300-1, if _h is less than min(h+oh, OH), continue the first layer inner cycle, and _h increases by 1 each time the cycle is completed;
[0043] S300-2, if _w is less than min(w+ow, OW), continue the second inner loop, and increase _w by 1 each time through the loop;
[0044] S300-3, if occ is less than min(oc+To, OC), continue the third inner loop, and increase occ by 1 each time;
[0045] S300-4, if icc is less than min(ic+Ti,IC), continue the fourth inner loop, and add 1 to icc each time;
[0046] S300-5, if kw is less than KW, continue the fifth inner loop, and kw increases by 1 each time;
[0047] S300-6, if kh is less than KH, continue the sixth inner loop, and increase kh by 1 each time;
[0048] S300-7, output=input*weight+output;
[0049] Where OW and OH represent the width and height of the output feature map respectively;
[0050] IC indicates the number of input channels;
[0051] OC represents the number of convolution kernels;
[0052] KW and KH represent the width and height of the convolution kernel respectively;
[0053] h, c, w, oc, and ic are all traversal symbols of the outer loop;
[0054] ow, To, and Ti are all the step lengths of the cyclic tiling, and their values are all greater than 1;
[0055] _h, _w, occ, icc, kw, kh are all traversal symbols of the inner loop;
[0056] output means output;
[0057] Input means input;
[0058] Weight indicates weight.
[0059] Further, the calculation of the clock cycles consumed in this manner includes:
[0060] S10, calculating the time it takes for the computing unit to process one block according to the inner loop sequence and the size of the loop tile; and then traversing all the blocks in the same way to obtain the total computing time of the computing unit;
[0061] S20, according to the outer loop sequence, the size of the loop tile and the data block replacement described in Table 3.1, calculate the memory method time of each outer loop; if the data in Table 3.1 is a miss, replace it.
[0062] S30, if the time of the second step is greater than the time of the first step, then the memory blocking time = the memory method time of the outer loop - the time of the fixed systolic array calculation; if the time of the second step is less than the time of the first step, the memory blocking time is 0; the total memory blocking time is the time of traversing all the outer loops;
[0063] S40, the total running time of the accelerator = the total computing time of the computing unit + the total memory blocking time.
[0064] Furthermore, the calculation formula for calculating the time taken by the computing unit to process a block is as follows:
[0065] a n (…(a2 (a 1 (a 0 +b)+b)+b)…)
[0066] where a n The number of loops corresponding to the inner loop sequence represented by n is n;
[0067] b represents the additional overhead of switching loops;
[0068] The size of the loop tiling is the specific value of the inner loop, i.e. a 0 ,a 1 ,...,a n ;
[0069] The memory method time of each outer loop = data exchange amount / memory bandwidth.
[0070] Furthermore, it also includes: adopting memory sharing and addressing methods, and enabling the compiler to support complex skip connection network structures through feature graph deep replication and operator execution order exchange strategies; the specific steps include:
[0071] S-1: For operators that do not involve data calculation operations, if the input feature map and the output feature map have overlapping data content, the overlapping data is shared by the related feature maps involved.
[0072] S-2, if the memory space is not continuous, the feature maps involved in data concatenation or splitting are divided into a shared area. If they are not involved, they are a separate shared area. The memory space size of the shared area is calculated according to the size of the feature map with the largest number of channels. Then the compiler calculates the relevant address offset based on the continuous memory or non-continuous memory.
[0073] S-3, if a feature map A is spliced with multiple other unrelated feature maps, a deep copy operator Copy is added, and the feature map is deeply copied into multiple identical feature maps, namely the first feature map A′, the second feature map A″... For the operator Copy, the convolution output corresponding to A is passed through the ALU module and stored in the first feature map A′, the second feature map A″ and other identical feature maps respectively. After the ALU module calculates, A writes the result back to the two addresses;
[0074] S-4, if the output of the splicing operator in the computation graph flows to the linear computation operator as input, move the linear computation operator forward and exchange the order with the splicing operator.
[0075] Furthermore, the address offset includes:
[0076] Address offsets for continuous memory include:
[0077] The address offset calculation formula of the compiler for each cycle is:
[0078] stride i =∏stride list [i+1:]*per Bytes
[0079] Where i represents the cycle of the dimension;
[0080] [i+1:] indicates that the offset value starts from i+1;
[0081] per Bytes Indicates how many bytes each data occupies in memory;
[0082] stride i Indicates the address offset in memory corresponding to the i-th dimension loop;
[0083] stride list Represents a list of circular offsets;
[0084] Address offsets for non-contiguous memory include:
[0085] Calculate the offset of each loop address:
[0086] stride i =∏stride list [i+1:]*per Bytes
[0087] stride list =(1,h,w,cc+c)
[0088] Where h represents the high value of the feature map;
[0089] w represents the width of the feature map;
[0090] c represents the channel value of the feature map;
[0091] cc+c represents the total channel value of the shared area to which the feature map belongs.
[0092] In summary, due to the adoption of the above technical solution, the present invention has the following advantages:
[0093] (1) Reduce the accelerator's memory access and storage space waste through operator fusion and / or BN fusion optimization methods, and use memory allocation address superposition to avoid data overlap between tensors.
[0094] (2) We designed different types of model quantization methods with variable bit widths on a fixed accelerator structure, implemented compiler support for variable bit width quantization, and achieved improved computational accuracy without changing the hardware.
[0095] Additional aspects and advantages of the present invention will be given in part in the following description and in part will be obvious from the following description, or will be learned through practice of the present invention. BRIEF DESCRIPTION OF THE DRAWINGS
[0096] The above and / or additional aspects and advantages of the present invention will become apparent and easily understood from the description of the embodiments in conjunction with the following drawings, in which:
[0097] Figure 1 It is a schematic diagram of the architecture of the dedicated deep learning compiler of the present invention.
[0098] Figure 2 It is a schematic diagram of the topological relationship between the operator node Node and the tensor Tensor of the present invention.
[0099] Figure 3 It is a schematic diagram of converting the fully connected layer into a 1x1 convolution in the present invention.
[0100] Figure 4 It is a schematic diagram of memory access before and after operator fusion of the present invention.
[0101] Figure 5 It is a schematic diagram of branch convolution merging of the present invention.
[0102] Figure 6 It is a memory allocation flow chart of the present invention.
[0103] Figure 7 It is a schematic diagram of the first address reading and writing after convolution filling of the present invention.
[0104] Figure 8 It is a schematic diagram of dividing the output feature map into tiles according to the present invention.
[0105] Fig. 9 It is the instruction generation flow chart of the present invention.
[0106] Fig.10 This is a schematic diagram of the DenseNet jump connection of the present invention.
[0107] Fig.11 It is a schematic diagram of the symmetric quantization and asymmetric quantization calculation modules of the present invention.
[0108] Fig.12 It is a schematic diagram of the data storage hierarchy in the accelerator of the present invention.
[0109] Fig.13 It is a memory distribution diagram of the NHWC data layout channel splicing of the present invention.
[0110] Fig.14 It is a schematic diagram of the shared area division of the present invention.
[0111] Fig.15 It is a schematic diagram of deep copying of overlapping parts of the shared area of the present invention.
[0112] Fig.16 This is a schematic diagram of the yolov4 tiny residual block structure conversion schematic diagram of the present invention.
[0113] Fig.17 It is a schematic diagram of the present invention according to the output position PE input shift addition.
[0114] Fig.18 It is a schematic diagram of PE weight shifting and addition of the present invention.
[0115] Fig.19 This is an example diagram of splitting the multiplication result after the shift addition of signed numbers in the present invention.
[0116] Fig. 20 It is a schematic diagram of the PE output structure of the present invention.
[0117] Fig.21 It is a schematic diagram of the format of different positions of INT8 quantized input data of the present invention.
[0118] Fig. 22 It is a schematic diagram of the model quantization flow chart of the present invention.
[0119] Fig.23 It is a schematic diagram of the XCZU19EG development board of the present invention.
[0120] Fig.24 This is the resource ratio of the CNN accelerator of the present invention on the 19EG development board.
[0121] Fig.25 It is a schematic diagram of the yolov4 tiny network structure of the present invention.
[0122] Fig.26 It is a schematic diagram of parallel calculation of 3*3 convolution kernels of the present invention.
[0123] Fig. 27 It is a schematic diagram of the water flow form of the pulsating array of the present invention.
[0124] Fig.28 It is a schematic diagram of the cyclic multiplication of the number of data replacement times of the present invention.
[0125] Fig.29 It is a schematic diagram of memory blocking of the present invention.
[0126] Fig.30 It is a schematic diagram of loop tiling and loop rearrangement optimization scheduling of the present invention.
[0127] Fig.31 It is a schematic diagram of performance comparison before and after scheduling optimization of the present invention.
[0128] Fig.32 It is a schematic diagram of the directory structure of the compiler of the present invention.
[0129] Fig.33 This is a schematic diagram of the fusion of conv0+bn+leakyRelu operators of the present invention.
[0130] Fig.34 It is a schematic diagram of the topological structure after the conv0 operator is fused according to the present invention.
[0131] Fig.35 It is a schematic diagram of the concat operator structure processing of the present invention.
[0132] Fig.36 It is a schematic diagram of the cyclic scheduling log of the present invention.
[0133] Fig.37 It is a partial instruction graph generated by the compiler of the present invention.
[0134] Fig.38 It is a schematic diagram of simulating and obtaining output logs of the present invention.
[0135] Fig.39 It is a schematic diagram comparing the software and hardware results of the present invention. DETAILED DESCRIPTION
[0136] Embodiments of the present invention are described in detail below, examples of which are shown in the accompanying drawings, wherein the same or similar reference numerals throughout represent the same or similar elements or elements having the same or similar functions. The embodiments described below with reference to the accompanying drawings are exemplary and are only used to explain the present invention, and cannot be understood as limiting the present invention.
[0137] 1 Research background and current status
[0138] 1.1 Research background and significance
[0139] Deep learning is a very important branch of machine learning algorithms. It has developed rapidly in recent years and has achieved remarkable results in computer vision, speech recognition, natural language processing, and autonomous driving. At the same time, deep learning has gradually brought artificial intelligence into people's daily lives. Convolutional Neural Networks (CNN) is the most widely used technology in deep learning. It mainly learns the inherent laws and feature information of samples from data sets to achieve the purpose of recognizing data such as images and text. CNN model training is a process of gradual learning and parameter adjustment. The more parameters that can be adjusted, the greater the degree of freedom that the network can adjust, and the better the final approximation effect. Therefore, with the demand for high accuracy of CNN models in actual applications, the size and computational complexity of CNN models are also gradually increasing, which also brings huge challenges to the application deployment of CNN models.
[0140] The high-density computing of CNN requires hardware platform support. The architecture of traditional central processing unit (CPU) is not suitable for processing large-scale matrix operations, while advanced graphics processing unit (GPU) has high parallelism and is widely used in the training and reasoning of CNN models. However, GPU has the problems of high power consumption and low resource utilization, and its high performance also depends on large batches of input data. In the actual application scenarios of CNN models, most of the time, single frames are processed, and the computing resources on the deployment device are also relatively limited. Therefore, GPU is not suitable as a hardware acceleration platform in the application deployment of CNN models.
[0141] In order to solve the problems of insufficient computing power, high power consumption and limited storage space of CNN models on embedded devices, one idea is to start with the model itself. For resource-constrained computing platforms, some lightweight models are designed, such as SqueezeNet, MobileNet, Xception, etc., and then model compression methods such as quantization and pruning can be used to further reduce the model size and make it easier to deploy on embedded devices. Another idea is to use field programmable gate arrays (FPGA) and application specific integrated circuits (ASIC) to customize the hardware platform as a dedicated accelerator for CNN model reasoning. Although ASIC-based accelerators have achieved very impressive performance, compared with the rapid development of CNN algorithms, the design of AISC lacks flexibility and has a long development cycle. The configurable characteristics of FPGA can make the accelerator highly flexible through reconstruction. Therefore, FPGA-based dedicated accelerators have received widespread attention from industry and academia.
[0142] The computational execution of hardware accelerators requires a corresponding compilation software system to support the changing network structure. At the same time, due to the diversity of the hardware structure of CNN-specific accelerators, the current relatively general deep learning compilers cannot provide compilation support for all hardware platforms. Therefore, self-developed AI compilers are very important for the use and promotion of CNN-specific accelerators. Without the corresponding compilation software tool chain, the hardware cannot play its maximum effect. However, there is still relatively little research on deep learning compilers for CNN-specific accelerators (referred to as "dedicated deep learning compilers") in China, and CNN models still face many challenges in deployment.
[0143] First, with the rapid development of CNN algorithms, the network structure of CNN models has become more and more complex. For example, popular network models such as DenseNet and Inception have a large number of skip connection structures. This structure requires the combination and splicing of feature maps at different levels. However, CNN-specific accelerators are difficult to flexibly support these complex network models. Secondly, due to the gradual increase in the scale and depth of CNN network models, the weight parameters of CNN models are also larger. Many studies have reduced the model size through quantization. At the same time, fixed-point operations can also reduce resource overhead compared to floating-point operations. However, different models are suitable for different quantization methods. It is difficult for dedicated accelerators to support different quantization methods at the same time without changing the hardware structure. For example, there is offset calculation in asymmetric quantization, so the accelerator needs an additional offset calculation module. At the same time, different models are suitable for different quantization bit widths. The compiler needs to make full use of computing resources such as the digital signal processor (DSP) in the FPGA to support different quantization schemes. Finally, convolution calculation is a large-scale multi-layer loop operation. Due to the limited resources of the on-chip cache, it is impossible to store all the data. The input feature map and weights need to be divided into blocks and sent to the cache to complete the calculation of the entire CNN network in the accelerator. However, there is data reuse in each layer of the convolution calculation loop. Different block sizes and different loop execution orders will affect the data interaction between the accelerator and the external memory, resulting in different execution performance. Therefore, how to combine the hardware architecture to perform loop tiling and convolution loop reordering is an important problem that the compiler needs to solve.
[0144] In summary, in order to achieve efficient deployment of CNN models on embedded devices, this paper proposes an optimized design for the deep learning compiler for CNN dedicated accelerators, and implements and verifies it on the open source CNN dedicated accelerator - DnnWeaver, which ultimately enables the CNN dedicated accelerator to process CNN models more flexibly and efficiently. At present, there are not many related studies on dedicated deep learning compilers in China, so this paper has certain research significance for promoting the application and deployment of CNN models.
[0145] 1.2 Research Development and Current Status
[0146] 1.2.1 Deep Learning Accelerator
[0147] The development of deep learning compilers is closely related to the development of deep learning accelerators. Currently, the development of deep learning accelerators is mainly in two directions. One is to use traditional computing architecture to improve the acceleration performance of hardware, such as GPU, AISC, FPGA, etc. In 2009, Clement Farabet and others tried to implement convolution computing functions on FPGA by using digital signal processors, and successfully applied a simple face detection model. In 2014, the DianNao neural network processor proposed by the domestic team Cambrian used a variety of deep learning acceleration algorithms, and achieved an effect that was dozens of times faster than the GPU at the time by optimizing numerical and storage modules, and also opened the precedent for deep learning neural network dedicated processors. In 2016, Google released an artificial intelligence chip TPU that uses a pulsating array computing core to accelerate matrix multiplication and convolution. It mainly serves the Tensorflow model. The first generation can only be used for reasoning, and the second generation adds the function of neural network model training. In the same year, domestic Deephi Technology also proposed DNNDK, a deep learning development framework based on XILINX FPGA chips, which greatly shortened the deployment cycle of deep models to hardware. At the same time, Yu-Hsin Chen and others designed a reconfigurable deep learning accelerator Eyeriss to address the problem of large amounts of data moving between cache and memory, mainly through row fixation (Row In 2018, the Thinker team of Tsinghua University launched a reconfigurable accelerator, which is a CGRA (Coarse Grained Reconfigurable Array) structure in the form of a pulsating array. By dynamically configuring the core computing units of the accelerator at the instruction level, it can support the operations of most deep learning models without changing the hardware.
[0148] Another development direction of accelerators is to subvert the traditional von Neumann architecture and adopt neuromorphic architecture to design brain-like neural structures to enhance computing power, represented by IBM's TrueNorth chip, but currently it can only recognize relatively simple data sets.
[0149] 1.2.2 Deep Learning Compiler
[0150] In the early days, the deployment of deep learning models could only achieve the effect of optimizing calculations with the help of third-party libraries (such as NVIDIA's matrix operation library cuBLAS and Intel's computing library MKL). However, as more and more new operators are proposed, the workload of developing and maintaining operator libraries is also increasing, which has led to the emergence of deep learning compilers. At present, the development of deep learning compilers is not mature, and the more well-known ones at this stage are Intel's nGraph, TVM, Facebook's Glow, TensorComprehension and Google's XLA.
[0151] XLA is a high-performance machine learning compiler launched by Google. It is used to compile models designed by Tensorflow, thereby solving the problem of insufficient computing performance caused by Tensorflow's design that only considers flexibility and scalability. XLA optimizes the computational graph represented by HLO IR regardless of the deployment platform, and optimizes it again based on the hardware architecture at the back end, and then converts the optimized HLO IR into a lower-level LLVM IR and generates machine code. At the same time, Google has also launched an intermediate expression form MLIR to improve the conversion efficiency and portability between various IRs. nGraph can simplify the deployment process across frameworks and hardware platforms, separate the framework defined by the model from the calculation, convert it into a framework-independent intermediate representation nGraph IR, and then further convert them into a form that can be executed on the hardware back end. Glow and XLA are similar in that they both abstract each Node in the computational graph into a series of simple linear algebra primitives to achieve acceleration. TVM is an end-to-end stack that can deploy deep learning workloads to hardware. It inherits the Halide architecture of separation of computing and scheduling, which is similar to Tensor Comprehension. The difference is that TVM's scheduling is manually specified by the user through instructions, while Tensor Comprehension describes the calculation in a domain-specific language (DSL) and then completely leaves it to the subsequent compiler to achieve automatic conversion of scheduling.
[0152] Due to limited computing resources, deep learning compilers also need to quantize models. TensorComprehension does not support quantization of models, while nGraph, Glow, XLA, and TVM can all implement INT8 quantization of models, but they cannot support multiple quantization methods (TVM can support non-fixed-point FP16 quantization on general hardware platforms). For the model quantization deployment of dedicated CNN accelerators, Zhang Fangfang used fixed INT16 symmetric quantization in the dedicated deep learning compiler she designed due to the limitations of the hardware structure. It only quantized the feasibility of the model in hardware deployment and did not consider whether the accuracy or compression rate of the model after quantization was applicable. Wang Zhuo used INT8 asymmetric quantization in his research on model compression on artificial intelligence chips. The activation function of his model was ReLU6, so the input data was represented by UINT8 to avoid the processing of asymmetric quantization zero-point offset, but this method requires limiting the activation function to control the distribution of input data.
[0153] Chen Zhang et al. proposed an analysis and design method using the Roo-fline model in their 2015 paper. They can use various optimization techniques to quantitatively analyze the memory bandwidth and computational throughput required for CNN design solutions. Then, with the help of the Roo-fline model, they can determine the solution with the lowest FPGA resource requirements and the best performance, and find the optimal block size for each layer in the search space, but they did not explore the execution order of the convolution loop. Chi Haoyu used the original feature data as input and the execution time as output to establish a scale-specific matrix multiplication execution time prediction model, and on this basis, he built a prediction model for the optimal block size. However, this prediction model is only for artificial neural networks and cannot be applied to convolutional neural networks with multiple layers of nested loops.
[0154] 2 Design Architecture and Optimization Problem Analysis of Dedicated Deep Learning Compiler
[0155] As deep learning applications gradually develop from the cloud to the edge, how to efficiently deploy deep learning models on embedded devices integrated with dedicated CNN accelerators has become a research hotspot. At present, there are still many challenges in deploying CNN models on resource-constrained accelerator platforms. At the same time, there is relatively little research on deep learning compilers for CNN dedicated accelerators in China. This paper takes the optimization of CNN model deployment on dedicated CNN accelerators as the starting point and proposes an optimized design for deep learning compilers for CNN dedicated accelerators.
[0156] 2.1 Basic Design Architecture of Dedicated Deep Learning Compiler
[0157] The work of the deep learning compiler is to generate the instructions or codes required for the hardware platform to execute the deep learning model through various optimization techniques. This paper uses a dedicated deep learning compiler architecture based on FPGA accelerator. Figure 1 As shown. Figure 1 It can be seen that the deployment of CNN models from the top to the accelerator hardware is a multi-level compilation process, which is mainly divided into three stages: front-end, middle optimizer and back-end. The model has different forms at each level. The front-end is mainly in the form of a model framework, such as the mainstream Tensorflow, PyTorch and Caffe, etc.; the middle layer mainly exists in the form of a custom calculation graph generated by the front-end analysis; and the back-end is an optimized calculation graph, which mainly performs optimization related to the hardware structure and generates instructions required for the accelerator to run. This three-stage structure is currently the most common deep learning compiler design method. The main designs of these three levels are explained below.
[0158] 2.1.1 Compiler front end
[0159] The front end of the deep learning compiler mainly plays the role of a parser, whose main task is to load, parse and convert the model into the computational graph. Compared with the traditional compiler, the parser is equivalent to the syntax analyzer, which is used to convert the text input of the program into the "abstract syntax tree" data format set by the compiler, and then further optimize it. The deep learning compiler belongs to the category of special fields, and the input object for parsing is a pre-defined model file. Due to the diversity of top-level model frameworks, most of the current compiler designs will convert the model file into a unified deep learning model standard representation format - ONNX in advance, and then send it to the parser for parsing, and finally generate a custom intermediate expression IR. At present, the mainstream model frameworks have different degrees of support for ONNX, which also facilitates the migration of algorithm models between different frameworks and the design of model parser interfaces.
[0160] In the design of the compiler in this paper, there are three data structures in the intermediate representation IR: Graph, Node, and Tensor. Graph is an abstract computational graph, which consists of a node list, a tensor list, and other attribute fields. Each node in the node list represents an operator operation, and each tensor in the tensor list is a storage and transmission medium for feature data and weight data. The topological relationship between nodes and tensors constitutes the network structure of the complete model. The topological relationship is as follows: Figure 2 As shown below, the properties of Node and Tensor in the compiler are introduced in detail.
[0161] ①Node
[0162] In the computational graph, the Node data structure can represent all nodes in the computational graph. Compared with Tensor, Node has more types, such as convolution, pooling, etc. Therefore, Node is abstracted as a base class with common attributes such as name, input Tensor list, output Tensor list and some other abstract method functions. Specific operator nodes are derived from the Node base class, and there are order and topological relationships between nodes. The order relationship indicates the execution order between nodes, and the execution order is determined by the storage order in the node list of the Graph; the topological relationship indicates that the node uses the values defined in other nodes.
[0163] Since most nodes in the convolutional neural network calculation graph represent convolution operators, the following mainly introduces some properties of the convolution operator:
[0164] 1) data: the feature map input data of convolution calculation, of type Tensor.
[0165] 2)weights, the weight data of the convolution calculation, of type Tensor. An exception judgment mechanism is set up inside the convolution operator. If the number of channels of data is not equal to the number of channels of a single convolution kernel of weights, an exception is thrown.
[0166] 3) bias, the bias data of convolution calculation, is of type Tensor. Similarly, an exception judgment mechanism is set to detect whether the number of convolution kernels is equal to the length of bias.
[0167] 4) stride, the step size of the convolution. The four data correspond to the step size of the input Tensor in the four directions of the data layout NHWC. Generally, the stride is . If the convolution step size is 2, the stride is .
[0168] 5) pad, the padding of the input feature map required for convolution calculation, the value is determined by the shape of weights and the padding type. If it is a 3*3 convolution and the "same" padding type, pad is [[0, 0], [1, 1], [1, 1], [0, 0]].
[0169] In a dedicated convolutional neural network accelerator, there is generally no dedicated computing unit for processing the fully connected layer. The compiler will convert it into the corresponding convolution operation when parsing the model. The computing operation of the fully connected layer is actually a convolution calculation where the size of the input feature map is consistent with the size of a single convolution kernel. The result calculated by each convolution kernel corresponds to a neuron output by the fully connected layer. Therefore, a "1x1" convolution operation is usually used to replace the fully connected layer, such as Figure 3The input neuron length shown is equivalent to the number of channels of the convolution input, while the output neuron length is the number of convolution kernels.
[0170] ②Tenor
[0171] In the computational graph, tensors are not only used as a medium for data storage, but also responsible for connecting various operators to form a complete computational graph. Tensors store multidimensional data, which is abstracted as the Tensor class in the compiler. In addition to the more intuitive data attributes, Tensors also extend several necessary attributes, including:
[0172] 1) dtype, which indicates the quantized data type. There are four main enumeration types: INT8, INT16, INT32, and INT64. INT32 and INT64 are mostly used to represent intermediate calculation results. They play a transitional role and are not actually stored in memory.
[0173] 2) shape, data layout in memory.
[0174] 3) pad, which indicates the dimension in which the data needs to be padded, usually due to the need for convolution calculations.
[0175] 4)address: the first address of the tensor stored in the hardware memory. Due to the existence of pad, the first address does not point to the actual valid data. For the accelerator, the shape of the tensor is shape+pad.
[0176] 5) add_vilid, determines whether memory space needs to be allocated to the tensor.
[0177] 6) scale and zero_point, the scaling factor and offset generated by the quantization of the tensor data.
[0178] 7) output_nodes, the list of nodes to which the tensor flows. A tensor may flow to multiple computing nodes. This attribute determines the topological structure of the entire computational graph.
[0179] In addition, the Tensor class also defines some methods that can quickly obtain tensor information, such as calculating the shape after filling, the byte size occupied by the entire Tensor (filled or unfilled), and so on.
[0180] 2.1.2 Compiler Intermediate Optimizer
[0181] The compiler's intermediate optimization is to optimize the computational graph independently of the hardware structure, reducing the spatial complexity and computational complexity of the model without affecting the computational results, thereby reducing the inference time of the model on the accelerator. The intermediate layer graph optimization strategy is mainly divided into layer-level optimization, tensor-level optimization, and element-level optimization according to the granularity.
[0182] Hierarchical optimization is to simplify the model network structure from the operator level. Common examples include operator fusion such as Conv+Relu and constant folding with fixed calculation results (using constants to replace calculation expressions). The following is a detailed introduction to the bn (Batch Normalization) fusion and operator fusion methods implemented by the compiler in this article:
[0183] ①Bn fusion
[0184] In deep learning, the convolution operator is usually followed by a BN operation to solve problems such as gradient disappearance during training. The general optimization strategy is to transform the BN calculation into the form of scale*data+shift during the inference phase. Since the convolution calculation and the BN operation are both linear transformations, the two can be fused during the inference phase, that is, the relevant parameters of the BN calculation are integrated into the convolution calculation to generate a new convolution. However, this has no effect on the structure of the convolution itself, but only changes the weight data therein. Ultimately, the acceleration effect is achieved by deleting the BN calculation node. The fusion rules are as follows:
[0185] X 1 =W conv X 0 +b conv #(3.1)
[0186]
[0187]
[0188] The input of the convolutional layer is X 0 , the output of the convolutional layer or the input of the BN layer is X 1 , the output of the bn layer is X 2 ; The weight and bias of the convolution are W conv and b conv , the parameters learned by the BN layer are mean μ, variance σ 2 , expansion parameter γ and translation parameter β, ∈ are fixed values to prevent a very small number from dividing by 0. Finally, the new convolution weights are formed after BN fusion. and bias These parameters are known in the inference phase, so they can be calculated in the compilation phase.
[0189] ② Operator fusion
[0190] Operator fusion is to put multiple computing operations in one core processing unit to avoid the movement of intermediate computing results between memory and cache, thereby reducing the accelerator's access to memory. It can also reduce the memory storage overhead of intermediate results at runtime and improve the computing efficiency of the model in the accelerator. Figure 4 As shown in the figure, the result of convolution and activation function can be used to continue to perform activation function calculation in the core processing unit without storing the convolution result back and reading it for calculation. In the operator sequence list of the calculation graph Graph, Conv is the main body of operator fusion (except convolution, other operators are basically element-by-element calculation), and other operators between adjacent Conv are combined into pu_ops and fused into the front Conv operator to form a new fusion node Marco Node. In the accelerator, a Marco Node corresponds to a complete convolution operation: first, the convolution calculation is performed in the pulsation array and the result is saved in the output cache, and then the output cache sends the intermediate result to the ALU to perform the linear calculation in pu_ops, and finally the ALU writes the result back to the external memory. In the Marco Node after operator fusion, only the Tensor finally written back by the ALU and the convolution-related input (in most cases, the input is the Tensor written back by the previous Marco Node), weights, and biases require actual external storage space to save data. Therefore, after the operator fusion, the add_vilid corresponding to these Tensors will be set to True for the backend to allocate actual memory space, and the add_vilid of the remaining related Tensors will all be set to False.
[0191] Tensor-level optimization mainly changes the storage of tensors in memory to facilitate accelerator calculations. Common optimization methods include tensor data layout conversion and branch convolution merging of the same input. The storage format of feature maps and weights after data layout conversion of the compiler in this paper is shown in formula (2.5). Branch convolution merging is as follows Figure 5 As shown in the figure, both the 3*3 convolution and the 1*1 convolution use the same input feature map. The 1*1 convolution kernel is padded with zeros to become 3*3 and merged with another 3*3 convolution kernel into a larger convolution kernel. Therefore, two input feature maps can be obtained in one convolution operation. Although the total amount of calculation is increased due to the padding of the convolution kernel, the memory repeated access overhead of the input feature map is reduced. Whether the performance can be improved depends on the specific hardware. If the convolution kernels are of the same size, the acceleration effect can be achieved in most cases.
[0192] Element-level optimization mainly starts from the data itself. The most commonly used method is model quantization, which reduces the amount of data storage and model calculation by narrowing the data bit width.
[0193] 2.1.3 Compiler Backend
[0194] At the back end of the deep learning compiler, the optimized IR is received for platform-specific optimization and hardware instruction generation for specific hardware. One method of back-end optimization is to convert the computational graph representation IR into LLVM IR to generate optimized CPU / GPU code using LLVM's infrastructure, while another method is to use deep learning domain knowledge to design custom optimizations to more effectively utilize the target hardware.
[0195] Since the CNN processor based on this paper is a dedicated accelerator (FPGA), the main work of the compiler backend is to map the relevant calculations in the optimized calculation graph to the various modules of the accelerator, and finally output the instruction sequence required for the accelerator to execute. The following is a detailed introduction to the work done in the backend based on the accelerator hardware structure in the compiler designed in this paper:
[0196] ①Memory allocation management
[0197] The compiler needs to allocate memory space to tensors based on the structure of the computational graph to facilitate the accelerator to read and write computational data. At the same time, memory management is also required to prevent address conflicts between tensors and data overwriting. At the same time, not all tensors need to be allocated memory space. For example, the intermediate results temporarily stored in the cache after operator fusion will not be written back to the memory. Allocating them will cause a waste of memory resources. The memory allocation process is as follows: Figure 6 As shown in the figure, after the middle layer optimization of the calculation graph, first initialize the starting address P of the actual external memory reserved for the accelerator space size, then traverse the Tensor list in the calculation graph Graph, and only allocate the actual memory size to the tensor whose add_vilid attribute is True. Each time the allocation is made, it is only necessary to point the address pointer P of the current memory space to the starting address of the tensor, and then superimpose and update the address pointer P according to the tensor size. The size of the allocated memory space is maintained by the size of the tensor itself, and finally repeat this operation to complete the memory allocation work for the tensors in the entire calculation graph.
[0198] Since convolution calculation involves padding of input, the memory space allocated to the tensor is not based on the actual shape attribute, but on the size (T) calculated by shape + pad. The data in the padding space is filled with 0 or asymmetric quantization zero offset depending on whether the quantization is symmetric. Therefore, the accelerator will initialize the memory space of each Tensor before running, and the initialized value is the padding value, such as Figure 7 As shown, when the calculation result data is written back, the actual first address written should be the first address when the memory is allocated plus the offset of the pad. The calculation formula for the address offset (data layout is NHWC) is:
[0199] (C+pad[-1][0]+pad[-1][1])*(W+2×pad[-2][0]+pad[2][1])#(3.4)
[0200] Among them, pad[-1][0] and pad[-1][1] represent the front and back padding numbers in the C direction, pad[-2][0] and pad[2][1] represent the left and right padding numbers in the W direction, and the numbers in pad are the subscripts of the array. When all the calculation results are written back to the offset address, the entire tensor is ready, and then when reading, the padded tensor data can be automatically read according to the first address when the tensor is allocated memory.
[0201] ②Computational logic management
[0202] Computational logic management is to generate related instruction sequences based on the instruction set architecture of the accelerator to complete convolution and other linear calculations. Convolution calculation is a 6-layer nested loop (7 layers if batches are added, but in the actual application of CNN models, the batch is generally 1), as shown in code 3.1. The 6 layers of loops are the width OW and height OH of the output feature map, the number of input channels IC, the number of convolution kernels OC, and the width KW and height KH of the convolution kernel. Because the on-chip cache of the accelerator is limited, the convolution needs to be loop-tiled. Usually, the width and height of the convolution kernel are relatively small (basically between 3 and 11, and sometimes 1), so there is no need to do loop tiling. The four loops OW, OH, IC, and OC really need to be tiled. The operation of loop tiling is to set the step size of each loop to be greater than 1. The step size of each loop forms a new nested inner loop to complete the actual calculation operation, and the main work of the outer loop is to complete the addressing function of each block after loop tiling, and then read a block of data into the cache. The specific division is shown in code 3.2.
[0203] Code 3.1 Pseudocode for convolution calculation 6 layers
[0204]
[0205] Code 3.2 Pseudocode for loop tiling calculation
[0206]
[0207]
[0208] Therefore, the complete convolution calculation in the accelerator is mainly divided into three loops:
[0209] 1) Outer loop. The number of loops of the outer loop determines the number of divided blocks. At the same time, the main work of the outer loop is to complete the addressing function of each block, and then read a block size of data into the cache, such as Figure 8The output feature map is divided as shown, and the addressing is to calculate the offset length from the first address of block 1 to the first address of block 2 in the example in the figure.
[0210] 2) Memory access loop. After the first address of the current block is determined by the outer loop, the corresponding data is read from the external memory according to the size of the divided block (the divided tensor blocks are also high-dimensional data and require nested loops to read).
[0211] 3) Inner loop. After the data of a tile block is sent to the respective cache through the memory access loop, the inner loop controls the cache to send the data to the computing module for convolution calculation. Therefore, the data flows from the external memory to the cache, and then to the systolic array computing unit. As shown in Code 3.2, the outer loop of the final convolution calculation is a 4-fold nested loop, while the inner loop that executes the calculation task is a 6-fold nested loop.
[0212] According to the principle of convolution loop tiling, relevant instructions can be generated for each Marco Node. Marco Node is a newly defined operator node after operator fusion. The instruction generation process is as follows: Fig. 9 As shown. The accelerator is mainly divided into two computing modules:
[0213] 1) Pulsating array convolution calculation. First, generate the convSatrtIns instruction to tell the accelerator to perform convolution calculations, and then use the baseAddrIns instruction to specify the base address of the input cache, weight cache, and bias cache for data reading in the external storage. Next is the outer loop related instructions, which are composed of loopIns instructions and strideIns. The same is true for memory access loops and inner loops. Each type of loop is formed by multiple loopIns instructions to form a nested loop. As shown in Code 3.2, there are 4 loopIns instructions in the outer loop, 3 loopIns instructions for each cache in the memory access loop, and 6 loopIns instructions in the inner loop. Under each loopIns instruction, 1 or 2 strideIns instructions are also generated. The strideIns instruction indicates the offset of each data address in each loop. For example, a feature map with a shape of (N, H, W, C) is accessed using a four-layer loop. The loop lengths are N, H, W, and C respectively, and the address offset step corresponding to each loop is (H*W*C, W*C, C, 1). There is actually a nested relationship between the three loop types. Each time the outer loop is executed, all operations of the memory access loop and the inner loop must be completed. Therefore, the outer loop belongs to the upper layer, while the memory access loop and the inner loop are at the same level.
[0214] 2) ALU linear calculation. The intermediate results of the convolution calculation will be saved in the output cache. When the intermediate results are accumulated, they will be sent to the ALU model for linear calculation. The compiler first generates an aluStartIns instruction to inform the accelerator that the subsequent instructions are ALU-related instructions, and then configures the base address of the output tensor (how to calculate the first address of the tensor write back has been described in the memory allocation management section). The loop instruction first traverses the output cache loop to obtain the calculation results in the output cache, and then generates an output write-back outer loop, which also serves the function of addressing the output feature map blocks. Finally, the write-back loop writes the actual data back. Each written-back data must first undergo the related linear calculation configured by the comIns type instruction. For example, the LeakyRelu or Relu-related instructions are a mul instruction and a max instruction (LeakyRelu multiplied by 0.1, Relu multiplied by 0, and then compared with the original number to find the maximum value). If it is a pooling operator, two sets of pooling length loops will be added before traversing the output cache loop, and the corresponding address offsets will also change. At the same time, a counter will be added. For example, 2*2 maximum pooling will write back the value in the register after traversing the output cache loop for 4 times (the register will update the maximum value each time). In the case of pooling operations, the block size in the output cache is not equal to the actual block size written back. This is because the data block in the cache is the block size of the convolution calculation result, and the data block written back by the ALU is the block size of the last linear calculation output after the operator fusion. For the upsampling operator, in contrast to pooling, two sets of upsampling length loops are added before the write-back loop (the accelerator currently only supports 2*2 upsampling).
[0215] Finally, the compiler completes the compilation of the entire network model by generating instructions for all Macro Nodes. The accelerator writes the instructions and quantized weights into the memory for initialization, and then sends the detection image to the specified address space to start the accelerator's operation.
[0216] 2.2 Analysis of optimization design problems
[0217] At present, there is relatively little research on dedicated deep learning compilers in China (most of them are based on general GPU / CPU platforms). There are still many challenges in the deployment of CNN model applications. The following will analyze and discuss the further optimization of the compiler from three aspects.
[0218] 2.2.1 Supporting complex skip connection network structures
[0219] With the rapid development of CNN algorithms, researchers hope to solve the gradient vanishing problem caused by the deep number of network layers by using cross-layer skip connection feature maps, thus generating many complex network structures. Fig.10The figure shows the jump connection of DenseNet, which is formed by connecting the feature maps of different layers in series through the concat operator, where the same feature map may be jump-connected to multiple feature maps. Compared with computationally intensive operators such as convolution, concat is memory-intensive. In order to realize cross-layer connection of feature maps in the accelerator, the accelerator needs to re-read the previous calculation results into the cache or keep them in the cache, but these designs are very complicated for dedicated accelerators.
[0220] If the data of each sub-feature map is still continuous in the memory space after splicing, then you only need to put each sub-feature map in the appropriate position to directly access the data of the sub-feature map and the total feature map, such as the branch convolution merging in Section 2.1.2. At present, many accelerators are based on NCHW data layout. The splicing in the channel C direction makes each tensor in the memory still continuous, so it is easy to split the output in the figure into output1 and output2. However, due to different data layouts, the data of the sub-feature map may be stored discontinuously in the memory, and the same feature map may have multiple unrelated feature maps for jump connections, such as Fig.10 Each ReLU output has some of the same feature maps that are interconnected. It is more difficult for the accelerator to handle this structural logic, and a compiler is needed to support this complex network structure.
[0221] 2.2.2 Flexible support for different quantization methods
[0222] For models deployed on dedicated accelerator hardware, they need to be quantized into fixed-point integers. Quantization is divided into symmetric quantization and asymmetric quantization. From the quantization formula (2.1) and formula (2.2), we can see that the difference between these two methods is that asymmetric quantization requires processing of the offset Z, and correspondingly, there must be a related processing module in the accelerator hardware. Fig.11In the PE multiplication and addition calculation unit shown, the symmetric quantized input and weight can directly enter the PE unit, while the asymmetric quantization needs to pass through the offset processing unit before entering. Therefore, under the fixed hardware structure of the accelerator, this is not friendly to the quantization of the model. At the same time, the accelerator generally adopts the form of symmetric quantization for the sake of design simplicity. However, if the distribution of data is very asymmetric, it will cause the accuracy loss of the model quantization to be particularly serious, especially after the convolution calculation, there will be an activation function, and the nonlinear operation of the activation function will inevitably cause the data distribution of the output feature map to be very different. For example, after the activation function leakyReLU, the distribution range of the eigenvalues on the positive and negative semi-axis can differ by about 10 times. Of course, there are also related studies that have considered using the activation function Relu to limit the output data to non-negative, so that the data can be represented by unsigned numbers, and the offset Z will be taken as 0, but this requires a fixed activation function to limit the range. At the same time, there is generally no activation function at the end of the model output to constrain the data range, and it is also necessary to handle the situation where both positive and negative data are present.
[0223] In addition, the quantization method can be further divided based on the bit width length, such as the commonly used INT8 quantization and INT16 quantization. Compared with low-bit width quantization, high-bit width quantization has a smaller loss of computational accuracy, while low-bit width quantization has a lower computational complexity. There is no absolute advantage or disadvantage between these two methods. However, when the hardware is fixed, the quantization bit width of the model is also fixed, and the model cannot choose the appropriate quantization bit width according to the distribution of its own data. At the same time, in the systolic array, each PE module is formed by a DSP unit. The DSP performs a multiplication and addition operation of the entire reserved bit width of the input, while the low-bit width quantization data only occupies a small part of the reserved bit width in the DSP, and cannot fully utilize the DSP's computing resources. For example, the DSP48E2 can achieve a maximum of 18*27 multiplications, but the calculation time is the same regardless of whether the input is 16 bits or 8 bits. At the same time, the fixed number of PEs means that the amount of calculation of the accelerator core module remains unchanged each time. Therefore, low-bit-width quantization does not reduce the number of calculations in the convolution. Due to the limitation of the number of DSPs on the hardware, low-bit-width quantization cannot reflect the acceleration effect compared to high-bit-width. Therefore, it is necessary to utilize the remaining reserved bit width in the DSP to achieve faster acceleration.
[0224] 2.2.3 Optimizing loop tiling and loop rearrangement
[0225] As the size of CNN models increases, limited on-chip resources make it impossible for the cache to store all feature maps and weight data. Therefore, the feature maps and weights need to be divided into blocks to complete the calculation of the entire network on the accelerator, that is, the convolution loop calculation needs to be looped. Each time the accelerator loads a block of data from the memory to the on-chip cache, the cache then enters the computing unit for calculation. The flow of data is as follows: Fig.12If the block size of the feature map and weight is too large, the cache may not be able to accommodate it and errors may occur; if the block size is too small, the cache utilization rate will be very low, resulting in frequent data changes between the cache and the memory, and the final time consumption will be very long.
[0226] At the same time, the input feature map and weights correspond to different caches, and the hits of each cache are not synchronized. This is related to the characteristics of the convolution calculation itself. The relationship between the loop type and the cache hit is shown in Table 3.1. True indicates a data hit, and False indicates a miss. Because the input and weight of the convolution have data reuse, the same block of input data will be calculated with different convolution kernels to generate different data on the output feature map channel, and the same block of weight data will be calculated with different inputs to generate different data on the output feature map plane. Therefore, it is necessary to optimize the loop tiling and loop rearrangement in the convolution operation according to the hardware structure to improve the performance of the accelerator.
[0227] Table 3.1 Relationship between loop type and cache data replacement
[0228] Input_buffer Weight_buffer Output_buffer Bias_buffer OW True False True False OH True False True False IC True True False False OC False True True True KW True True False False KH True True False False
[0229] 2.3 Summary
[0230] By describing the basic design architecture of a dedicated deep learning compiler and analyzing some existing challenges, this paper proposes further optimized designs of a dedicated deep learning compiler from three aspects: supporting complex skip connection network structures, flexibly supporting different quantization methods, and optimizing loop tiling and loop rearrangement. Through the above analysis, the research content and objectives of this paper are more clearly defined, laying the foundation for further optimization design.
[0231] 3 Optimization design and implementation of a dedicated deep learning compiler
[0232] With the popularity of deep learning applications, CNN dedicated accelerators have been gradually integrated on embedded devices, and how to efficiently deploy neural network models in such embedded environments has become a research hotspot. Deep learning compilation can quickly map models to deep learning accelerators, but there is still relatively little research in this area. The deployment of convolutional neural network models still faces many challenges. In the previous chapter, the goals of further optimizing the compiler design have been clarified: first, supporting complex skip connection network structures; second, flexibly supporting different quantization methods through the compiler under a fixed hardware structure; third, optimizing loop tiling and loop reordering to improve accelerator performance. Based on solving the above problems, some optimization designs for dedicated deep learning compilers are proposed to improve the efficiency and flexibility of model deployment. Relevant experiments are designed in Sections 3.2 and 3.3 to test the optimized performance, and the overall functional test of the optimized compiler will be described in the next chapter through the simulation platform.
[0233] 3.1 Processing of skip connection network structure based on memory sharing
[0234] The reason why the structures of many convolutional neural networks are complex is that there are a large number of jump connection structures, which are mainly various combinations of feature map splicing operators. It is difficult to handle this structure through hardware design. This type of operator should be simplified by the compiler during the compilation process to generate a solution that adapts to the accelerator hardware structure.
[0235] 3.1.1 Memory Sharing
[0236] For operators such as concat or split, there is no calculation operation involving related data, and the input feature map and the output feature map will have overlapping data content. This overlapping data should be shared by the related feature maps involved instead of letting each feature map have an independent memory. The total memory space size is maintained by the feature map with the largest size, that is, the concat operator and the split operator apply for memory space from the output feature map and the input feature map respectively. Each sub-feature map in the total memory does not need to apply for additional memory space, and only needs to maintain a first address in the shared area. This does not violate the first address superposition described in Section 2.1.3, because the sub-feature maps will not overwrite each other's data. At the same time, the total feature map only has read operations and will not rewrite the data content in the sub-feature map (split is the opposite).
[0237] Different data layouts and different splicing dimensions will lead to different arrangements of various feature maps in memory. For example, in the data layout of NCHW and the concat operator that often splices in the C direction, each sub-feature map stores data continuously in its own memory, which is easy for the accelerator to read. However, for the data layout of NHWC, each feature map is stored discontinuously in memory. Fig.13 As shown, the data layout is that the three feature maps A, B, and C of NHWC are spliced through channels to form feature map D. The memory size allocation of the entire space is determined by the size of feature map D. A, B, and C get their own first addresses based on the order of splicing and the first address of D. Since the memory space is discontinuous, the compiler needs to address it through a special addressing method.
[0238] 3.1.2 Shared area division and addressing
[0239] The feature maps that participate in data splicing or splitting are divided into a splicing area - a shared area (if not participating, it is a separate shared area), and the memory space size of this area is calculated according to the size of the feature map with the largest number of channels. As shown in 4.2, the six feature maps are divided into three shared areas, namely: {A}, {B, C, D} and {E, F}, and the feature maps A, D and E determine the memory size allocation. In the {B, C, D} area, D first applies for a piece of memory size, and B and C each occupy their own part of the non-contiguous memory (because B and C are sub-feature maps in the entire shared area, the distribution only occupies a part of the memory of the entire space). When B and C have completed the convolution operation, the part of the memory corresponding to D has been written with the data as the next convolution input, and the accelerator can directly perform the convolution calculation. Therefore, the accelerator does not need to call memory for operations such as concatenation or splitting operations. The compiler deletes the concatenation or splitting operators from the calculation graph after addressing. The accelerator only calculates each convolution operation in the Marco Node in sequence. Therefore, as long as the offset relationship between addresses is managed well, any branch structure of this type can be processed. The following introduces the compiler's address offset in continuous memory and non-continuous memory respectively:
[0240] ① Continuous memory
[0241] This situation does not involve shared memory or C-direction splicing under the NCHW data layout described in the previous section. Assume that the data layout of the feature map is NHWC, which is a shared area with a shape and size of:
[0242] shape = (1, h, w, c) # (4.1)
[0243] The reading of each data needs to be split into 4 nested loops (actually 3, the first dimension is 1 in the model inference stage) according to the shape to control. When running the innermost c loop, the address offset of each data is 1; when running the second innermost w loop, the address offset is c; and when running the outermost h loop, the address offset is c*w, so the loop offset list stride is defined list =shape. The address offset calculation formula of each loop of the compiler is:
[0244] stride i =∏stride list [i+1:]*per Bytes #(4.2)
[0245] Where i represents the number of dimensions of the loop, per Bytes Indicates how many bytes each data occupies in memory, stride i Indicates the address offset in memory corresponding to the loop of the i-th dimension. If the tensor is divided into blocks, the stride list It should be equal to the size of the complete tensor, and the loop is still executed according to the size of the block, that is, the number of loops is not always consistent with the address offset length.
[0246] ② Non-contiguous memory
[0247] exist Fig.13 In the memory distribution shown, the data of each feature map is not stored continuously in the memory. In order to obtain all the data of each sub-feature map, an attribute is added to the Tensor in the calculation graph - Concat_Channel (abbreviated as cc), which indicates the total number of channels involved in concatenating the remaining feature maps in the shared area to which the feature map belongs (0 indicates a single shared area). Therefore, for the feature map of the shape and size shown in formula (4.1), its address loop offset list is:
[0248] stride list =(1,h,w,cc+c)#(4.3)
[0249] The offset of each loop address is still calculated using formula (4.2). In this case, shape and stride listThe difference is that one is the channel c of the feature map itself, and the other is the total channel cc+c of the shared area. cc also means that every c consecutive data of the feature map in the memory will be separated by cc data, and the number of loops to access the data is still represented by shape, so that the data in the non-continuous memory can be accessed. For the splicing of other dimensions or other data layouts, the corresponding Concat_Weight and Concat_Height attributes can also be added. Therefore, the compiler only needs to divide the shared area to allocate the first address and add an additional attribute to the Tensor. The address offset instruction can be used to handle the situation where the data is not continuous in the memory. The address offset calculation of the read operation and the write operation is the same.
[0250] 3.1.3 Feature map deep copy and operator exchange order
[0251] If a feature map is concatenated with multiple unrelated feature maps, that is, a feature map may belong to two different shared areas at the same time, such as Fig.15 As shown on the left, there are two shared areas: {A, B, D} and {A, C, E}. These two areas have an overlapping feature map A. Therefore, when setting the first address for feature map A, the compiler does not know whether to find the first address of A based on feature map D or feature map E. Therefore, as shown on the right side of 4.3, a deep copy operator - Copy is added to deeply copy feature map A into feature maps A′ and A″. At this time, the shared areas become {A′, B, D} and {A″, C, E}, and the Copy operator will also participate in operator fusion. The processing of the Copy operator is to pass the convolution output corresponding to A (feature map A has no actual memory) through the ALU module and store it in the feature map A′ and feature map A″ respectively. Because the data of the two are consistent and do not require additional calculation, A writes the results back to the two addresses of A′ and A″ after the ALU module completes the calculation, that is, Fig. 9 The ALU module instruction generation only requires one more instruction to set the output base address and one more address offset instruction in each write-back cycle (the offset is calculated by the shared area to which A′ and A″ belong respectively).
[0252] The concatenation operator is implemented by the compiler through shared memory and addressing, and no additional corresponding computing modules are required in the hardware structure. If the output of the concatenation operator in the computation graph flows as input to the pool or other linear computing operators, such as activation functions, the computation graph structure needs to be transformed accordingly. For example Fig.16The residual structure in the yolov4tiny network shown in the figure has a maximum pooling operation after the second splicing operator. The maximum pooling or other linear calculation operators directly calculate the convolution results in the output buffer, while the processing of the splicing operator is aimed at the address logic of the data in the external memory. In order to achieve consistency between the two, the maximum pooling or other linear calculation operators are moved forward and exchanged with the splicing operator. Only splicing or splitting operations in the C direction of the feature map channel are supported here, because operators such as pooling and activation are operations on the feature map plane, and each channel is independent of each other, and the exchange order will not affect the calculation results of the entire network. In addition, the order of Maxpool and activation functions can be exchanged, because Maxpool in the front can reduce the number of activation calculations.
[0253] Memory sharing and addressing can be used to stitch together multiple feature maps. Deep copying of feature maps to divide the memory sharing area can further simplify the complex skip connection structure. At the same time, the order of some operators in the calculation graph needs to be exchanged to match the hardware structure of the accelerator. The above design can basically support most complex network models with skip connection structures.
[0254] 3.2 Quantization scheme of convolutional neural network model
[0255] Model quantization based on general platform processors usually does not consider the processing of bias, because the bias is an addition calculation and the quantized bias does not improve performance, so the bias is still processed with floating point numbers and there are quantization and dequantization operations in the calculation process. However, floating point calculations are relatively complex on FPGA architectures. At the same time, quantization is divided into symmetric quantization and asymmetric quantization. Asymmetric quantization also needs to consider the processing of offsets during the calculation process. For the processor, additional addition and subtraction modules are required to calculate the offset. Therefore, the deployment of the model needs to consider the quantization and processing of the bias.
[0256] 3.2.1 Quantization Processing Based on Bias and Offset Fusion
[0257] According to the calculation principle of convolutional neural network and quantization formula (2.2), the quantization formula of convolution calculation process can be obtained as follows (here we take asymmetric quantization as an example):
[0258]
[0259] Where ∑ represents the convolution summation, q 1 ,q 2 ,q 3 , S 1 , S 2 , S 3 , Z 1 , Z 2and Z 3 They represent input fixed-point numbers, weight fixed-point numbers, output fixed-point numbers, input scaling factors, weight scaling factors, output scaling factors, input offsets, weight offsets, and output offsets. Because CNN dedicated accelerators are cumbersome to handle floating-point operations, the tensors of the model are represented by fixed-point integers throughout the calculation process, so the bias (bi as ) is also quantized. The calculation of the bias is placed in the accumulation process of the systolic array in the accelerator of this paper, so the quantization of the bias is:
[0260] B=round(bias*S 1 *S 2 )#(4.5)
[0261] The complete convolution quantization formula after quantization bias is:
[0262]
[0263] because It represents a floating point number. 2 of them -n It can be represented by a right shift operation of n bits, M 0 is an integer; (the larger the value of n, the smaller the error, and the maximum value of n depends on the hardware structure), so the conversion of the scaling factor can be achieved by multiplying by a fixed-point number and right shifting, and these operations are performed in the ALU related modules.
[0264] For asymmetric quantization, the input and weight need to have an offset subtraction operation, and the output also needs an offset addition operation. That is, the CNN dedicated accelerator needs to add a subtraction module before sending the input to the convolution calculation. Similarly, an addition module is also required when writing the result back. Since the bias is quantized, the processing of the offset Z can be put into the bias together. At the same time, thanks to the relatively uniform distribution of weight data, the industry basically adopts symmetric quantization, that is, Z 2 =0, that is, asymmetric quantization is generally only for input. According to the distribution law of convolution calculation, the convolution calculation formula becomes:
[0265]
[0266]
[0267]
[0268]
[0269]
[0270] S 1, S 2 , S 3 , Z 1 , Z 3 ,q 2 and bias are fixed values and will not change during the model inference phase. 1 q 2 Z 1 and q 2 The convolution calculation can be calculated in advance during the compilation stage, that is, B′ is also a constant, which combines the input offset and the output offset as the new quantized convolution bias and puts it into the systolic array. The accelerator only needs to calculate q like symmetric quantization to process this asymmetric quantization. 1 q 2 This is common for processing symmetric quantization and asymmetric quantization under the same hardware structure.
[0271] For the quantization of the skip connection network structure, in order to achieve consistent scaling of the data in the feature map after connection, it is necessary to unify the data distribution of all feature maps before connection to calculate the common S and Z, so that the feature map after connection can be directly used for subsequent calculations.
[0272] 3.2.2INT8 / INT16 variable bit width quantization
[0273] Quantization is the use of fixed-point integers to represent 32-bit floating-point numbers. Due to the different data distribution ranges, INT16 quantization or INT8 quantization is generally used. In actual model deployment applications, there are often multiple models on a dedicated processor. For example, there are two models, face detection and face recognition, in a face recognition system. Some models require different quantization data bit widths due to precision loss and detection speed, but there is only one processor architecture, so the compiler needs to implement variable bit width quantization processing.
[0274] Each PE module in the accelerator is implemented by a DSP unit, and a multiplication operation is performed in the PE (addition is not considered for the time being). The INT16 quantization calculates the result of a data point (or intermediate result), while the INT8 quantization method can calculate the results of multiple data points in a PE at the same time, as shown in the formula:
[0275] (A<<m+B)*(C<<n+D)
[0276] =AC<<(m+n)+AD<<m+BC<<n+BD#(4.8)
[0277] Where A and B represent two inputs respectively;
[0278] C and D represent two weights respectively;
[0279] m and n represent the number of bits shifted;
[0280] <<means left shift;
[0281] If BD<1<<n, BC<<n<1<<m, AD<<m<1<<(m+n), the results of AC, AD, BC and BD can be obtained by splitting the calculation results according to the data bit width, because they do not overlap the data on the same bit. Therefore, shifting and adding two inputs and two weight values to PE at the same time can get four calculation results at the same time (this is the case when both the input and weight are positive numbers, and the case of negative numbers will be discussed later), but this is theoretical. Due to hardware limitations, it is not possible to shift and add inputs and weights at the same time. For example, the high bit width is quantized to INT16 and the low bit width is quantized to INT8. The m and n that satisfy formula (4.8) are at least 16 and 32 respectively. The maximum reserved bit width of the two transmission channels in PE cannot accommodate the left-shifted 32-bit data (the maximum bit width in DSP48E2 is only 27 bits), so only input shift addition or weight shift addition can be used. The following introduces these two methods respectively.
[0282] ① Input shift addition
[0283] The double input sent to the PE multiplication input channel must act on different output results. The data in the feature map C direction is not advisable because it needs to be accumulated. Therefore, the input splitting should start from the feature map plane. Fig.17 As shown in the figure, according to the distance between the positions of the two data sent into the PE input channel, it can be divided into adjacent input shift addition and half input shift addition. The figure assumes a 3*3 convolution calculation with a step size of 1.
[0284] The adjacent input shift addition is to shift and add the input value at the same position corresponding to the next adjacent output point and then send it to PE. The calculated result will correspond to two adjacent output points on the output feature map after splitting. The step size of the next set of outputs is 2, and the step size of the corresponding input feature map is also 2. This method is actually to divide the output feature map into two parts. The half-type input shift addition, that is, the output feature map is divided equally up and down, will read the input data corresponding to the lower half of the output feature map in a leapfrog manner, and the distance between the upper and lower input points is fixed (the fixed distance of the adjacent type is 1). Therefore, it is also easy to find the following input data each time for shift addition and then send it to PE for multiplication calculation. At this time, the input offset step size is 1, but the number of rows OH in the loop needs to be halved.
[0285] ②Weight shift addition
[0286] For the same input, the logic of different weights of a single convolution kernel plane and its dot product result is difficult to control, and the weights on different channels and the input are not of the same dimension, so the two values of weight shift addition can only come from the same corresponding position on different convolution kernels. Fig.18 As shown in the figure, similar to the input shift addition, the weights at the same position on two adjacent convolution kernels are shifted and added and then sent to the weight channel of PE. The result after calculation corresponds to the two adjacent channel values at the same position of the output feature map. The calculation process of a single convolution kernel remains unchanged, which is equivalent to halving the number of convolution kernels OC.
[0287] For the shift addition of signed numbers, there will be errors if the final multiplication result is directly split. Fig.19 In the example, all the numbers involved in the calculation are 3-bit signed numbers. After a 6-bit left shift, the final multiplication result is a 12-bit signed number, where the upper 6 bits and the lower 6 bits are the calculation results of the first two numbers involved in the shift addition and the multiplicand. As can be seen from the figure, the result of the upper 6 bits is biased, and the lower 6 bits of sign bits need to be added to get the correct calculation value. Therefore, when splitting the output result of PE, the sign bit of the lower data needs to be added to the upper data.
[0288] In the systolic array, each PE unit accumulates the output result of a PE, and then sends it to the next PE unit for further accumulation. In order to ensure consistency with the INT16 quantization calculation process and that the carry generated by the low-order result in the accumulation process in the INT8 quantization mode will not overwrite the content of the high-order data and the high-order result will not overflow, an "overflow bit" will be added to be compatible with the carry of data accumulation. For example, for INT16 quantization and INT8 quantization, only the shift addition of PE input in the INT8 quantization mode is considered for formula (4-8), and the formula is:
[0289] (A<<m+B)*C=AC<<m+AB#(4.9)
[0290] At this time, the result of AB is 16 bits. If there is a single PE, m only needs to be 16, but there may be carry in multiple PEs. By adding overflow bits, it can be ensured that the content of the high-order data will not be affected. The final PE output structure is as follows Fig. 20As shown. The choice of overflow bit is related to the hardware structure, that is, the number of accumulated PEs (consider how many times the carry will occur in the worst case, and then take the logarithm), so the value of m should be 16 plus the number of overflow bits. However, due to the limited input channel width in the DSP (DSP48E2 in the accelerator can achieve a maximum of 18*27 multiplication, not considering that the overflow bit has occupied 24 bits, leaving only 3 bits of error tolerance), the overflow bit cannot be added to m to shift and add the input, so m is still only 16 and the addition function in the DSP is abandoned, that is, the upper and lower PEs in the accelerator are no longer directly connected for accumulation, but an accumulation module is added outside, the output of each PE is split and the "overflow bit" is shifted (at this time, the operation of adding the high-order result of the signed result to the low-order result sign bit will also be completed) and then spliced and accumulated in the new accumulation module, which ultimately reduces the time of multiplication and increases the time of addition, but in hardware, multiplication is more than 10 times slower than addition. These are the collaborative optimizations made by our research group on the accelerator and compiler to support variable bit-width quantization. The compiler will generate instruction signals of the quantization bit-width length and calculate the relative address offset of two numbers for shifting and adding, and specify the route for accumulating the results. INT16 quantization performs cumulative calculations according to the original accelerator mode, while INT8 quantization performs input shift addition and takes a new accumulation route.
[0291] After all the corresponding points of an output point are multiplied and accumulated, the fused quantized bias B′ will be added. Because under INT8 quantization, a calculation result is actually the output value of two points, so B′ will also be spliced. If it is PE weight splicing, the spliced B′ is taken from the values corresponding to different convolution kernels; if it is PE input splicing, the spliced B′ is the same value.
[0292] The data formats of INT8 quantized input data at different locations are as follows Fig.21 As shown in the figure, the inputs at corresponding upper and lower positions are still in the INT16 quantization data format cache (with high and low bits respectively). The data written from the input cache to the PE is transparent to the quantization bit width. 16 bits are sent in each time, and then the compiler generates INT8 related signal instructions for m-bit shift and addition operations, and then sent to the PE. If it is INT16 quantization, this operation is skipped. Therefore, the INT16 input cache can still be fully utilized for the INT8 mode, and there is no need to change the cache structure.
[0293] 3.2.3 Model Quantization Process
[0294] Through the design of quantization offset processing and variable bit width quantization of INT8 / INT16 in the above two sections, the compiler can implement multiple quantization methods without changing the hardware. The model quantization process of the compiler is as follows: Fig. 22As shown (INT8 uses half-up and half-down shift addition of the input), the specific steps include the following:
[0295] ① Run the calibration set to obtain the dynamic distribution range of the feature map, mainly to obtain its maximum and minimum values in the calibration set. Since the weight is a static value in the inference stage, its distribution range can be obtained without a calibration set.
[0296] ② Check the quantization bit width option. Currently, only INT8 and INT16 are supported. If INT8 quantization is used, a corresponding flag signal will be generated. This flag will generate the corresponding instruction Int8_Ctr_Instruction in the backend of the compiler to inform the accelerator that the bit width of the convolution quantization data of this layer is INT8 (the default is INT16).
[0297] ③ Traverse the computational graph and determine whether there is a jump connection between feature graphs. If so, unify the scaling factor and offset.
[0298] ④ Check the quantization compilation form option, calculate the scaling factor scale and zero offset according to the selection of INT8 or INT16 in the previous step, and if it is asymmetric quantization, merge the bias and offset.
[0299] 3.2.4 Experimental results and analysis
[0300] The quantization design in this paper is verified on the open source FPGA convolutional neural network accelerator - DnnWeaver. After optimization, the compiler is used to enable the processor to support both INT16 quantization and INT8 quantization. The accelerator system-on-chip is first modeled using hardware description language, and then burned into the XCZU19EG development board of the UltraScale+MPSOC architecture series after synthesis and implementation (see Fig.23 ), the clock in FPGA is 100M, and the resources occupied by CNN accelerator are as follows Fig.24 As shown in the figure, it is necessary to implement quantization in the compiler to reduce the storage and bandwidth pressure of resource-constrained target devices. This section verifies different quantization schemes under fixed hardware and compares the performance of some optimized ones.
[0301] Based on the processing and design of the skip connection network structure in Section 3.1, the network model used in this test is yolov4 tiny, which is a simplified version of the yolov4 model. It is a lightweight model and is often used in target detection tasks. Fig.25 As shown, the entire network structure has 38 layers, in which three residual units are used. The structure of each residual block is as follows Fig.16As shown, the experiment in this section also verifies the supportability of the skip connection network model. Under fixed accelerator hardware, the compiler uses three quantization methods for the yolov4 tiny model: INT8 asymmetric quantization, INT16 symmetric quantization, and INT8 symmetric quantization. The test set for this experiment is VOC2007-test, with confidence Confidence = 0.24 and nms_iou = 0.5. In addition to the several methods processed by the compiler, there are also two groups of comparative experiments on the original PyTorch framework floating-point model before quantization and the conventional asymmetric quantization calculation using the Pytorch quantization tool. They are all run on the CPU. The CPU specifications are shown in Table 4.1.
[0302] Table 4.1 CPU system specification parameters
[0303] CPU Parameters Size operating system Ubuntu 20.04 model Intel(R)Core(TM)i9-10900X Frequency 3.70GHZ Number of cores 10 Second level cache 10MiB
[0304] Table 4.2 Comparison of different quantization types, parameters, average accuracy and frame rate
[0305] Quantization Type Parameters (MB) 20 types of maps (%) Frame rate (FPS) Floating point model (FP32, CPU) 22.612 81.02 15 Asymmetric quantization (INT8, CPU) 5.655 79.26 1.5 Symmetric quantization (INT16, FPGA) 11.308 79.92 21 Asymmetric quantization (INT8, FPGA) 5.653 79.31 39 Symmetric quantization (INT8, FPGA) 5.653 73.43 39
[0306] The final experimental results are shown in Table 4.2. It can be seen from the table that INT16 quantization and INT8 can reduce the number of parameters to 1 / 2 and 1 / 4 respectively compared with the original model. The reason why the model parameters processed by the Pytorch quantization tool using the INT8 quantization method on the CPU are slightly higher than those on the dedicated accelerator is that the bias is not quantized and the floating point number FP32 is still used. In order to prevent overflow during the quantization process, the bias on the dedicated accelerator uses a higher bit width INT16, but it is also smaller than the floating point number of the original model. In terms of precision loss, although the INT16 quantization experimental group uses symmetric quantization, it still has a lower precision loss than INT8 asymmetric quantization due to the advantage of bit width. The precision loss of INT8 symmetric quantization is relatively high because the activation function in the model uses LeakyRelu, which leads to an extremely unbalanced positive and negative distribution of the feature map, and most of the precision of the negative semi-axis is wasted. Therefore, it is very necessary to use asymmetric quantization for low bit widths, and finally the precision can be improved by about 6%. The INT8 group that quantizes the bias on the accelerator has a slightly lower precision loss than the INT8 group that does not quantize the bias on the CPU. The reason may be that the data rounding strategy in the accelerator is inconsistent with the rounding method in the CPU, which makes the final calculation result in the accelerator closer to the original floating-point model. Because the right shift operation in the FPGA is rounded down, in order to improve the accuracy, this paper adopts the strategy of adding 0.5 first and then right shifting to achieve rounding. The binary representation of 0.5 is:
[0307] {~data[m],{n{data[m]}}}#(4.10)
[0308] Among them, {} represents binary bit concatenation, ~ represents the inversion operation, data is the binary number to be right-shifted, m is the highest sign bit, and n is the right-shift number minus 1.
[0309] In terms of model calculation acceleration, compared with CPU floating-point calculation, the acceleration ratio of INT16 quantization is 1.40, while the acceleration ratio of INT8 quantization is 2.60. The main reason why the reasoning speed of Pytorch quantization tools is particularly slow is that there are a large number of quantization and dequantization modules in the calculation process. This section verifies the feasibility of deploying multiple quantization methods under fixed accelerator hardware through experiments. At the same time, INT8 quantization has a nearly 2 times acceleration ratio compared to INT16 quantization.
[0310] 3.3 Convolution calculation loop scheduling optimization strategy
[0311] Due to limited on-chip resources, each cache cannot store the complete feature map and weights at one time. The data needs to be processed in blocks. Each block can perform convolution operations to calculate intermediate results. At the same time, the cache can also avoid frequent access to external storage data. This section will discuss how to optimize the scheduling of feature map blocking and loop reordering to achieve higher convolution calculation efficiency.
[0312] 3.3.1 Weight Cache Bandwidth Optimization
[0313] Before optimizing loop scheduling, we need to optimize the bandwidth of the weight cache in the accelerator in this article. According to the characteristics of convolution calculation, the calculation between each convolution kernel is independent (each convolution kernel corresponds to a channel of the output feature map), so the calculation of multiple convolution kernels is performed in parallel in the accelerator (that is, one input will be calculated in parallel with multiple weights), and when the calculation data in the systolic array is replaced, the weight needs to be replaced several times the amount of input data (the number of times is determined by the degree of parallelism, that is, the number of PUs in the systolic array). Fig.26 As shown in the figure, the number of input channels is 32, and the number of convolution kernels in the parallel convolution kernel group is also 32. Assuming that the size of PE in the systolic array is 32*32, when going from convolution kernel calculation point 1 to calculation point 2, the input cache will re-transmit 32 data to the systolic in a unit cycle, then the corresponding weight cache needs to re-transmit 32*32 data, that is, the cache needs to send 8196bit data into the systolic array in one clock cycle (assuming the quantization type is INT8). Although the data has been quantized in the accelerator, the bandwidth pressure on the weight cache is still particularly large, which is not easy to converge the accelerator timing.
[0314] From Table 3.1, we can see that different inner loop orders (consistent with the outer loop) of convolution calculation will produce three types of data fixation:
[0315] ① Input stationary - do the To(OC) cycle first;
[0316] ②Weight stationary: first do the ow, oh (OW, OH) cycle;
[0317] ③ Output stationary - do KW, KH, Ti (IC) cycle first.
[0318] The width OW and height OH of the output feature map, the number of input channels IC, the number of convolution kernels OC, and the width KW and height KH of the convolution kernel are shown in lowercase letters.
[0319] like Fig. 27 As shown in the figure, each PU computing unit is responsible for the parallel calculation of a convolution kernel, and there are 32 PE computing engines inside the PU to perform multiplication and addition calculations. Similarly, in the weight stationary mode, the input data in the SA in the ow and oh loops are replaced every cycle, that is, 32 input data will be sent to the input pipeline queue of the SA in each cycle (the first cycle after entering the figure will execute a 0 , and then the next cycle will execute a 1 ), the weight cache will initially send 32*32 weight data corresponding to the input into the weight pipeline queue of SA, and then the weight cache will be idle. This article removes the pipeline form of weights. In each cycle of the ow and oh loops, only the weight data of each PE in the PU corresponding to the input data in the current cycle will be transmitted (that is, the weight cache will only transmit 32 weight data relative to one row of SA each time). Because a new set of 32*32 data will not be replaced during the period, the weights will be sent to SA in 32 cycles, so that the bandwidth pressure of the weight cache can be reduced to the same as the input cache. Of course, the premise of all this is to ensure that the inner loop is in weightstationary mode and the total number of ow*oh loop cycles must be greater than the number of PEs in a single PU to meet the transmission requirements. This requires the compiler to control when tiling the loop.
[0320] When the compiler sets the address offset of the inner loop, the address offset of the cache in the ow and oh loops needs to be specially handled; in the text, uppercase letters are outer loops, lowercase letters are inner loops, so ow and oh are inner loops. In the normal ow loop (assuming the inner loop order is ow, oh, Ti / 32, To / 32, KW, KH), the address offsets of the input cache and the output cache are both 1 (the cache width is 32 data), while the weight cache has no address offset. Only when the Ti / 32 loop is performed will the corresponding address offset be set due to the change of weight data. At this time, the weight cache address offset in the ow loop is set to 1, and the address offset in the oh loop is set to the size of ow. When ow*oh>=32 is satisfied, the Ti / 32 loop switches to the next batch of weights to be read in, and the previous batch of weight data that should have been read and written in the unit clock cycle completes the work within 32 cycles. When ow*oh exceeds 32, SA will only receive the weight data of the first 32 cycles. The compiler is designed in this way to improve the timing of the accelerator, because before bandwidth optimization, it is difficult for the accelerator to converge even when running at 100M clock.
[0321] 3.3.2 Latency-based loop scheduling optimization strategy
[0322] Section 2.1.3 describes the three loop operations after loop tiling. The outer loop is to determine the starting address of each tile block in each loop. According to Table 3.1, different outer loop orders involve whether the data of the tile blocks in the cache are replaced; the memory access loop is to write the data that needs to be updated into each cache in blocks, and the time consumed is determined by the total amount of updated data and the data bandwidth of the external memory; the inner loop can be understood as the computational time consumption of the pulsating array for pipeline calculation, which is mainly related to the loop order. Therefore, the time consumption of the entire convolution calculation is mainly divided into two categories: ① Memory access. When doing nested outer loops, different loop types will produce different data movement situations. For example, when doing OC loops, the data in the input cache does not need to be replaced, while the weight cache needs to replace the data corresponding to a tile size. Such as Fig.28In the multi-layer nested loop shown in the figure, from the bottom layer to the outermost layer, once a certain layer of loop starts to replace the data in the cache, the total number of times the cache needs to replace the data is the number of loops in this layer multiplied by the number of loops in the outer layer, because the outer layer loop must complete the entire inner layer loop every time it loops, and so on. During the entire convolution calculation process, the calculation of the total data access volume of each cache to the external memory is shown in Algorithm 4.1. Finally, the total data access volume is divided by the data bandwidth of the external memory to obtain the approximate memory access consumption time. ②SA calculation (the ALU performs pipeline calculations, and the time is mainly concentrated on writing back the final result, which belongs to the output cache memory access). The clock cycles consumed by the systolic array calculation are synchronized with the inner loop. In the case of pipeline calculation, each loop consumes one clock cycle. During this period, the cache will send the required data to the systolic array, and the systolic array will perform a multiplication and accumulation calculation in a "pipeline" manner. In the accelerator, each loop type switch will involve some changes in the state machine, which requires additional overhead. The calculation of the clock cycle consumed by the inner loop SA is shown in formula (4.11), where {a n} represents the number of loops corresponding to the inner loop sequence, b represents the additional overhead of switching loops, and obviously {a n} Arranging them from large to small gives the smallest value for calculation formula (4.11), so the calculation of the minimum clock cycle consumed by SA is shown in Algorithm 4.2 (the weight bandwidth optimization described in 3.2.2 is considered here).
[0323] a n (…(a 2 (a 1 (a 0 +b)+b)+b)…)#(4.11)
[0324]
[0325]
[0326] There will be overlap in the above two time consumptions. Since each cache adopts the design format of ping-pong cache, half of the cache sends data to the systolic array for calculation while the other half writes the next block of data from the external memory into the cache, thus achieving the effect of hiding the memory access delay. Fig.29As shown in the figure, due to the different block sizes and the different inner and outer loop orders, the calculation time may not be enough to complete the hidden memory access time, that is, the current block has been calculated but the next block has not been written (it may have been written long ago). At this time, the systolic array has to stop waiting. This part of the time when SA needs to wait because the memory access has not yet ended is called "memory blocking". The special memory blocking is the initial reading of data from the memory and the writing of the last block of data back to the memory after all calculations are completed. During this period, the accelerator is idle, so the entire time period belongs to the memory blocking stage.
[0327] For the above aspects, different hardware parameters such as loop tile size, inner and outer loop order, and cache size will produce different computing performance. The purpose of a good loop scheduling strategy is to achieve very low computing latency. This paper proposes a loop scheduling strategy based on achieving the minimum clock cycle consumed by the accelerator. Fig.30 As shown, first, the outer loop sequence is enumerated (120 calculation sequences are fixed), and the loop tiling size space is explored between different outer loops through multi-threading. The loop tiling size is also enumerated to obtain the block data size corresponding to each cache (ow*oh needs to be greater than 32), and then the clock cycle consumed by this method is calculated according to the information of the FPGA hardware. The calculation pseudocode is shown in Algorithm 4.3, and finally the loop scheduling scheme that consumes the least clock cycle is adopted through comparison. In Algorithm 4.3, since each cache starts to change data in a certain layer loop, all loops in the outer layer are divided by the current layer loop according to Table 3.1 regardless of whether the data will be changed. All loop numbers in the inner layer represent the period T where the data is fixed. s , and the total number of subsequent cycles is the period T that needs to be replaced c , that is, per T s The data in the cache will be replaced once every cycle, and a total of T c As the cycle moves outward, c In the next loop, other cache data that needs to be replaced will gradually increase. Finally, the corresponding memory blocking cycle can be calculated by subtracting the clock cycle consumed by each outer loop memory access from the clock cycle calculated by the minimum and fixed systolic array.
[0328]
[0329] 3.3.3 Experimental results and analysis
[0330] Table 4.4 Accelerator related parameters
[0331] FPGA accelerator related parameters Size Systolic Array Size 32*32 Cyclic switching state overhead 2(clock) DRAM Bandwidth 256bit / clock Input Buffer 16*32*3072bit Weight Cache 16*32*2048bit Output Cache 64*32*2048bit Bias Buffer 32*32*512bit
[0332] The accelerator architecture and FPGA development board used in the experiment in this section are consistent with the quantization experiment in Section 3.2.4. The test models used are yolov2 tiny, yolov3 tiny, and yolov4 tiny. Since there are currently no other compilers that can provide compilation support for the dedicated accelerator based on this article, only the compiler itself is compared before and after optimization. The relevant parameters of the accelerator are shown in Table 4.4. The comparison experiment is the manual convolution loop tiling and loop rearrangement before optimization. The experiments are all based on the bandwidth optimization of the weight cache. The test data is the average running time of detecting 3600 images. The final experimental results are shown in Fig.31 shown.
[0333] from Fig.31 It can be seen that although yolov4 tiny has more convolution layers, since many convolutions are 1*1 and the convolution step size in the first two layers of yolov4 tiny is 2, the inference speed of yolov4 tiny is faster than that of yolov2 tiny and yolo v3 tiny with fewer layers (the number of convolution kernels in yolov2 tiny is relatively large and only the last layer output is 1*1 convolution). Through the performance comparison of the three models before and after compiler optimization, the convolution calculation loop scheduling strategy can improve the performance by 10%-20%. The loop scheduling optimization strategy in this article only roughly estimates the execution time of the accelerator, but it can also be used as a performance standard. Finally, the experiment also shows that the loop scheduling optimization strategy can make full use of the accelerator's resources to achieve the effect of improving performance.
[0334] 3.4 Summary
[0335] First, a memory sharing and addressing method is designed, and the computational graph is simplified by deep copying of feature maps and exchanging the order of operators so that the compiler can support jump-connected network structures; secondly, model quantization methods of different types and variable bit widths are designed on a fixed accelerator structure, and the acceleration ratio of INT8 over INT16 without increasing DSP resources is verified through experiments; finally, a latency-based convolution calculation loop scheduling optimization strategy is designed based on optimizing the weight cache bandwidth, and the performance improvement of the optimization strategy is demonstrated through experimental comparison before and after compiler optimization.
[0336] 4. Compiler overall function test and application verification
[0337] This paper introduces the basic design architecture of the compiler in Chapter 3, and completes further optimization design in Chapter 4 and tests its performance through relevant experiments. This chapter mainly introduces the basic design architecture of the compiler in Chapter 4. c o c The OTB simulation platform demonstrates and tests the overall functions of the optimized compiler and verifies the application of target detection tasks.
[0338] 4.1 Compiler Directory Structure
[0339] The compiler directory structure is as follows Fig.32 As shown in the figure, each subdirectory corresponds to a functional module of the compiler. All modules work together to complete the compilation process of the CNN model. The specific work content of each functional module is explained as follows:
[0340] ①compiler. The compiler backend is used to convert the computational operations of the CNN model into instruction sequences executed by the corresponding hardware. It includes a convolutional computation compiler (conv_compiler) and a linear computation compiler (pu_compiler) after operator fusion. It is also responsible for memory allocation management of the required feature maps.
[0341] ②FPGA. The RTL code related to the hardware platform also includes information such as the size of the systolic array and the cache size. It is also responsible for the memory management of the FPGA, and provides an interface for initializing the weight data of the calculation graph, sending input data, and obtaining output results during the simulation process.
[0342] ③graph. Computational graph, intermediate representation IR defined by the compiler. It is mainly composed of data types such as tensor Tensor and computing node NodeOp through topological relationships.
[0343] ④isa. The instruction set architecture system corresponding to the accelerator mainly generates the corresponding instruction sequence based on this instruction set in the compiler module to complete the mapping of the model on the accelerator.
[0344] ⑤ optimizer. The computational graph optimization module includes operator fusion optimization and computational graph structure transformation for skip connection processing, and modifies the value of Concat_Channel in the relevant Tensor (initialized to 0).
[0345] ⑥parser. Deep learning model parser, used to convert CNN models into defined computational graphs, and supports loading model files in ONNX format.
[0346] ⑦Quantization. The compiler quantization module supports multiple quantization modes under a fixed hardware structure, including INT8 symmetric quantization, INT8 asymmetric quantization, INT16 symmetric quantization, and INT16 asymmetric quantization. The input of the asymmetric quantization mode is asymmetric quantization, and the weight still uses symmetric quantization.
[0347] ⑧schedule. The convolution loop scheduling module seeks the optimal loop tiling and loop rearrangement scheme in the search space. If the quantization type is INT8, the OH attribute will be halved during scheduling.
[0348] ⑨sim. The simulation module uses the instructions generated by the compiler and the corresponding weight files to perform accelerator simulation tests on the Python-based IC verification platform - Cocotb to verify the correctness of the instructions.
[0349] 4.2 Compiler Function Test
[0350] In order to test the compilation function of the overall structure of the compiler, the test network model selected in this section is the yolov4tiny model and the input size is changed to 480*352. This is also to verify the feasibility of the compiler on non-square input network models. Because the actual running performance of the network model on the FPGA development board has been demonstrated in the relevant experiments in Chapter 4, this chapter mainly uses simulation to test the overall function of the compiler and verify the application results of the accelerator. The following introduces the running test of the main modules:
[0351] ①Quantization module
[0352] Due to the limited on-chip resources and the complexity of dedicated accelerators in handling floating-point calculations, a quantization module is added to the compiler to accelerate model reasoning. Through the design of the quantization scheme, the compiler can implement multiple quantization types under a fixed hardware structure. The test quantization option in this section selects INT8 asymmetric quantization. As shown in Table 5.1, the quantization of the first 6 layers of convolution of yolov4 tiny, the ALU outputs of Conv2 and Conv5, Conv3 and Conv4 in the network structure will be concat operated, so they will be processed uniformly, and the ALU output results will be used as input for the next layer of convolution calculation. Because this compiler uses a symmetric method for weight quantization regardless of symmetric or asymmetric quantization, the only difference is the quantization method of the input feature map. Because there is no module for processing zero_point in the accelerator, the non-zero zero_point of the input is integrated into the bias after quantization through the compiler. Therefore, the input in the accelerator also uses symmetric quantization, that is, zero_point=0, but its scale is obtained through asymmetric quantization, but the real zero_point is hidden in the bias, which can reduce the complexity of accelerator calculation.
[0353] Table 5.1 Scaling factors of the first 6 convolution weights and output eigenvalues of Yolov4 Tiny
[0354] Layer Weight_Scale ALU_Output_Scale Conv0 0.124245524 0.138176888 Conv1 0.025978136 0.121351070 Conv2 0.015619760 0.065793789 Conv3 0.009466293 0.087572626 Conv4 0.006844555 0.087572626 Conv5 0.011748414 0.065793789
[0355] ②Computational graph optimization module
[0356] After the quantization module compresses the model weights, the calculation graph will be optimized by the optimizer module, where operations include BN fusion, operator fusion, etc. Fig.25 In the yolov4 tiny structure shown in the figure, the first three layers are operated as conv+bn+leakyRelu. The structure after the calculation graph optimization is as follows Fig.33 As shown, the fused new node is a Macro node, which consists of sys_array_op and pu_op_list. sys_array_op is the convolution operator used for calculation in the systolic array, while pu_op is responsible for the related linear calculation directly from the output buffer to the ALU module. It can be seen from the figure that there is no bn operator in pu_op after bn fusion, only leakyRelu activation function, and bn integrates the relevant parameters into the weight and bias of the convolution calculation, which can reduce the amount of calculation of the model. There is also an operator TypeCast in pu_op that is irrelevant to the model structure itself. This is because both convolution calculation and other linear calculations will increase the data bit width of the calculation result. For example, the final result of INT8 type convolution after adding bias is 32 bits, and its corresponding scaling factor is also the product of weight and input. It needs to be converted to 8 bits according to the quantization requirements, and TypeCast is responsible for this. It can be seen from the figure that the input_Tensors and output_Tensors of each operator node determine the topological structure of the entire calculation graph. The forward input of conv0 contains three tensors: data, weights, and bias, and the backward output is the result of the convolution calculation. Its bit width is 32 bits and the corresponding scaling factor is the attribute out_scale (it is just the scale output by the convolution operator, which is the product of the input and weight scaling factor, that is, the scaling factor of bias. The quantization test set statistics the scaling factor of the final output of ALU). Therefore, the actual topological structure of conv0 after the calculation graph is optimized is as follows: Fig.34 shown. Fig.34 The convolution calculation result conv_out is placed in the output buffer, and then enters the ALU module for calculation in pu_op. The final result stored back to the external memory is the data of tensor out1 (if there is no activation function, the data stored back is the data of tensor out0). At the same time, only the last tensor written back will be allocated memory in the external storage, which can save memory.
[0357] In addition, for Fig.25The first residual block of yolov4 tiny in the image has its first convolution (the result will be concatenated with the last convolution result in the channel direction and then a maximum pooling is performed. After the branch processing strategy in Section 4.1, the first convolution (the third convolution of the total network structure) and the structure after operator fusion are as follows Fig.35 As shown in the figure, the branch processing is to exchange the order of the splicing operation and the maximum pooling and delete the splicing operation from the calculation graph. Therefore, there is a corresponding Maxpool operator in the pu_op of the Macro Node of the first convolution of the residual block, and the concat_c attribute of its output is the number of channels of the result after the Maxpool operation of another branch. After the memory space is finally allocated, the first addresses of the input tensor and output tensor of the residual branch structure are shown in Table 5.2. The entire memory space is allocated according to the size of the output tensor. The first address of the Maxpool0 tensor located in the front of the splicing is consistent with the first address of the output tensor (the input of the next residual block), which is 0x41157800, while the first address of the Maxpool1 tensor located after the splicing differs from the front by 0x40, that is, the address length of 64 INT8 data, which is exactly the number of channels of Maxpool0. The length of their intermittent addresses is the attribute concat_c. When Maxpool0 and Maxpool1 have been written back, the input data of the next residual block is naturally ready and continuous data can be read directly from the memory.
[0358] Table 5.2 The first address and size of the input and output tensors of the residual branch structure
[0359] Tensor First address Size (B) Maxpool0 0x41157800 88*120*64 Maxpool1 0x41157840 88*120*64 Next resblock data 0x41157800 88*120*128
[0360] ③Convolution calculation loop scheduling module
[0361] Due to the limited on-chip resources of the accelerator, the convolution calculation needs to be flattened in a loop. The loop scheduling module is responsible for finding the most reasonable block solution and loop execution order in the search space. Fig.36The compiler loop scheduling optimization log is printed. The figure shows the optimal scheduling scheme that is continuously updated in the process of traversing the search space for the first two layers of convolution (the first layer input is 3 channels, which cannot meet the cumulative need of 32 PEs to fill it into 32 channels. In order to avoid this operation, the accelerator makes special treatment for the first layer during optimization and improvement, so the compiler needs to fix the first layer plane block size to 8*8). The total number of OH loop directions in the second layer of the log is 44, not 88 in the original model structure. This is because the INT8 quantization mode is selected and the input upper and lower shift addition is used, which corresponds to the upper and lower split of the output. Therefore, the total number of OH loops is halved to calculate the upper and lower results at the same time. IC and OC correspond to the rows and columns of the systolic array (32*32) respectively, so the granularity when dividing is 32. Finally, the optimal loop scheduling scheme is selected through comparison. In the second layer, because the number of input channels and the number of convolution kernels are relatively small, only OH / oh and OW / ow are divided in the outer loop, and the loop order of the inner loop is naturally sorted from large to small based on the premise of weight optimization bandwidth.
[0362] ④Instruction generation module
[0363] The instructions generated by the compiler are as follows Fig.37 As shown in the figure, some related instructions generated by conv0 are shown. The 0000 opcode indicates the start of the convolution operation, and then the opcode 1001 is used to set the corresponding first address of the input, weight and bias in the memory, that is, the base address of each cache to read and write data from the external memory. The address offset of the subsequent loop instructions is based on this. Since the immediate field of the instruction is only 16 bits wide, two instructions corresponding to each cache are used to set the high and low addresses of the base address, for a total of 6 instructions; then the 1101 opcode instruction is used to set the INT8 quantization mode, and its immediate number represents the address offset of the upper and lower shift addition of the PE input. Similarly, because the address span is relatively large, two instructions are used to combine the high and low bits.
[0364] Next is the loop instruction, whose opcode is 0111. The middle field is used to distinguish the different stages of the loop. As can be seen in the figure, the outer loop has only two layers, corresponding to Fig.36 In loop scheduling, conv0 only performs tiling division of OW and OH, and the instruction immediate number represents the number of loop repetitions (the number of loops minus 1). Fig.36 The number of repetitions of the inner and outer loops are 1010=10 and 11101=29, which is consistent with the (11,8) and (30,8) divisions of the OH and OW loops. The 0110 and 0101 instructions under the instruction loop are used to represent the high and low bits of the address offset of each tensor in the memory in each loop. If it does not exceed the 16-bit representation range, only the 0110 bit is used to represent it. The actual address offset is superimposed from the loop address offset from the outside to the inside.
[0365] 4.3 CNN model application verification
[0366] After generating the instructions and related weight files, the Python cocotb platform is used to directly use the RTL hardware code for inference simulation testing. The image is preprocessed and quantized and sent to the image input interface of the simulation program. After the calculation is completed, the corresponding output result can be obtained through the output interface. Fig.38 As shown in the figure, all tensors allocated by the compiler can read bytes of the corresponding size from the memory according to their first address and size, and then use the reshape function to restore the original shape of the tensor. For tensors shared in memory, the entire shared area is first taken out and then the data of the channel is divided.
[0367] For the yolov4 tiny object detection model, its output has two feature maps for object classification and regression, with sizes of (11, 15, 75) and (22, 30, 75) respectively. The classification branch is used for object recognition, and the regression branch is used for object positioning. The final object detection result is as follows: Fig.39 As shown in the figure, the box on the left is drawn by the calculation result of the yolov4 tiny model algorithm, and the box on the right is the result of the calculation of the compiler-generated instructions via the accelerator. The positions of the two boxes in the figure are basically the same, but there are some slight differences in the confidence values. This is caused by the loss of model quantization accuracy. The specific loss can be seen in Table 4.2. The accuracy loss of different types of quantization is statistically shown. The comparison between the two shows that the quantization method designed by the compiler and the generated instructions are reliable and accurate.
[0368] 4.4 Summary
[0369] First, the functional module catalog of the compiler is introduced. Then, the main quantization modules, computational graph optimization model, loop scheduling and generated instructions are tested by compiling the yolov4tiny model on the simulation platform to illustrate the integrity of the basic functions of the compiler. Finally, the accuracy of the compiler compilation results is verified by comparing the results of the target detection task software and hardware.
[0370] 5. Conclusion
[0371] As an important branch of machine learning, deep learning has a rapid development trend, especially in the fields of computer vision and speech recognition, showing ultra-high recognition accuracy. Although the deep learning model is very powerful in the cloud, its computationally intensive characteristics also make it difficult to deploy the model on resource-constrained embedded devices. In order to solve the problem of deep learning model implementation, many dedicated neural network accelerators have been designed, and the mapping of models to hardware is inseparable from software tools such as deep learning compilers. However, there are not many domestic compilation studies on dedicated CNN accelerators, and problems such as complex network structure, limited quantization methods and reasonable division of feature maps need to be solved. Therefore, the optimized design and implementation of a deep learning compiler for CNN dedicated accelerator is proposed. After summarizing, the main work completed by the present invention is as follows:
[0372] ① The basic design of a deep learning compiler based on a CNN-specific accelerator was carried out. During the design and implementation, optimization methods such as operator fusion were used to reduce the accelerator's access to memory and the waste of storage space. At the same time, the memory allocation address superposition method was used to avoid data overlap between tensors.
[0373] ② A memory sharing and addressing method is designed to handle the cross-layer Concat network structure. Through strategy compilation such as deep copying of feature maps and operator exchange order, it can support network models such as yolov3 tiny and yolov4tiny.
[0374] ③ A flexible model quantization method under fixed hardware is implemented. By integrating the offset and convolution bias of asymmetric quantization, the hardware structure corresponding to symmetric quantization can also support asymmetric quantization. At the same time, under hardware support, two input values are sent to the DSP through compiler configuration for shift addition to calculate two output values at the same time, so as to realize the compiler's quantization support for variable bit width of the model. Experiments show that asymmetric quantization can improve the accuracy by about 6%, and INT8 quantization can achieve nearly 2 times the acceleration ratio of INT16 quantization without increasing DSP resources.
[0375] ④ The time overhead of convolution calculation after feature maps and weights are divided into blocks is analyzed. Under the premise of hiding the accelerator delay, a scheduling strategy for optimizing loop tiling and loop rearrangement is designed according to hardware information to improve the computing efficiency of the accelerator. Finally, by comparing the scheduling strategy before and after optimization, the performance can be improved by 10%-20%.
[0376] The deep learning compiler is a bridge between the top-level model algorithm and the underlying complex hardware structure, and is also a very important part of the entire AI chip software ecosystem. At present, there is not much research on the compilation of dedicated neural network accelerators in China. Through the research of AI compilers, we can not only expand our understanding of deep learning related knowledge, but also help the process of coordinated hardware and software design.
[0377] Although the embodiments of the present invention have been shown and described, it will be appreciated by those skilled in the art that various changes, modifications, substitutions and variations may be made to the embodiments without departing from the principles and spirit of the present invention, and that the scope of the present invention is defined by the claims and their equivalents.
Claims
1. A deep learning compiler optimization method dedicated to CNN accelerator, characterized in that: The following steps are involved: S1, reduce the accelerator's memory access and storage space waste through operator fusion and / or bn fusion optimization methods, and use memory allocation address superposition to avoid data overlap between tensors; the method of using memory allocation address superposition is: after the middle layer optimization of the calculation graph, first initialize the first address P of the actual external memory reserved for the accelerator space size, then traverse the Tensor list in the calculation graph Graph, and only allocate the actual memory size to the tensor whose add_vilid attribute is True. Each time the allocation is made, it is only necessary to point the address pointer P of the current memory space to the first address of the tensor, and then the address pointer P is superimposed and updated according to the tensor size, and the allocated memory space size is maintained by the size of the tensor itself, and finally repeat this operation to complete the memory allocation work for the tensors in the entire calculation graph; S2, adopts multiple model quantization deployment schemes under fixed hardware, and makes the hardware structure corresponding to symmetric quantization support asymmetric quantization by integrating the offset and convolution bias of asymmetric quantization. At the same time, through the coordinated optimization of the compiler and accelerator, the input data of the DSP is configured as the shift addition of two numbers, so that two multiplication operations are performed simultaneously in one DSP, and finally the compiler supports variable bit width quantization. S2-1, run the calibration set to obtain the dynamic distribution range of the feature map; S2-2, detect the quantization bit width option and determine whether it is INT8 or INT16. If it is INT8, use input shift-add or weight shift-add; S2-3, traverse the computation graph and determine whether there is a jump connection relationship between feature graphs. If so, unify the scaling factor and offset; S2-4, detect the quantization compilation form option, calculate the scaling factor scale and zero offset according to the selection of INT8 or INT16 in the previous step, and merge the bias and offset if it is asymmetric quantization; The fusion of the bias and offset includes: For asymmetric quantization, the quantization formula of the convolution calculation process is: Among them, q1, q2, q3 represent input fixed-point number, weight fixed-point number, and output fixed-point number respectively; S1, S2, and S3 are the input scaling factor, weight scaling factor, and output scaling factor, respectively; Z1, Z2, and Z3 are the input offset, weight offset, and output offset, respectively; 2 -n Indicates right shift n bits operation; M0 is an integer; ∑ represents convolution summation; B′ represents the new bias; round(·) means rounding to the nearest integer; Bias means bias.
2. The deep learning compiler optimization method dedicated to CNN accelerator according to claim 1, characterized in that: The input shift addition comprises: Adjacent input shift addition: The input value at the same position corresponding to the next adjacent output point is shifted and added before being sent to the processing engine PE. The calculated result will correspond to two adjacent output points on the output feature map after splitting; the step length of the next group of outputs is 2, and the step length of the corresponding input feature map is also 2; Or half-input shift addition: the output feature map is evenly divided up and down, and the input data corresponding to the lower half of the output feature map will be read in a leapfrog manner, while the distance between the upper and lower input points is fixed. At this time, the input offset step is 1, and the number of rows OH in the loop is halved; The weight shift addition includes: the weights at the same position on two adjacent convolution kernels are shifted and added and then sent to the weight channel of PE. The result after calculation is split into two adjacent channel values corresponding to the same position of the output feature map. The calculation process of a single convolution kernel remains unchanged. At this time, the number of convolution kernels OC is halved.
3. The deep learning compiler optimization method dedicated to CNN accelerator according to claim 2, characterized in that: The weighted shift addition also includes: when performing shift addition on a signed number, the output result of the PE is evenly split into high-order data and low-order data according to the number of bits, and the high-order data needs to be added with the sign bit of the low-order data.
4. The deep learning compiler optimization method dedicated to CNN accelerator according to claim 2, characterized in that: Also includes: In the systolic array, each PE unit accumulates the output result of a PE and then sends it to the next PE unit for further accumulation, adding an overflow bit to be compatible with the carry of data accumulation.
5. The deep learning compiler optimization method dedicated to CNN accelerator according to claim 1, characterized in that: It also includes: using optimized convolution loop tiling and loop rearrangement scheduling strategies to improve the performance of the accelerator. First, the outer loop sequence is enumerated, and the loop tiling size space is explored between different outer loops through multi-threading. The loop tiling size is also enumerated to obtain the block data size corresponding to each cache, and then the clock cycle consumed by this method is calculated based on the information of the FPGA hardware. Finally, the loop scheduling solution that consumes the least clock cycle is adopted through comparison.
6. The deep learning compiler optimization method dedicated to CNN accelerator according to claim 5, characterized in that: The specific steps of the loop tiling are as follows: S100, external circulation: S100-1, if h is less than OH, continue the first outer cycle, and h increases by 1 each time; S100-2, if c is less than OW, continue the second outer loop, and w = w + ow for each loop; S100-3, if oc is less than OC, continue the third outer loop, and oc=oc+To for each loop; S100-4, if ic is less than IC, continue the fourth outer loop, and ic=ic+Ti every time the loop is repeated; S200, loading data into cache; S300, internal circulation: S300-1, if _h is less than min(h+oh, OH), continue the first layer inner cycle, and _h increases by 1 each time the cycle is completed; S300-2, if _w is less than min(w+ow, OW), continue the second inner loop, and increase _w by 1 each time through the loop; S300-3, if occ is less than min(oc+To, OC), continue the third inner loop, and increase occ by 1 each time; S300-4, if icc is less than min(ic+Ti,IC), continue the fourth inner loop, and add 1 to icc each time; S300-5, if kw is less than KW, continue the fifth inner loop, and kw increases by 1 each time; S300-6, if kh is less than KH, continue the sixth inner loop, and increase kh by 1 each time; S300-7, output=input*weight+output; Where OW and OH represent the width and height of the output feature map respectively; IC indicates the number of input channels; OC represents the number of convolution kernels; KW and KH represent the width and height of the convolution kernel respectively; h, c, w, oc, and ic are all traversal symbols of the outer loop; ow, To, and Ti are all the step lengths of the cyclic tiling, and their values are all greater than 1; _h, _w, occ, icc, kw, kh are all traversal symbols of the inner loop; output means output; Input means input; Weight indicates weight.
7. The deep learning compiler optimization method dedicated to CNN accelerator according to claim 5, characterized in that: The calculation of the clock cycles consumed in this manner includes: S10, calculating the time it takes for the computing unit to process one block according to the inner loop sequence and the size of the loop tile; and then traversing all the blocks in the same way to obtain the total computing time of the computing unit; S20, according to the outer loop sequence, the size of the loop tile and the data block replacement, calculate the memory method time of each outer loop; S30, if the time of the second step is greater than the time of the first step, then the memory blocking time = the memory method time of the outer loop - the time of the fixed systolic array calculation; if the time of the second step is less than the time of the first step, the memory blocking time is 0; the total memory blocking time is the time of traversing all the outer loops; S40, the total running time of the accelerator = the total computing time of the computing unit + the total memory blocking time.
8. The deep learning compiler optimization method dedicated to CNN accelerator according to claim 7, characterized in that: The calculation formula for calculating the time taken by the computing unit to process a block is as follows: a n (...(a2(a1(a0+b)+b)+b)...) where a n The number of loops corresponding to the inner loop sequence represented by n is n; b represents the additional overhead of switching loops; The size of the loop tiling is the specific value of the inner loop, i.e. a0, a1, ..., a n ; The memory method time of each outer loop = data exchange amount / memory bandwidth.
