{
 "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": [
    "# Mutable Python Custom Operators {#python-custom-ops-mutable}\n",
    "\n",
    "`Functional custom operators <python-custom-ops-functional>`{.interpreted-text\n",
    "role=\"ref\"} showed `numpy.sin` as an operator that returns a fresh\n",
    "Tensor. This page shows the mutable version: a kernel that writes\n",
    "`sin(x)` into an existing output Tensor. Mutable operators have a\n",
    "different contract from functional operators.\n",
    "\n",
    "Before writing the operator, read the required schema and\n",
    "mutation/aliasing contract rules in\n",
    "`python-custom-ops-schema-contract`{.interpreted-text role=\"ref\"}.\n",
    "\n",
    "Checklist:\n",
    "\n",
    "-   choose one mutation pattern and keep it stable;\n",
    "-   list every mutated Tensor argument in `mutates_args`;\n",
    "-   do not return mutated inputs unless you are using a tagged in-place\n",
    "    or `out=` operator (available starting in PyTorch 2.13);\n",
    "-   validate the operator with `torch.library.opcheck`.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Choose one mutation contract\n",
    "\n",
    "Choose the mutation behavior before adding optional registrations.\n",
    "PyTorch needs this contract for functionalization in `torch.compile` and\n",
    "autograd.\n",
    "\n",
    "If the operator does not mutate any Tensor input, use the functional\n",
    "operator path instead.\n",
    "\n",
    "If the operator mutates the first positional Tensor and returns it, use\n",
    "a tagged in-place operator, starting in PyTorch 2.13.\n",
    "\n",
    "If the operator accepts write-only keyword-only `out=` Tensor arguments\n",
    "and returns them, use a tagged `out=` operator, starting in PyTorch\n",
    "2.13.\n",
    "\n",
    "For other mutable operators, list every mutated argument in\n",
    "`mutates_args` and do not return mutated inputs or their aliases.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import torch\n",
    "from torch import Tensor"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Example: write NumPy sin into an output buffer\n",
    "\n",
    "Functions that mutate inputs are common because that is how many\n",
    "low-level kernels are written; for example, a kernel that computes `sin`\n",
    "may take in the input and an output tensor and write `input.sin()` to\n",
    "the output tensor.\n",
    "\n",
    "This operator writes `sin(x)` into `out` and returns `None`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "@torch.library.custom_op(\n",
    "    \"mylib_mutable::numpy_sin_out\",\n",
    "    mutates_args={\"out\"},\n",
    "    device_types=\"cpu\",\n",
    ")\n",
    "def numpy_sin_out(x: Tensor, out: Tensor) -> None:\n",
    "    if x.shape != out.shape:\n",
    "        raise RuntimeError(\"x and out must have the same shape\")\n",
    "    if x.dtype != out.dtype:\n",
    "        raise RuntimeError(\"x and out must have the same dtype\")\n",
    "    if x.device != out.device:\n",
    "        raise RuntimeError(\"x and out must be on the same device\")\n",
    "    np.sin(x.detach().numpy(), out=out.numpy())\n",
    "\n",
    "\n",
    "x = torch.randn(5)\n",
    "out = torch.empty_like(x)\n",
    "numpy_sin_out(x, out)\n",
    "torch.testing.assert_close(out, x.sin())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Because the operator doesn\\'t return anything, there is no need to\n",
    "register a `FakeTensor` kernel (meta kernel) to get it to work with\n",
    "`torch.compile`. If a mutable operator also returns a fresh Tensor,\n",
    "register a fake kernel for that output.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "@torch.compile(fullgraph=True)\n",
    "def compiled_numpy_sin_out(x):\n",
    "    out = torch.empty_like(x)\n",
    "    numpy_sin_out(x, out)\n",
    "    return out\n",
    "\n",
    "\n",
    "torch.testing.assert_close(compiled_numpy_sin_out(x), x.sin())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# PyTorch-style in-place and out= operators\n",
    "\n",
    "Starting in PyTorch 2.13, `torch.library.custom_op` supports tagged\n",
    "in-place and `out=` custom operators. Tagged in-place operators return\n",
    "the same Tensor they mutate. Tagged `out=` operators return their\n",
    "keyword-only output buffers in declaration order. This example uses\n",
    "`mylib_mutable::sin_` for a tagged in-place custom operator and\n",
    "`mylib_mutable::sin_out` for a tagged `out=` custom operator.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "supports_tagged_mutable_ops = (\n",
    "    hasattr(torch, \"Tag\")\n",
    "    and hasattr(torch.Tag, \"inplace\")\n",
    "    and hasattr(torch.Tag, \"out\")\n",
    ")\n",
    "\n",
    "if supports_tagged_mutable_ops:\n",
    "\n",
    "    @torch.library.custom_op(\n",
    "        \"mylib_mutable::sin_\",\n",
    "        mutates_args={\"x\"},\n",
    "        tags=torch.Tag.inplace,\n",
    "    )\n",
    "    def sin_(x: Tensor) -> Tensor:\n",
    "        x.sin_()\n",
    "        return x\n",
    "\n",
    "\n",
    "    @torch.library.custom_op(\n",
    "        \"mylib_mutable::sin_out\",\n",
    "        mutates_args={\"out\"},\n",
    "        tags=torch.Tag.out,\n",
    "    )\n",
    "    def sin_out(x: Tensor, *, out: Tensor) -> Tensor:\n",
    "        torch.sin(x, out=out)\n",
    "        return out\n",
    "\n",
    "\n",
    "    x_for_inplace = torch.randn(3)\n",
    "    expected = x_for_inplace.sin()\n",
    "    torch.testing.assert_close(sin_(x_for_inplace), expected)\n",
    "\n",
    "    out_for_sin = torch.empty_like(x)\n",
    "    torch.testing.assert_close(\n",
    "        sin_out(x, out=out_for_sin),\n",
    "        x.sin(),\n",
    "    )\n",
    "    torch.testing.assert_close(out_for_sin, x.sin())\n",
    "\n",
    "    torch.library.opcheck(sin_, (torch.randn(3),))\n",
    "    torch.library.opcheck(\n",
    "        sin_out,\n",
    "        (torch.randn(3),),\n",
    "        {\"out\": torch.empty(3)},\n",
    "    )\n",
    "else:\n",
    "    print(\"Tagged in-place and out= custom operators require PyTorch 2.13 or later.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Validate the operator\n",
    "\n",
    "And here\\'s an `opcheck` run telling us that we did indeed register the\n",
    "operator correctly. `opcheck` would error out if we forgot to add `out`\n",
    "to `mutates_args`, for example.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "examples = [\n",
    "    (torch.randn(5), torch.empty(5)),\n",
    "    (torch.randn(0, 3), torch.empty(0, 3)),\n",
    "    (\n",
    "        torch.randn(2, 3, dtype=torch.double),\n",
    "        torch.empty(2, 3, dtype=torch.double),\n",
    "    ),\n",
    "    (\n",
    "        torch.randn(2, 3).t(),\n",
    "        torch.empty_strided((3, 2), (1, 3)),\n",
    "    ),\n",
    "]\n",
    "\n",
    "for example in examples:\n",
    "    torch.library.opcheck(numpy_sin_out, example)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For autograd, `torch.vmap`, or other subsystem behavior, continue to\n",
    "`python-custom-ops-registrations`{.interpreted-text role=\"ref\"}.\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
}
