\n",
" \n",
"

\n",
"\"\"\"\n",
"display(HTML(html_code))"
]
},
{
"cell_type": "markdown",
"id": "29562581",
"metadata": {},
"source": [
"\n",
"\n",
"Tensors are the central data abstraction in PyTorch. This interactive\n",
"notebook provides an in-depth introduction to the `torch.Tensor` class.\n",
"\n",
"First things first, let's import the PyTorch module. We'll also add\n",
"Python's math module to facilitate some of the examples.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import torch\n",
"import math"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Creating Tensors\n",
"================\n",
"\n",
"The simplest way to create a tensor is with the `torch.empty()` call:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"x = torch.empty(3, 4)\n",
"print(type(x))\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's unpack what we just did:\n",
"\n",
"- We created a tensor using one of the numerous factory methods\n",
" attached to the `torch` module.\n",
"- The tensor itself is 2-dimensional, having 3 rows and 4 columns.\n",
"- The type of the object returned is `torch.Tensor`, which is an alias\n",
" for `torch.FloatTensor`; by default, PyTorch tensors are populated\n",
" with 32-bit floating point numbers. (More on data types below.)\n",
"- You will probably see some random-looking values when printing your\n",
" tensor. The `torch.empty()` call allocates memory for the tensor,\n",
" but does not initialize it with any values - so what you're seeing\n",
" is whatever was in memory at the time of allocation.\n",
"\n",
"A brief note about tensors and their number of dimensions, and\n",
"terminology:\n",
"\n",
"- You will sometimes see a 1-dimensional tensor called a *vector.*\n",
"- Likewise, a 2-dimensional tensor is often referred to as a *matrix.*\n",
"- Anything with more than two dimensions is generally just called a\n",
" tensor.\n",
"\n",
"More often than not, you'll want to initialize your tensor with some\n",
"value. Common cases are all zeros, all ones, or random values, and the\n",
"`torch` module provides factory methods for all of these:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"zeros = torch.zeros(2, 3)\n",
"print(zeros)\n",
"\n",
"ones = torch.ones(2, 3)\n",
"print(ones)\n",
"\n",
"torch.manual_seed(1729)\n",
"random = torch.rand(2, 3)\n",
"print(random)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The factory methods all do just what you'd expect - we have a tensor\n",
"full of zeros, another full of ones, and another with random values\n",
"between 0 and 1.\n",
"\n",
"Random Tensors and Seeding\n",
"==========================\n",
"\n",
"Speaking of the random tensor, did you notice the call to\n",
"`torch.manual_seed()` immediately preceding it? Initializing tensors,\n",
"such as a model's learning weights, with random values is common but\n",
"there are times - especially in research settings - where you'll want\n",
"some assurance of the reproducibility of your results. Manually setting\n",
"your random number generator's seed is the way to do this. Let's look\n",
"more closely:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"torch.manual_seed(1729)\n",
"random1 = torch.rand(2, 3)\n",
"print(random1)\n",
"\n",
"random2 = torch.rand(2, 3)\n",
"print(random2)\n",
"\n",
"torch.manual_seed(1729)\n",
"random3 = torch.rand(2, 3)\n",
"print(random3)\n",
"\n",
"random4 = torch.rand(2, 3)\n",
"print(random4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What you should see above is that `random1` and `random3` carry\n",
"identical values, as do `random2` and `random4`. Manually setting the\n",
"RNG's seed resets it, so that identical computations depending on random\n",
"number should, in most settings, provide identical results.\n",
"\n",
"For more information, see the [PyTorch documentation on\n",
"reproducibility](https://pytorch.org/docs/stable/notes/randomness.html).\n",
"\n",
"Tensor Shapes\n",
"=============\n",
"\n",
"Often, when you're performing operations on two or more tensors, they\n",
"will need to be of the same *shape* - that is, having the same number of\n",
"dimensions and the same number of cells in each dimension. For that, we\n",
"have the `torch.*_like()` methods:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"x = torch.empty(2, 2, 3)\n",
"print(x.shape)\n",
"print(x)\n",
"\n",
"empty_like_x = torch.empty_like(x)\n",
"print(empty_like_x.shape)\n",
"print(empty_like_x)\n",
"\n",
"zeros_like_x = torch.zeros_like(x)\n",
"print(zeros_like_x.shape)\n",
"print(zeros_like_x)\n",
"\n",
"ones_like_x = torch.ones_like(x)\n",
"print(ones_like_x.shape)\n",
"print(ones_like_x)\n",
"\n",
"rand_like_x = torch.rand_like(x)\n",
"print(rand_like_x.shape)\n",
"print(rand_like_x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The first new thing in the code cell above is the use of the `.shape`\n",
"property on a tensor. This property contains a list of the extent of\n",
"each dimension of a tensor - in our case, `x` is a three-dimensional\n",
"tensor with shape 2 x 2 x 3.\n",
"\n",
"Below that, we call the `.empty_like()`, `.zeros_like()`,\n",
"`.ones_like()`, and `.rand_like()` methods. Using the `.shape` property,\n",
"we can verify that each of these methods returns a tensor of identical\n",
"dimensionality and extent.\n",
"\n",
"The last way to create a tensor that will cover is to specify its data\n",
"directly from a PyTorch collection:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"some_constants = torch.tensor([[3.1415926, 2.71828], [1.61803, 0.0072897]])\n",
"print(some_constants)\n",
"\n",
"some_integers = torch.tensor((2, 3, 5, 7, 11, 13, 17, 19))\n",
"print(some_integers)\n",
"\n",
"more_integers = torch.tensor(((2, 4, 6), [3, 6, 9]))\n",
"print(more_integers)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using `torch.tensor()` is the most straightforward way to create a\n",
"tensor if you already have data in a Python tuple or list. As shown\n",
"above, nesting the collections will result in a multi-dimensional\n",
"tensor.\n",
"\n",
"\n",
"

\n",
"\n",
"Tensor Data Types\n",
"=================\n",
"\n",
"Setting the datatype of a tensor is possible a couple of ways:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.ones((2, 3), dtype=torch.int16)\n",
"print(a)\n",
"\n",
"b = torch.rand((2, 3), dtype=torch.float64) * 20.\n",
"print(b)\n",
"\n",
"c = b.to(torch.int32)\n",
"print(c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The simplest way to set the underlying data type of a tensor is with an\n",
"optional argument at creation time. In the first line of the cell above,\n",
"we set `dtype=torch.int16` for the tensor `a`. When we print `a`, we can\n",
"see that it's full of `1` rather than `1.` - Python's subtle cue that\n",
"this is an integer type rather than floating point.\n",
"\n",
"Another thing to notice about printing `a` is that, unlike when we left\n",
"`dtype` as the default (32-bit floating point), printing the tensor also\n",
"specifies its `dtype`.\n",
"\n",
"You may have also spotted that we went from specifying the tensor's\n",
"shape as a series of integer arguments, to grouping those arguments in a\n",
"tuple. This is not strictly necessary - PyTorch will take a series of\n",
"initial, unlabeled integer arguments as a tensor shape - but when adding\n",
"the optional arguments, it can make your intent more readable.\n",
"\n",
"The other way to set the datatype is with the `.to()` method. In the\n",
"cell above, we create a random floating point tensor `b` in the usual\n",
"way. Following that, we create `c` by converting `b` to a 32-bit integer\n",
"with the `.to()` method. Note that `c` contains all the same values as\n",
"`b`, but truncated to integers.\n",
"\n",
"For more information, see the [data types\n",
"documentation](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype).\n",
"\n",
"Math & Logic with PyTorch Tensors\n",
"=================================\n",
"\n",
"Now that you know some of the ways to create a tensor... what can you do\n",
"with them?\n",
"\n",
"Let's look at basic arithmetic first, and how tensors interact with\n",
"simple scalars:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ones = torch.zeros(2, 2) + 1\n",
"twos = torch.ones(2, 2) * 2\n",
"threes = (torch.ones(2, 2) * 7 - 1) / 2\n",
"fours = twos ** 2\n",
"sqrt2s = twos ** 0.5\n",
"\n",
"print(ones)\n",
"print(twos)\n",
"print(threes)\n",
"print(fours)\n",
"print(sqrt2s)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As you can see above, arithmetic operations between tensors and scalars,\n",
"such as addition, subtraction, multiplication, division, and\n",
"exponentiation are distributed over every element of the tensor. Because\n",
"the output of such an operation will be a tensor, you can chain them\n",
"together with the usual operator precedence rules, as in the line where\n",
"we create `threes`.\n",
"\n",
"Similar operations between two tensors also behave like you'd\n",
"intuitively expect:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"powers2 = twos ** torch.tensor([[1, 2], [3, 4]])\n",
"print(powers2)\n",
"\n",
"fives = ones + fours\n",
"print(fives)\n",
"\n",
"dozens = threes * fours\n",
"print(dozens)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It's important to note here that all of the tensors in the previous code\n",
"cell were of identical shape. What happens when we try to perform a\n",
"binary operation on tensors if dissimilar shape?\n",
"\n",
"`torch.tensor()`

creates a copy of the data.

\n",
"

\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the general case, you cannot operate on tensors of different shape\n",
"this way, even in a case like the cell above, where the tensors have an\n",
"identical number of elements.\n",
"\n",
"In Brief: Tensor Broadcasting\n",
"=============================\n",
"\n",
"The following cell throws a run-time error. This is intentional.

\n", "`a = torch.rand(2, 3)\n", "b = torch.rand(3, 2)\n", "`

`print(a * b)`

\n",
"

\n",
"\n",
"The exception to the same-shapes rule is *tensor broadcasting.* Here's\n",
"an example:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"rand = torch.rand(2, 4)\n",
"doubled = rand * (torch.ones(1, 4) * 2)\n",
"\n",
"print(rand)\n",
"print(doubled)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What's the trick here? How is it we got to multiply a 2x4 tensor by a\n",
"1x4 tensor?\n",
"\n",
"Broadcasting is a way to perform an operation between tensors that have\n",
"similarities in their shapes. In the example above, the one-row,\n",
"four-column tensor is multiplied by *both rows* of the two-row,\n",
"four-column tensor.\n",
"\n",
"This is an important operation in Deep Learning. The common example is\n",
"multiplying a tensor of learning weights by a *batch* of input tensors,\n",
"applying the operation to each instance in the batch separately, and\n",
"returning a tensor of identical shape - just like our (2, 4) \\* (1, 4)\n",
"example above returned a tensor of shape (2, 4).\n",
"\n",
"The rules for broadcasting are:\n",
"\n",
"- Each tensor must have at least one dimension - no empty tensors.\n",
"- Comparing the dimension sizes of the two tensors, *going from last\n",
" to first:*\n",
" - Each dimension must be equal, *or*\n",
" - One of the dimensions must be of size 1, *or*\n",
" - The dimension does not exist in one of the tensors\n",
"\n",
"Tensors of identical shape, of course, are trivially \"broadcastable\", as\n",
"you saw earlier.\n",
"\n",
"Here are some examples of situations that honor the above rules and\n",
"allow broadcasting:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.ones(4, 3, 2)\n",
"\n",
"b = a * torch.rand( 3, 2) # 3rd & 2nd dims identical to a, dim 1 absent\n",
"print(b)\n",
"\n",
"c = a * torch.rand( 3, 1) # 3rd dim = 1, 2nd dim identical to a\n",
"print(c)\n",
"\n",
"d = a * torch.rand( 1, 2) # 3rd dim identical to a, 2nd dim = 1\n",
"print(d)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Look closely at the values of each tensor above:\n",
"\n",
"- The multiplication operation that created `b` was broadcast over\n",
" every \"layer\" of `a`.\n",
"- For `c`, the operation was broadcast over every layer and row of\n",
" `a` - every 3-element column is identical.\n",
"- For `d`, we switched it around - now every *row* is identical,\n",
" across layers and columns.\n",
"\n",
"For more information on broadcasting, see the [PyTorch\n",
"documentation](https://pytorch.org/docs/stable/notes/broadcasting.html)\n",
"on the topic.\n",
"\n",
"Here are some examples of attempts at broadcasting that will fail:\n",
"\n",
"If you are familiar with broadcasting semantics in NumPyndarrays, youâ€™ll find the same rules apply here.

\n", "\n",
"

\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"More Math with Tensors\n",
"======================\n",
"\n",
"PyTorch tensors have over three hundred operations that can be performed\n",
"on them.\n",
"\n",
"Here is a small sample from some of the major categories of operations:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# common functions\n",
"a = torch.rand(2, 4) * 2 - 1\n",
"print('Common functions:')\n",
"print(torch.abs(a))\n",
"print(torch.ceil(a))\n",
"print(torch.floor(a))\n",
"print(torch.clamp(a, -0.5, 0.5))\n",
"\n",
"# trigonometric functions and their inverses\n",
"angles = torch.tensor([0, math.pi / 4, math.pi / 2, 3 * math.pi / 4])\n",
"sines = torch.sin(angles)\n",
"inverses = torch.asin(sines)\n",
"print('\\nSine and arcsine:')\n",
"print(angles)\n",
"print(sines)\n",
"print(inverses)\n",
"\n",
"# bitwise operations\n",
"print('\\nBitwise XOR:')\n",
"b = torch.tensor([1, 5, 11])\n",
"c = torch.tensor([2, 7, 10])\n",
"print(torch.bitwise_xor(b, c))\n",
"\n",
"# comparisons:\n",
"print('\\nBroadcasted, element-wise equality comparison:')\n",
"d = torch.tensor([[1., 2.], [3., 4.]])\n",
"e = torch.ones(1, 2) # many comparison ops support broadcasting!\n",
"print(torch.eq(d, e)) # returns a tensor of type bool\n",
"\n",
"# reductions:\n",
"print('\\nReduction ops:')\n",
"print(torch.max(d)) # returns a single-element tensor\n",
"print(torch.max(d).item()) # extracts the value from the returned tensor\n",
"print(torch.mean(d)) # average\n",
"print(torch.std(d)) # standard deviation\n",
"print(torch.prod(d)) # product of all numbers\n",
"print(torch.unique(torch.tensor([1, 2, 1, 2, 1, 2]))) # filter unique elements\n",
"\n",
"# vector and linear algebra operations\n",
"v1 = torch.tensor([1., 0., 0.]) # x unit vector\n",
"v2 = torch.tensor([0., 1., 0.]) # y unit vector\n",
"m1 = torch.rand(2, 2) # random matrix\n",
"m2 = torch.tensor([[3., 0.], [0., 3.]]) # three times identity matrix\n",
"\n",
"print('\\nVectors & Matrices:')\n",
"print(torch.linalg.cross(v2, v1)) # negative of z unit vector (v1 x v2 == -v2 x v1)\n",
"print(m1)\n",
"m3 = torch.linalg.matmul(m1, m2)\n",
"print(m3) # 3 times m1\n",
"print(torch.linalg.svd(m3)) # singular value decomposition"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is a small sample of operations. For more details and the full\n",
"inventory of math functions, have a look at the\n",
"[documentation](https://pytorch.org/docs/stable/torch.html#math-operations).\n",
"For more details and the full inventory of linear algebra operations,\n",
"have a look at this\n",
"[documentation](https://pytorch.org/docs/stable/linalg.html).\n",
"\n",
"Altering Tensors in Place\n",
"=========================\n",
"\n",
"Most binary operations on tensors will return a third, new tensor. When\n",
"we say `c = a * b` (where `a` and `b` are tensors), the new tensor `c`\n",
"will occupy a region of memory distinct from the other tensors.\n",
"\n",
"There are times, though, that you may wish to alter a tensor in place\n",
"-for example, if you're doing an element-wise computation where you can\n",
"discard intermediate values. For this, most of the math functions have a\n",
"version with an appended underscore (`_`) that will alter a tensor in\n",
"place.\n",
"\n",
"For example:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.tensor([0, math.pi / 4, math.pi / 2, 3 * math.pi / 4])\n",
"print('a:')\n",
"print(a)\n",
"print(torch.sin(a)) # this operation creates a new tensor in memory\n",
"print(a) # a has not changed\n",
"\n",
"b = torch.tensor([0, math.pi / 4, math.pi / 2, 3 * math.pi / 4])\n",
"print('\\nb:')\n",
"print(b)\n",
"print(torch.sin_(b)) # note the underscore\n",
"print(b) # b has changed"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For arithmetic operations, there are functions that behave similarly:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.ones(2, 2)\n",
"b = torch.rand(2, 2)\n",
"\n",
"print('Before:')\n",
"print(a)\n",
"print(b)\n",
"print('\\nAfter adding:')\n",
"print(a.add_(b))\n",
"print(a)\n",
"print(b)\n",
"print('\\nAfter multiplying')\n",
"print(b.mul_(b))\n",
"print(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that these in-place arithmetic functions are methods on the\n",
"`torch.Tensor` object, not attached to the `torch` module like many\n",
"other functions (e.g., `torch.sin()`). As you can see from `a.add_(b)`,\n",
"*the calling tensor is the one that gets changed in place.*\n",
"\n",
"There is another option for placing the result of a computation in an\n",
"existing, allocated tensor. Many of the methods and functions we've seen\n",
"so far - including creation methods! - have an `out` argument that lets\n",
"you specify a tensor to receive the output. If the `out` tensor is the\n",
"correct shape and `dtype`, this can happen without a new memory\n",
"allocation:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.rand(2, 2)\n",
"b = torch.rand(2, 2)\n",
"c = torch.zeros(2, 2)\n",
"old_id = id(c)\n",
"\n",
"print(c)\n",
"d = torch.matmul(a, b, out=c)\n",
"print(c) # contents of c have changed\n",
"\n",
"assert c is d # test c & d are same object, not just containing equal values\n",
"assert id(c) == old_id # make sure that our new c is the same object as the old one\n",
"\n",
"torch.rand(2, 2, out=c) # works for creation too!\n",
"print(c) # c has changed again\n",
"assert id(c) == old_id # still the same object!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copying Tensors\n",
"===============\n",
"\n",
"As with any object in Python, assigning a tensor to a variable makes the\n",
"variable a *label* of the tensor, and does not copy it. For example:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.ones(2, 2)\n",
"b = a\n",
"\n",
"a[0][1] = 561 # we change a...\n",
"print(b) # ...and b is also altered"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"But what if you want a separate copy of the data to work on? The\n",
"`clone()` method is there for you:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.ones(2, 2)\n",
"b = a.clone()\n",
"\n",
"assert b is not a # different objects in memory...\n",
"print(torch.eq(a, b)) # ...but still with the same contents!\n",
"\n",
"a[0][1] = 561 # a changes...\n",
"print(b) # ...but b is still all ones"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**There is an important thing to be aware of when using\n",
"\\`\\`clone()\\`\\`.** If your source tensor has autograd, enabled then so\n",
"will the clone. **This will be covered more deeply in the video on\n",
"autograd,** but if you want the light version of the details, continue\n",
"on.\n",
"\n",
"*In many cases, this will be what you want.* For example, if your model\n",
"has multiple computation paths in its `forward()` method, and *both* the\n",
"original tensor and its clone contribute to the model's output, then to\n",
"enable model learning you want autograd turned on for both tensors. If\n",
"your source tensor has autograd enabled (which it generally will if it's\n",
"a set of learning weights or derived from a computation involving the\n",
"weights), then you'll get the result you want.\n",
"\n",
"On the other hand, if you're doing a computation where *neither* the\n",
"original tensor nor its clone need to track gradients, then as long as\n",
"the source tensor has autograd turned off, you're good to go.\n",
"\n",
"*There is a third case,* though: Imagine you're performing a computation\n",
"in your model's `forward()` function, where gradients are turned on for\n",
"everything by default, but you want to pull out some values mid-stream\n",
"to generate some metrics. In this case, you *don't* want the cloned copy\n",
"of your source tensor to track gradients - performance is improved with\n",
"autograd's history tracking turned off. For this, you can use the\n",
"`.detach()` method on the source tensor:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.rand(2, 2, requires_grad=True) # turn on autograd\n",
"print(a)\n",
"\n",
"b = a.clone()\n",
"print(b)\n",
"\n",
"c = a.detach().clone()\n",
"print(c)\n",
"\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What's happening here?\n",
"\n",
"- We create `a` with `requires_grad=True` turned on. **We haven't\n",
" covered this optional argument yet, but will during the unit on\n",
" autograd.**\n",
"- When we print `a`, it informs us that the property\n",
" `requires_grad=True` - this means that autograd and computation\n",
" history tracking are turned on.\n",
"- We clone `a` and label it `b`. When we print `b`, we can see that\n",
" it's tracking its computation history - it has inherited `a`'s\n",
" autograd settings, and added to the computation history.\n",
"- We clone `a` into `c`, but we call `detach()` first.\n",
"- Printing `c`, we see no computation history, and no\n",
" `requires_grad=True`.\n",
"\n",
"The `detach()` method *detaches the tensor from its computation\n",
"history.* It says, \"do whatever comes next as if autograd was off.\" It\n",
"does this *without* changing `a` - you can see that when we print `a`\n",
"again at the end, it retains its `requires_grad=True` property.\n",
"\n",
"Moving to GPU\n",
"=============\n",
"\n",
"One of the major advantages of PyTorch is its robust acceleration on\n",
"CUDA-compatible Nvidia GPUs. (\"CUDA\" stands for *Compute Unified Device\n",
"Architecture*, which is Nvidia's platform for parallel computing.) So\n",
"far, everything we've done has been on CPU. How do we move to the faster\n",
"hardware?\n",
"\n",
"First, we should check whether a GPU is available, with the\n",
"`is_available()` method.\n",
"\n",
"The following cell throws a run-time error. This is intentional.

\n", "`a = torch.ones(4, 3, 2)\n", "`

b = a * torch.rand(4, 3) # dimensions must match last-to-first

\n", "c = a * torch.rand( 2, 3) # both 3rd & 2nd dims different

\n", "

`d = a * torch.rand((0, )) # can't broadcast with an empty tensor`

\n",
"

\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"if torch.cuda.is_available():\n",
" print('We have a GPU!')\n",
"else:\n",
" print('Sorry, CPU only.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Once we've determined that one or more GPUs is available, we need to put\n",
"our data someplace where the GPU can see it. Your CPU does computation\n",
"on data in your computer's RAM. Your GPU has dedicated memory attached\n",
"to it. Whenever you want to perform a computation on a device, you must\n",
"move *all* the data needed for that computation to memory accessible by\n",
"that device. (Colloquially, \"moving the data to memory accessible by the\n",
"GPU\" is shorted to, \"moving the data to the GPU\".)\n",
"\n",
"There are multiple ways to get your data onto your target device. You\n",
"may do it at creation time:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"if torch.cuda.is_available():\n",
" gpu_rand = torch.rand(2, 2, device='cuda')\n",
" print(gpu_rand)\n",
"else:\n",
" print('Sorry, CPU only.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"By default, new tensors are created on the CPU, so we have to specify\n",
"when we want to create our tensor on the GPU with the optional `device`\n",
"argument. You can see when we print the new tensor, PyTorch informs us\n",
"which device it's on (if it's not on CPU).\n",
"\n",
"You can query the number of GPUs with `torch.cuda.device_count()`. If\n",
"you have more than one GPU, you can specify them by index:\n",
"`device='cuda:0'`, `device='cuda:1'`, etc.\n",
"\n",
"As a coding practice, specifying our devices everywhere with string\n",
"constants is pretty fragile. In an ideal world, your code would perform\n",
"robustly whether you're on CPU or GPU hardware. You can do this by\n",
"creating a device handle that can be passed to your tensors instead of a\n",
"string:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"if torch.cuda.is_available():\n",
" my_device = torch.device('cuda')\n",
"else:\n",
" my_device = torch.device('cpu')\n",
"print('Device: {}'.format(my_device))\n",
"\n",
"x = torch.rand(2, 2, device=my_device)\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you have an existing tensor living on one device, you can move it to\n",
"another with the `to()` method. The following line of code creates a\n",
"tensor on CPU, and moves it to whichever device handle you acquired in\n",
"the previous cell.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"y = torch.rand(2, 2)\n",
"y = y.to(my_device)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is important to know that in order to do computation involving two or\n",
"more tensors, *all of the tensors must be on the same device*. The\n",
"following code will throw a runtime error, regardless of whether you\n",
"have a GPU device available:\n",
"\n",
"``` {.sourceCode .python}\n",
"x = torch.rand(2, 2)\n",
"y = torch.rand(2, 2, device='gpu')\n",
"z = x + y # exception will be thrown\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Manipulating Tensor Shapes\n",
"==========================\n",
"\n",
"Sometimes, you'll need to change the shape of your tensor. Below, we'll\n",
"look at a few common cases, and how to handle them.\n",
"\n",
"Changing the Number of Dimensions\n",
"---------------------------------\n",
"\n",
"One case where you might need to change the number of dimensions is\n",
"passing a single instance of input to your model. PyTorch models\n",
"generally expect *batches* of input.\n",
"\n",
"For example, imagine having a model that works on 3 x 226 x 226 images\n",
"-a 226-pixel square with 3 color channels. When you load and transform\n",
"it, you'll get a tensor of shape `(3, 226, 226)`. Your model, though, is\n",
"expecting input of shape `(N, 3, 226, 226)`, where `N` is the number of\n",
"images in the batch. So how do you make a batch of one?\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.rand(3, 226, 226)\n",
"b = a.unsqueeze(0)\n",
"\n",
"print(a.shape)\n",
"print(b.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `unsqueeze()` method adds a dimension of extent 1. `unsqueeze(0)`\n",
"adds it as a new zeroth dimension - now you have a batch of one!\n",
"\n",
"So if that's *un*squeezing? What do we mean by squeezing? We're taking\n",
"advantage of the fact that any dimension of extent 1 *does not* change\n",
"the number of elements in the tensor.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"c = torch.rand(1, 1, 1, 1, 1)\n",
"print(c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Continuing the example above, let's say the model's output is a\n",
"20-element vector for each input. You would then expect the output to\n",
"have shape `(N, 20)`, where `N` is the number of instances in the input\n",
"batch. That means that for our single-input batch, we'll get an output\n",
"of shape `(1, 20)`.\n",
"\n",
"What if you want to do some *non-batched* computation with that output\n",
"-something that's just expecting a 20-element vector?\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.rand(1, 20)\n",
"print(a.shape)\n",
"print(a)\n",
"\n",
"b = a.squeeze(0)\n",
"print(b.shape)\n",
"print(b)\n",
"\n",
"c = torch.rand(2, 2)\n",
"print(c.shape)\n",
"\n",
"d = c.squeeze(0)\n",
"print(d.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can see from the shapes that our 2-dimensional tensor is now\n",
"1-dimensional, and if you look closely at the output of the cell above\n",
"you'll see that printing `a` shows an \"extra\" set of square brackets\n",
"`[]` due to having an extra dimension.\n",
"\n",
"You may only `squeeze()` dimensions of extent 1. See above where we try\n",
"to squeeze a dimension of size 2 in `c`, and get back the same shape we\n",
"started with. Calls to `squeeze()` and `unsqueeze()` can only act on\n",
"dimensions of extent 1 because to do otherwise would change the number\n",
"of elements in the tensor.\n",
"\n",
"Another place you might use `unsqueeze()` is to ease broadcasting.\n",
"Recall the example above where we had the following code:\n",
"\n",
"``` {.sourceCode .python}\n",
"a = torch.ones(4, 3, 2)\n",
"\n",
"c = a * torch.rand( 3, 1) # 3rd dim = 1, 2nd dim identical to a\n",
"print(c)\n",
"```\n",
"\n",
"The net effect of that was to broadcast the operation over dimensions 0\n",
"and 2, causing the random, 3 x 1 tensor to be multiplied element-wise by\n",
"every 3-element column in `a`.\n",
"\n",
"What if the random vector had just been 3-element vector? We'd lose the\n",
"ability to do the broadcast, because the final dimensions would not\n",
"match up according to the broadcasting rules. `unsqueeze()` comes to the\n",
"rescue:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = torch.ones(4, 3, 2)\n",
"b = torch.rand( 3) # trying to multiply a * b will give a runtime error\n",
"c = b.unsqueeze(1) # change to a 2-dimensional tensor, adding new dim at the end\n",
"print(c.shape)\n",
"print(a * c) # broadcasting works again!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `squeeze()` and `unsqueeze()` methods also have in-place versions,\n",
"`squeeze_()` and `unsqueeze_()`:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"batch_me = torch.rand(3, 226, 226)\n",
"print(batch_me.shape)\n",
"batch_me.unsqueeze_(0)\n",
"print(batch_me.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Sometimes you'll want to change the shape of a tensor more radically,\n",
"while still preserving the number of elements and their contents. One\n",
"case where this happens is at the interface between a convolutional\n",
"layer of a model and a linear layer of the model - this is common in\n",
"image classification models. A convolution kernel will yield an output\n",
"tensor of shape *features x width x height,* but the following linear\n",
"layer expects a 1-dimensional input. `reshape()` will do this for you,\n",
"provided that the dimensions you request yield the same number of\n",
"elements as the input tensor has:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"output3d = torch.rand(6, 20, 20)\n",
"print(output3d.shape)\n",
"\n",
"input1d = output3d.reshape(6 * 20 * 20)\n",
"print(input1d.shape)\n",
"\n",
"# can also call it as a method on the torch module:\n",
"print(torch.reshape(output3d, (6 * 20 * 20,)).shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you do not have a CUDA-compatible GPU and CUDA driversinstalled, the executable cells in this section will not execute anyGPU-related code.

\n", "\n",
"

\n",
"\n",
"When it can, `reshape()` will return a *view* on the tensor to be\n",
"changed - that is, a separate tensor object looking at the same\n",
"underlying region of memory. *This is important:* That means any change\n",
"made to the source tensor will be reflected in the view on that tensor,\n",
"unless you `clone()` it.\n",
"\n",
"There *are* conditions, beyond the scope of this introduction, where\n",
"`reshape()` has to return a tensor carrying a copy of the data. For more\n",
"information, see the\n",
"[docs](https://pytorch.org/docs/stable/torch.html#torch.reshape).\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"NumPy Bridge\n",
"============\n",
"\n",
"In the section above on broadcasting, it was mentioned that PyTorch's\n",
"broadcast semantics are compatible with NumPy's - but the kinship\n",
"between PyTorch and NumPy goes even deeper than that.\n",
"\n",
"If you have existing ML or scientific code with data stored in NumPy\n",
"ndarrays, you may wish to express that same data as PyTorch tensors,\n",
"whether to take advantage of PyTorch's GPU acceleration, or its\n",
"efficient abstractions for building ML models. It's easy to switch\n",
"between ndarrays and PyTorch tensors:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"numpy_array = np.ones((2, 3))\n",
"print(numpy_array)\n",
"\n",
"pytorch_tensor = torch.from_numpy(numpy_array)\n",
"print(pytorch_tensor)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"PyTorch creates a tensor of the same shape and containing the same data\n",
"as the NumPy array, going so far as to keep NumPy's default 64-bit float\n",
"data type.\n",
"\n",
"The conversion can just as easily go the other way:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"pytorch_rand = torch.rand(2, 3)\n",
"print(pytorch_rand)\n",
"\n",
"numpy_rand = pytorch_rand.numpy()\n",
"print(numpy_rand)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is important to know that these converted objects are using *the same\n",
"underlying memory* as their source objects, meaning that changes to one\n",
"are reflected in the other:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"numpy_array[1, 1] = 23\n",
"print(pytorch_tensor)\n",
"\n",
"pytorch_rand[1, 1] = 17\n",
"print(numpy_rand)"
]
}
],
"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.10.14"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
The `(6 * 20 * 20,)`

argument in the final line of the cellabove is because PyTorch expects a when specifying atensor shape - but when the shape is the first argument of a method, itlets us cheat and just use a series of integers. Here, we had to add theparentheses and comma to convince the method that this is really aone-element tuple.