{
 "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": [
    "# Adding Training and Other Registrations to Python Custom Operators {#python-custom-ops-registrations}\n",
    "\n",
    "Start here after a base operator passes `torch.library.opcheck`:\n",
    "\n",
    "-   `python-custom-ops-functional`{.interpreted-text role=\"ref\"}\n",
    "-   `python-custom-ops-mutable`{.interpreted-text role=\"ref\"}\n",
    "\n",
    "Registrations do not change the base contract. After adding one, rerun\n",
    "`torch.library.opcheck` on representative inputs for that subsystem.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Adding training support for NumPy sin\n",
    "\n",
    "Use `torch.library.register_autograd` to add training support for an\n",
    "operator. Prefer this over directly using `torch.autograd.Function`;\n",
    "some compositions of `autograd.Function` with PyTorch operator\n",
    "registration APIs can lead to (and has led to) silent incorrectness when\n",
    "composed with `torch.compile`.\n",
    "\n",
    "If you don\\'t need training support, there is no need to use\n",
    "`torch.library.register_autograd`. If you end up training with a\n",
    "`custom_op` that doesn\\'t have an autograd registration, we\\'ll raise an\n",
    "error message.\n",
    "\n",
    "This page uses the same `numpy.sin` operation as the functional and\n",
    "mutable pages so the only new concept is the autograd registration.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import torch\n",
    "from torch import Tensor\n",
    "\n",
    "\n",
    "@torch.library.custom_op(\n",
    "    \"mylib_training::numpy_sin\",\n",
    "    mutates_args=(),\n",
    "    device_types=\"cpu\",\n",
    ")\n",
    "def numpy_sin(x: Tensor) -> Tensor:\n",
    "    result = torch.empty_like(x)\n",
    "    np.sin(x.detach().numpy(), out=result.numpy())\n",
    "    return result\n",
    "\n",
    "\n",
    "@numpy_sin.register_fake\n",
    "def _(x):\n",
    "    return torch.empty_like(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The fake kernel must describe the same output metadata as the real\n",
    "kernel, including shape, strides, dtype, device, layout, and storage\n",
    "offset when relevant. Here the real kernel returns\n",
    "`torch.empty_like(x)`, so the fake kernel does the same.\n",
    "\n",
    "The gradient formula for `sin(x)` is `cos(x)`. The backward formula must\n",
    "be written in terms of PyTorch-understood operations or other custom\n",
    "operators. Do not directly use non-traceable Python or NumPy code from\n",
    "the backward formula.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def numpy_sin_setup_context(ctx, inputs, output):\n",
    "    (x,) = inputs\n",
    "    ctx.save_for_backward(x)\n",
    "\n",
    "\n",
    "def numpy_sin_backward(ctx, grad_output):\n",
    "    (x,) = ctx.saved_tensors\n",
    "    return grad_output * x.cos()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Register the backward formula and the context setup function:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "numpy_sin.register_autograd(\n",
    "    numpy_sin_backward,\n",
    "    setup_context=numpy_sin_setup_context,\n",
    ")\n",
    "\n",
    "\n",
    "x = torch.randn(5, requires_grad=True)\n",
    "y = numpy_sin(x)\n",
    "y.sum().backward()\n",
    "torch.testing.assert_close(x.grad, x.detach().cos())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Testing autograd registration\n",
    "\n",
    "`opcheck` verifies that autograd was registered in a supported way, but\n",
    "it does not prove that the gradient formula is mathematically correct.\n",
    "Use separate numerical tests for that, either manual ones or\n",
    "`torch.autograd.gradcheck`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "gradcheck_input = torch.randn(3, dtype=torch.double, requires_grad=True)\n",
    "torch.autograd.gradcheck(numpy_sin, (gradcheck_input,))\n",
    "\n",
    "examples = [\n",
    "    (torch.randn(5),),\n",
    "    (torch.randn(0, 3),),\n",
    "    (torch.randn(4, requires_grad=True),),\n",
    "    (torch.randn(2, dtype=torch.double, requires_grad=True),),\n",
    "    (torch.randn(2, 3).t(),),\n",
    "    (torch.randn(8)[1:],),\n",
    "]\n",
    "\n",
    "for example in examples:\n",
    "    torch.library.opcheck(numpy_sin, example)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Other registrations\n",
    "\n",
    "Add these only when users need them.\n",
    "\n",
    "-   **Multiple device kernels:** pass `device_types=\"cpu\"` or\n",
    "    `device_types=\"cuda\"` if the implementation only works on one\n",
    "    device. Register device-specific kernels when devices need different\n",
    "    code.\n",
    "-   **\\`\\`torch.vmap\\`\\`:** register a vmap rule with\n",
    "    `torch.library.register_vmap` when batching over the operator should\n",
    "    do something different from a Python loop over the batch dimension.\n",
    "-   **Tensor subclasses or modes:** use\n",
    "    `torch.library.register_torch_dispatch` when a Tensor subclass or\n",
    "    `TorchDispatchMode` needs special behavior.\n",
    "-   **Autocast:** for C++/CUDA operators that should participate in\n",
    "    autocast, add an autocast registration as described in the C++\n",
    "    custom operator guide.\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
}
