{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Forward Propagation, Backward Propagation, and Computational Graphs\n",
"\n",
"In the previous sections, we used mini-batch \n",
"stochastic gradient descent to train our models. \n",
"When we implemented the algorithm, \n",
"we only worried about the calculations involved \n",
"in *forward propagation* through the model.\n",
"In other words, we implemented the calculations\n",
"required for the model to generate output \n",
"corresponding to come given input, \n",
"but when it came time to calculate the gradients of each of our parameters,\n",
"we invoked the `backward` function,\n",
"relying on the `autograd` module to figure out what to do. \n",
"\n",
"The automatic calculation of gradients profoundly simplifies \n",
"the implementation of deep learning algorithms. \n",
"Before automatic differentiation, \n",
"even small changes to complicated models would require \n",
"recalculating lots of derivatives by hand.\n",
"Even academic papers would too often have to allocate\n",
"lots of page real estate to deriving update rules.\n",
"\n",
"While we plan to continue relying on `autograd`,\n",
"and we have already come a long way \n",
"without every discussing how these gradients \n",
"are calculated efficiently under the hood,\n",
"it's important that you know \n",
"how updates are actually calculated\n",
"if you want to go beyond a shallow understanding of deep learning.\n",
"\n",
"In this section, we'll peel back the curtain on some of the details\n",
"of backward propagation (more commonly called *backpropagation* or *backprop*).\n",
"To convey some insight for both the techniques and how they are implementated,\n",
"we will rely on both mathematics and computational graphs \n",
"to describe the mechanics behind neural network computations.\n",
"To start, we will focus our exposition on \n",
"a simple multilayer perceptron with a single hidden layer \n",
"and $\\ell_2$ norm regularization. \n",
"\n",
"\n",
"## Forward Propagation\n",
"\n",
"Forward propagation refers to the calculation and storage \n",
"of intermediate variables (including outputs) \n",
"for the neural network within the models \n",
"in the order from input layer to output layer. \n",
"In the following, we work in detail through the example of a deep network \n",
"with one hidden layer step by step. \n",
"This is a bit tedious but it will serve us well \n",
"when discussing what really goes on when we call `backward`.\n",
"\n",
"For the sake of simplicity, let’s assume \n",
"that the input example is $\\mathbf{x}\\in \\mathbb{R}^d$ \n",
"and there is no bias term. \n",
"Here the intermediate variable is:\n",
"\n",
"$$\\mathbf{z}= \\mathbf{W}^{(1)} \\mathbf{x}$$\n",
"\n",
"$\\mathbf{W}^{(1)} \\in \\mathbb{R}^{h \\times d}$ \n",
"is the weight parameter of the hidden layer. \n",
"After entering the intermediate variable $\\mathbf{z}\\in \\mathbb{R}^h$ \n",
"into the activation function $\\phi$ operated by the basic elements, \n",
"we will obtain a hidden layer variable with the vector length of $h$,\n",
"\n",
"$$\\mathbf{h}= \\phi (\\mathbf{z}).$$\n",
"\n",
"The hidden variable $\\mathbf{h}$ is also an intermediate variable. \n",
"Assuming the parameters of the output layer \n",
"only possess a weight of $\\mathbf{W}^{(2)} \\in \\mathbb{R}^{q \\times h}$, \n",
"we can obtain an output layer variable with a vector length of $q$:\n",
"\n",
"$$\\mathbf{o}= \\mathbf{W}^{(2)} \\mathbf{h}.$$\n",
"\n",
"Assuming the loss function is $l$ and the example label is $y$,\n",
"we can then calculate the loss term for a single data example,\n",
"\n",
"$$L = l(\\mathbf{o}, y).$$\n",
"\n",
"According to the definition of $\\ell_2$ norm regularization, \n",
"given the hyper-parameter $\\lambda$, the regularization term is\n",
"\n",
"$$s = \\frac{\\lambda}{2} \\left(\\|\\mathbf{W}^{(1)}\\|_F^2 + \\|\\mathbf{W}^{(2)}\\|_F^2\\right),$$\n",
"\n",
"where the Frobenius norm of the matrix is equivalent \n",
"to the calculation of the $L_2$ norm \n",
"after flattening the matrix to a vector. \n",
"Finally, the model's regularized loss on a given data example is\n",
"\n",
"$$J = L + s.$$\n",
"\n",
"We refer to $J$ as the objective function of a given data example \n",
"and refer to it as the ‘objective function’ in the following discussion.\n",
"\n",
"\n",
"## Computational Graph of Forward Propagation\n",
"\n",
"Plotting computational graphs helps us visualize \n",
"the dependencies of operators and variables within the calculation. \n",
"The figure below contains the graph associated \n",
"with the simple network described above. \n",
"The lower-left corner signifies the input \n",
"and the upper right corner the output. \n",
"Notice that the direction of the arrows (which illustrate data flow) \n",
"are primarily rightward and upward.\n",
"\n",
"![Computational Graph](../img/forward.svg)\n",
"\n",
"\n",
"## Backpropagation\n",
"\n",
"Backpropagation refers to the method of calculating \n",
"the gradient of neural network parameters. \n",
"In general, back propagation calculates and stores \n",
"the intermediate variables of an objective function \n",
"related to each layer of the neural network \n",
"and the gradient of the parameters \n",
"in the order of the output layer to the input layer \n",
"according to the ‘chain rule’ in calculus. \n",
"Assume that we have functions $\\mathsf{Y}=f(\\mathsf{X})$ \n",
"and $\\mathsf{Z}=g(\\mathsf{Y}) = g \\circ f(\\mathsf{X})$, \n",
"in which the input and the output \n",
"$\\mathsf{X}, \\mathsf{Y}, \\mathsf{Z}$ \n",
"are tensors of arbitrary shapes. \n",
"By using the chain rule, we can compute \n",
"the derivative of $\\mathsf{Z}$ wrt. $\\mathsf{X}$ via\n",
"\n",
"$$\\frac{\\partial \\mathsf{Z}}{\\partial \\mathsf{X}} = \\text{prod}\\left(\\frac{\\partial \\mathsf{Z}}{\\partial \\mathsf{Y}}, \\frac{\\partial \\mathsf{Y}}{\\partial \\mathsf{X}}\\right).$$\n",
"\n",
"Here we use the $\\text{prod}$ operator \n",
"to multiply its arguments after the necessary operations, \n",
"such as transposition and swapping input positions have been carried out. \n",
"For vectors, this is straightforward: \n",
"it is simply matrix-matrix multiplication \n",
"and for higher dimensional tensors we use the appropriate counterpart. \n",
"The operator $\\text{prod}$ hides all the notation overhead.\n",
"\n",
"The parameters of the simple network with one hidden layer \n",
"are $\\mathbf{W}^{(1)}$ and $\\mathbf{W}^{(2)}$. \n",
"The objective of backpropagation is to \n",
"calculate the gradients $\\partial J/\\partial \\mathbf{W}^{(1)}$ \n",
"and $\\partial J/\\partial \\mathbf{W}^{(2)}$. \n",
"To accompish this, we will apply the chain rule \n",
"and calculate, in turn, the gradient of \n",
"each intermediate variable and parameter. \n",
"The order of calculations are reversed \n",
"relative to those performed in forward propagation, \n",
"since we need to start with the outcome of the compute graph \n",
"and work our way towards the parameters. \n",
"The first step is to calculate the gradients \n",
"of the objective function $J=L+s$ \n",
"with respect to the loss term $L$ \n",
"and the regularization term $s$.\n",
"\n",
"$$\\frac{\\partial J}{\\partial L} = 1 \\text{ and } \\frac{\\partial J}{\\partial s} = 1$$\n",
"\n",
"Next, we compute the gradient of the objective function \n",
"with respect to variable of the output layer $\\mathbf{o}$ \n",
"according to the chain rule.\n",
"\n",
"$$\n",
"\\frac{\\partial J}{\\partial \\mathbf{o}}\n",
"= \\text{prod}\\left(\\frac{\\partial J}{\\partial L}, \\frac{\\partial L}{\\partial \\mathbf{o}}\\right)\n",
"= \\frac{\\partial L}{\\partial \\mathbf{o}}\n",
"\\in \\mathbb{R}^q\n",
"$$\n",
"\n",
"Next, we calculate the gradients of the regularization term \n",
"with respect to both parameters.\n",
"\n",
"$$\\frac{\\partial s}{\\partial \\mathbf{W}^{(1)}} = \\lambda \\mathbf{W}^{(1)}\n",
"\\text{ and }\n",
"\\frac{\\partial s}{\\partial \\mathbf{W}^{(2)}} = \\lambda \\mathbf{W}^{(2)}$$\n",
"\n",
"Now we are able calculate the gradient \n",
"$\\partial J/\\partial \\mathbf{W}^{(2)} \\in \\mathbb{R}^{q \\times h}$ \n",
"of the model parameters closest to the output layer. \n",
"Using the chain rule yields:\n",
"\n",
"$$\n",
"\\frac{\\partial J}{\\partial \\mathbf{W}^{(2)}}\n",
"= \\text{prod}\\left(\\frac{\\partial J}{\\partial \\mathbf{o}}, \\frac{\\partial \\mathbf{o}}{\\partial \\mathbf{W}^{(2)}}\\right) + \\text{prod}\\left(\\frac{\\partial J}{\\partial s}, \\frac{\\partial s}{\\partial \\mathbf{W}^{(2)}}\\right)\n",
"= \\frac{\\partial J}{\\partial \\mathbf{o}} \\mathbf{h}^\\top + \\lambda \\mathbf{W}^{(2)}\n",
"$$\n",
"\n",
"To obtain the gradient with respect to $\\mathbf{W}^{(1)}$ \n",
"we need to continue backpropagation \n",
"along the output layer to the hidden layer. \n",
"The gradient with respect to the hidden layer's outputs\n",
"$\\partial J/\\partial \\mathbf{h} \\in \\mathbb{R}^h$ is given by\n",
"\n",
"\n",
"$$\n",
"\\frac{\\partial J}{\\partial \\mathbf{h}}\n",
"= \\text{prod}\\left(\\frac{\\partial J}{\\partial \\mathbf{o}}, \\frac{\\partial \\mathbf{o}}{\\partial \\mathbf{h}}\\right)\n",
"= {\\mathbf{W}^{(2)}}^\\top \\frac{\\partial J}{\\partial \\mathbf{o}}.\n",
"$$\n",
"\n",
"Since the activation function $\\phi$ applies element-wise, \n",
"calculating the gradient $\\partial J/\\partial \\mathbf{z} \\in \\mathbb{R}^h$ \n",
"of the intermediate variable $\\mathbf{z}$ \n",
"requires that we use the element-wise multiplication operator,\n",
"which we denote by $\\odot$.\n",
"\n",
"$$\n",
"\\frac{\\partial J}{\\partial \\mathbf{z}}\n",
"= \\text{prod}\\left(\\frac{\\partial J}{\\partial \\mathbf{h}}, \\frac{\\partial \\mathbf{h}}{\\partial \\mathbf{z}}\\right)\n",
"= \\frac{\\partial J}{\\partial \\mathbf{h}} \\odot \\phi'\\left(\\mathbf{z}\\right).\n",
"$$\n",
"\n",
"Finally, we can obtain the gradient \n",
"$\\partial J/\\partial \\mathbf{W}^{(1)} \\in \\mathbb{R}^{h \\times d}$ \n",
"of the model parameters closest to the input layer. \n",
"According to the chain rule, we get\n",
"\n",
"$$\n",
"\\frac{\\partial J}{\\partial \\mathbf{W}^{(1)}}\n",
"= \\text{prod}\\left(\\frac{\\partial J}{\\partial \\mathbf{z}}, \\frac{\\partial \\mathbf{z}}{\\partial \\mathbf{W}^{(1)}}\\right) + \\text{prod}\\left(\\frac{\\partial J}{\\partial s}, \\frac{\\partial s}{\\partial \\mathbf{W}^{(1)}}\\right)\n",
"= \\frac{\\partial J}{\\partial \\mathbf{z}} \\mathbf{x}^\\top + \\lambda \\mathbf{W}^{(1)}.\n",
"$$\n",
"\n",
"## Training a Model\n",
"\n",
"When training networks, forward and backward propagation depend on each other. In particular, for forward propagation,\n",
"we traverse the compute graph in the direction of dependencies \n",
"and compute all the variables on its path. \n",
"These are then used for backpropagation \n",
"where the compute order on the graph is reversed. \n",
"One of the consequences is that we need to retain \n",
"the intermediate values until backpropagation is complete.\n",
"This is also one of the reasons why backpropagation \n",
"requires significantly more memory than plain 'inference'—we end up \n",
"computing tensors as gradients \n",
"and need to retain all the intermediate variables \n",
"to invoke the chain rule. \n",
"Another reason is that we typically train \n",
"with minibatches containing more than one variable, \n",
"thus more intermediate activations need to be stored.\n",
"\n",
"## Summary\n",
"\n",
"* Forward propagation sequentially calculates and stores intermediate variables within the compute graph defined by the neural network. It proceeds from input to output layer.\n",
"* Back propagation sequentially calculates and stores the gradients of intermediate variables and parameters within the neural network in the reversed order.\n",
"* When training deep learning models, forward propagation and back propagation are interdependent.\n",
"* Training requires significantly more memory and storage.\n",
"\n",
"\n",
"## Exercises\n",
"\n",
"1. Assume that the inputs $\\mathbf{x}$ are matrices. What is the dimensionality of the gradients?\n",
"1. Add a bias to the hidden layer of the model described in this chapter.\n",
" * Draw the corresponding compute graph.\n",
" * Derive the forward and backward propagation equations.\n",
"1. Compute the memory footprint for training and inference in model described in the current chapter.\n",
"1. Assume that you want to compute *second* derivatives. What happens to the compute graph? Is this a good idea?\n",
"1. Assume that the compute graph is too large for your GPU.\n",
" * Can you partition it over more than one GPU?\n",
" * What are the advantages and disadvantages over training on a smaller minibatch?\n",
"\n",
"## Scan the QR Code to [Discuss](https://discuss.mxnet.io/t/2344)\n",
"\n",
"![](../img/qr_backprop.svg)"
]
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 2
}