{
 "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": [
    "[Learn the Basics](intro.html) \\|\\|\n",
    "[Quickstart](quickstart_tutorial.html) \\|\\| **Tensors** \\|\\| [Datasets &\n",
    "DataLoaders](data_tutorial.html) \\|\\|\n",
    "[Transforms](transforms_tutorial.html) \\|\\| [Build\n",
    "Model](buildmodel_tutorial.html) \\|\\|\n",
    "[Autograd](autogradqs_tutorial.html) \\|\\|\n",
    "[Optimization](optimization_tutorial.html) \\|\\| [Save & Load\n",
    "Model](saveloadrun_tutorial.html)\n",
    "\n",
    "# Tensors\n",
    "\n",
    "Tensors are a specialized data structure that are very similar to arrays\n",
    "and matrices. In PyTorch, we use tensors to encode the inputs and\n",
    "outputs of a model, as well as the model's parameters.\n",
    "\n",
    "Tensors are similar to [NumPy's](https://numpy.org/) ndarrays, except\n",
    "that tensors can run on GPUs or other hardware accelerators. In fact,\n",
    "tensors and NumPy arrays can often share the same underlying memory,\n",
    "eliminating the need to copy data (see\n",
    "`bridge-to-np-label`{.interpreted-text role=\"ref\"}). Tensors are also\n",
    "optimized for automatic differentiation (we\\'ll see more about that\n",
    "later in the [Autograd](autogradqs_tutorial.html) section). If you're\n",
    "familiar with ndarrays, you'll be right at home with the Tensor API. If\n",
    "not, follow along!\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Initializing a Tensor\n",
    "\n",
    "Tensors can be initialized in various ways. Take a look at the following\n",
    "examples:\n",
    "\n",
    "**Directly from data**\n",
    "\n",
    "Tensors can be created directly from data. The data type is\n",
    "automatically inferred.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "data = [[1, 2],[3, 4]]\n",
    "x_data = torch.tensor(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**From a NumPy array**\n",
    "\n",
    "Tensors can be created from NumPy arrays (and vice versa - see\n",
    "`bridge-to-np-label`{.interpreted-text role=\"ref\"}).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "np_array = np.array(data)\n",
    "x_np = torch.from_numpy(np_array)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**From another tensor:**\n",
    "\n",
    "The new tensor retains the properties (shape, datatype) of the argument\n",
    "tensor, unless explicitly overridden.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x_ones = torch.ones_like(x_data) # retains the properties of x_data\n",
    "print(f\"Ones Tensor: \\n {x_ones} \\n\")\n",
    "\n",
    "x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data\n",
    "print(f\"Random Tensor: \\n {x_rand} \\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**With random or constant values:**\n",
    "\n",
    "`shape` is a tuple of tensor dimensions. In the functions below, it\n",
    "determines the dimensionality of the output tensor.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "shape = (2,3)\n",
    "rand_tensor = torch.rand(shape)\n",
    "ones_tensor = torch.ones(shape)\n",
    "zeros_tensor = torch.zeros(shape)\n",
    "\n",
    "print(f\"Random Tensor: \\n {rand_tensor} \\n\")\n",
    "print(f\"Ones Tensor: \\n {ones_tensor} \\n\")\n",
    "print(f\"Zeros Tensor: \\n {zeros_tensor}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "------------------------------------------------------------------------\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Attributes of a Tensor\n",
    "\n",
    "Tensor attributes describe their shape, datatype, and the device on\n",
    "which they are stored.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "tensor = torch.rand(3,4)\n",
    "\n",
    "print(f\"Shape of tensor: {tensor.shape}\")\n",
    "print(f\"Datatype of tensor: {tensor.dtype}\")\n",
    "print(f\"Device tensor is stored on: {tensor.device}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "------------------------------------------------------------------------\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Operations on Tensors\n",
    "\n",
    "Over 1200 tensor operations, including arithmetic, linear algebra,\n",
    "matrix manipulation (transposing, indexing, slicing), sampling and more\n",
    "are comprehensively described\n",
    "[here](https://pytorch.org/docs/stable/torch.html).\n",
    "\n",
    "Each of these operations can be run on the CPU and\n",
    "[Accelerator](https://pytorch.org/docs/stable/torch.html#accelerators)\n",
    "such as CUDA, MPS, MTIA, or XPU. If you're using Colab, allocate an\n",
    "accelerator by going to Runtime \\> Change runtime type \\> GPU.\n",
    "\n",
    "By default, tensors are created on the CPU. We need to explicitly move\n",
    "tensors to the accelerator using `.to` method (after checking for\n",
    "accelerator availability). Keep in mind that copying large tensors\n",
    "across devices can be expensive in terms of time and memory!\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# We move our tensor to the current accelerator if available\n",
    "if torch.accelerator.is_available():\n",
    "    tensor = tensor.to(torch.accelerator.current_accelerator())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Try out some of the operations from the list. If you\\'re familiar with\n",
    "the NumPy API, you\\'ll find the Tensor API a breeze to use.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Standard numpy-like indexing and slicing:**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "tensor = torch.ones(4, 4)\n",
    "print(f\"First row: {tensor[0]}\")\n",
    "print(f\"First column: {tensor[:, 0]}\")\n",
    "print(f\"Last column: {tensor[..., -1]}\")\n",
    "tensor[:,1] = 0\n",
    "print(tensor)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Joining tensors** You can use `torch.cat` to concatenate a sequence of\n",
    "tensors along a given dimension. See also\n",
    "[torch.stack](https://pytorch.org/docs/stable/generated/torch.stack.html),\n",
    "another tensor joining operator that is subtly different from\n",
    "`torch.cat`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "t1 = torch.cat([tensor, tensor, tensor], dim=1)\n",
    "print(t1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Arithmetic operations**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value\n",
    "# ``tensor.T`` returns the transpose of a tensor\n",
    "y1 = tensor @ tensor.T\n",
    "y2 = tensor.matmul(tensor.T)\n",
    "\n",
    "y3 = torch.rand_like(y1)\n",
    "torch.matmul(tensor, tensor.T, out=y3)\n",
    "\n",
    "\n",
    "# This computes the element-wise product. z1, z2, z3 will have the same value\n",
    "z1 = tensor * tensor\n",
    "z2 = tensor.mul(tensor)\n",
    "\n",
    "z3 = torch.rand_like(tensor)\n",
    "torch.mul(tensor, tensor, out=z3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Single-element tensors** If you have a one-element tensor, for example\n",
    "by aggregating all values of a tensor into one value, you can convert it\n",
    "to a Python numerical value using `item()`:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "agg = tensor.sum()\n",
    "agg_item = agg.item()\n",
    "print(agg_item, type(agg_item))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**In-place operations** Operations that store the result into the\n",
    "operand are called in-place. They are denoted by a `_` suffix. For\n",
    "example: `x.copy_(y)`, `x.t_()`, will change `x`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(f\"{tensor} \\n\")\n",
    "tensor.add_(5)\n",
    "print(tensor)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>In-place operations save some memory, but can be problematic when computing derivatives because of an immediate lossof history. Hence, their use is discouraged.</p>\n",
    "\n",
    "</div>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "------------------------------------------------------------------------\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Bridge with NumPy {#bridge-to-np-label}\n",
    "\n",
    "Tensors on the CPU and NumPy arrays can share their underlying memory\n",
    "locations, and changing one will change the other.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tensor to NumPy array\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "t = torch.ones(5)\n",
    "print(f\"t: {t}\")\n",
    "n = t.numpy()\n",
    "print(f\"n: {n}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A change in the tensor reflects in the NumPy array.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "t.add_(1)\n",
    "print(f\"t: {t}\")\n",
    "print(f\"n: {n}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# NumPy array to Tensor\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "n = np.ones(5)\n",
    "t = torch.from_numpy(n)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Changes in the NumPy array reflects in the tensor.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "np.add(n, 1, out=n)\n",
    "print(f\"t: {t}\")\n",
    "print(f\"n: {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
}
