{
 "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": [
    "# MaskedTensor Overview\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This tutorial is designed to serve as a starting point for using\n",
    "MaskedTensors and discuss its masking semantics.\n",
    "\n",
    "MaskedTensor serves as an extension to `torch.Tensor`{.interpreted-text\n",
    "role=\"class\"} that provides the user with the ability to:\n",
    "\n",
    "-   use any masked semantics (for example, variable length tensors,\n",
    "    nan\\* operators, etc.)\n",
    "-   differentiation between 0 and NaN gradients\n",
    "-   various sparse applications (see tutorial below)\n",
    "\n",
    "For a more detailed introduction on what MaskedTensors are, please find\n",
    "the [torch.masked\n",
    "documentation](https://pytorch.org/docs/master/masked.html).\n",
    "\n",
    "# Using MaskedTensor\n",
    "\n",
    "In this section we discuss how to use MaskedTensor including how to\n",
    "construct, access, the data and mask, as well as indexing and slicing.\n",
    "\n",
    "## Preparation\n",
    "\n",
    "We\\'ll begin by doing the necessary setup for the tutorial:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "from torch.masked import masked_tensor, as_masked_tensor\n",
    "import warnings\n",
    "\n",
    "# Disable prototype warnings and such\n",
    "warnings.filterwarnings(action='ignore', category=UserWarning)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Construction\n",
    "\n",
    "There are a few different ways to construct a MaskedTensor:\n",
    "\n",
    "-   The first way is to directly invoke the MaskedTensor class\n",
    "-   The second (and our recommended way) is to use\n",
    "    `masked.masked_tensor`{.interpreted-text role=\"func\"} and\n",
    "    `masked.as_masked_tensor`{.interpreted-text role=\"func\"} factory\n",
    "    functions, which are analogous to `torch.tensor`{.interpreted-text\n",
    "    role=\"func\"} and `torch.as_tensor`{.interpreted-text role=\"func\"}\n",
    "\n",
    "Throughout this tutorial, we will be assuming the import line: [from\n",
    "torch.masked import masked_tensor]{.title-ref}.\n",
    "\n",
    "# Accessing the data and mask\n",
    "\n",
    "The underlying fields in a MaskedTensor can be accessed through:\n",
    "\n",
    "-   the `MaskedTensor.get_data`{.interpreted-text role=\"meth\"} function\n",
    "-   the `MaskedTensor.get_mask`{.interpreted-text role=\"meth\"} function.\n",
    "    Recall that `True` indicates \\\"specified\\\" or \\\"valid\\\" while\n",
    "    `False` indicates \\\"unspecified\\\" or \\\"invalid\\\".\n",
    "\n",
    "In general, the underlying data that is returned may not be valid in the\n",
    "unspecified entries, so we recommend that when users require a Tensor\n",
    "without any masked entries, that they use\n",
    "`MaskedTensor.to_tensor`{.interpreted-text role=\"meth\"} (as shown above)\n",
    "to return a Tensor with filled values.\n",
    "\n",
    "# Indexing and slicing\n",
    "\n",
    "`MaskedTensor`{.interpreted-text role=\"class\"} is a Tensor subclass,\n",
    "which means that it inherits the same semantics for indexing and slicing\n",
    "as `torch.Tensor`{.interpreted-text role=\"class\"}. Below are some\n",
    "examples of common indexing and slicing patterns:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "data = torch.arange(24).reshape(2, 3, 4)\n",
    "mask = data % 2 == 0\n",
    "\n",
    "print(\"data:\\n\", data)\n",
    "print(\"mask:\\n\", mask)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# float is used for cleaner visualization when being printed\n",
    "mt = masked_tensor(data.float(), mask)\n",
    "\n",
    "print(\"mt[0]:\\n\", mt[0])\n",
    "print(\"mt[:, :, 2:4]:\\n\", mt[:, :, 2:4])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Why is MaskedTensor useful?\n",
    "\n",
    "Because of `MaskedTensor`{.interpreted-text role=\"class\"}\\'s treatment\n",
    "of specified and unspecified values as a first-class citizen instead of\n",
    "an afterthought (with filled values, nans, etc.), it is able to solve\n",
    "for several of the shortcomings that regular Tensors are unable to;\n",
    "indeed, `MaskedTensor`{.interpreted-text role=\"class\"} was born in a\n",
    "large part due to these recurring issues.\n",
    "\n",
    "Below, we will discuss some of the most common issues that are still\n",
    "unresolved in PyTorch today and illustrate how\n",
    "`MaskedTensor`{.interpreted-text role=\"class\"} can solve these problems.\n",
    "\n",
    "## Distinguishing between 0 and NaN gradient\n",
    "\n",
    "One issue that `torch.Tensor`{.interpreted-text role=\"class\"} runs into\n",
    "is the inability to distinguish between gradients that are undefined\n",
    "(NaN) vs. gradients that are actually 0. Because PyTorch does not have a\n",
    "way of marking a value as specified/valid vs. unspecified/invalid, it is\n",
    "forced to rely on NaN or 0 (depending on the use case), leading to\n",
    "unreliable semantics since many operations aren\\'t meant to handle NaN\n",
    "values properly. What is even more confusing is that sometimes depending\n",
    "on the order of operations, the gradient could vary (for example,\n",
    "depending on how early in the chain of operations a NaN value\n",
    "manifests).\n",
    "\n",
    "`MaskedTensor`{.interpreted-text role=\"class\"} is the perfect solution\n",
    "for this!\n",
    "\n",
    "### torch.where\n",
    "\n",
    "In [Issue 10729](https://github.com/pytorch/pytorch/issues/10729), we\n",
    "notice a case where the order of operations can matter when using\n",
    "`torch.where`{.interpreted-text role=\"func\"} because we have trouble\n",
    "differentiating between if the 0 is a real 0 or one from undefined\n",
    "gradients. Therefore, we remain consistent and mask out the results:\n",
    "\n",
    "Current result:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x = torch.tensor([-10., -5, 0, 5, 10, 50, 60, 70, 80, 90, 100], requires_grad=True, dtype=torch.float)\n",
    "y = torch.where(x < 0, torch.exp(x), torch.ones_like(x))\n",
    "y.sum().backward()\n",
    "x.grad"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`MaskedTensor`{.interpreted-text role=\"class\"} result:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x = torch.tensor([-10., -5, 0, 5, 10, 50, 60, 70, 80, 90, 100])\n",
    "mask = x < 0\n",
    "mx = masked_tensor(x, mask, requires_grad=True)\n",
    "my = masked_tensor(torch.ones_like(x), ~mask, requires_grad=True)\n",
    "y = torch.where(mask, torch.exp(mx), my)\n",
    "y.sum().backward()\n",
    "mx.grad"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The gradient here is only provided to the selected subset. Effectively,\n",
    "this changes the gradient of [where]{.title-ref} to mask out elements\n",
    "instead of setting them to zero.\n",
    "\n",
    "# Another torch.where\n",
    "\n",
    "[Issue 52248](https://github.com/pytorch/pytorch/issues/52248) is\n",
    "another example.\n",
    "\n",
    "Current result:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "a = torch.randn((), requires_grad=True)\n",
    "b = torch.tensor(False)\n",
    "c = torch.ones(())\n",
    "print(\"torch.where(b, a/0, c):\\n\", torch.where(b, a/0, c))\n",
    "print(\"torch.autograd.grad(torch.where(b, a/0, c), a):\\n\", torch.autograd.grad(torch.where(b, a/0, c), a))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`MaskedTensor`{.interpreted-text role=\"class\"} result:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "a = masked_tensor(torch.randn(()), torch.tensor(True), requires_grad=True)\n",
    "b = torch.tensor(False)\n",
    "c = torch.ones(())\n",
    "print(\"torch.where(b, a/0, c):\\n\", torch.where(b, a/0, c))\n",
    "print(\"torch.autograd.grad(torch.where(b, a/0, c), a):\\n\", torch.autograd.grad(torch.where(b, a/0, c), a))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This issue is similar (and even links to the next issue below) in that\n",
    "it expresses frustration with unexpected behavior because of the\n",
    "inability to differentiate \\\"no gradient\\\" vs \\\"zero gradient\\\", which\n",
    "in turn makes working with other ops difficult to reason about.\n",
    "\n",
    "# When using mask, x/0 yields NaN grad\n",
    "\n",
    "In [Issue 4132](https://github.com/pytorch/pytorch/issues/4132), the\n",
    "user proposes that [x.grad]{.title-ref} should be [\\[0, 1\\]]{.title-ref}\n",
    "instead of the [\\[nan, 1\\]]{.title-ref}, whereas\n",
    "`MaskedTensor`{.interpreted-text role=\"class\"} makes this very clear by\n",
    "masking out the gradient altogether.\n",
    "\n",
    "Current result:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x = torch.tensor([1., 1.], requires_grad=True)\n",
    "div = torch.tensor([0., 1.])\n",
    "y = x/div # => y is [inf, 1]\n",
    "mask = (div != 0)  # => mask is [0, 1]\n",
    "y[mask].backward()\n",
    "x.grad"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`MaskedTensor`{.interpreted-text role=\"class\"} result:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x = torch.tensor([1., 1.], requires_grad=True)\n",
    "div = torch.tensor([0., 1.])\n",
    "y = x/div # => y is [inf, 1]\n",
    "mask = (div != 0) # => mask is [0, 1]\n",
    "loss = as_masked_tensor(y, mask)\n",
    "loss.sum().backward()\n",
    "x.grad"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# `torch.nansum`{.interpreted-text role=\"func\"} and `torch.nanmean`{.interpreted-text role=\"func\"}\n",
    "\n",
    "In [Issue 67180](https://github.com/pytorch/pytorch/issues/67180), the\n",
    "gradient isn\\'t calculate properly (a longstanding issue), whereas\n",
    "`MaskedTensor`{.interpreted-text role=\"class\"} handles it correctly.\n",
    "\n",
    "Current result:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "a = torch.tensor([1., 2., float('nan')])\n",
    "b = torch.tensor(1.0, requires_grad=True)\n",
    "c = a * b\n",
    "c1 = torch.nansum(c)\n",
    "bgrad1, = torch.autograd.grad(c1, b, retain_graph=True)\n",
    "bgrad1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`MaskedTensor`{.interpreted-text role=\"class\"} result:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "a = torch.tensor([1., 2., float('nan')])\n",
    "b = torch.tensor(1.0, requires_grad=True)\n",
    "mt = masked_tensor(a, ~torch.isnan(a))\n",
    "c = mt * b\n",
    "c1 = torch.sum(c)\n",
    "bgrad1, = torch.autograd.grad(c1, b, retain_graph=True)\n",
    "bgrad1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Safe Softmax\n",
    "\n",
    "Safe softmax is another great example of [an\n",
    "issue](https://github.com/pytorch/pytorch/issues/55056) that arises\n",
    "frequently. In a nutshell, if there is an entire batch that is \\\"masked\n",
    "out\\\" or consists entirely of padding (which, in the softmax case,\n",
    "translates to being set [-inf]{.title-ref}), then this will result in\n",
    "NaNs, which can lead to training divergence.\n",
    "\n",
    "Luckily, `MaskedTensor`{.interpreted-text role=\"class\"} has solved this\n",
    "issue. Consider this setup:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "data = torch.randn(3, 3)\n",
    "mask = torch.tensor([[True, False, False], [True, False, True], [False, False, False]])\n",
    "x = data.masked_fill(~mask, float('-inf'))\n",
    "mt = masked_tensor(data, mask)\n",
    "print(\"x:\\n\", x)\n",
    "print(\"mt:\\n\", mt)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For example, we want to calculate the softmax along [dim=0]{.title-ref}.\n",
    "Note that the second column is \\\"unsafe\\\" (i.e. entirely masked out), so\n",
    "when the softmax is calculated, the result will yield [0/0 =\n",
    "nan]{.title-ref} since [exp(-inf) = 0]{.title-ref}. However, what we\n",
    "would really like is for the gradients to be masked out since they are\n",
    "unspecified and would be invalid for training.\n",
    "\n",
    "PyTorch result:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x.softmax(0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`MaskedTensor`{.interpreted-text role=\"class\"} result:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "mt.softmax(0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Implementing missing torch.nan\\* operators\n",
    "\n",
    "In [Issue 61474](https://github.com/pytorch/pytorch/issues/61474), there\n",
    "is a request to add additional operators to cover the various\n",
    "[torch.nan\\*]{.title-ref} applications, such as `torch.nanmax`,\n",
    "`torch.nanmin`, etc.\n",
    "\n",
    "In general, these problems lend themselves more naturally to masked\n",
    "semantics, so instead of introducing additional operators, we propose\n",
    "using `MaskedTensor`{.interpreted-text role=\"class\"} instead. Since\n",
    "[nanmean has already\n",
    "landed](https://github.com/pytorch/pytorch/issues/21987), we can use it\n",
    "as a comparison point:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x = torch.arange(16).float()\n",
    "y = x * x.fmod(4)\n",
    "z = y.masked_fill(y == 0, float('nan'))  # we want to get the mean of y when ignoring the zeros"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(\"y:\\n\", y)\n",
    "# z is just y with the zeros replaced with nan's\n",
    "print(\"z:\\n\", z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(\"y.mean():\\n\", y.mean())\n",
    "print(\"z.nanmean():\\n\", z.nanmean())\n",
    "# MaskedTensor successfully ignores the 0's\n",
    "print(\"torch.mean(masked_tensor(y, y != 0)):\\n\", torch.mean(masked_tensor(y, y != 0)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the above example, we\\'ve constructed a [y]{.title-ref} and would\n",
    "like to calculate the mean of the series while ignoring the zeros.\n",
    "[torch.nanmean]{.title-ref} can be used to do this, but we don\\'t have\n",
    "implementations for the rest of the [torch.nan\\*]{.title-ref}\n",
    "operations. `MaskedTensor`{.interpreted-text role=\"class\"} solves this\n",
    "issue by being able to use the base operation, and we already have\n",
    "support for the other operations listed in the issue. For example:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "torch.argmin(masked_tensor(y, y != 0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Indeed, the index of the minimum argument when ignoring the 0\\'s is the\n",
    "1 in index 1.\n",
    "\n",
    "`MaskedTensor`{.interpreted-text role=\"class\"} can also support\n",
    "reductions when the data is fully masked out, which is equivalent to the\n",
    "case above when the data Tensor is completely `nan`. `nanmean` would\n",
    "return `nan` (an ambiguous return value), while MaskedTensor would more\n",
    "accurately indicate a masked out result.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x = torch.empty(16).fill_(float('nan'))\n",
    "print(\"x:\\n\", x)\n",
    "print(\"torch.nanmean(x):\\n\", torch.nanmean(x))\n",
    "print(\"torch.nanmean via maskedtensor:\\n\", torch.mean(masked_tensor(x, ~torch.isnan(x))))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is a similar problem to safe softmax where [0/0 = nan]{.title-ref}\n",
    "when what we really want is an undefined value.\n",
    "\n",
    "# Conclusion\n",
    "\n",
    "In this tutorial, we\\'ve introduced what MaskedTensors are, demonstrated\n",
    "how to use them, and motivated their value through a series of examples\n",
    "and issues that they\\'ve helped resolve.\n",
    "\n",
    "# Further Reading\n",
    "\n",
    "To continue learning more, you can find our [MaskedTensor Sparsity\n",
    "tutorial](https://pytorch.org/tutorials/prototype/maskedtensor_sparsity.html)\n",
    "to see how MaskedTensor enables sparsity and the different storage\n",
    "formats we currently support.\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
}
