{
 "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 Advanced Semantics\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import warnings\n",
    "\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Before working on this tutorial, please make sure to review our\n",
    "[MaskedTensor Overview tutorial\n",
    "\\<https://pytorch.org/tutorials/prototype/maskedtensor_overview.html\\>]{.title-ref}.\n",
    "\n",
    "The purpose of this tutorial is to help users understand how some of the\n",
    "advanced semantics work and how they came to be. We will focus on two\n",
    "particular ones:\n",
    "\n",
    "*. Differences between MaskedTensor and \\`NumPy\\'s MaskedArray\n",
    "\\<https://numpy.org/doc/stable/reference/maskedarray.html\\>\\`\\_\\_*.\n",
    "Reduction semantics\n",
    "\n",
    "# Preparation\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "from torch.masked import masked_tensor\n",
    "\n",
    "# Disable prototype warnings and such\n",
    "warnings.filterwarnings(action=\"ignore\", category=UserWarning)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# MaskedTensor vs NumPy\\'s MaskedArray\n",
    "\n",
    "NumPy\\'s `MaskedArray` has a few fundamental semantics differences from\n",
    "MaskedTensor.\n",
    "\n",
    "*. Their factory function and basic definition inverts the mask (similar to \\`\\`torch.nn.MHA\\`\\`); that is, MaskedTensor uses \\`\\`True\\`\\` to denote \\\"specified\\\" and \\`\\`False\\`\\` to denote \\\"unspecified\\\", or \\\"valid\\\"/\\\"invalid\\\", whereas NumPy does the opposite. We believe that our mask definition is not only more intuitive, but it also aligns more with the existing semantics in PyTorch as a whole.*. Intersection semantics. In NumPy, if one of two elements are masked out, the resulting element will be\n",
    "\n",
    ":   masked out as well \\-- in practice, they [apply the logical_or\n",
    "    operator](https://github.com/numpy/numpy/blob/68299575d8595d904aff6f28e12d21bf6428a4ba/numpy/ma/core.py#L1016-L1024).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "data = torch.arange(5.0)\n",
    "mask = torch.tensor([True, True, False, True, False])\n",
    "npm0 = np.ma.masked_array(data.numpy(), (~mask).numpy())\n",
    "npm1 = np.ma.masked_array(data.numpy(), (mask).numpy())\n",
    "\n",
    "print(\"npm0:\\n\", npm0)\n",
    "print(\"npm1:\\n\", npm1)\n",
    "print(\"npm0 + npm1:\\n\", npm0 + npm1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Meanwhile, MaskedTensor does not support addition or binary operators\n",
    "with masks that don\\'t match \\--to understand why, please find the\n",
    "`section on reductions <reduction-semantics>`{.interpreted-text\n",
    "role=\"ref\"}.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "mt0 = masked_tensor(data, mask)\n",
    "mt1 = masked_tensor(data, ~mask)\n",
    "print(\"mt0:\\n\", mt0)\n",
    "print(\"mt1:\\n\", mt1)\n",
    "\n",
    "try:\n",
    "    mt0 + mt1\n",
    "except ValueError as e:\n",
    "    print(\"mt0 + mt1 failed. Error: \", e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "However, if this behavior is desired, MaskedTensor does support these\n",
    "semantics by giving access to the data and masks and conveniently\n",
    "converting a MaskedTensor to a Tensor with masked values filled in using\n",
    "`to_tensor`{.interpreted-text role=\"func\"}. For example:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "t0 = mt0.to_tensor(0)\n",
    "t1 = mt1.to_tensor(0)\n",
    "mt2 = masked_tensor(t0 + t1, mt0.get_mask() & mt1.get_mask())\n",
    "\n",
    "print(\"t0:\\n\", t0)\n",
    "print(\"t1:\\n\", t1)\n",
    "print(\"mt2 (t0 + t1):\\n\", mt2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the mask is [mt0.get_mask() & mt1.get_mask()]{.title-ref}\n",
    "since `MaskedTensor`{.interpreted-text role=\"class\"}\\'s mask is the\n",
    "inverse of NumPy\\'s.\n",
    "\n",
    "# Reduction Semantics\n",
    "\n",
    "Recall in [MaskedTensor\\'s Overview\n",
    "tutorial](https://pytorch.org/tutorials/prototype/maskedtensor_overview.html)\n",
    "we discussed \\\"Implementing missing torch.nan\\* ops\\\". Those are\n",
    "examples of reductions \\-- operators that remove one (or more)\n",
    "dimensions from a Tensor and then aggregate the result. In this section,\n",
    "we will use reduction semantics to motivate our strict requirements\n",
    "around matching masks from above.\n",
    "\n",
    "Fundamentally, :class:\\`MaskedTensor\\`s perform the same reduction\n",
    "operation while ignoring the masked out (unspecified) values. By way of\n",
    "example:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "data = torch.arange(12, dtype=torch.float).reshape(3, 4)\n",
    "mask = torch.randint(2, (3, 4), dtype=torch.bool)\n",
    "mt = masked_tensor(data, mask)\n",
    "\n",
    "print(\"data:\\n\", data)\n",
    "print(\"mask:\\n\", mask)\n",
    "print(\"mt:\\n\", mt)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, the different reductions (all on dim=1):\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(\"torch.sum:\\n\", torch.sum(mt, 1))\n",
    "print(\"torch.mean:\\n\", torch.mean(mt, 1))\n",
    "print(\"torch.prod:\\n\", torch.prod(mt, 1))\n",
    "print(\"torch.amin:\\n\", torch.amin(mt, 1))\n",
    "print(\"torch.amax:\\n\", torch.amax(mt, 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Of note, the value under a masked out element is not guaranteed to have\n",
    "any specific value, especially if the row or column is entirely masked\n",
    "out (the same is true for normalizations). For more details on masked\n",
    "semantics, you can find this\n",
    "[RFC](https://github.com/pytorch/rfcs/pull/27).\n",
    "\n",
    "Now, we can revisit the question: why do we enforce the invariant that\n",
    "masks must match for binary operators? In other words, why don\\'t we use\n",
    "the same semantics as `np.ma.masked_array`? Consider the following\n",
    "example:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "data0 = torch.arange(10.0).reshape(2, 5)\n",
    "data1 = torch.arange(10.0).reshape(2, 5) + 10\n",
    "mask0 = torch.tensor(\n",
    "    [[True, True, False, False, False], [False, False, False, True, True]]\n",
    ")\n",
    "mask1 = torch.tensor(\n",
    "    [[False, False, False, True, True], [True, True, False, False, False]]\n",
    ")\n",
    "npm0 = np.ma.masked_array(data0.numpy(), (mask0).numpy())\n",
    "npm1 = np.ma.masked_array(data1.numpy(), (mask1).numpy())\n",
    "\n",
    "print(\"npm0:\", npm0)\n",
    "print(\"npm1:\", npm1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let\\'s try addition:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(\"(npm0 + npm1).sum(0):\\n\", (npm0 + npm1).sum(0))\n",
    "print(\"npm0.sum(0) + npm1.sum(0):\\n\", npm0.sum(0) + npm1.sum(0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sum and addition should clearly be associative, but with NumPy\\'s\n",
    "semantics, they are not, which can certainly be confusing for the user.\n",
    "\n",
    "`MaskedTensor`{.interpreted-text role=\"class\"}, on the other hand, will\n",
    "simply not allow this operation since [mask0 != mask1]{.title-ref}. That\n",
    "being said, if the user wishes, there are ways around this (for example,\n",
    "filling in the MaskedTensor\\'s undefined elements with 0 values using\n",
    "`to_tensor`{.interpreted-text role=\"func\"} like shown below), but the\n",
    "user must now be more explicit with their intentions.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "mt0 = masked_tensor(data0, ~mask0)\n",
    "mt1 = masked_tensor(data1, ~mask1)\n",
    "\n",
    "print((mt0.to_tensor(0) + mt1.to_tensor(0)).sum(0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Conclusion\n",
    "\n",
    "In this tutorial, we have learned about the different design decisions\n",
    "behind MaskedTensor and NumPy\\'s MaskedArray, as well as reduction\n",
    "semantics. In general, MaskedTensor is designed to avoid ambiguity and\n",
    "confusing semantics (for example, we try to preserve the associative\n",
    "property amongst binary operations), which in turn can necessitate the\n",
    "user to be more intentional with their code at times, but we believe\n",
    "this to be the better move. If you have any thoughts on this, please\n",
    "[let us know](https://github.com/pytorch/pytorch/issues)!\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
}
