{
 "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": [
    "# torch.vmap\n",
    "\n",
    "This tutorial introduces torch.vmap, an autovectorizer for PyTorch\n",
    "operations. torch.vmap is a prototype feature and cannot handle a number\n",
    "of use cases; however, we would like to gather use cases for it to\n",
    "inform the design. If you are considering using torch.vmap or think it\n",
    "would be really cool for something, please contact us at\n",
    "<https://github.com/pytorch/pytorch/issues/42368>.\n",
    "\n",
    "## So, what is vmap?\n",
    "\n",
    "vmap is a higher-order function. It accepts a function\n",
    "[func]{.title-ref} and returns a new function that maps\n",
    "[func]{.title-ref} over some dimension of the inputs. It is highly\n",
    "inspired by JAX\\'s vmap.\n",
    "\n",
    "Semantically, vmap pushes the \\\"map\\\" into PyTorch operations called by\n",
    "[func]{.title-ref}, effectively vectorizing those operations.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "# NB: vmap is only available on nightly builds of PyTorch.\n",
    "# You can download one at pytorch.org if you're interested in testing it out.\n",
    "from torch import vmap"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first use case for vmap is making it easier to handle batch\n",
    "dimensions in your code. One can write a function [func]{.title-ref}\n",
    "that runs on examples and then lift it to a function that can take\n",
    "batches of examples with [vmap(func)]{.title-ref}. [func]{.title-ref}\n",
    "however is subject to many restrictions:\n",
    "\n",
    "-   it must be functional (one cannot mutate a Python data structure\n",
    "    inside of it), with the exception of in-place PyTorch operations.\n",
    "-   batches of examples must be provided as Tensors. This means that\n",
    "    vmap doesn\\'t handle variable-length sequences out of the box.\n",
    "\n",
    "One example of using [vmap]{.title-ref} is to compute batched dot\n",
    "products. PyTorch doesn\\'t provide a batched [torch.dot]{.title-ref}\n",
    "API; instead of unsuccessfully rummaging through docs, use\n",
    "[vmap]{.title-ref} to construct a new function:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "torch.dot                            # [D], [D] -> []\n",
    "batched_dot = torch.vmap(torch.dot)  # [N, D], [N, D] -> [N]\n",
    "x, y = torch.randn(2, 5), torch.randn(2, 5)\n",
    "batched_dot(x, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[vmap]{.title-ref} can be helpful in hiding batch dimensions, leading to\n",
    "a simpler model authoring experience.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "batch_size, feature_size = 3, 5\n",
    "weights = torch.randn(feature_size, requires_grad=True)\n",
    "\n",
    "# Note that model doesn't work with a batch of feature vectors because\n",
    "# torch.dot must take 1D tensors. It's pretty easy to rewrite this\n",
    "# to use `torch.matmul` instead, but if we didn't want to do that or if\n",
    "# the code is more complicated (e.g., does some advanced indexing\n",
    "# shenanigins), we can simply call `vmap`. `vmap` batches over ALL\n",
    "# inputs, unless otherwise specified (with the in_dims argument,\n",
    "# please see the documentation for more details).\n",
    "def model(feature_vec):\n",
    "    # Very simple linear model with activation\n",
    "    return feature_vec.dot(weights).relu()\n",
    "\n",
    "examples = torch.randn(batch_size, feature_size)\n",
    "result = torch.vmap(model)(examples)\n",
    "expected = torch.stack([model(example) for example in examples.unbind()])\n",
    "assert torch.allclose(result, expected)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[vmap]{.title-ref} can also help vectorize computations that were\n",
    "previously difficult or impossible to batch. This bring us to our second\n",
    "use case: batched gradient computation.\n",
    "\n",
    "-   <https://github.com/pytorch/pytorch/issues/8304>\n",
    "-   <https://github.com/pytorch/pytorch/issues/23475>\n",
    "\n",
    "The PyTorch autograd engine computes vjps (vector-Jacobian products).\n",
    "Using vmap, we can compute (batched vector) - jacobian products.\n",
    "\n",
    "One example of this is computing a full Jacobian matrix (this can also\n",
    "be applied to computing a full Hessian matrix). Computing a full\n",
    "Jacobian matrix for some function f: R\\^N -\\> R\\^N usually requires N\n",
    "calls to [autograd.grad]{.title-ref}, one per Jacobian row.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Setup\n",
    "N = 5\n",
    "def f(x):\n",
    "    return x ** 2\n",
    "\n",
    "x = torch.randn(N, requires_grad=True)\n",
    "y = f(x)\n",
    "basis_vectors = torch.eye(N)\n",
    "\n",
    "# Sequential approach\n",
    "jacobian_rows = [torch.autograd.grad(y, x, v, retain_graph=True)[0]\n",
    "                 for v in basis_vectors.unbind()]\n",
    "jacobian = torch.stack(jacobian_rows)\n",
    "\n",
    "# Using `vmap`, we can vectorize the whole computation, computing the\n",
    "# Jacobian in a single call to `autograd.grad`.\n",
    "def get_vjp(v):\n",
    "    return torch.autograd.grad(y, x, v)[0]\n",
    "\n",
    "jacobian_vmap = vmap(get_vjp)(basis_vectors)\n",
    "assert torch.allclose(jacobian_vmap, jacobian)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The third main use case for vmap is computing per-sample-gradients. This\n",
    "is something that the vmap prototype cannot handle performantly right\n",
    "now. We\\'re not sure what the API for computing per-sample-gradients\n",
    "should be, but if you have ideas, please comment in\n",
    "<https://github.com/pytorch/pytorch/issues/7786>.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def model(sample, weight):\n",
    "    # do something...    \n",
    "    return torch.dot(sample, weight)\n",
    "\n",
    "def grad_sample(sample):\n",
    "    return torch.autograd.functional.vjp(lambda weight: model(sample), weight)[1]\n",
    "\n",
    "# The following doesn't actually work in the vmap prototype. But it\n",
    "# could be an API for computing per-sample-gradients.\n",
    "\n",
    "# batch_of_samples = torch.randn(64, 5)\n",
    "# vmap(grad_sample)(batch_of_samples)"
   ]
  }
 ],
 "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
}
