{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# For tips on running notebooks in Google Colab, see\n",
    "# https://docs.pytorch.org/tutorials/beginner/colab\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Visualizing Gradients\n",
    "\n",
    "**Author:** [Justin Silver](https://github.com/j-silv)\n",
    "\n",
    "This tutorial explains how to extract and visualize gradients at any\n",
    "layer in a neural network. By inspecting how information flows from the\n",
    "end of the network to the parameters we want to optimize, we can debug\n",
    "issues such as [vanishing or exploding\n",
    "gradients](https://arxiv.org/abs/1211.5063) that occur during training.\n",
    "\n",
    "Before starting, make sure you understand [tensors and how to manipulate\n",
    "them](https://docs.pytorch.org/tutorials/beginner/basics/tensorqs_tutorial.html).\n",
    "A basic knowledge of [how autograd\n",
    "works](https://docs.pytorch.org/tutorials/beginner/basics/autogradqs_tutorial.html)\n",
    "would also be useful.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Setup\n",
    "\n",
    "First, make sure [PyTorch is\n",
    "installed](https://pytorch.org/get-started/locally/) and then import the\n",
    "necessary libraries.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "import torch.nn.functional as F\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we'll be creating a network intended for the MNIST dataset,\n",
    "similar to the architecture described by the [batch normalization\n",
    "paper](https://arxiv.org/abs/1502.03167).\n",
    "\n",
    "To illustrate the importance of gradient visualization, we will\n",
    "instantiate one version of the network with batch normalization\n",
    "(BatchNorm), and one without it. Batch normalization is an extremely\n",
    "effective technique to resolve [vanishing/exploding\n",
    "gradients](https://arxiv.org/abs/1211.5063), and we will be verifying\n",
    "that experimentally.\n",
    "\n",
    "The model we use has a configurable number of repeating fully-connected\n",
    "layers which alternate between `nn.Linear`, `norm_layer`, and\n",
    "`nn.Sigmoid`. If batch normalization is enabled, then `norm_layer` will\n",
    "use\n",
    "[BatchNorm1d](https://docs.pytorch.org/docs/stable/generated/torch.nn.BatchNorm1d.html),\n",
    "otherwise it will use the\n",
    "[Identity](https://docs.pytorch.org/docs/stable/generated/torch.nn.Identity.html)\n",
    "transformation.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def fc_layer(in_size, out_size, norm_layer):\n",
    "    \"\"\"Return a stack of linear->norm->sigmoid layers\"\"\"\n",
    "    return nn.Sequential(nn.Linear(in_size, out_size), norm_layer(out_size), nn.Sigmoid())\n",
    "\n",
    "class Net(nn.Module):\n",
    "    \"\"\"Define a network that has num_layers of linear->norm->sigmoid transformations\"\"\"\n",
    "    def __init__(self, in_size=28*28, hidden_size=128,\n",
    "                 out_size=10, num_layers=3, batchnorm=False):\n",
    "        super().__init__()\n",
    "        if batchnorm is False:\n",
    "            norm_layer = nn.Identity\n",
    "        else:\n",
    "            norm_layer = nn.BatchNorm1d\n",
    "\n",
    "        layers = []\n",
    "        layers.append(fc_layer(in_size, hidden_size, norm_layer))\n",
    "\n",
    "        for i in range(num_layers-1):\n",
    "            layers.append(fc_layer(hidden_size, hidden_size, norm_layer))\n",
    "\n",
    "        layers.append(nn.Linear(hidden_size, out_size))\n",
    "\n",
    "        self.layers = nn.Sequential(*layers)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = torch.flatten(x, 1)\n",
    "        return self.layers(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next we set up some dummy data, instantiate two versions of the model,\n",
    "and initialize the optimizers.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# set up dummy data\n",
    "x = torch.randn(10, 28, 28)\n",
    "y = torch.randint(10, (10, ))\n",
    "\n",
    "# init model\n",
    "model_bn = Net(batchnorm=True, num_layers=3)\n",
    "model_nobn = Net(batchnorm=False, num_layers=3)\n",
    "\n",
    "model_bn.train()\n",
    "model_nobn.train()\n",
    "\n",
    "optimizer_bn = optim.SGD(model_bn.parameters(), lr=0.01, momentum=0.9)\n",
    "optimizer_nobn = optim.SGD(model_nobn.parameters(), lr=0.01, momentum=0.9)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can verify that batch normalization is only being applied to one of\n",
    "the models by probing one of the internal layers:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(model_bn.layers[0])\n",
    "print(model_nobn.layers[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Registering hooks\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Because we wrapped up the logic and state of our model in a `nn.Module`,\n",
    "we need another method to access the intermediate gradients if we want\n",
    "to avoid modifying the module code directly. This is done by\n",
    "[registering a\n",
    "hook](https://docs.pytorch.org/docs/stable/notes/autograd.html#backward-hooks-execution).\n",
    "\n",
    "<div style=\"background-color: #e94f3b; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>WARNING:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>Using backward pass hooks attached to output tensors is preferred over using <code>retain_grad()</code> on the tensors themselves. An alternative method is to directly attach module hooks (e.g. <code>register_full_backward_hook()</code>) so long as the <code>nn.Module</code> instance does not do perform any in-place operations. For more information, please refer to <a href=\"https://github.com/pytorch/pytorch/issues/61519\">this issue</a>.</p>\n",
    "\n",
    "</div>\n",
    "\n",
    "The following code defines our hooks and gathers descriptive names for\n",
    "the network's layers.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# note that wrapper functions are used for Python closure\n",
    "# so that we can pass arguments.\n",
    "\n",
    "def hook_forward(module_name, grads, hook_backward):\n",
    "    def hook(module, args, output):\n",
    "        \"\"\"Forward pass hook which attaches backward pass hooks to intermediate tensors\"\"\"\n",
    "        output.register_hook(hook_backward(module_name, grads))\n",
    "    return hook\n",
    "\n",
    "def hook_backward(module_name, grads):\n",
    "    def hook(grad):\n",
    "        \"\"\"Backward pass hook which appends gradients\"\"\"\n",
    "        grads.append((module_name, grad))\n",
    "    return hook\n",
    "\n",
    "def get_all_layers(model, hook_forward, hook_backward):\n",
    "    \"\"\"Register forward pass hook (which registers a backward hook) to model outputs\n",
    "\n",
    "    Returns:\n",
    "        - layers: a dict with keys as layer/module and values as layer/module names\n",
    "                  e.g. layers[nn.Conv2d] = layer1.0.conv1\n",
    "        - grads: a list of tuples with module name and tensor output gradient\n",
    "                 e.g. grads[0] == (layer1.0.conv1, tensor.Torch(...))\n",
    "    \"\"\"\n",
    "    layers = dict()\n",
    "    grads = []\n",
    "    for name, layer in model.named_modules():\n",
    "        # skip Sequential and/or wrapper modules\n",
    "        if any(layer.children()) is False:\n",
    "            layers[layer] = name\n",
    "            layer.register_forward_hook(hook_forward(name, grads, hook_backward))\n",
    "    return layers, grads\n",
    "\n",
    "# register hooks\n",
    "layers_bn, grads_bn = get_all_layers(model_bn, hook_forward, hook_backward)\n",
    "layers_nobn, grads_nobn = get_all_layers(model_nobn, hook_forward, hook_backward)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Training and visualization\n",
    "\n",
    "Let's now train the models for a few epochs:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "epochs = 10\n",
    "\n",
    "for epoch in range(epochs):\n",
    "\n",
    "    # important to clear, because we append to\n",
    "    # outputs everytime we do a forward pass\n",
    "    grads_bn.clear()\n",
    "    grads_nobn.clear()\n",
    "\n",
    "    optimizer_bn.zero_grad()\n",
    "    optimizer_nobn.zero_grad()\n",
    "\n",
    "    y_pred_bn = model_bn(x)\n",
    "    y_pred_nobn = model_nobn(x)\n",
    "\n",
    "    loss_bn = F.cross_entropy(y_pred_bn, y)\n",
    "    loss_nobn = F.cross_entropy(y_pred_nobn, y)\n",
    "\n",
    "    loss_bn.backward()\n",
    "    loss_nobn.backward()\n",
    "\n",
    "    optimizer_bn.step()\n",
    "    optimizer_nobn.step()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After running the forward and backward pass, the gradients for all the\n",
    "intermediate tensors should be present in `grads_bn` and `grads_nobn`.\n",
    "We compute the mean absolute value of each gradient matrix so that we\n",
    "can compare the two models.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def get_grads(grads):\n",
    "    layer_idx = []\n",
    "    avg_grads = []\n",
    "    for idx, (name, grad) in enumerate(grads):\n",
    "        if grad is not None:\n",
    "            avg_grad = grad.abs().mean()\n",
    "            avg_grads.append(avg_grad)\n",
    "            # idx is backwards since we appended in backward pass\n",
    "            layer_idx.append(len(grads) - 1 - idx)\n",
    "    return layer_idx, avg_grads\n",
    "\n",
    "layer_idx_bn, avg_grads_bn = get_grads(grads_bn)\n",
    "layer_idx_nobn, avg_grads_nobn = get_grads(grads_nobn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the average gradients computed, we can now plot them and see how\n",
    "the values change as a function of the network depth. Notice that when\n",
    "we don't apply batch normalization, the gradient values in the\n",
    "intermediate layers fall to zero very quickly. The batch normalization\n",
    "model, however, maintains non-zero gradients in its intermediate layers.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.plot(layer_idx_bn, avg_grads_bn, label=\"With BatchNorm\", marker=\"o\")\n",
    "ax.plot(layer_idx_nobn, avg_grads_nobn, label=\"Without BatchNorm\", marker=\"x\")\n",
    "ax.set_xlabel(\"Layer depth\")\n",
    "ax.set_ylabel(\"Average gradient\")\n",
    "ax.set_title(\"Gradient flow\")\n",
    "ax.grid(True)\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Conclusion\n",
    "\n",
    "In this tutorial, we demonstrated how to visualize the gradient flow\n",
    "through a neural network wrapped in a `nn.Module` class. We\n",
    "qualitatively showed how batch normalization helps to alleviate the\n",
    "vanishing gradient issue which occurs with deep neural networks.\n",
    "\n",
    "If you would like to learn more about how PyTorch's autograd system\n",
    "works, please visit the [references](#references) below. If you have any\n",
    "feedback for this tutorial (improvements, typo fixes, etc.) then please\n",
    "use the [PyTorch Forums](https://discuss.pytorch.org/) and/or the [issue\n",
    "tracker](https://github.com/pytorch/tutorials/issues) to reach out.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# (Optional) Additional exercises\n",
    "\n",
    "-   Try increasing the number of layers (`num_layers`) in our model and\n",
    "    see what effect this has on the gradient flow graph\n",
    "-   How would you adapt the code to visualize average activations\n",
    "    instead of average gradients? (*Hint: in the hook_forward() function\n",
    "    we have access to the raw tensor output*)\n",
    "-   What are some other methods to deal with vanishing and exploding\n",
    "    gradients?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# References\n",
    "\n",
    "-   [A Gentle Introduction to\n",
    "    torch.autograd](https://docs.pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html)\n",
    "-   [Automatic Differentiation with\n",
    "    torch.autograd](https://docs.pytorch.org/tutorials/beginner/basics/autogradqs_tutorial)\n",
    "-   [Autograd\n",
    "    mechanics](https://docs.pytorch.org/docs/stable/notes/autograd.html)\n",
    "-   [Batch Normalization: Accelerating Deep Network Training by Reducing\n",
    "    Internal Covariate Shift](https://arxiv.org/abs/1502.03167)\n",
    "-   [On the difficulty of training Recurrent Neural\n",
    "    Networks](https://arxiv.org/abs/1211.5063)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
