Hardware Design for AI Lecture 1 Acknowledgements: Some slides are taken from a course by Prof. Song Han (MIT) 1 Why hardware design for AI? Let’s take image classification application as case-study (Frames Per Second) C = Conv2D, M = MaxPooling2D, F = Flatten, D = Dense, DR = Dropout, BN = BatchNormalization, DC = DepthwiseConv2d, AP = AveragePooling2D, GA = GlobalAveragePooling2D Results obtained on AMD-Xilinx ZCU104 board Image Classification 3 AI Task Example: Image Recognition IIT JODHPUR 4 Adapted from Scale-sim Tutorial slides (ASPLOS 2021) Supervised Learning: Image Classification Unsupervised Learning: Image Classification 5 Small/Large Language Model (SLMs/LLMs) 6 Reinforcement Learning 7 AI Training & Inference 8 Different Hardware Platforms 1. CPU (Central Processing Units) 2. GPU (Graphics Processing Units) 3. TPU (Tensor Processing Units) 4. NPU (Neural Processing Units) 5. FPGAs 9 Comparative Evaluation of Different Devices Adapted from Hao et al., “Enabling Design Methodologies and Future Trends for Edge AI: Specialization and Co-design”, IEEE Design & Test, 2021 10 CPU & Instruction Set Architecture (ISA) 11 12 Graphics Processing Unit (GPU) 13 GPU v/s CPU 14 Hardware Accelerator Accelerator 15 Neural Network: Getting inspired from our brain Neural Networks is a type of Machine learning algorithm inspired from structure of brain. 16 AI Hardware Example 1 17 AI Hardware Example 2 18 AI Hardware Example 3 19 AI Hardware Example 4 20 AI Hardware Example 5 21 AI Hardware Example 6 22 AI Chip Vendors https://www.forbes.com/sites/karlfreund/2024/02/13/ai-chip-vendors-a-look-at-whos-who-in-the-zoo-in2024/?sh=3fb71410f6ed 23 Course Evaluation Scheme This is the tentative scheme: Minor 24 OPEN-NOTES Major 44 OPEN-NOTES Lab Assignments 12 For offline students, maximum group size=2, For executive students, maxim size of group=3 Quiz/Mini CourseProject 08 (2 quizzes for offline students) Single Viva for ONLINE students For Executive Mtech-AI students: A mini course-project could be done in a group of maximum 3 people. Course-Project 12 For offline students, maximum group size=2, For executive students, maxim size of group=3 24 Hardware Design for AI Lecture 02 Many slides are taken from Prof. Eric Eaton’s (UPenn) course materials 1 Machine Learning (ML) 2 Supervised Learning Training data are labeled, i.e. the output class of all training data are given In supervised learning, the algorithm is given labeled data to train on. The labeled data acts as a teacher, providing the algorithm with examples of what the correct output should be. Supervised learning is typically used when the goal is to make accurate predictions on new, unseen data. This is because the algorithm has access to labeled data, which helps it learn the underlying patterns and relationships between the input and output data. 3 Machine Learning: 2 major applications Classification uses an algorithm to accurately assign test data into specific categories. It recognizes specific entities within the dataset and attempts to draw some conclusions on how those entities should be labeled or defined. Common classification algorithms are linear classifiers, support vector machines (SVM), decision trees, k-nearest neighbor, and random forest. Regression is used to understand the relationship between dependent and independent variables. It is commonly used to make projections, such as for sales revenue for a given business. Linear regression, logistic regression, and polynomial regression are popular regression algorithms. 4 Machine Learning: 2 major applications Classification uses an algorithm to accurately assign test data into specific categories. It recognizes specific entities within the dataset and attempts to draw some conclusions on how those entities should be labeled or defined. Common classification algorithms are linear classifiers, support vector machines (SVM), decision trees, k-nearest neighbor, and random forest. Regression is used to understand the relationship between dependent and independent variables. It is commonly used to make projections, such as for sales revenue for a given business. Linear regression, logistic regression, and polynomial regression are popular regression algorithms. Linear Regression 5 Unsupervised Learning Training data are not labeled Output classes must be generated during training Similarity across features of training examples creates different classes Unsupervised learning is like a treasure hunt — you’re given a map, but it’s up to you to figure out where the treasure is. Unsupervised learning is typically used when the goal is to identify patterns and relationships in data. Unsupervised learning is typically used when working with large datasets where labeling the data may be time-consuming or impractical. 6 Unsupervised Learning 7 Unsupervised Learning: Clustering Technique 8 Unsupervised Learning: Clustering 9 Function Approximation & Sample Dataset 10 ML Problem Formulation: Decision Tree 11 How Learning happens in Decision Trees? Consider two variables: x1 and x2 12 Supervised Learning Example: Decision Tree 13 Supervised Learning Example: Decision Tree 14 Supervised Learning Example: Decision Tree 15 Supervised Learning Example: Decision Tree 16 Algorithm of Decision Tree Construction 17 Algorithm of Decision Tree Construction 18 How to construct an useful Decision Tree from dataset? We want to determine which attribute in a given set of training feature vectors is most useful for discriminating between the classes to be learned. • Information gain tells us how important a given attribute of the feature vectors is. • We will use it to decide the ordering of attributes in the nodes of a decision tree. 19 20 Training Examples: Decision Tree Construction Play Tennis? 21 How to construct an useful Decision Tree from dataset? One challenge is to select the next attribute. 22 How to construct an useful Decision Tree from dataset? 23 Hardware Implementation of Decision Tree What components would be required for the hardware realization of decision tree? Comparators, …….. 24 Hardware realization of decision tree: Pipelined Processor (CPU) IF: Instruction Fetch, ID: Instruction Decode, EX: Execution https://en.wikipedia.org/wiki/Instruction_pipelining 25 Hardware implementation of decision tree inverter Ref: Mario Barbareschi, HARDWARE ACCELERATOR OF DECISION TREE BASED CLASSIFIERS 26 Hardware Design for AI Lecture-03 1 Course Summary so far AI algorithms can be run on any hardware but performance and resource consumption matters! Suited for a particular application CPU GPU Accelerator (custom-silicon) 2 ways to design: a) Hand-coded in hardware language b) use high-level synthesis (beginning from C/C++) 2 Example design: system to compute GCD Algorithm: 3 Illustration of GCD code optimization IR = Intermediate Representation 4 STATE0: when we are reading the inputs STATE1: when we are comparing the inputs STATE2: when we are subtracting the inputs STATE3: when we are checking equality of the intermediate values 5 ML task example: classification ML task example: regression 6 Classification Evaluation Metrics β True positive: An instance for which both predicted and actual values are positive. β True negative: An instance for which both predicted and actual values are negative. β False Positive: An instance for which predicted value is positive but actual value is negative. β False Negative: An instance for which predicted value is negative but actual value is positive. Find accuracy here? as the percentage of correct predictions made by our Accuracy can be defined classification model. 7 Classification Evaluation Metrics 8 Error metrics 9 Intersection over Union (IOU) metric Intersection over Union is a popular metric to measure localization accuracy and compute localization errors in object detection models. 10 Overfitting and Underfitting Overfitting is a phenomenon that occurs when a Machine Learning model is constrained to the training set and not able to perform well on unseen data. That is when our model learns the noise in the training data as well. This is the case when our model memorizes the training data instead of learning the patterns in it. Underfitting on the other hand is the case when our model is not able to learn even the basic patterns available in the dataset. In the case of the underfitting model is unable to perform well even on the training data hence we cannot expect it to perform well on the validation data. This is the case when we are supposed to increase the complexity of the model or add more features to the feature set. Let Y be the actual values of the target variable, and Y^ be the predicted values of the target variable. E[Y^] is the expected value of the predicted values. Here expected value is averaged over all the training data. 11 Epoch: Training iterations In machine learning (ML), an epoch is a single pass of the entire training dataset through an algorithm. It's also known as a training cycle. Overfitting occurs when the model cannot generalize and fits too closely to the training dataset instead. Overfitting happens due to several reasons, such as: The training data size is too small and does not contain enough data samples to accurately represent all possible input data values. Underfitting is a scenario in data science where a data model is unable to capture the relationship between the input and output variables accurately, generating a high error rate on both the training set and unseen data. Underfitting occurs when a model is too simple, which can be a result of a model needing more training time, more input features. 12 Decision Trees: Recap 13 Decision Tree Implementation 14 Random Forest 15 Random Forest It is called a Random Forest because we use Random subsets of data and features and we end up building a Forest of decision trees (many trees). Random Forest is also a classic example of a bagging approach as we use different subsets of data in each model to make predictions. 16 Hardware Implementation of Random Forest Vitis-HLS (from Xilinx) is one of the popular high-level synthesis (HLS) tools Reference: https://oaktrust.library.tamu.edu/bitstream/handle/1969.1/196607 /WANG-FINALTHESIS-2022.pdf?sequence=1 17 Linear Regression: Supervised Learning Mean Squared Error (MSE) Since the Linear Regression algorithm represents a linear relationship between a dependent (y) and one or more independent (y) variables, it is known as Linear Regression. This means it finds how the value of the dependent variable changes according to the change in the value of the independent variable. The relation between independent and dependent variables is a straight line with a slope. 18 Regression: Learning to predict a value from data Linear Regression 19 Regression: Learning to predict a value from data 20 Gradient Descent for Linear Regression A linear regression model can be trained using the optimization algorithm gradient descent by iteratively modifying the model’s parameters to reduce the mean squared error (MSE) of the model on a training dataset. To update θ 1 and θ2 values in order to reduce the Cost function (minimizing RMSE value) and achieve the best-fit line the model uses Gradient Descent. The idea is to start with random θ 1 and θ2 values and then iteratively update the values, reaching minimum cost. Predicted value Actual value π³2 21 Gradient Descent for Linear Regression 22 Hardware implementation of linear regression Consider y = mx + c READY is a status signal which indicates when output is actually available 23 Hardware Design for AI Lecture 04 1 AI task example: Multi-spectral image classification Hyperspectral imaging collects hundreds of images at different wavelengths for the same spatial area. While the human eye has only three color receptors in the blue, green and red, hyperspectral imaging measures the continuous spectrum of the light for each pixel of the scene with fine wavelength resolution, not only in the visible but also in the near-infrared. Let’s say number of spectral bands is B = 224 and the image dimension is N =614×512. System to classify skin patches? Can we identify the important bands in this scenario? Let’s say we can have B as 24 2 Principal Component Analysis (PCA) Algorithm EVD: Eigenvalue decomposition SVD: Singular value decomposition PC: Principal components 3 Example of Eigen Vector Computataion 4 Example of Eigen Vector Computataion …..continued from previous slide… Next we will repeat this process to find the basic eigenvector for λ2=−3. We wish to find all vectors X≠0 such that AX=−3X. These are the solutions to ((−3)I−A)X=0 ……………..(do it yourself)............ 5 Eigen Values and Eigen Vectors We can write the previous equation as below: (A − λI)x = 0, where I is the identity matrix. It gives the homogeneous linear system of equations. The determinant of the coefficient for this linear system of equations should be zero to have a nontrivial solution. Roots of the characteristic equation are the eigenvalues of matrix A. The value of x that leads to (A − λI)v = 0 is called Eigen vector 6 Step 1: Standardize the Data PCA rotates the data to find directions of maximum variance and keeps only the most important ones. 7 Final step of PCA: finding the important variable Let’s suppose that our data set is 2-dimensional with 2 variables x,y and that the eigenvectors and eigenvalues of the covariance matrix are as follows: If we rank the eigenvalues in descending order, we get λ1>λ2, which means that the eigenvector that corresponds to the first principal component (PC1) is v1 and the one that corresponds to the second principal component (PC2) is v2. After having the principal components, to compute the percentage of variance (information) accounted for by each component, we divide the eigenvalue of each component by the sum of eigenvalues. If we apply this on the example above, we find that PC1 and PC2 carry respectively 96 percent and 4 percent of the variance of the data. https://builtin.com/data-science/step-step-explanation-principal-component-analysis 8 Final step of PCA: finding the important variable Continuing with the example from the previous step, we can either form a feature vector with both of the eigenvectors v1 and v2: Discard the eigenvector v2, which is the one of lesser significance, and form a feature vector with v1 only: Discarding the eigenvector v2 will reduce dimensionality by 1, and will consequently cause a loss of information in the final data set. But given that v2 was carrying only 4 percent of the information, the loss will be therefore not important and we will still have 96 percent of the information that is carried by v1. 9 PCA Hardware Implementation nx1 ZMCV = Zero-mean centering vector nx1 1xn nxn The above PCA architecture uses a signal validOut to indicate that outputs including PCAScore, PCACoeff (reordered eigenvectors), and PCALatent (sorted eigenvalues) are ready. PCAScore and PCACoeff are two output vectors of size n × n and 1xn respectively and the PCALatent is a scalar output. 10 PCA Hardware Implementation zero mean centering vector hardware Pipeline Vector element accumulator The critical path of this structure resides in the adder chain, which has pipeline registers to reduce its combinational delay. 11 PCA Hardware Implementation zero mean centering vector hardware Hardware datapath of parallel vector scalar subtractor 12 PCA Hardware Implementation This module has an input databus InVec that takes a row vector of the input matrix at each time unit when the input signal validIn = 1. It stores the entire input matrix before transposing it. After receiving the entire input matrix, the module MatrixTranspose transposes the stored input matrix. Output handshaking signal validOut = 1 indicates that the transposed matrix output is ready. The MatrixTranspose module outputs a row vector of the transposed matrix at each time unit through the databus OutVec. 13 PCA Hardware Implementation Hardware architecture of the parallel vector-dot product with adder-multiplier dataflow tree 14 PCA Hardware Implementation VDP = Vector Dot Product 15 Hardware architecture of the covariance matrix calculation 16 In the context of PCA, Singular Value Decomposition (SVD) is the most practical and numerically stable way to compute principal components. Instead of forming covariance explicitly, apply SVD directly to centered data. 17 Implementation of PCA via HLS A DDR memory is used to store the input image pixels and the covariance matrix as well as the output of the PCA block. The Memory Controller is in charge of reading and writing data from and to the memory. It uses the AXI connect block to share one AXI port for both writing to the Data Dispatcher and reading from the PCA block. The Data Dispatcher receives first the covariance matrix and sends it to the BRAM; then it receives the input pixels from different spectral bands and sends them to the FIFOs. While the pixels are transferred to the FIFOs, the PCA block reads the covariance matrix from the BRAM, performs SVD calculation, and sorts and selects the principal components. Such concurrency of SVD computation and pixel transfer allows us to significantly reduce the overall latency. Finally, the input data are projected into the new base, resulting in lower dimensional output data. 18 Implementation of PCA via HLS In the Projection Unit (PU), the input data matrix of image pixels is multiplied by the matrix of principal components to remove the redundant information from the input images. This is one of the critical parts of the design due to the large number of input pixels. Incorporation of FIFOs into the design is to address the problem of large data communication, to let the transfer of input data matrix occur at the same time with SVD computation, and to improve the execution time of the PU. Since these are dual-clock FIFOs, we could have the Data Dispatcher run at a higher clock frequency than the PCA block, which allowed us to speed up the data transfer. The same is true for the Dual-Port BRAM used to store the covariance matrix, in which the two ports are associated to two different clock domains. Ref: See results at https://ieeexplore.ieee.org/document/8787782 19 Hardware Design for AI Lecture-05 1 What comes next in this course? Convolution Operations 2 Challenge In AI (Neural Metwork) Computations PE: Processing Element RF: Register File DRAM: Dynamic Random Access Memory Adapted from Scale-sim Tutorial slides (ASPLOS 2021) 3 LLM (Large Language Model) Acceleration 4 Eο¬cient Neural Network Implementation: Parallelization More resources/More throughput 5 Design Example 6 Mapping of C/C++ constructs to Hardware 7 FPGAs: Ideal targets for AI algorithm implementations 8 Optimizations: Loop Unrolling the compiler 9 Design Optimization Techniques: pragma HLS unroll Loop unrolling by a factor of 2 effectively transforms the code to look like the following code where the break construct is used to ensure the functionality remains the same, and the loop exits at the appropriate point. Benefits include reduced latency whereas disadvantages include resource consumption 10 Pragma in Design Synthesis Without Pragma (Latency=545,LUT's=171) Unroll inner loop (Latency=169,LUT's=1298) 11 Loop Pipelining Pipelining a loop allows the operations of the loop to be implemented in a concurrent manner as shown in the following figure. In the figure, (A) shows the default sequential operation where there are three clock cycles between each input read (II=3), and it requires eight clock cycles before the last output write is performed. (B) shows the pipelined operations that show one cycle between reads (II=1), and 4 cycles to the last write. 12 Loop Pipelining Initiation Interval (II) is the crucial metric for pipelined loops, representing the number of clock cycles between the start of one loop iteration and the next. 13 Pragma in Design Synthesis Initiation Interval (II) is the crucial metric for pipelined loops, representing the number of clock cycles between the start of one loop iteration and the next. 14 Eο¬cient Neural Network design: parallelization 15 Eο¬cient Neural Network design: parallelization 16 Fixed-point precision means representing numbers with a fixed number of digits for the integer and fractional parts C++ Implementation Of Decision Tree 17 Hardware Design Development with Python (FIR Filter) def fir(x, bs): rwidth = len(x) # bitwidth of the registers ntaps = len(bs) # number of coefficients zs = [x] + [pyrtl.Register(rwidth) for _ in range(ntaps-1)] for i in range(1,ntaps): zs[i].next <<= zs[i-1] # produce the final sum of products return sum(z*b for z,b in zip(zs, bs)) x = pyrtl.Input(8, 'x') y = pyrtl.Output(8, 'y') y <<= fir(x, [0, 1]) https://ucsbarchlab.github.io/PyRTL/ 18 Hardware Design Development with Python (GCD) https://ucsbarchlab.github.io/PyRTL/ 19 Hardware Design for AI Lecture-06 Acknowledgements: Many slides are taken from https://bpb-usw2.wpmucdn.com/sites.coecis.cornell.edu/dist/7/587/files/2023/06/chen_2016_eyeriss.pdf 1 Neural Network The idea is to learn like a human brain with the help of neurons 2 Neural Network 3 Different Network Topologies Multi-layer feed-forward networks 4 5 Algorithm for learning ANN 6 Formulating gradient descent 7 Formulating gradient descent 8 Single Hidden Layer and Single Outputs One hidden layer with πΎ nodes and a single output (e.g., scalar-valued regression or binary classification) 9 Single Hidden Layer and Multiple Outputs One hidden layer with πΎ nodes and a vector of πΆ output (e.g., vector-valued regression or multi-class classification or multi-label classification) 10 Why Neural Networks Work Better? 11 Hardware Implementation Register 12 Convolution neural networks Convolutional Neural Networks are a bit different from ANN. First of all, the layers are organised in 3 dimensions: width, height and depth. Further, the neurons in one layer do not connect to all the neurons in the next layer but only to a small region of it. Lastly, the final output will be reduced to a single vector of probability scores, organized along the depth dimension. 13 Components of CNN: Feature Extraction Part Hidden layers/Feature extraction part: In this part, the network will perform a series of convolutions and pooling operations during which the features are detected. If you had a picture of a zebra, this is the part where the network would recognise its stripes, two ears, and four legs. 14 Components of CNN: Classification Part Classification part: Here, the fully connected layers will serve as a classifier on top of these extracted features. They will assign a probability for the object on the image being what the algorithm predicts it is. 15 Feature Extraction In the case of a CNN, the convolution is performed on the input data with the use of a filter or kernel (these terms are used interchangeably) to then produce a feature map. 16 Convolution computation 17 Convolution computation How can we bring down the number of clock cycles? 18 Feature Extraction Each image is namely represented as a 3D matrix with a dimension for width, height, and depth. Depth is a dimension because of the colours channels used in an image (RGB). 19 Hardware for performing CONV computations PE: Processing Element, RF: Register File 20 Hardware Design for AI Lecture-07 1 Tensor Explanation Tensors are mathematical objects that describe linear relationships between sets of multidimensional data. o, i, f and b are the tensors of the ofmaps, ifmaps, ο¬lters, and biases, respectively. U is stride size. 2 CNN: Hyperparameters Following are the four hyperparameters: β the kernel size β the filter count (that is, how many filters do we want to use) β stride (how big are the steps of the filter) β padding 3 CNN: Complete Picture K = 2 filters, each with a spatial extent F = 3 , stride, S = 2, and input padding P = 1 4 CNN: classification portion After the convolution and pooling layers, our classification part consists of a few fully connected layers. However, these fully connected layers can only accept 1 Dimensional data. To convert our 3D data to 1D, we perform flattening. 5 Convolution Operations 6 Convolution Neural Network (CNN) https://towardsdatascience.com/a-comprehensive-guide-to-convolutional-neural-networks-the-eli5-way-3bd2b1164a53 7 Understanding Convolution Neural Network Opertaions A large number of computations are involved! 8 Processing Element Computations Final value: 14 20 26 H=ifmap plane width/height, R=filter plane width/height, U=stride size 9 Dataflow Movement 3 possible data-flow mechanisms are shown 10 Computations in DNN/CNN 11 Adapted from Eyeriss tutorial slides (ISCA 2019) Need of a dataflow 12 Implementing Convolution Step 1 Adapted from Eyeriss tutorial slides (ISCA 2019) 13 Implementing Convolution Step 2 Adapted from Eyeriss tutorial slides (ISCA 2019) Step 3 14 2D convolution in a PE array 15 2D convolution in a PE array 16 2D convolution in a PE array 17 Data Flow: Data Reuse 18 Data Flow: Data Reuse 19 Dedicated Hardware: Tensor Processing Unit (TPU) 20 Dedicated Hardware: Tensor Processing Unit (TPU) 21 Dedicated Hardware: Tensor Processing Unit (TPU) 22 Hardware Design for AI Lecture-08 Reference Paper: https://eems.mit.edu/wpcontent/uploads/2016/04/eyeriss_isca_2016.pdf 1 Hardware Implementation Issues Resource Efficiency: Understanding FLOPs helps in estimating the computational cost of a neural network. By optimizing the number of FLOPs, one can potentially reduce the time taken to train or run a neural network. Memory Efficiency: MAC operations often dictate the memory usage of the network since they are directly related to the number of parameters and activations in the network. Reducing MACs can help in making the network memory efficient. Power Efficiency: Both FLOPs and MAC operations contribute to the power consumption of the hardware on which the neural network is running. By optimizing these metrics, one can potentially reduce the energy requirements of running the network, which is particularly important in mobile and embedded devices. 2 Neural Network Implementation: The Python Picture 3 Neural Network Model Implementation Step 1: Understand the Definitions FLOP A FLOP (Floating Point OPeration) is considered to be either an addition, subtraction, multiplication, or division operation. MAC A MAC (Multiply-ACCumulate) operation is essentially a multiplication followed by an addition, i.e., MAC = a * b + c. It counts as two FLOPs (one for multiplication and one for addition). 4 Neural Network Model Implementation Step 2: Analyze Each Layer Calculating the number of floating-point operations or multiply-accumulate operations to understand the computational complexity of each layer. 1. Fully Connected Layer (Dense Layer) Now, we will create a simple neural network with 3 layers and begin counting the operations involved. Here is the formula for calculating the operations in the first linear layer, which is a fully connected (or dense) layer: For a fully connected layer with I inputs and O outputs, the number of operations are as follows: β β MACs: I × O FLOPs: 2 × (I × O) (since each MAC counts as two FLOPs) 5 Neural Network Model Implementation Step 2: Calculating FLOPs and MACs Now, calculate MACs and FLOPs for each layer: step 1: Identifying Layer Parameters For the given model, we have three linear layers defined as: Layer fc1: MACs = 10 × 20 = 200 β β β fc1: 10 input features, 20 output features fc2: 20 input features, 15 output features fc3: 15 input features, 1 output feature FLOPs = 2 × MACs = 2 × 200 = 400 Layer fc2: MACs = 20 × 15 = 300 FLOPs = 2 × MACs = 2 × 300 = 600 Layer fc3: MACs = 15 × 1 = 15 FLOPs = 2 × MACs = 2 × 15 = 30 β β Total MACs = MACs(fc1) + MACs(fc2) + MACs(fc3) = 200 + 300 + 15 = 515 Total FLOPs = FLOPs(fc1) + FLOPs(fc2) + FLOPs(fc3) = 400 + 600 + 30 = 1030 6 Convolution Neural Network (CNN) Implementation step 1: Identifying Layer Parameters For the given model, we have two conv layers and one linear layer defined as: (padding=1, stride=1) β β β Step 2: Calculating FLOPs and MACs Now, calculate MACs and FLOPs for each layer: formula is output_image_size * kernel shape * output_channels Layer conv1: conv1: 1 input channels, 16 output channels, kernel size is 3 conv2: 16 input channels, 32 output channels fc: 32*28*28 input features, 1 output feature. because our image is not changed in the convolutional layers MACs = 28 * 28 * 3 * 3 * 1 * 16 = 1,12,896 FLOPs = 2 × MACs = 2 × 1,12,896 = 2,25,792 Layer conv2: class SimpleConv(nn.Module): def __init__(self): super(SimpleConv, self).__init__() self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=3, stride=1, padding=1) self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1) self.fc = nn.Linear(in_features=32*28*28, out_features=10) In calculations shown on right-hand side, deliberately image size is taken as 28x28 in each layer. Please see next 2 slides. MACs = 28 × 28 * 3 * 3 * 16 * 32 = 3,612,672 FLOPs = 2 × MACs = 2 × 3,612,672 = 7,225,344 Layer fc: MACs = 32 * 28 * 28 * 10 = 250,880 FLOPs = 2 × MACs = 2 × 250,880 = 501,760 β β Total MACs = MACs(conv1) + MACs(conv2) + MACs(fc) = 1,12,896 + 3,612,672 + 250,880 = 39,76,448 7 Total FLOPs = FLOPs(fc1) + FLOPs(fc2) + FLOPs(fc3) = 2,25,792 + 7,225,344 + 501,760 = 7,952,896 Example of calculation for MNIST dataset 8 Example of calculation for MNIST dataset 9 The Need For Neural Network Accelerators β Remember: “VGG-16 requires 138 million weights and 15.5G MACs to process one 224 × 224 input image” β CPU at 3 GHz, 1 IPC, (3 Giga Operations Per Second – GOPS): 5+ seconds per image β Also significant power consumption! β (Optimistically assuming 3 GOPS/thread at 8 threads using 100 W, 0.24 GOPS/W) * Old data (2011), and performance varies greatly by implementation, some reporting 3+ GOPS/thread on an i7 Trend is still mostly true! Farabet et. al., “NeuFlow: A Runtime Reconfigurable Dataflow Processor for Vision” Two Major Layers β Convolution Layer β Many small (1x1, 3x3, 11x11, …) filters β Small number of weights per filter, relatively small number in total vs. FC β Over 90% of the MAC operations in a typical model β Fully-Connected Layer β N-to-N connection between all neurons, large number of weights Conv: * Input map FC: = Filters Output map × Weights Input vector = Output vector Spatial Mapping of Compute Units Memory Processing Element β Typically a 2D matrix of Processing Elements β Each PE is a simple multiply-accumulator β Extremely large number of PEs β Very high peak throughput! β Is memory the bottleneck (Again)? Memory Access is (Typically) the Bottleneck β 100 GOPS requires over 300 Billion weight/activation accesses β Assuming 4 byte floats, 1.2 TB/s of memory accesses β AlexNet requires 724 Million MACs to process a 227 x 227 image, over 2 Billion weight/activation accesses β Assuming 4 byte floats, that is over 8 GB of weight accesses per image β 240 GB/s to hit 30 frames per second β An interesting questions: β Can CPUs achieve this kind of performance? β Maybe, but not at low power “About 35% of cycles are spent waiting for weights to load from memory into the matrix unit …” – Jouppi et. al., Google TPU Spatial Mapping of Compute Units Memory β Optimization 1: On-chip network moves data (weights/activations/output) between PEs and memory for reuse β Optimization 2: Small, local memory on each PE β Typically using a Register File, a special type of memory with zero-cycle latency, but at high spatial overhead β Cache invalidation/work assignment… how? β Computation is very regular and predictable Register file Processing Element A class of accelerators deal only with problems that fit entirely in on-chip memory. This distinction is important. Different Strategies of Data Reuse β Weight Stationary β Try to maximize local weight reuse β Output Stationary β Try to maximize local partial sum reuse β Row Stationary β Try to maximize inter-PE data reuse of all kinds β No Local Reuse β Single/few global on-chip buffer, no per-PE register file and its space/power overhead Terminology from Sze et. al., “Efficient Processing of Deep Neural Networks: A Tutorial and Survey,” Proceedings of the IEEE 2017 Weight Stationary βKeep weights cached in PE register files o Effective for convolution especially if all weights can fit in-PEs βEach activation is broadcast to all PEs, and computed partial sum is forwarded to other PEs to complete computation o Intuition: Each PE is working on an adjacent position of an input row Weight stationary convolution for a row in the convolution Partial sum of a previous activation row if any nn-X, nuFlow, and others Partial sum for stored for next activation row, or final sum Output Stationary β Keep partial sums cached on PEs – Work on subset of output at a time β Effective for FC layers, where each output depend on many input/weights β Also for convolution layers when it has too many layers β Each weight is broadcast to all PEs, and input relayed to neighboring PEs β Intuition: Each PE is working on an adjacent position in an output sub-space cache d × ShiDianNao, and others Weight s = Input Output vecto vector r Row Stationary β Keep as much related to the same filter row cached… Across PEs β Filter weights, input, output… βNot much reuse in a PE o Weight stationary if filter row fits in register file Eyeriss, and Row Stationary β Lots of reuse across different PEs β Filter row reused horizontally β Input row reused diagonally β Partial sum reused vertically βEven further reuse by interleaving multiple input rows and multiple filter rows Google TPU Architecture Static Resource Mapping Sze et. al., “Efficient Processing of Deep Neural Networks: A Tutorial and Survey,” Proceedings of the IEEE 2017 Map And Fold For Efficient Use of Hardware Requires a flexible on-chip network Sze et. al., “Efficient Processing of Deep Neural Networks: A Tutorial and Survey,” Proceedings of the IEEE 2017 Power Efficiency Comparisons β Any of the presented architectures reduce memory pressure enough that memory access is no longer the dominant bottleneck β Now what’s important is the power efficiency Goal becomes to reduce as much DRAM access as possible! Joel Emer et. al., “Hardware Architectures for Deep Neural Networks,” tutorial from ISCA 2017 Power Efficiency Comparisons * Some papers report different numbers [1] where NLR with a carefully designed global on-chip memory hierarchy is superior. [1] Yang et. al., “DNN Dataflow Choice Is Overrated,” ArXiv 2018 Sze et. al., “Efficient Processing of Deep Neural Networks: A Tutorial and Survey,” Proceedings of the IEEE 2017 Power Consumption Comparison Between Convolution and FC Layers βData reuse in FC in inherently low o Unless we have enough onchip buffers to keep all weights, systems methods are not going to be enough Sze et. al., “Efficient Processing of Deep Neural Networks: A Tutorial and Survey,” Proceedings of the IEEE 2017 Hardware Design for AI Lecture-09: Tensor Cores Many slides are taken from here: https://developer.download.nvidia.com/video/gputechconf/gtc/2020/presentations/s 21929-tensor-core-performance-on-nvidia-gpus-the-ultimate-guide.pdf 1 Why Tensor Cores? 2 Recap: Volta Streaming Multiprocessor 3 WHAT LIMITS PERFORMANCE? 4 WHAT LIMITS PERFORMANCE in GPU? 5 Quantifying Computation v/s Communication 6 ARITHMETIC INTENSITY for FC layer 7 ARITHMETIC INTENSITY for FC layer Memory-limited Math-limited 8 MATRIX MULTIPLY ABSTRACTION 9 MATRIX MULTIPLY ABSTRACTION for FCN & Conv Layers 10 Recap: FLOPS per MMA (Matrix Multiply Accumulate) 11 ENABLING TENSOR CORES 12 ENABLING TENSOR CORES 13 Running an example (on Volta) 14 Running the same example (on A100) 15 Warp Matrix Multiply and Accumulate (WMMA) WMMA (Warp Matrix Multiply and Accumulate) is a CUDA programming abstraction that allows a warp (32 threads) to cooperatively perform matrix multiply-accumulate: D=A×B+C Threads are grouped into thread blocks that work cooperatively Thread blocks produce tiles of the output matrix Tiled outer product approach: sum partial products over the K dimension to complete the output tile Each Cooperative Thread Array (CTA) consists of 8 warps and computes one 128-by-128 tile, using shared memory for the matrix C. 16 Microarchitecture of Volta Tensor Core Alternate DPU Architecture https://arxiv.org/pdf/1811.08309 17 Warp Matrix Multiply and Accumulate (WMMA) 18 EFFICIENT PARALLELIZATION on GPU 19 EFFICIENT PARALLELIZATION on GPU via Quantization 20 EFFICIENT PARALLELIZATION: parallelization case 21 Wave Quantization on GPU Wave quantization (also called warp/wavefront quantization) is a performance effect that happens when GPU work is scheduled in fixed-size execution groups. GPUs execute threads in lockstep groups: β On NVIDIA GPUs → called a warp (32 threads) β On AMD GPUs → called a wavefront (usually 64 threads) A “wave” = smallest schedulable SIMD execution unit. 22 EFFICIENT PARALLELIZATION: Tile quantization 23 EFFICIENT PARALLELIZATION: Wave quantization 24 EFFICIENT PARALLELIZATION: Tile & Wave quantization 25 EFFICIENT PARALLELIZATION (Transformer Workload) 26
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )