Files
pytorch-deep-learning/00_pytorch_fundamentals.ipynb
T

57 KiB

Open In Colab

00. PyTorch Fundamentals

TK - intro to PyTorch

TK - What is PyTorch?

TK - What can PyTorch be used for?

TK - Who uses PyTorch?

TK - Why use PyTorch?

Researchers love using PyTorch -- https://paperswithcode.com/trends

TK - What we're going to cover in this module...

  • Introduction to Tensors
  • Creating tensors
  • Getting information from tensors
  • Manipulating tensors
  • Tensor operations (neural networks involve manipulating tensors...)
  • Tensors and NumPy
  • Running tensors on GPU
In [1]:
import torch
print(torch.__version__)
1.9.1

TK - Introduction to tensors

TK - Creating tensors

All you need to know - https://pytorch.org/docs/stable/generated/torch.tensor.html#torch.tensor

Many different ops for PyTorch tensors - https://pytorch.org/docs/stable/torch.html

In [2]:
# Scalar
scalar = torch.tensor(7)
scalar
Out [2]:
tensor(7)
In [3]:
scalar.ndim
Out [3]:
0
In [4]:
# Get the Python number within a tensor (only works with one-element tensors)
scalar.item()
Out [4]:
7
In [5]:
# Vector
vector = torch.tensor([7, 7])
vector
Out [5]:
tensor([7, 7])
In [6]:
vector.ndim
Out [6]:
1
In [7]:
# Matrix
matrix = torch.tensor([[7, 8], 
                       [9, 10]])
matrix
Out [7]:
tensor([[ 7,  8],
        [ 9, 10]])
In [8]:
matrix.ndim
Out [8]:
2
In [9]:
# Tensor
tensor = torch.tensor([[[3, 6, 9],
                        [3, 6, 9],
                        [3, 6, 9]]])
tensor
Out [9]:
tensor([[[3, 6, 9],
         [3, 6, 9],
         [3, 6, 9]]])
In [10]:
tensor.ndim
Out [10]:
3
In [19]:
# Note: torch.tensor() always makes a copy
tensor_A = torch.tensor([1, 2, 3])
tensor_B = torch.tensor(tensor_A) # Creating a tensor like this produces a warning

tensor_A, tensor_B
Out [19]:
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:3: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).
  This is separate from the ipykernel package so we can avoid doing imports until
(tensor([1, 2, 3]), tensor([1, 2, 3]))
In [20]:
# Change tensor_B, doesn't change tensor_A
tensor_B[0] = 4

tensor_A, tensor_B
Out [20]:
(tensor([1, 2, 3]), tensor([4, 2, 3]))
In [21]:
# Change tensor_A, doesn't change tensor_B
tensor_A[1] = 4

tensor_A, tensor_B
Out [21]:
(tensor([1, 4, 3]), tensor([4, 2, 3]))
In [27]:
# Random
random_tensor = torch.rand(size=(3, 4))
random_tensor, random_tensor.dtype
Out [27]:
(tensor([[0.6109, 0.1709, 0.9683, 0.5726],
         [0.6924, 0.6208, 0.8857, 0.1900],
         [0.7239, 0.4225, 0.0904, 0.8145]]), torch.float32)
In [29]:
# Zeros
zeros = torch.zeros(size=(3, 4))
zeros, zeros.dtype
Out [29]:
(tensor([[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]]), torch.float32)
In [30]:
# torch.arange(), torch.range() is deprecated 
zero_to_ten = torch.arange(0, 10)
zero_to_ten
Out [30]:
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [32]:
# Can also create a tensor of zeros similar to another tensor
ten_zeros = torch.zeros_like(zero_to_ten) # will have same shape
ten_zeros
Out [32]:
tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
In [23]:
# Default datatype for tensors is float32
float_32_tensor = torch.tensor([3.0, 6.0, 9.0],
                               dtype=None, # defaults to None, which is torch.float32 or whatever datatype is passed
                               device=None, # defaults to None, which uses the default tensor type
                               requires_grad=False) # if True, operations perfromed on the tensor are recorded 

float_32_tensor.shape, float_32_tensor.dtype, float_32_tensor.device
Out [23]:
(torch.Size([3]), torch.float32, device(type='cpu'))
In [24]:
float_16_tensor = torch.tensor([3.0, 6.0, 9.0],
                               dtype=torch.float16)

float_16_tensor.dtype
Out [24]:
torch.float16

TK - Getting information from tensors

In [34]:
some_tensor = torch.rand(3, 4)

print(some_tensor)
print(f"Shape of tensor: {some_tensor.shape}")
print(f"Datatype of tensor: {some_tensor.dtype}")
print(f"Device tensor is stored on: {some_tensor.device}") # will default to CPU
tensor([[0.7211, 0.2743, 0.2621, 0.0821],
        [0.0890, 0.7967, 0.8323, 0.2623],
        [0.8343, 0.2572, 0.4677, 0.1218]])
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

TK - Manipulating tensors (tensor operations)

Basic operations

In [94]:
tensor = torch.tensor([1, 2, 3])
tensor + 10
Out [94]:
tensor([11, 12, 13])
In [44]:
tensor * 10
Out [44]:
tensor([10, 20, 30])
In [45]:
# Tensors don't change unless reassigned
tensor
Out [45]:
tensor([1, 2, 3])
In [46]:
tensor = tensor - 10
tensor
Out [46]:
tensor([-9, -8, -7])
In [47]:
tensor = tensor + 10
tensor
Out [47]:
tensor([1, 2, 3])
In [48]:
# Can also use torch functions
torch.multiply(tensor, 10)
Out [48]:
tensor([10, 20, 30])
In [49]:
# Original tensor is still unchanged 
tensor
Out [49]:
tensor([1, 2, 3])
In [55]:
# Element-wise multiplication
tensor * tensor
Out [55]:
tensor([1, 4, 9])

Matrix multiplcation

Neural networks are mostly matrix multiplcation - https://marksaroufim.substack.com/p/working-class-deep-learner

In [2]:
import torch
tensor = torch.tensor([1, 2, 3])
tensor
Out [2]:
tensor([1, 2, 3])
In [3]:
torch.matmul(tensor, tensor)
Out [3]:
tensor(14)
In [4]:
tensor @ tensor
Out [4]:
tensor(14)
In [5]:
sum(tensor * tensor.T)
Out [5]:
tensor(14)
In [6]:
# By hand (avoid doing operations with for loops at all cost, they are computationally expensive)
value = 0
for i in range(len(tensor)):
  value += tensor[i] * tensor[i]
value
Out [6]:
tensor(14)
In [7]:
# Shapes need to be in the right way (this will error) 
tensor_A = torch.tensor([[1, 2],
                         [3, 4],
                         [5, 6]], dtype=torch.float32)

tensor_B = torch.tensor([[7, 8],
                         [9, 10], 
                         [11, 12]], dtype=torch.float32)

torch.matmul(tensor_A, tensor_B)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
/tmp/ipykernel_34033/854767186.py in <module>
      8                          [11, 12]], dtype=torch.float32)
      9 
---> 10 torch.matmul(tensor_A, tensor_B)

RuntimeError: mat1 and mat2 shapes cannot be multiplied (3x2 and 3x2)
In [8]:
torch.matmul(tensor_A, tensor_B.T)
Out [8]:
tensor([[ 23.,  29.,  35.],
        [ 53.,  67.,  81.],
        [ 83., 105., 127.]])
In [9]:
# torch.mm is a shortcut for matmul
torch.mm(tensor_A, tensor_B.T)
Out [9]:
tensor([[ 23.,  29.,  35.],
        [ 53.,  67.,  81.],
        [ 83., 105., 127.]])
In [79]:
# This uses matrix mutliplcation...
linear = torch.nn.Linear(in_features=3, out_features=2)
input = tensor_A
output = linear(input.T)
output, output.shape
Out [79]:
(tensor([[ 1.4391, -1.4383],
         [ 1.5400, -1.5229]], grad_fn=<AddmmBackward>), torch.Size([2, 2]))
In [80]:
tensor_A.T.shape
Out [80]:
torch.Size([2, 3])

TK - Finding the min, max, mean, sum, etc (aggregation)

See here for more operations - https://pytorch.org/docs/stable/tensors.html

In [103]:
x = torch.arange(0, 100, 10)
x
Out [103]:
tensor([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
In [104]:
print(f"Minimum: {x.min()}")
print(f"Maximum: {x.max()}")
print(f"Mean: {x.type(torch.float32).mean()}") # won't work without float datatype
print(f"Sum: {x.sum()}")
Minimum: 0
Maximum: 90
Mean: 45.0
Sum: 450
In [106]:
torch.max(x), torch.min(x), torch.mean(x.type(torch.float32)), torch.sum(x)
Out [106]:
(tensor(90), tensor(0), tensor(45.), tensor(450))

TK - Positional min/max

In [83]:
# Returns index of max value
tensor = torch.arange(10, 100, 10)
tensor, tensor.argmax()
Out [83]:
(tensor([10, 20, 30, 40, 50, 60, 70, 80, 90]), tensor(8))
In [86]:
# Returns index of min value
tensor = torch.arange(10, 100, 10)
tensor, tensor.argmin()
Out [86]:
(tensor([10, 20, 30, 40, 50, 60, 70, 80, 90]), tensor(0))

TK - Change tensor datatype

See torch datatypes here - https://pytorch.org/docs/stable/tensors.html

In [87]:
tensor = torch.arange(10., 100., 10.)
tensor.dtype
Out [87]:
torch.float32
In [92]:
tensor_float16 = tensor.type(torch.float16)
tensor_float16
Out [92]:
tensor([10., 20., 30., 40., 50., 60., 70., 80., 90.], dtype=torch.float16)
In [93]:
tensor_int32 = tensor.type(torch.int32)
tensor_int32
Out [93]:
tensor([10, 20, 30, 40, 50, 60, 70, 80, 90], dtype=torch.int32)

TK - Reshaping, stacking, squeezing and unsqueezing

Why do any of these?

Avoid for loops in your tensor code.

For loops slow things down.

In [16]:
import torch
x = torch.arange(1., 8.)
x
Out [16]:
tensor([1., 2., 3., 4., 5., 6., 7.])
In [17]:
# Add an extra dimension
x_reshaped = x.reshape(1, 7)
x_reshaped, x_reshaped.shape
Out [17]:
(tensor([[1., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))
In [18]:
# Change view (keeps same data as original but changes view)
# See more: https://stackoverflow.com/a/54507446/7900723
z = x.view(1, 7)
z, z.shape
Out [18]:
(tensor([[1., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))
In [19]:
# Changing z changes x
z[:, 0] = 5
z, x
Out [19]:
(tensor([[5., 2., 3., 4., 5., 6., 7.]]), tensor([5., 2., 3., 4., 5., 6., 7.]))
In [20]:
# Stack tensors on top of each other
x_stacked = torch.stack([x, x, x, x], dim=0)
x_stacked
Out [20]:
tensor([[5., 2., 3., 4., 5., 6., 7.],
        [5., 2., 3., 4., 5., 6., 7.],
        [5., 2., 3., 4., 5., 6., 7.],
        [5., 2., 3., 4., 5., 6., 7.]])
In [116]:
# Remove extra dimension from x_reshaped
x_squeezed = x_reshaped.squeeze()
x_squeezed, x_squeezed.shape
Out [116]:
(tensor([1., 2., 3., 4., 5., 6., 7.]), torch.Size([7]))
In [120]:
# Add an extra dimension with unsqueeze
x_unsqueezed = x_squeezed.unsqueeze(dim=0)
x_unsqueezed, x_unsqueezed.shape
Out [120]:
(tensor([[1., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))

TK - Indexing (selecting data from tensors)

In [23]:
import torch
tensor = torch.arange(0, 9, 1).view(1, 3, 3)
tensor
Out [23]:
tensor([[[0, 1, 2],
         [3, 4, 5],
         [6, 7, 8]]])
In [24]:
tensor[0]
Out [24]:
tensor([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]])
In [25]:
tensor[:, 0]
Out [25]:
tensor([[0, 1, 2]])
In [26]:
tensor[:, :, 1]
Out [26]:
tensor([[1, 4, 7]])
In [28]:
tensor[:, 1, 1]
Out [28]:
tensor([4])
In [31]:
tensor[:, :, 0]
Out [31]:
tensor([[0, 3, 6]])

TK - Changing values

Use scatter() to change values for things like one-hot encoding.

https://pytorch.org/docs/stable/generated/torch.Tensor.scatter_.html#torch.Tensor.scatter_

In [ ]:
# TODO - add in example of scatter

TK - PyTorch tensors & NumPy

In [130]:
# NumPy array to tensor
import numpy as np
array = np.arange(1, 8)
tensor = torch.from_numpy(array)
array, tensor
Out [130]:
(array([1, 2, 3, 4, 5, 6, 7]), tensor([1, 2, 3, 4, 5, 6, 7]))
In [131]:
# Change the array, keep the tensor
array = array + 1
array, tensor
Out [131]:
(array([2, 3, 4, 5, 6, 7, 8]), tensor([1, 2, 3, 4, 5, 6, 7]))
In [134]:
# Tensor to NumPy array
tensor = torch.ones(7)
numpy_tensor = tensor.numpy()
tensor, numpy_tensor
Out [134]:
(tensor([1., 1., 1., 1., 1., 1., 1.]),
 array([1., 1., 1., 1., 1., 1., 1.], dtype=float32))
In [135]:
# Change the tensor, keep the array the same
tensor = tensor + 1
tensor, numpy_tensor
Out [135]:
(tensor([2., 2., 2., 2., 2., 2., 2.]),
 array([1., 1., 1., 1., 1., 1., 1.], dtype=float32))

TK - Reproducibility

  • Create tensors with same values...
  • Show PyTorch random seed so we can all use similar values

See: https://pytorch.org/docs/stable/notes/randomness.html

In [32]:
# No seed
import torch

random_tensor_A = torch.rand(3, 4)
random_tensor_B = torch.rand(3, 4)

random_tensor_A == random_tensor_B
Out [32]:
tensor([[False, False, False, False],
        [False, False, False, False],
        [False, False, False, False]])
In [40]:
# With seed
import torch

# Set the random seed
torch.random.manual_seed(42)
random_tensor_C = torch.rand(3, 4)

# Have to reset the seed every time a new rand() is called 
torch.random.manual_seed(42) # Without this, tensor_D would be different to tensor_C
random_tesnor_D = torch.rand(3, 4)

random_tensor_C == random_tesnor_D
Out [40]:
tensor([[True, True, True, True],
        [True, True, True, True],
        [True, True, True, True]])

TK - Running tensors on GPUs

The cuda module is what you'll want:

In [42]:
# Check for GPU
import torch
torch.cuda.is_available()
Out [42]:
True
In [14]:
# Set device type
device = "cuda" if torch.cuda.is_available() else "cpu"
device
Out [14]:
'cuda'
In [41]:
# Count number of devices
torch.cuda.device_count()
Out [41]:
1

You can put tensors on the GPU using to().

GPUs offer far faster numerical computing than CPUs do.

Note: Putting a tensor on GPU using to(device) (e.g. some_tensor.to(device)) returns a copy of that tensor, e.g. the same tensor will be on CPU and GPU. To overwrite tensors, reassign them:

some_tensor = some_tensor.to(device)

In [21]:
# Create tensor (default on CPU)
tensor = torch.tensor([1, 2, 3])

# Tensor not on GPU
print(tensor, tensor.device)

# Move tensor to GPU
tensor_on_gpu = tensor.to(device)
tensor_on_gpu
Out [21]:
tensor([1, 2, 3]) cpu
tensor([1, 2, 3], device='cuda:0')

What if we wanted to move the tensor back to CPU?

For example, you'll want to do this if you want to interact with your tensors with NumPy.

Let's try using the numpy() method on our tensor_on_gpu.

In [25]:
# If tensor is on GPU, can't transform it to NumPy (this will error)
tensor_on_gpu.numpy()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_7994/1481451780.py in <module>
      1 # If tensor is on GPU, can't transform it to NumPy
----> 2 tensor_on_gpu.numpy()

TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

Instead, to get a tensor back to CPU and usable with NumPy we can use Tensor.cpu().

This copies the tensor to CPU memory so it's usable with CPUs.

In [29]:
# Instead, copy the tensor back to cpu
tensor_back_on_cpu = tensor_on_gpu.cpu().numpy()
tensor_back_on_cpu
Out [29]:
array([1, 2, 3])

The above returns a copy of the GPU tensor in CPU memory so the original tensor is still on GPU.

In [30]:
tensor_on_gpu
Out [30]:
tensor([1, 2, 3], device='cuda:0')

UPTOHERE:

  • add in scatter (for changing values)
  • go back through headings and make sure cells are complete