{
 "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": [
    "# Functional Python Custom Operators {#python-custom-ops-functional}\n",
    "\n",
    "Use this path when the operator mutates no Tensor inputs and returns\n",
    "fresh Tensor outputs.\n",
    "\n",
    "If the operator must work with `torch.compile` or `torch.export`,\n",
    "`register a fake kernel <python-custom-ops-functional-register-fake>`{.interpreted-text\n",
    "role=\"ref\"}. The fake kernel describes output metadata without running\n",
    "the real kernel.\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",
    "-   use `mutates_args=()`;\n",
    "-   return tensors that do not alias any input;\n",
    "-   register a fake kernel for `torch.compile` and `torch.export`;\n",
    "-   validate the operator with `torch.library.opcheck`.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Example: wrapping NumPy sin into a custom operator\n",
    "\n",
    "Let\\'s say that we are using NumPy\\'s `sin` operation. This is an\n",
    "ordinary Python function from PyTorch\\'s point of view: it converts the\n",
    "Tensor to a NumPy array, calls NumPy, and returns a fresh Tensor.\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",
    "def numpy_sin_impl(x: Tensor) -> Tensor:\n",
    "    result = torch.empty_like(x)\n",
    "    np.sin(x.detach().numpy(), out=result.numpy())\n",
    "    return result\n",
    "\n",
    "\n",
    "x = torch.randn(5)\n",
    "torch.testing.assert_close(numpy_sin_impl(x), x.sin())\n",
    "\n",
    "# This small example focuses on the custom-operator mechanics. More complex\n",
    "# Python or third-party library calls may not be handled effectively\n",
    "# out-of-the-box by ``torch.compile``: ``torch.compile`` may induce a\n",
    "# `\"graph break\" <https://pytorch.org/docs/stable/torch.compiler_faq.html#graph-breaks>`_\n",
    "# on functions it is unable to handle, and graph breaks are bad for performance.\n",
    "# A custom operator gives PyTorch an explicit boundary for such code.\n",
    "#\n",
    "# To make ``numpy_sin_impl`` available as a custom operator that works with\n",
    "# ``torch.compile`` and ``torch.export``, we need to do two things:\n",
    "#\n",
    "# 1. wrap the function into a PyTorch custom operator.\n",
    "# 2. add a \"``FakeTensor`` kernel\" (aka \"meta kernel\") to the operator.\n",
    "#    Given some ``FakeTensors`` inputs (dummy Tensors that don't have storage),\n",
    "#    this function should return dummy Tensors of your choice with the correct\n",
    "#    Tensor metadata (shape/strides/``dtype``/device).\n",
    "\n",
    "\n",
    "@torch.library.custom_op(\n",
    "    \"mylib_functional::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"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::: {#python-custom-ops-functional-register-fake}\n",
    "Use `register_fake` to add a `FakeTensor` kernel for the operator.\n",
    "`numpy_sin` returns one Tensor with the same shape, strides, dtype,\n",
    "device, and storage offset as `torch.empty_like(x)`, so the fake kernel\n",
    "can return `empty_like(x)`. In general, the fake kernel must match all\n",
    "output metadata, including storage offset when relevant.\n",
    ":::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "@numpy_sin.register_fake\n",
    "def _(x):\n",
    "    return torch.empty_like(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After this, `numpy_sin` can be used under `torch.compile`:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "@torch.compile(fullgraph=True)\n",
    "def f(x):\n",
    "    return numpy_sin(x)\n",
    "\n",
    "\n",
    "result = f(x)\n",
    "torch.testing.assert_close(result, x.sin())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A PIL image transform, Python binding to a C++ extension, or another\n",
    "third-party library call follows the same pattern. If it returns\n",
    "tensors, write the fake kernel to match the real output metadata\n",
    "exactly: shape, strides, dtype, device, layout, and storage offset when\n",
    "relevant.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Example: fake kernels must match strides\n",
    "\n",
    "The fake kernel must match the real output strides, not only the shape.\n",
    "This operator returns a fresh Tensor with the same shape as `x` but\n",
    "different strides.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def numpy_sin_strided_impl(x: Tensor) -> Tensor:\n",
    "    result = torch.empty_strided(\n",
    "        x.shape,\n",
    "        tuple(reversed(x.stride())),\n",
    "        dtype=x.dtype,\n",
    "        device=x.device,\n",
    "    )\n",
    "    np.sin(x.detach().numpy(), out=result.numpy())\n",
    "    return result\n",
    "\n",
    "\n",
    "@torch.library.custom_op(\n",
    "    \"mylib_functional::numpy_sin_strided_bad\",\n",
    "    mutates_args=(),\n",
    "    device_types=\"cpu\",\n",
    ")\n",
    "def numpy_sin_strided_bad(x: Tensor) -> Tensor:\n",
    "    return numpy_sin_strided_impl(x)\n",
    "\n",
    "\n",
    "@numpy_sin_strided_bad.register_fake\n",
    "def _(x):\n",
    "    return torch.empty_like(x)\n",
    "\n",
    "\n",
    "try:\n",
    "    torch.library.opcheck(numpy_sin_strided_bad, (torch.randn(2, 3),))\n",
    "except Exception as exc:\n",
    "    print(f\"opcheck caught incorrect fake kernel metadata: {type(exc).__name__}\")\n",
    "else:\n",
    "    torch_version = tuple(\n",
    "        int(part) for part in torch.__version__.split(\"+\")[0].split(\".\")[:2]\n",
    "    )\n",
    "    if torch_version >= (2, 13):\n",
    "        raise AssertionError(\"Expected opcheck to fail\")\n",
    "    print(\"PyTorch versions before 2.13 may not catch this metadata mismatch\")\n",
    "\n",
    "\n",
    "@torch.library.custom_op(\n",
    "    \"mylib_functional::numpy_sin_strided\",\n",
    "    mutates_args=(),\n",
    "    device_types=\"cpu\",\n",
    ")\n",
    "def numpy_sin_strided(x: Tensor) -> Tensor:\n",
    "    return numpy_sin_strided_impl(x)\n",
    "\n",
    "\n",
    "@numpy_sin_strided.register_fake\n",
    "def _(x):\n",
    "    return torch.empty_strided(\n",
    "        x.shape,\n",
    "        tuple(reversed(x.stride())),\n",
    "        dtype=x.dtype,\n",
    "        device=x.device,\n",
    "    )\n",
    "\n",
    "\n",
    "torch.library.opcheck(numpy_sin_strided, (torch.randn(2, 3),))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Testing Python custom operators\n",
    "\n",
    "Use `torch.library.opcheck` to test that the custom operator was\n",
    "registered correctly. This does not test numerical correctness; write\n",
    "separate tests for that.\n",
    "\n",
    "To use `opcheck`, pass it a set of example inputs to test against. If\n",
    "your operator supports training, then the examples should include\n",
    "Tensors that require grad. If your operator supports multiple devices,\n",
    "then the examples should include Tensors from each device.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "examples = [\n",
    "    (torch.randn(5),),\n",
    "    (torch.randn(0, 3),),\n",
    "    (torch.randn(2, 3, dtype=torch.double),),\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": [
    "To add autograd, `torch.vmap`, or other subsystem support, 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
}
