Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/main/beginner_source/blitz/autograd_tutorial.py
Views: 713
# -*- coding: utf-8 -*-1"""2A Gentle Introduction to ``torch.autograd``3===========================================45``torch.autograd`` is PyTorch’s automatic differentiation engine that powers6neural network training. In this section, you will get a conceptual7understanding of how autograd helps a neural network train.89Background10~~~~~~~~~~11Neural networks (NNs) are a collection of nested functions that are12executed on some input data. These functions are defined by *parameters*13(consisting of weights and biases), which in PyTorch are stored in14tensors.1516Training a NN happens in two steps:1718**Forward Propagation**: In forward prop, the NN makes its best guess19about the correct output. It runs the input data through each of its20functions to make this guess.2122**Backward Propagation**: In backprop, the NN adjusts its parameters23proportionate to the error in its guess. It does this by traversing24backwards from the output, collecting the derivatives of the error with25respect to the parameters of the functions (*gradients*), and optimizing26the parameters using gradient descent. For a more detailed walkthrough27of backprop, check out this `video from283Blue1Brown <https://www.youtube.com/watch?v=tIeHLnjs5U8>`__.2930313233Usage in PyTorch34~~~~~~~~~~~~~~~~35Let's take a look at a single training step.36For this example, we load a pretrained resnet18 model from ``torchvision``.37We create a random data tensor to represent a single image with 3 channels, and height & width of 64,38and its corresponding ``label`` initialized to some random values. Label in pretrained models has39shape (1,1000).4041.. note::42This tutorial works only on the CPU and will not work on GPU devices (even if tensors are moved to CUDA).4344"""45import torch46from torchvision.models import resnet18, ResNet18_Weights47model = resnet18(weights=ResNet18_Weights.DEFAULT)48data = torch.rand(1, 3, 64, 64)49labels = torch.rand(1, 1000)5051############################################################52# Next, we run the input data through the model through each of its layers to make a prediction.53# This is the **forward pass**.54#5556prediction = model(data) # forward pass5758############################################################59# We use the model's prediction and the corresponding label to calculate the error (``loss``).60# The next step is to backpropagate this error through the network.61# Backward propagation is kicked off when we call ``.backward()`` on the error tensor.62# Autograd then calculates and stores the gradients for each model parameter in the parameter's ``.grad`` attribute.63#6465loss = (prediction - labels).sum()66loss.backward() # backward pass6768############################################################69# Next, we load an optimizer, in this case SGD with a learning rate of 0.01 and `momentum <https://towardsdatascience.com/stochastic-gradient-descent-with-momentum-a84097641a5d>`__ of 0.9.70# We register all the parameters of the model in the optimizer.71#7273optim = torch.optim.SGD(model.parameters(), lr=1e-2, momentum=0.9)7475######################################################################76# Finally, we call ``.step()`` to initiate gradient descent. The optimizer adjusts each parameter by its gradient stored in ``.grad``.77#7879optim.step() #gradient descent8081######################################################################82# At this point, you have everything you need to train your neural network.83# The below sections detail the workings of autograd - feel free to skip them.84#858687######################################################################88# --------------89#909192######################################################################93# Differentiation in Autograd94# ~~~~~~~~~~~~~~~~~~~~~~~~~~~95# Let's take a look at how ``autograd`` collects gradients. We create two tensors ``a`` and ``b`` with96# ``requires_grad=True``. This signals to ``autograd`` that every operation on them should be tracked.97#9899import torch100101a = torch.tensor([2., 3.], requires_grad=True)102b = torch.tensor([6., 4.], requires_grad=True)103104######################################################################105# We create another tensor ``Q`` from ``a`` and ``b``.106#107# .. math::108# Q = 3a^3 - b^2109110Q = 3*a**3 - b**2111112113######################################################################114# Let's assume ``a`` and ``b`` to be parameters of an NN, and ``Q``115# to be the error. In NN training, we want gradients of the error116# w.r.t. parameters, i.e.117#118# .. math::119# \frac{\partial Q}{\partial a} = 9a^2120#121# .. math::122# \frac{\partial Q}{\partial b} = -2b123#124#125# When we call ``.backward()`` on ``Q``, autograd calculates these gradients126# and stores them in the respective tensors' ``.grad`` attribute.127#128# We need to explicitly pass a ``gradient`` argument in ``Q.backward()`` because it is a vector.129# ``gradient`` is a tensor of the same shape as ``Q``, and it represents the130# gradient of Q w.r.t. itself, i.e.131#132# .. math::133# \frac{dQ}{dQ} = 1134#135# Equivalently, we can also aggregate Q into a scalar and call backward implicitly, like ``Q.sum().backward()``.136#137external_grad = torch.tensor([1., 1.])138Q.backward(gradient=external_grad)139140141#######################################################################142# Gradients are now deposited in ``a.grad`` and ``b.grad``143144# check if collected gradients are correct145print(9*a**2 == a.grad)146print(-2*b == b.grad)147148149######################################################################150# Optional Reading - Vector Calculus using ``autograd``151# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^152#153# Mathematically, if you have a vector valued function154# :math:`\vec{y}=f(\vec{x})`, then the gradient of :math:`\vec{y}` with155# respect to :math:`\vec{x}` is a Jacobian matrix :math:`J`:156#157# .. math::158#159#160# J161# =162# \left(\begin{array}{cc}163# \frac{\partial \bf{y}}{\partial x_{1}} &164# ... &165# \frac{\partial \bf{y}}{\partial x_{n}}166# \end{array}\right)167# =168# \left(\begin{array}{ccc}169# \frac{\partial y_{1}}{\partial x_{1}} & \cdots & \frac{\partial y_{1}}{\partial x_{n}}\\170# \vdots & \ddots & \vdots\\171# \frac{\partial y_{m}}{\partial x_{1}} & \cdots & \frac{\partial y_{m}}{\partial x_{n}}172# \end{array}\right)173#174# Generally speaking, ``torch.autograd`` is an engine for computing175# vector-Jacobian product. That is, given any vector :math:`\vec{v}`, compute the product176# :math:`J^{T}\cdot \vec{v}`177#178# If :math:`\vec{v}` happens to be the gradient of a scalar function :math:`l=g\left(\vec{y}\right)`:179#180# .. math::181#182#183# \vec{v}184# =185# \left(\begin{array}{ccc}\frac{\partial l}{\partial y_{1}} & \cdots & \frac{\partial l}{\partial y_{m}}\end{array}\right)^{T}186#187# then by the chain rule, the vector-Jacobian product would be the188# gradient of :math:`l` with respect to :math:`\vec{x}`:189#190# .. math::191#192#193# J^{T}\cdot \vec{v}=\left(\begin{array}{ccc}194# \frac{\partial y_{1}}{\partial x_{1}} & \cdots & \frac{\partial y_{m}}{\partial x_{1}}\\195# \vdots & \ddots & \vdots\\196# \frac{\partial y_{1}}{\partial x_{n}} & \cdots & \frac{\partial y_{m}}{\partial x_{n}}197# \end{array}\right)\left(\begin{array}{c}198# \frac{\partial l}{\partial y_{1}}\\199# \vdots\\200# \frac{\partial l}{\partial y_{m}}201# \end{array}\right)=\left(\begin{array}{c}202# \frac{\partial l}{\partial x_{1}}\\203# \vdots\\204# \frac{\partial l}{\partial x_{n}}205# \end{array}\right)206#207# This characteristic of vector-Jacobian product is what we use in the above example;208# ``external_grad`` represents :math:`\vec{v}`.209#210211212213######################################################################214# Computational Graph215# ~~~~~~~~~~~~~~~~~~~216#217# Conceptually, autograd keeps a record of data (tensors) & all executed218# operations (along with the resulting new tensors) in a directed acyclic219# graph (DAG) consisting of220# `Function <https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function>`__221# objects. In this DAG, leaves are the input tensors, roots are the output222# tensors. By tracing this graph from roots to leaves, you can223# automatically compute the gradients using the chain rule.224#225# In a forward pass, autograd does two things simultaneously:226#227# - run the requested operation to compute a resulting tensor, and228# - maintain the operation’s *gradient function* in the DAG.229#230# The backward pass kicks off when ``.backward()`` is called on the DAG231# root. ``autograd`` then:232#233# - computes the gradients from each ``.grad_fn``,234# - accumulates them in the respective tensor’s ``.grad`` attribute, and235# - using the chain rule, propagates all the way to the leaf tensors.236#237# Below is a visual representation of the DAG in our example. In the graph,238# the arrows are in the direction of the forward pass. The nodes represent the backward functions239# of each operation in the forward pass. The leaf nodes in blue represent our leaf tensors ``a`` and ``b``.240#241# .. figure:: /_static/img/dag_autograd.png242#243# .. note::244# **DAGs are dynamic in PyTorch**245# An important thing to note is that the graph is recreated from scratch; after each246# ``.backward()`` call, autograd starts populating a new graph. This is247# exactly what allows you to use control flow statements in your model;248# you can change the shape, size and operations at every iteration if249# needed.250#251# Exclusion from the DAG252# ^^^^^^^^^^^^^^^^^^^^^^253#254# ``torch.autograd`` tracks operations on all tensors which have their255# ``requires_grad`` flag set to ``True``. For tensors that don’t require256# gradients, setting this attribute to ``False`` excludes it from the257# gradient computation DAG.258#259# The output tensor of an operation will require gradients even if only a260# single input tensor has ``requires_grad=True``.261#262263x = torch.rand(5, 5)264y = torch.rand(5, 5)265z = torch.rand((5, 5), requires_grad=True)266267a = x + y268print(f"Does `a` require gradients?: {a.requires_grad}")269b = x + z270print(f"Does `b` require gradients?: {b.requires_grad}")271272273######################################################################274# In a NN, parameters that don't compute gradients are usually called **frozen parameters**.275# It is useful to "freeze" part of your model if you know in advance that you won't need the gradients of those parameters276# (this offers some performance benefits by reducing autograd computations).277#278# In finetuning, we freeze most of the model and typically only modify the classifier layers to make predictions on new labels.279# Let's walk through a small example to demonstrate this. As before, we load a pretrained resnet18 model, and freeze all the parameters.280281from torch import nn, optim282283model = resnet18(weights=ResNet18_Weights.DEFAULT)284285# Freeze all the parameters in the network286for param in model.parameters():287param.requires_grad = False288289######################################################################290# Let's say we want to finetune the model on a new dataset with 10 labels.291# In resnet, the classifier is the last linear layer ``model.fc``.292# We can simply replace it with a new linear layer (unfrozen by default)293# that acts as our classifier.294295model.fc = nn.Linear(512, 10)296297######################################################################298# Now all parameters in the model, except the parameters of ``model.fc``, are frozen.299# The only parameters that compute gradients are the weights and bias of ``model.fc``.300301# Optimize only the classifier302optimizer = optim.SGD(model.parameters(), lr=1e-2, momentum=0.9)303304##########################################################################305# Notice although we register all the parameters in the optimizer,306# the only parameters that are computing gradients (and hence updated in gradient descent)307# are the weights and bias of the classifier.308#309# The same exclusionary functionality is available as a context manager in310# `torch.no_grad() <https://pytorch.org/docs/stable/generated/torch.no_grad.html>`__311#312313######################################################################314# --------------315#316317######################################################################318# Further readings:319# ~~~~~~~~~~~~~~~~~~~320#321# - `In-place operations & Multithreaded Autograd <https://pytorch.org/docs/stable/notes/autograd.html>`__322# - `Example implementation of reverse-mode autodiff <https://colab.research.google.com/drive/1VpeE6UvEPRz9HmsHh1KS0XxXjYu533EC>`__323# - `Video: PyTorch Autograd Explained - In-depth Tutorial <https://www.youtube.com/watch?v=MswxJw-8PvE>`__324325326