What actually happens when you call 'loss.backward()'
I've called loss.backward() hundreds of times without knowing what happens when I do. So I wrote the thing myself, about a hundred lines of Python, no PyTorch, no TensorFlow. I worked from Andrej Karpathy's micrograd video, building each piece before checking his implementation, and the mechanism turned out to be smaller and stranger than I expected. Here's what I learned.
Typically one would use PyTorch or TensorFlow to build and train their Deep Learning AI models. Autograd is a gradient calculation engine that is at the core of these frameworks.
Context:
Whenever you train a neural network, you expect it to predict a correct output given the input. But the untrained models most often predict an output that is wrong. You compare the output with the ground truth that you have for that input and calculate the loss. Using that loss as the signal, you adjust the parameters of your neurons. The process of predicting the output is called the forward pass, the process of calculating the gradients of the loss with respect to the parameters is called backpropagation. So, you calculate the loss and backpropagate its gradients towards your inner layers of neurons and then use those gradients to adjust the parameters.
There is a mathematical way to adjust the parameters. You have the loss(difference between the prediction and the ground truth), and you compute the gradients of the loss with respect to the parameters and update those parameters using the calculated gradients. All you need to do this in hand is to be good at calculus.
Doing by hand will make sense only for learning purpose and it is not practical in real world scenarios as there will be billions of parameters. So, you calculate them programmatically and that's where autograd engine comes handy. It's the programmatic way of doing the backpropagation.
So, what is Autograd?
Autograd is an engine/process that does the backpropagation and computes the gradients and a separate model training loop adjusts the parameters based on the calculated gradients. It is at the core of every AI model training. It operates on scalars and operations. It has no concept of neurons and the neural network is a thin wrapper written on top of the Autograd engine. So, essentially, computation of gradients is a separate abstracted layer which the neural network wrapper imports and uses to compute the gradients during the time of training.
Components of Autograd engine:
1) An entity to store:
If you start to structure your thoughts to put the mathematical procedure of backpropagation into a program, the first thing you need is an entity that wraps different operations of the backpropagation. Think about a forward pass and a backward pass and all the operations you need for it. You need to add, multiply, raise power, introduce non linearity(ReLu, tanh). This is the entity where you will define all the operations. As you are aware, we apply chain rule while calculating the derivatives, so this entity should also capture, what are all the set of input operations that produced the current output. So, technically, this entity, should store the values of grads of parameters, the operations that produced an output(children(operands) and operators(+, -, *)), the backward closure and supporting operations like addition, multiplication, subtraction and so on.
An example entity called Value in python:
class Value:
def __init__(self, data, _children = (), _op = '', label=''):
self.data = data
self._prev = set(_children)
self._op = _op
self.label = label
self._backward = lambda : None
self.grad = 0.0
def __repr__(self):
return f"Value(data={self.data})"
def __add__(self, other):
def _backward():
# see repo
def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other), '*')
def _backward():
self.grad += other.data * out.grad
other.grad += self.data * out.grad
out._backward = _backward
return out
def __pow__(self, other):
def _backward():
# see repo
def exp(self):
def _backward():
# see repo
def tanh(self):
def _backward():
# see repo
def backward(self):
def build_topo(v):
# see repo
2) Forward pass:
Once you define an entity that wraps all your supporting operations, you can define a relation and execute it using the entity. Say for example, a = 2, b = 3, c = a*b. Once you execute this, a graph can be computed which tells us the lineage of operands that produced c(since we store the children of c(a and b), and the operation that produced c(multiplication)). The above process is called forward propagation. Now you will have the output, you will have the ground truth and you can compute the loss.
3) backward method:
After computing the loss, you need to calculate the gradients of each contributor in your relation. This is where the backward method that you defined in the entity comes handy. In a computational graph, a node's gradient isn't finished until every node that consumes it has contributed. That's why we use topological sort. It guarantees that you never call a node's backward closure(the gradient calculator) before all its consumers have run. Backpropagation starts by setting the output node's gradient to 1.0, since its influence on itself is 1. Without that, nothing propagates and every gradient stays 0.
Example backprop implementation in python:
def backward(self):
stack = []
visited = set()
def build_topo(v):
if v not in visited:
visited.add(v)
for child in v._prev:
build_topo(child)
stack.append(v)
build_topo(self)
self.grad = 1.0
for n in reversed(stack):
n._backward()
4) zero_grad():
Everytime you forward pass, you have to reset the gradients to 0 before you do the backward pass and update the parameters. Otherwise the gradients will accumulate across all the epochs which will lead to unstable training and inaccurate model. The reason why the gradient accumulates is the backward closure(the gradient calculator) uses '+=' on the gradient calculation to ensure we sum all the downstream contributions of a node and the gradient accumulation comes as a side effect at each epoch.
An example backward closure from sum operation:
def _backward():
self.grad += out.grad
other.grad += out.grad
5) Why not calculate the gradients through forward pass?
One can certainly calculate the gradients during forward pass as well instead of a backward pass. It is called forward-mode automatic differentiation. But the problem with it is, in forward pass, you propagate the derivative of one input through the computation, forward, to obtain the derivative of the loss with respect to that particular input. So, you need to repeat forward pass, once per input parameter, obtaining one component of the gradient per pass and then you collect these components to form the gradient of the loss with respect to all the parameters. And the number of input parameters can sometimes be large. In backward pass, you can calculate the differentiation of one output(loss) with respect to all the parameters. Deep learning typically requires the gradient of one scalar loss with respect to a very large number of parameters and the reverse-mode AD does this efficiently.
Once you understand what the autograd is and what it does, the next step is to build the neural network layer on top of it and train your model. But keep in mind that this handmade engine operates only on scalar values. Real frameworks like PyTorch, TensorFlow extend the automatic differentiation to tensors, allowing them to handle vectors, matrices and high-dimensional data efficiently.
PS: Full engine and a small neural network on top of it: my-micrograd. If you want to build this yourself, start with Karpathy's micrograd video, it's the best two hours you'll spend on this.