Full text
Journal of Parallel and Distributed Computing 167 (2022) 240–254 Contents lists available at ScienceDirect Journal of Parallel and Distributed Computing www.elsevier.com/locate/jpdc Efficient and portable GEMM-based convolution operators for deep neural network training on multicore processors Sergio Barrachina a, Manuel F. Dolz a,∗, Pablo San Juan b, Enrique S. Quintana-Ortí c aDepto. de Ingeniería y Ciencia de Computadores, Universidad Jaume I, Castellón, Spain bDepto. de Sistemas Informáticos y Computación, Universitat Politècnica de València, Spain cDepto. de Informática de Sistemas y Computadores, Universitat Politècnica de València, Spain a r t i c l e i n f o a b s t r a c t Article history: Received 27 February 2021 Received in revised form 4 April 2022 Accepted 21 May 2022 Available online 30 May 2022 Keywords: Convolutional neural networks Distributed training High performance Python Clusters of multicore processors Convolutional Neural Networks (CNNs) play a crucial role in many image recognition and classification tasks, recommender systems, brain-computer interfaces, etc. As a consequence, there is a notable interest in developing high performance realizations of the convolution operators, which concentrate a significant portion of the computational cost of this type of neural networks. In a previous work, we introduced a portable, high performance convolution algorithm, based on the BLIS realization of matrix multiplication, which eliminates most of the runtime and memory overheads that impair the performance of the convolution operators appearing in the forward training pass, when performed via explicit im2col transform. In this paper, we extend our ideas to the full training process of CNNs on multicore processors, proposing new high performance strategies to tackle the convolution operators that are present in the more complex backward pass of the training process, while maintaining the portability of the realizations. In addition, we conduct a full integration of these algorithms into a framework for distributed training of CNNs on clusters of computers, providing a complete experimental evaluation of the actual benefits in terms of both performance and memory consumption. Compared with baseline implementation, the use of the new convolution operators using pre-allocated memory can accelerate the training by a factor of about 6%–25%, provided there is sufficient memory available. In comparison, the operator variants that do not rely on persistent memory can save up to 70% of memory. ©2022 The Author(s). Published by Elsevier Inc. This is an open access article under the CC BY-NC-ND license (http://creativecommons.org/licenses/by-nc-nd/4.0/). 1. Introduction Machine learning via deep neural networks (DNNs) is being increasingly adopted to tackle a large variety of applications beyond the traditional cubbyhole of this technology in image recognition and signal processing [15,5,22,28,35]. To improve their accuracy, many of the DNN models designed for these applications need to be trained over an extremely large amount of data [24]. For the same reason, both the dimension (number of layers) and complexity of DNNs are growing rapidly, and recent models involve up to billions of parameters [13,27,6]. In consequence, DNN training is currently conducted using distributed algorithms on high performance computing (HPC) facilities, with dozens or even hundreds of nodes, sometimes enhanced with fast memory modules (high bandwidth memory, or HBM) and high performance interconnection networks (e.g., Infiniband) [22]. At this initial point, we recognize that DNN training can significantly be accelerated using *Corresponding author. E-mail address: [email protected] (M.F. Dolz). hardware accelerators, such as AMD/NVIDIA’s graphics processors (GPUs) or Google’s tensor processing units (TPUs). However, we also point out the interest of companies like Facebook to exploit idle workload cycles in their HPC facilities, which leave a significant number of (general-purpose) multicore CPUs to perform distributed model (re-)training during off-peak periods [15]. In this paper, we address how to leverage efficiently these idle resources to perform distributed training of CNNs. Convolutional (deep) neural networks (CNNs) are a specialized type of multilayer perceptrons with application in image recognition, recommender systems, image classification, medical image analysis, natural language processing, brain-computer interfaces, and financial time series, among others. CNNs exhibit an implicit regularization that takes advantage of the hierarchical structure of the data in order to avoid overfitting. This property is achieved via the application of convolution operators, which concentrate a significant fraction of the computational cost for CNNs. A flexible, reliable, and, in many cases, high performance approach to realize a convolution operator consists in applying the im2col transform [10]to the layer activation inputs, followed by a general matrix multiplication (gemm) that takes advantage of https://doi.org/10.1016/j.jpdc.2022.05.009 0743-7315/©2022 The Author(s). Published by Elsevier Inc. This is an open access article under the CC BY-NC-ND license (http://creativecommons.org/licenses/by-nc-nd/4.0/).
S. Barrachina, M.F. Dolz, P.S. San Juan et al. Journal of Parallel and Distributed Computing 167 (2022) 240–254 optimized realizations of this computational kernel in high performance linear algebra libraries (e.g., Intel MKL, OpenBLAS, GotoBLAS2, BLIS, ATLAS, etc.). Unfortunately, there are two major problems with this approach: 1) a large memory workspace is required to host the intermediate matrix generated by the im2col transform; and, especially for training, 2) the time to apply this transform is not negligible for complex CNNs. In [26], we presented a portable high performance convolution algorithm based on the BLIS [33]realization of gemm, named convgemm, that practically eliminates the memory and time cost of the im2col transform, while maintaining the portability and performance of the underlying realization of the BLIS gemm for multicore processors. In this paper, we extend our previous work in [26]to obtain an efficient integration of the convolution operators in a framework for distributed training of DNNs on clusters of computers equipped with multicore processors. In particular, this work makes the following contributions: •For the computation of the downstream gradients with respect to the inputs, we adopt an approach similar to that in [26] to integrate a col2im operator within the BLIS realization of gemm, yielding a deconvgemm operator that avoids the creation of a large intermediate matrix, while maintaining the portability and, to a certain extent, performance. •For the computation of the downstream gradients with respect to the filters, we leverage the existing convgemm algorithm via a novel Reindex transform that re-arranges one of the input matrices to avoid the explicit operation with the transposed of that operand. As an alternative, we also address this calculation via a transposed variant of the convgemm operator. •We complete the general discussion of the convgemm and deconvgemm operators and associated transforms with a detailed description using high level code that should allow to reproduce our implementations. In addition, we discuss several variations of the convolution operators that trade off memory consumption for performance. •We integrate the resulting convgemm/deconvgemm algorithms and the Reindex transform into PyDTNN (Python Distributed Training of Neural Networks), a deep learning framework that offers a fair combination of functionality, computational performance, and friendly interface, prioritizing flexibility to prototype new research ideas. •We perform a complete experimental evaluation showing the performance advantages and memory savings over the baseline approach that operates with large workspaces using the explicit im2col and col2im transforms. This evaluation includes four popular DNNs (ResNet34, VGG16, DenseNet121, and GoogLeNet) and two datasets (CIFAR-10 and ImageNet), and targets a state-of-the-art cluster equipped with Intel Xeon Gold 5120 processors with the nodes connected via an Infiniband EDR network. The rest of the paper is structured as follows. In Section 2, we offer a short review of supervised iterative training for DNNs via the stochastic gradient descent (SGD), paying special attention to the convolution layers appearing in the forward-backward iteration. In Section 3, we first discuss the BLIS kernel for gemm and explain how this was leveraged in [26]to obtain an efficient realization of the convolution operator in the forward pass of the training process. In the same section, we next discuss how to extend that idea to the more complex backward propagation stage, which constitutes one of the major contributions of this work. In Section 4, we elaborate on the integration of the new operators and transforms into PyDTNN, and assess the benefits of the result via a complete experimental validation. In Section 5, we revisit some related work on gemm-based operators and compare them with those presented in this work. Finally, in Section 6, we close the paper with a short summary and a collection of concluding remarks. 2. Convolutional neural networks 2.1. Overview of supervised training Consider a collection of input vectors, denoted by x1, x2, ..., xs∈ Rm, with associated output vectors y1, y2, ..., ys∈Rn(also known as labels or ground truth). From the mathematical perspective, a DNN defines a non-linear function F:Rm→Rnso that F(xr) = ˜ yr, where we expect that ˜ yr≈yr, for r=1, 2, ..., s; see [30,18,23]. In supervised training, the DNN “learns” from the labeled data, adjusting its model parameters (that is, weights and biases) to diminish the difference (deviation or error) between the ground truth and the output computed by the DNN as part of the forward pass (FP); that is, reduces the “error” yr−˜ yr(for all r). This learning process is usually conducted via the SGD method (or some related variant) [18], which is an iterative “back-propagation” (BP) procedure that, given an output-label pair, computes the gradients for the DNN parameters that minimize this difference. The gradients are then used to update the DNN parameters, in preparation for the next FP-BP iteration, with a new input sample; see, e.g. [18]. These two stages of BP are referred to in our work as gradient computation (BP-GC) and weight updates (BP-WU). The convergence of the training process is accelerated in practice by applying the FP-BP iteration in batches of tsamples at a time, for a moderate value tin the order of few hundreds. This also helps to overcome the memory bandwidth constraints of current computer architectures, by turning training into a computebound process. On the negative side, augmenting the batch size may affect the convergence and accuracy of the training process, often requiring a complex and application-dependent tuning of the learning rate, which needs to be dynamically adjusted as the training process evolves [36]. 2.2. Convolutional neural networks A DNN is composed of a number of “neurons” organized into layers, with each neuron contributing to the output with a particular intermediate computation. In CNNs, the FP stage for a convolution layer (conv) comprises a convolution operator that applies a collection of filters Fto an input Ito produce the output O: O=conv(F,I). Let us consider that Fconsists of knfilters (or kernels) of dimension kh×kw×ci, where kh×kwspecify the dimensions of the (2D) filter and cistands for the number of input channels.1Fur- thermore, assume the layer receives an input tensor Icomposed of tsamples of dimension hi×wi×cieach; and produces an output tensor Owith toutputs of size ho×wo×kneach. Then, each of the knindividual filters in this layer combines a (sub)tensor of the inputs, with the same dimension as the filter, to produce a single scalar value (entry) in one of the knoutputs. By repeatedly applying the filter to the whole input in a sliding window manner (and with a certain vertical/horizontal stride svand sh), the convolution operator produces the complete entries of this single output; see [30]. Assuming vertical/horizontal paddings given by pvand ph, the output dimensions become ho=(hi−kh+2pv)/sv+1 1Unless otherwise explicitly stated, in the following algorithms and data structures we adopt a generalization of the Fortran memory storage convention for multidimensional arrays (tensors) where the entries are stored in consecutive positions in memory starting from the leftmost indices. 241
S. Barrachina, M.F. Dolz, P.S. San Juan et al. Journal of Parallel and Distributed Computing 167 (2022) 240–254 Table 1 Dimensions of tensor operands for the convolution O =conv(F, I)without and with the im2col transform (top and bottom, respectively). In the latter case, the convolution is performed as the gemm C=A ·B, where C≡O, A ≡F, and B =im2col(I). In this table, for simplicity we assume that sv=sh=1andpv=ph=0. Stage OFI FP ho×wo×kn×tk h×kw×ci×knhi×wi×ci×t BP (∂O/∂ I)hi×wi×ci×tk h×kw×ci×knho×wo×kn×t BP (∂O/∂ F)kh×kw×ci×knho×wo×kn×th i×wi×ci×t Stage CAB FP kn×(ho·wo·t)kn×(kh·kw·ci)(kh·kw·ci)×(ho·wo·t) BP (∂O/∂ I)(kh·kw·ci)×(ho·wo·t)kn×(kh·kw·ci)kn×(ho·wo·t) BP (∂O/∂ F)kn×(kh·kw·ci)kn×(ho·wo·t)(kh·kw·ci)×(ho·wo·t) L1: for it=0,...,t−1 L2: for ic=0,...,ci−1 L3: for iw=0,...,wo−1 L4: for ih=0,...,ho−1 c=ih+iw·hi+it·wi·hi L5: for ikw =0,...,kw−1 L6: for ikh =0,...,kh−1 r=ikh +ikw ·kh+ic·kw·kh B[r][c]=I[ih·s+ikh][iw·s+ikw][ic][it] Fig. 1. Algorithm for the im2col transform. The actual implementation eliminates some of the loop invariants inside Loops L4 and L6 to reduce the indexing arithmetic overhead. and wo=(wi−kw+2ph)/sh+1. The top part of Table 1displays the dimensions of the tensor operands involved in a convolution operator in the three stages of DNN training: FP, BP-GC and BPWU; see [7]for details. 2.3. Convolution operators via gemm: the im2col in FP In modern computer architectures, the performance of a direct realization of the convolution operator is constrained by the memory bandwidth, delivering only a fraction of the processor peak floating-point throughput. In practice, higher performance can be attained via an indirect (or gemm-based) approach that casts this operator in terms of a matrix multiplication, as explained next. Concretely, the im2col transform [10], applied to the convolution operator appearing in the FP stage, transforms the input tensor I into an augmented matrix Bso that the output of the application of the convolution O =conv(F, I)can be obtained from the gemm: C=A·B=A·im2col(I), where C≡O →kn×(ho·wo·t)is the output tensor viewed as an m ×nmatrix, with m =knand n =ho·wo·t; A ≡F→kn×(kh· kw·ci) =m ×kcontains the filters; and B →(kh·kw·ci) ×(ho· wo·t) =k ×nresults from applying the im2col transform to the input tensor Iaccording to the filter dimensions and strides (kh, kw, sv, sh). Fig. 1shows the algorithmic realization of the im2col transform. Fig. 2depicts graphically the transformation of the convolution operator into a gemm realized via the im2col transform. The use of the “reshape” operator A ≡Reshape(F)there re-arranges the input 4D filter tensor Fas the 2D matrix A. In addition, the reshape followed by a transpose O ≡Reshape(C)T(1,2,0,3), where the superindex (1, 2, 0, 3)specifies the permutation applied to the dimensions of Reshape(C), re-organizes the resulting Cmatrix back into the 4D output tensor O. In general, the FP stage of a convolution layer using the im2col transform can be represented as the computational graph in (the blue parts of) Fig. 3. The nodes in that graph represent the kernels (gemm and element-wise addition), while the edges are tagged with the corresponding transforms (im2col,Reshape, and transpose). We also include the model biases (b), as a vector of length kn. 2.4. The col2im/im2col in BP The operations in BP for a convolution layer include the computation of gradients of the output with respect to the inputs (∂O/∂ I), filters (∂O/∂ F), and biases (∂O/∂b), as explained next: •To compute the downstream gradient with respect to the inputs (∂O/∂ I), it is necessary to “reverse” the operations in the FP stage using the upstream gradient (∂O/∂ O), as shown in (red in) the top left branch of the computational graph in Fig. 3. This computation can be realized using a gemm involving ATand ∂O/∂C, followed by a col2im operator applied to the result: ∂O/∂ I=col2im(AT·∂O/∂C), where ∂O/∂ I→(hi×wi×ci×t)is the tensor resulting from the application of col2im (considering the parameters kh, kw, sv, sh) to the result of the matrix multiplication of the transposed filters AT≡FT→(kh·kw·ci) ×knwith the upstream gradient ∂O/∂C→kn×(ho·wo·t). Basically, the col2im transform, given in Fig. 4, reverses the effect of im2col, except for the fact that col2im accumulates several partial results on the same 4D output coordinates. •The downstream gradient with respect to the filters (∂O/∂ I) is computed via the gemm: ∂O/∂ F=Reshape(∂ O/∂C·BT), where ∂O/∂ F→(kh×kw×ci×kn)is the 4D reshaped tensor resulting from the output 2D tensor from the gemm on the upstream gradient ∂O/∂C→kn×(ho·wo·t), and BT≡ im2col(I)T→(ho·wo·t) ×(kh·kw·ci); see middle left graph branch in (red in) Fig. 3. Here Bis the same augmented matrix that resulted from applying the im2col transform with respect to the inputs in the FP stage. In consequence, provided all the augmented matrices assembled in the convolution layers (one per layer) during FP were stored, they can be re-used at this point by operating on their transpose. However, this requires a large amount of memory, which can easily exceed the memory capacity of a computer node for CNNs with many layers. •Finally, the downstream gradient with respect to the biases (∂O/∂b) is straight-forward to compute by summing the rows of the (2D tensor) transformed upstream gradient ∂O/∂C(see bottom left graph branch in red in Fig. 3), yielding a bias update vector of length kn. 3. Efficient realization of convolution operators via BLIS GEMM The previous section exposes that the gemm is a key kernel for the efficient realization of the convolution. In this section, we re- 242
S. Barrachina, M.F. Dolz, P.S. San Juan et al. Journal of Parallel and Distributed Computing 167 (2022) 240–254 Fig. 2. Convolution operator via the im2col transform for FP. Fig. 3. Computational graph of the convolution layer using the im2col transform. From left to right, the flow denoted in blue corresponds to the FP stage. The inputs are the activations from the previous layer (I), the filters (F), and the biases (b). From right to left, the flow in red specifies the operations for the BP stage that distribute the upstream gradient (∂O/∂ O) back to the inputs (∂O/∂ I), filters (∂O/∂ F), and biases (∂O/∂b). L1: for it=0,...,t−1 L2: for ic=0,...,ci−1 L3: for iw=0,...,wo−1 L4: for ih=0,...,ho−1 c=ih+iw·hi+it·wi·hi L5: for ikw =0,...,kw−1 L6: for ikh =0,...,wh−1 r=ikh +ikw ·kh+ic·kw·kh ∂O/∂ I[ih·s+ikh][iw·s+ikw][ic][it]+=(AT·∂O/∂C)[r][c] Fig. 4. Algorithm for the col2im transform. The actual implementation eliminates some of the loop invariants inside Loops L4 and L6 to reduce the indexing arithmetic overhead; for simplicity, this is not shown in the algorithm. L1: for jc=0,...,n−1in steps of nc L2: for pc=0,...,k−1in steps of kc B(pc:pc+kc−1,jc:jc+nc−1)→Bc// Pack into Bc L3: for ic=0,...,m−1in steps of mc A(ic:ic+mc−1,pc:pc+kc−1)→Ac// Pack into Ac C(ic:ic+mc−1,jc:jc+nc−1)+= Ac·Bc// Macro-kernel Fig. 5. High performance implementation of gemm in BLIS. Ac, Bcdenote buffers that are involved in data copies. For simplicity, we consider that m, n, kare integer multiples of mc, nc, kc, respectively. view in some detail the open implementation of this kernel in the BLIS framework, as a preliminary step to illustrate how to integrate the convolution operators appearing in the FP-BP iteration inside the BLIS gemm. 3.1. BLIS: open and portable kernels for dense linear algebra Consider the gemm operation C+= A ·B, where C→m ×n, A →m ×k, and B →k ×n. BLIS implements this kernel (as well as any variant with transposed Aand/or B) as three nested loops around a macro-kernel plus two packing routines; see Fig. 5. BLIS decomposes the macro-kernel into two-three additional loops plus a micro-kernel; see [26]for details. There are a few key points in BLIS gemm that are worthy of being highlighted: •The loop ordering, together with the packing routines and a proper selection of the loop strides nc, kc, mcthat matches the processor cache configuration, orchestrates a regular pattern of data transfers through the memory hierarchy [33,21]. •All routines are encoded in plain C except for a small component inside the macro-kernel, known as the micro-kernel, which is vectorized using either architecture-dependent assembly instructions or vector intrinsics [33]. This enhances portability as porting all the BLIS library to a particular processor architecture only needs to develop an efficient realization of that component for the target processor, and to adjust the 243
S. Barrachina, M.F. Dolz, P.S. San Juan et al. Journal of Parallel and Distributed Computing 167 (2022) 240–254 values for nc, kc, and mc, to the processor cache/memory configuration. •The loops of the gemm kernel to be parallelized can be selected at execution time. The multi-threaded parallelization of the BLIS gemm kernel has been previously analyzed for conventional multicore processors [34], modern many-threaded architectures [29], and low-power (asymmetric) ARM-based processors in [8]. •The purpose of the packing routines is to arrange the elements of Aand Binto Acand Bc, respectively, so that the elements of these buffers are accessed with unit stride when executing the micro-kernel [17]. In practice, provided mis large enough, the cost of the packing for Bcis negligible compared with the number of flops performed inside Loop L3. (A similar reasoning applies to the overhead due to the packing for Ac.) As we argue in the following, the packing routines are particularly important for our implementation of the convolution operator. 3.2. Integration of the im2col transform in FP inside BLIS gemm In [26], we proposed to integrate the im2col transform into the packing of Bonto the buffer Bcthat occurs within BLIS.2For this purpose, during the execution of the gemm kernel, the buffer Bc is directly constructed from the contents of the input tensor I, instead of using the augmented matrix B, which is never explicitly assembled. In the following, we will refer to our solution as an indirect convolution via the convgemm operator: O=convgemm(F,I). This solution presents three key advantages: •Reduced workspace: We avoid the use of the large workspace associated with the explicit assembly of the large augmented matrix B →(kh·kw·ci) ×(ho·wo·t), as the only “additional” storage that is needed is the relatively small buffer for Bc →kc×nc, which in any case was already necessary in the gemm kernel. (In case the augmented matrices are explicitly assembled and preserved for the BP stage, the requirements grow linearly with the number of convolution layers.) This is especially important for DNN inference, which only involves the FP stage and is often performed in memory-constrained devices, but not so much for DNN training. •High performance: As argued earlier, the memory access cost associated with the packing of Bcis well amortized with the flops that are performed in the innermost loops of the BLIS gemm. Therefore, the overhead of implicitly applying the im2col transform can be expected to be low. •Portability: The approach has the additional advantage that the only change that is needed in the BLIS gemm is to replace the original packing routine for Bcwith a procedure that reads (and packs) the second input operand for the matrix multiplication directly from the input tensor. There is no need to modify the routine that performs the packing onto Ac. More importantly, there is no need to change the microkernel, which enhances the portability of our solution: the only part that is modified is encoded in C and depends on a small number of architecture-dependent parameters that are adjusted during the process of porting BLIS. The parameters that define the filter dimensions are “embedded” within the 2The BLIS-based convgemm operators are available at https://gitlab .com / comtacts /convgemm, under a GNU General Public License v3.0. L1: for jr=0,...,nc−1in steps of nr i=0 L2: for ps=0,...,kc−1 ic=(pc+ps)/(kh·kw) ikw =((pc+ps)mod (kh·kw))/kh ikh =((pc+ps)mod (kh·kw)) mod kh L3: for js=0,...,nr−1 it=(jc+jr+js)/(ho·wo) iw=(( jc+jr+js)mod (ho·wo))/ho ih=(( jc+jr+js)mod (ho·wo)) mod ho Bc[i][ jr]=I[ikh +ih·s][ikw +iw·s][ic][it] i=i+1 Fig. 6. Algorithm for packing Iinto Bcwhile simultaneously applying the im2col transform. The indices (pc, jc)correspond to the coordinates of the top-left entry for the block of matrix B =im2col(I)that is packed; see Fig. 5. as well as parallelizes the outermost loop using an OpenMP parallel for construct. dimensions of the resulting matrix and, therefore, require no specific optimization. The algorithm in Fig. 6illustrates how to pack the corresponding entries of the input tensor Iinto the buffer Bcduring the execution of the BLIS gemm kernel in Fig. 5, while simultaneously performing the im2col transform. The algorithm packs the kc×nc block of matrix Bstarting at row pcand column jcinto the buffer Bc, reading the corresponding entries directly from the input tensor I. 3.3. Integration of the col2im transform in BP inside BLIS gemm The downstream gradient with respect to the inputs, ∂O/∂ I, can be obtained by applying the col2im transform to the result of multiplying ATwith ∂O/∂C: ∂O/∂ I=col2im(AT·∂O/∂C). Therefore, if explicitly built, the result of this matrix multiplication, C=AT·∂O/∂C→(kh·kw·ci) ×(ho·wo·t), would consume the same amount of memory as the augmented matrix Bproduced by the im2col transform. To tackle this, we have designed a deconvgemm operator that integrates the col2im transform into the BLIS realization of gemm while accumulating the results in the actual output matrix: ∂O/∂ I=deconvgemm(AT,∂O/∂C), without explicitly building the intermediate matrix C. Unfortunately, for the col2im case we cannot leverage the strategy proposed for the convgemm operator, which integrated the transform inside one of the existing packing routines. The reason is that the realization of gemm in BLIS writes its output matrix directly into memory from the microkernel, without any packing/unpacking of the data; see subsection 3.1. Therefore, to perform the col2im transform inside the BLIS gemm, we had to modify this kernel to operate with an actual buffer Cc, of size m ×nc, as well as develop an unpacking procedure that stores the data from Cc onto the output 4D tensor ∂O/∂ Iwhile simultaneously performing the col2im transform during this process. This unpacking takes place at the end of each iteration of loop L1 in Fig. 5, once the corresponding m ×ncpanel of the gemm output matrix has been computed. The algorithm in Fig. 7illustrates the unpacking procedure. The main advantage of the deconvgemm operator lies in the memory savings that result from avoiding the explicit creation of the intermediate matrix C. Concretely, the memory needed to perform this operation decreases from (kh·kw·ci) ×(ho·wo·t), when using gemm followed by col2im, to the workspace Cc→m ×nc= 244
S. Barrachina, M.F. Dolz, P.S. San Juan et al. Journal of Parallel and Distributed Computing 167 (2022) 240–254 L1: for r=0,...,nc−1 i=0 it=(jc+r)/(ho·wo) iw=(( jc+r)mod (ho·wo))/ho ih=(( jc+r)mod (ho·wo)) mod ho L2: for s=0,...,m−1 ic=s/(kh·kw) ikw =(smod (kh·kw))/kh ikh =(smod (kh·kw)) mod kh ∂O/∂ I[ikh +ih·s][ikw +iw·s][ic][it]+ = Cc[i][r] i=i+1 Fig. 7. Algorithm for unpacking Ccinto ∂O/∂ Iwhile simultaneously applying the col2im transform. The index jccorresponds to the first column of the block of matrix Cthat is unpacked; see Fig. 5. (kh·kw·ci) ×ncfor deconvgemm. In addition, the unpacking algorithm is encoded in C, depends only on the cache parameter nc, and does not affect the coding of the micro-kernel, having thus no impact on the portability of the solution. Regarding performance, the unpacking can introduce some overhead, depending on the convolution parameters, as this mechanism may evict some data for Acand/or Bcfrom the cache hierarchy. A second source of performance inefficiency appears for the deconvgemm operator because the unpacking of Ccinto ∂O/∂ Icannot be parallelized due to data dependencies between iterations, as different positions of Ccmay need to be accumulated into the same entries of ∂O/∂ I.3In summary, the utilization of the deconvgemm operator poses a trade-off between performance and memory consumption. 3.4. Integration of the im2col transform in BP inside BLIS gemm The computation of the downstream gradient with respect to the filters, ∂O/∂ F, requires a gemm where the second matrix operand corresponds to the transposed result of the im2col transform on the input tensor I, that is, ∂O/∂ F=Reshape(∂ O/∂C·BT)=Reshape(∂ O/∂C·im2col(I)T). Although this operation resembles that performed by the convgemm operator in FP, it differs in the fact that the result of im2col transform appears transposed in the gemm operation. In the next two subsections, we describe two options or alternatives to deal with this. 3.4.1. Re-indexing To tackle the aforementioned variant of the convgemm operator, we propose a novel “re-indexing” algorithm (Reindex) that transforms the input 4D-tensor Iinto Iso that im2col(kh,kw,sv,sh)(I)T≡im2col(kh=ho,kw=wo,sv=ho,sh=wo)(I). Concretely, the Reindex transform re-orders the dimensions hi and wiof I(that is, the rows and columns of all image channels in the batch) taking into account sv, sh, ho, and woto obtain I; see the algorithm in Fig. 8. Fig. 9illustrates the details of this transform using the re-indexing of an example image Iof size hi=wi=7 padded with pv=ph=1, which has to be convolved with a filter of size kh=kw=3using a stride of sv=sh=2in 3The overhead due to the unpacking operation depends on the convolution parameters, which are different depending on the layer and model. For many CNNs, these parameters vary significantly, and so are the case for the overheads. To quantify this overhead, we have measured the execution time of the unpack operation on the ResNet34 with Imagenet on 1node with 1, 4, 8, and 16 threads. These overheads were 3.88%, 4.04%, 4.81%, and 5.66% of the total time, respectively. L1: for it=0,...,t−1 L2: for ic=0,...,ci−1 L3: for ih=0,...,h o−1 i h=ih/ho+(ihmod ho)·sv L4: for iw=0,...,w o−1 i w=iw/wo+(iwmod wo)·sh I[it][ic][ih][iw]=I[it][ic][i h][i w] Fig. 8. Algorithm for the Reindex of Ito obtain Iaccording to sv, sh, ho, and wo in a conv layer. This transform results into a memory-bound operation which can be accelerated using an OpenMP parallel for construct in loop L1, provided the batch size is large enough. This algorithm uses the C convention for multidimensional arrays: the entries of the tensors are stored in consecutive positions in memory starting from the rightmost indices. the FP stage. As illustrated by the colored cells, the coordinates in Ithat are two units apart (sv=sh=2), are unraveled (and repeated) in Isuch that there appear 3 ×3clusters of size 4 ×4. In consequence, this matches the number of clusters with the filter size kw=kw=3 and the cluster size with the output dimensions ho=wo=4. Furthermore, this allows us to leverage our convgemm operator using ∂O/∂Cas a filter that is convolved on the strides sv=ho=4 and sh=wo=4with the transformed Ito obtain ∂O/∂ F. In sum, the Reindex transform combined with the convgemm operator becomes: ∂O/∂ F =Reshape(convgemm(sv=ho,sh=wo)(∂ O/∂C,I)) =Reshape(convgemm(sv=ho,sh=wo)(∂ O/∂C,Reindex(I))). It is important to note that, even though both the re-indexed tensor Iand the augmented matrix BT≡im2col(I)Trequire a workspace of size (ho·wo·t) ×(kh·kw·ci), the re-index algorithm has a more favorable memory access pattern than the im2col transform, which helps in reducing the cost of calculating ∂O/∂ F. Also, this solution inherits the high performance and portability advantages derived from the use of the convgemm operator. At this point, it is also worth reminding that the augmented matrices appearing in the convolution layers of the FP stage are never assembled thanks to the integration of the im2col transform within the BLIS realization of gemm. In contrast, in this first option we assemble explicitly the augmented tensor Iinvolved in the BP stage. Unlike the scenario in FP though, this matrix does not participate in subsequent layers during the BP stage and, therefore, the corresponding workspace can be re-utilized (for subsequent layers) after the gemm operation. In practice, a single workspace of this size is affordable for most current computer nodes, especially in a training scenario using a large HPC facility. 3.4.2. Transpose operand in gemm As an alternative option to carry out the computation of the downstream gradient with respect to the filters, ∂O/∂ F, we implemented a transposed version of the convgemm operator such that: ∂O/∂ F=Reshape(∂ O/∂C·im2col(I)T) =convgemm_trans(∂ O/∂C,I). To achieve this, we developed a packing routine for the gemm input matrix that packs im2col(I)Tdirectly into Bc, reading the corresponding entries directly without ever assembling (or transforming) Iexplicitly. Fig. 10 shows a simplified pseudocode of the packing routine. The algorithm packs the corresponding nc×kc block of matrix Bstarting at row jcand column pc. This alternative approach based on a “transposed” convgemm operator maintains all the advantages of the convgemm operator 245
S. Barrachina, M.F. Dolz, P.S. San Juan et al. Journal of Parallel and Distributed Computing 167 (2022) 240–254 Fig. 9. Example of re-index of Ito obtain Iassuming a conv layer with hi=wi=7, ho=wo=4, kh=kw=3, pv=ph=1and sv=sh=2. In this example, Iis padded with pv=ph=1(see border cells) prior applying Reindex (as these padding values were used in the FP). L1: for jr=0,...,nc−1in steps of nr i=0 L2: for ps=0,...,kc−1 it=(pc+ps)/(ho·wo) iw=((pc+ps)mod (ho·wo))/ho ih=((pc+ps)mod (ho·wo)) mod ho L3: for js=0,...,nr−1 ic=(jc+jr+js)/(kh·kw) ikw =(( jc+jr+js)mod (kh·kw))/kh ikh =(( jc+jr+js)mod (kh·kw)) mod kh Bc[i][ jr]=I[ikh +ih·s][ikw +iw·s][ic][it] i=i+1 Fig. 10. Algorithm for packing Iinto Bcwhile simultaneously applying the im2col transform and transposing the input matrix I. The indices (jc, pc)correspond to the coordinates of the top-left entry for the block of matrix B =im2col(I)Tthat is packed; see Fig. 5. The actual realization of this algorithm eliminates some loop invariants and integer arithmetic to reduce the overhead, as well as parallelizes the outermost loop using an OpenMP parallel for construct. described in Section 3.2: reduced workspace, high performance, and portability. 4. Integration with PyDTNN and experimental validation In this section, we describe the integration of our new convgemm-based realizations of the convolution operators in Py- DTNN, a framework for distributed training of DNNs on clusters of computers. In addition, we demonstrate the benefits of the proposed approach, in comparison with one based on the explicit im2col/col2im transforms, for the distributed training of representative CNNs and datasets. 4.1. Overview of PyDTNN PyDTNN4is a lightweight framework for distributed training of DNNs on clusters of computers that has been designed as a research-oriented tool with a low learning curve. PyDTNN presents the following appealing properties: •Flexible: PyDTNN considers extensibility (and, to a certain extent, simplicity) as a first-class citizen to facilitate that users can customize the framework to prototype their research ideas. •Ample functionality: PyDTNN covers DL training (and inference) for a significant part of the most common DNN models: multi-layer perceptrons (MLPs), convolutional neural networks (CNNs), residual networks (ResNets), and transformers for natural language processing. In practice, PyDTNN provides training and validation accuracies on par with those attained by Google’s TensorFlow [2]. 4The PyDTNN framework is available at https://github .com /hpca -uji /PyDTNN/, under a GNU General Public License v3.0. •High performance: PyDTNN exploits data parallelism (DP) [4], relying on specialized message-passing libraries for efficient communication, and kernels from high performance multithreaded libraries for the major computational operations in CPU and GPUs. In particular, when the target cluster is equipped with NVIDIA’s GPUs, PyDTNN leverages cuDNN, cuBLAS, and NCCL to deliver parallel performance that is competitive with that of TensorFlow. •User-amiable interface: PyDTNN is developed in Python and offers an interface akin to that exposed by popular DL packages such as Keras. While we recognize that PyDTNN lacks the level of maturity and the complete functionality of production-level frameworks, such as TensorFlow or PyTorch, we honestly believe that PyDTNN offers a more accessible and easier-to-customize solution, which allows us to integrate and validate the benefits of our proposed approach in the distributed training of some state-of-the-art CNNs. In any case, the proposed algorithms are orthogonal to the training framework and, as part of future work, we plan to integrate them in more sophisticated frameworks. In a previous work [2], we demonstrated that PyDTNN delivers training/validation accuracy as well as convergence rates similar to those attained by TensorFlow. The techniques, operators, and transforms introduced in this paper do not modify the arithmetic operations performed by the convolution operators when performed via the explicit im2col/col2im transforms, only the order in which they are carried out. The small differences in the rounding errors of individual convolutions, due to this distinct order, may render slight variations in the training/validation accuracy and the convergence rate for an iterative process based on SGD (especially when combined with non-linear functions such as ReLU). We note, however, that these differences do not imply that the accuracy/convergence metrics offer necessarily worse (nor better) results. 4.2. Distributed training of DNNs Training a DNN is a costly process that is usually performed on distributed high performance platforms. In practice, this tuning is often carried out on a cluster of computer nodes, each equipped with one or more multi-core processors (in some cases enhanced with graphics accelerators). Most distributed DNN training frameworks exploit DP, distributing the input data among the cluster nodes across the batch dimension, while replicating the DNN model in all nodes [4]. The DP scheme exhibits linear scalability with the number of nodes provided 1) the batch size can be increased linearly with the number of nodes; and 2) the full model fits in the node memory. Distributed DP training requires a few types of (messagepassing) collective communications [9,32]: First, the initial model has to be replicated in all nodes (Broadcast) before the training commences. Second, each FP-BP iteration requires a batch of 246
S. Barrachina, M.F. Dolz, P.S. San Juan et al. Journal of Parallel and Distributed Computing 167 (2022) 240–254 Fig. 11. Dependencies in the DP distributed training scheme. The colored boxes correspond to the computational stages: FP, (BP-)GC, and (BP-)WU; the circles denote the AR exchanges; and the arrows indicate data dependencies. The dashed lines of different colors identify groups of operations that can be overlapped. samples to be distributed (Scatter) among the nodes. Third, during the BP stage, all nodes need to perform a global reduction (Allreduce or AR) of their local weights/biases onto the parameters that define the DNN model [4,7]. Given the large number of FP-BP iterations that are required to train a DNN model and the possibility of overlapping the distribution of the future batches with the FP-BP processing of the current one, the major communication bottleneck lies in the AR operation. Fig. 11 illustrates the data dependencies and AR exchanges appearing in the DP scheme. Note the strict dependencies between adjacent layers of the FP and BP-GC stages, but the possibility of overlapping the latter with the reductions and the BP-WU computations. 4.3. Integration in PyDTNN The efficient integration in PyDTNN of the convgemm operator for the FP (and BP) stage(s) required the implementation of a new module for interfacing the convgemm BLIS-based shared-library, developed in C, from Python using the ctypes library. This module allows passing Numpy arrays directly to the convgemm routine so that it can be seamlessly invoked from the methods for the FP (and BP) stage(s) (for conv layers) in PyDTNN. The versions of PyDTNN that integrate convgemm also parallelize the pad and transpose methods in Numpy by means of Cython OpenMP-parallel routines, which helps to accelerate the execution. The integration of the convgemm operator in the BP stage leverages the same module used for FP with extended support for the Reindex + convgemm approach, in addition to the convgemm_trans and deconvgemm operators. We note that PyDTNN uses a row-major (or C style) memory layout for multidimensional arrays while the convgemm library follows the BLAS convention for column-major (or Fortran style) memory layout. Due to this, the integration also includes the necessary memory layout rearrangements to allow full compatibility between PyDTNN and the convgemm library. 4.4. Experimental validation 4.4.1. Setup The experimental evaluation in this section has been carried out on a cluster platform consisting of 8 nodes, each equipped with two Intel Xeon Gold 5120 processors (14 cores with a nominal frequency of 2.20 GHz), and 190 GiB DDR4 non-uniform memory access (NUMA) RAM, giving each processor 95 GiB of “local” memory. The nodes are interconnected via an Infiniband EDR network with a bandwidth of 100 Gbps. Regarding the software layer, we use Intel Python 3.7.4 to run PyDTNN configured to use Numpy on top of BLIS (version 0.8.0) along with the novel convgemm and deconvgemm routines for the Convolution proposed in this paper. The communication layer used to exploit DP is provided by Intel MPI (version 2019) configured to use the Infiniband network. For the experiments, we consider two configurations: 1) execution on a single node, exploiting multicore parallelism using multiple threads; and 2) execution using several cluster nodes with a single MPI rank and 14 threads per node. The reason to include the multi-node configurations is that varying the number of nodes modifies the relationship between computational and communication costs, which may impact the benefits of our new Convolution operators. Training a DNN is a costly iterative procedure that often requires several epochs, each involving enough “batched” FP-BP passes to process the complete training dataset. To reduce the cost of our tests, we trained the DNN models for a fixed number of 60 FP–BP iterations, and computed the training throughput as the number of samples per batch, multiplied by 60, and divided by the time to perform the test. The fact that we perform the training for several batches, using the same FP-BP process per batch, which does not depend on the numerical values of the batch samples, has an averaging effect on the measurements. In general, for any number of nodes and threads, we observed that the throughput increased from the beginning till it stabilizes after a few seconds (iterations) due to the impact of initialization overhead. To avoid this effect, we measure the first 60 iterations to render this overhead negligible. Raising the batch size can be expected to increase linearly the execution time and memory requirements. At the same time, augmenting the batch size affects the convergence of training, often asking for an application-dependent tuning of the learning rate, which needs to be dynamically varied as the training process evolves. This is a complex technique that requires special knowledge and care, but it is out-of-scope for our work [36]. In general, we set the batch size to t=64 per cluster node. We consider this is a reasonable value that offers a good balance between multi-threaded performance and small numerical distortion of the convergence rate. Increasing the batch size in general raises the cost of the explicit im2col/col2im transforms, and therefore should augment the advantage of our convgemm/deconvgemm alternative. Also, in those cases where the memory requirements of the baseline approach exceeded the node capacity, affecting performance (due to disk swapping), the batch size was accordingly decreased. Concretely, for Resnet34 with ImageNet, the batch size was set to 24, and for DenseNet121 and GoogLeNet with ImageNet, to 16. To analyze the parallel scalability of the proposed solutions with respect to the naive im2col approach, we train four representative CNN models (VGG16, ResNet34, DenseNet121, and GoogLeNet) on two datasets (CIFAR-10 and ImageNet), using the SGD optimizer and a learning rate of 0.01 for VGG16, DenseNet121, and GoogLeNet, and 0.1 for ResNet34. VGG16 is a CNN that features a 16-layer network architecture where the convolutional layer depth (number of filters) is gradually increased on a set of small (3 ×3) filters [28]. ResNet34 is a 34-layer CNN belonging to the residual-based network family proposed by He et al., which introduces residual layer functions intending to ease the training of very deep CNNs [16]. Similarly, DenseNet121 is a 121-layer CNN that uses direct connections between any two layers with the same feature-map size, yielding to consistent improvements in accuracy with growing number of parameters, without signs of performance degradation or overfitting [19]. Finally, the GoogLeNet model is a 22-layer CNN that is carefully crafted to allow increasing the depth and width of the network while keeping the computational bud- 247
S. Barrachina, M.F. Dolz, P.S. San Juan et al. Journal of Parallel and Distributed Computing 167 (2022) 240–254 Table 2 PyDTNN variants for the computation of Oin the FP stage, and ∂O/∂ F, ∂O/∂ Iin the BP stage of a conv layer relying on the Reindex, convgemm/convgemm_trans, and deconvgemm operators. Variant FP (O)BP(∂O/∂ F)BP(∂O/∂ I) base im2col +gemm im2col +transposedgemm gemm +col2im rdx convgemm Reindex +convgemm cgt convgemm_transcgt+pm cgt+dg deconvgemm get constant [31]. The input conv layer in these CNNs is adapted to operate on two different datasets: i) the CIFAR-10 dataset, consisting of 60,000 32 ×32 color images in 10 classes with 50,000 and 10,000 training and test images, respectively [20]; and ii) ImageNet, a dataset comprised of 1.4 M of human-annotated color photographs grouped into 1,000 classes and designed for developing computer vision algorithms [25]. In the second case, the input image size for all the networks has been downscaled to 224 ×224 pixels. 4.4.2. Experiments In this subsection, we assess the performance of the training process using the baseline approach that explicitly builds all augmented matrices via im2col and col2im (referred to hereafter as base) versus four new variants that rely on the convgemm/ deconvgemm operators. All these variants leverage the convgemm routine to compute Oin the FP stage. Furthermore, except for the last variant, they compute ∂O/∂ Iby invoking the BLIS gemm followed by a call to a multi-threaded routine for col2im written in Cython and parallelized with OpenMP. They differ as described next: RDX This implementation leverages the Reindex transform to calculate ∂O/∂ Fin the BP stage; see subsection 3.4.1. CGT This implementation replaces the Reindex transform with an operator based on convgemm_trans; see subsection 3.4.2. CGT+PM This variant uses the same routines as cgt in addition to persistent memory for storing the intermediate matrices required to interface PyDTNN with the external convgemm routines. This implementation aims at reducing the overhead for memory allocation/release time that are intrinsically incurred by the Python runtime (garbage collector), at the expense of yielding a higher memory footprint. CGT+DG This variant leverages the same routines as cgt except that it replaces the indirect gemm + col2im approach to compute ∂O/∂ Iby the BLIS-based deconvgemm routine. This alternative prevents the allocation of the augmented matrix that has to be passed to col2im, though it might impact performance due to the deconvgemm packing inefficiencies discussed in subsection 3.3. Table 2identifies the specific procedure to calculate O, ∂O/∂ F, ∂O/∂ Ifor base and each of the four variants. In Figs. 12 and 13, we report the performance of the training procedure using the previous realizations on a single node and on a cluster, respectively, and measured in samples/s for the selected CNNs and the two datasets. The number at the top of each bar in the performance plots specifies the speedup of the new convgemm-based variants with respect to the base reference. Furthermore, the horizontal line and the number above the base bar respectively represent the peak throughput and speedup that could be achieved if the time costs related to the im2col transform were negligible. Both im2col followed by gemm and convgemm perform the same number of floating-point operations. Given that gemm is a highly optimized operation, its execution without the overhead imposed by the im2col transform offers a practical theoretical bound for what we could expect to achieve with convgemm if we can totally hide the overhead of the intrinsic re-organization of the data during the implicit (blocked) im2col that is done during packing. Focusing on the performance results on a single node (see Fig. 12), we note that the rdx, cgt, and cgt+pm variants outperform, in most cases, the base approach. For ResNet34 on Imagenet with 14 threads, and for GoogLeNet on Imagenet with 8 and 14 threads, there is not enough work for all the threads, which negatively affects the performance of the base approach. Thus, to keep the comparison fair, we do not report the gains of the other variants for these scenarios in the next discussion. By hiding the costs of the im2col transform within the gemm realization, the rdx variant improves the throughput by a factor that ranges from 1% to 11%, in most of the cases being close to the peak acceleration indicated by the horizontal line on the top of the base baseline. For CIFAR-10, we also detect that the cgt variant is slightly more competitive than rdx. We explain this effect due to the different loop orderings in the convgemm and convgemm_trans operators used in rdx and cgt respectively, which affect the performance depending on the input operand sizes. On the other hand, higher performance benefits can be attained by adding the persistent memory mechanism (variant cgt+pm) that prevents the Python runtime from releasing memory at execution time. In this case, the speedups range from 7% to 24%, yet they are far from yielding good strong scalability with the number of threads. (We remind that the batch size remains constant per node.) In particular, in a NUMA system, cgt+pm is only effective if the processor can access sufficient local RAM. Unfortunately, the memory requirements of DenseNet121 and GoogLeNet on ImageNet exceed the available local RAM in the target platform. In contrast, the cgt+dg variant outperforms base on single-threaded executions but, given the sequential unpacking (due to data dependencies) in the deconvgemm routine, it is only competitive on large models/datasets. However, in such cases rdx/cgt are still the recommended options. Regarding the results in multi-node scenarios (see Fig. 13), we detect similar trends for the new convgemm-based variants, with cgt+pm being the most efficient option except for DenseNet121 and GoogLeNet on ImageNet, where the highest throughput is delivered by rdx. It is also important to remark that the throughput scaling attained in the multi-node scenario is more favorable than in a single node. This is due to the linear scaling of the workload (local batch) with the number of processes/nodes (weak-scaling). In the multi-threaded scenario, the batch size remains constant while increasing the number of threads (strong-scaling), so increasing the parallel resources reports speedups (with respect to a single thread) that are in the range [1.39, 2.79]for 4 threads, [1.48, 3.72]for 8 threads, and [1.51, 4.34]for 14 threads. Fig. 14 shows the maximum training memory consumption of the convgemm-based variants on a single node and distinct numbers of threads.5(The memory consumption per node for the multi-node configurations should show no differences.) For CIFAR- 10, we find that rdx, cgt and cgt+dg produce memory savings ranging between 10% and 40% with respect to base, and that cgt is the most favorable variant. Contrarily, the use of persistent memory (cg+pm) largely exceeds the memory requirements of the base 5The memory consumption measurements were retrieved via the getrusage function from the resource Python module, which internally performs the getrusage POSIX system call. The routine getrusage was invoked twice, passing the RUSAGE_SELF and RUSAGE_CHILDREN arguments, respectively, and summing up the ru_maxrss statistic to account for the largest amount of physical memory occupied by the process and its children. 248