Learn PyTorch Β· 1/12

Introduction to PyTorch and Tensors

9 min read

Introduction to PyTorch and Tensors

Welcome to the fascinating world of PyTorch! πŸš€ This guide is your first step into building amazing things with one of the most popular deep learning frameworks. We'll start with the absolute basics and build up from there, making sure you have a solid foundation.


What is PyTorch? Ecosystem and Local Setup

Definition and Problem:

Before we dive in, let's understand what we're dealing with. At its core, PyTorch is an open-source machine learning library developed by Facebook's AI Research lab (FAIR). It's known for its simplicity, flexibility, and strong community support. But why do we need something like PyTorch? Imagine trying to perform the massive calculations required for deep learning, like training a model to recognize images, using standard Python lists. It would be incredibly slow and inefficient. PyTorch solves this by providing a powerful data structure called a tensor and tools to perform calculations on them very, very fast, especially with the help of GPUs.

What is PyTorch?

Think of PyTorch as a super-powered calculator for deep learning. It excels at two main things:

  • Tensor computation: Similar to NumPy arrays, but with the massive advantage of being able to run on Graphics Processing Units (GPUs) to accelerate computing.
  • Building deep neural networks: It has a module called autograd that automates the calculation of gradients (a key part of training neural networks).

The PyTorch Ecosystem 🌍

PyTorch isn't just a single library; it's the center of a large ecosystem of tools and libraries that help you with various stages of your machine learning projects. This ecosystem includes tools for:

  • Model Serving: Like TorchServe, which helps you deploy your trained models for real-world applications.
  • Reinforcement Learning: Libraries such as Stable Baselines3 provide easy-to-use implementations of reinforcement learning algorithms.
  • And much more! The ecosystem is constantly growing with community contributions.

A funny exaggeration: Trying to do deep learning without a framework like PyTorch is like trying to build a skyscraper with only a hammer and a box of nails. You might get a wall up, but you're going to have a bad time.

Local Setup (Installation) πŸ’»

Getting PyTorch up and running on your machine is a straightforward process. The official PyTorch website has an installation command generator that makes it super easy.

Here’s a step-by-step guide for a typical setup:

  1. Create a Virtual Environment (Highly Recommended): This keeps your project's dependencies isolated.

    bash
    python -m venv pytorch-env
    source pytorch-env/bin/activate  # On Windows use `pytorch-env\Scripts\activate`
  2. Go to the Official PyTorch Website: https://pytorch.org/get-started/locally/

  3. Use the Installation Matrix: Select your preferences for:

    • PyTorch Build: Stable is recommended for most users.
    • Your OS: Windows, Linux, or macOS.
    • Package: Pip (most common) or Conda.
    • Language: Python.
    • Compute Platform: CPU, or if you have a compatible NVIDIA GPU, select the appropriate CUDA version. For Apple Silicon Macs, you'll use the MPS backend.
  4. Run the Generated Command: Copy the command and paste it into your terminal. For example, a common command for a CPU-only installation on Linux or macOS would be:

    bash
    pip3 install torch torchvision torchaudio

Verifying Your Installation:
To make sure everything is installed correctly, open a Python interpreter and run:

python
import torch
print(torch.__version__)

If it prints a version number, you're good to go!


Tensor Basics: Creation, Shape, and Data Types

Definition and Problem:

The fundamental building block of PyTorch is the Tensor. A tensor is a multi-dimensional array, very similar to NumPy's ndarray. So why not just use NumPy? While NumPy is fantastic for numerical operations on the CPU, PyTorch tensors can also be moved to a GPU for massive speed-ups, which is crucial for deep learning.

Creating Tensors πŸ‘¨β€πŸ”¬

There are several ways to create tensors in PyTorch. Let's look at the most common ones.

  • From a Python list: This is the most direct way.

    python
    import torch
    
    # A 1-dimensional tensor (or vector)
    my_list = [1, 2, 3, 4, 5]
    tensor_from_list = torch.tensor(my_list)
    print(tensor_from_list)
    # Output: tensor([1, 2, 3, 4, 5])
  • From a NumPy array: You can easily convert NumPy arrays to PyTorch tensors and vice-versa.

    python
    import numpy as np
    
    numpy_array = np.array([1, 2, 3])
    tensor_from_numpy = torch.from_numpy(numpy_array)
    print(tensor_from_numpy)
    # Output: tensor([1, 2, 3])
  • Tensors with specific values:

    • torch.zeros(): Creates a tensor filled with zeros.
    • torch.ones(): Creates a tensor filled with ones.
    • torch.rand(): Creates a tensor with random numbers from a uniform distribution on the interval [0, 1).
    python
    zeros_tensor = torch.zeros(2, 3) # 2 rows, 3 columns
    print(zeros_tensor)
    # Output:
    # tensor([[0., 0., 0.],
    #         [0., 0., 0.]])
    
    ones_tensor = torch.ones(3, 2)
    print(ones_tensor)
    # Output:
    # tensor([[1., 1.],
    #         [1., 1.],
    #         [1., 1.]])

Tensor Shape πŸ“

The shape of a tensor tells you the size of each dimension. You can access the shape of a tensor using the .shape attribute.

python
a_tensor = torch.rand(2, 3, 4) # A 3D tensor
print(a_tensor.shape)
# Output: torch.Size([2, 3, 4])

Understanding the shape of your tensors is critical, as many errors in deep learning come from shape mismatches.

Data Types (dtype) πŸ”’

Every tensor has a data type, which you can check with the .dtype attribute. The most common data type for deep learning is torch.float32. By default, PyTorch infers the data type from the input data, but you can also specify it.

python
int_tensor = torch.tensor([1, 2, 3])
print(int_tensor.dtype)
# Output: torch.int64

float_tensor = torch.tensor([1.0, 2.0, 3.0])
print(float_tensor.dtype)
# Output: torch.float32

# Specifying the data type
explicit_float_tensor = torch.tensor([1, 2, 3], dtype=torch.float32)
print(explicit_float_tensor.dtype)
# Output: torch.float32

Tensor Operations: Math, Slicing, and Reshaping

Definition and Problem:

Now that we know how to create tensors, let's see what we can do with them. PyTorch provides a rich set of operations to manipulate tensors. These operations are the foundation of all the complex calculations in a neural network.

Mathematical Operations βž•βž–βœ–οΈβž—

You can perform element-wise arithmetic operations on tensors using standard Python operators.

python
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])

# Addition
print(a + b) # or torch.add(a, b)
# Output: tensor([5, 7, 9])

# Multiplication
print(a * b) # or torch.mul(a, b)
# Output: tensor([ 4, 10, 18])

PyTorch also offers a wide range of other mathematical functions like torch.sin(), torch.log(), etc.

Slicing and Indexing πŸ”ͺ

Accessing parts of a tensor is similar to how you would do it with Python lists or NumPy arrays.

python
a_2d_tensor = torch.tensor([[1, 2, 3],
                            [4, 5, 6],
                            [7, 8, 9]])

# Get the first row
print(a_2d_tensor[0])
# Output: tensor([1, 2, 3])

# Get the element at the second row, third column
print(a_2d_tensor[1, 2])
# Output: tensor(6)

# Slicing: Get the first two rows and columns 1 and 2
print(a_2d_tensor[:2, 1:])
# Output:
# tensor([[2, 3],
#         [5, 6]])

Reshaping Tensors πŸ”„

Often, you'll need to change the shape of a tensor to make it compatible with the next operation in your model. The most common way to do this is with .view() or .reshape().

  • .view(): Returns a new tensor with the same data but a different shape. It's very fast because it doesn't copy the data. However, it only works on contiguous tensors (tensors stored in a contiguous block of memory).
  • .reshape(): Is more flexible. It will try to return a view, but if that's not possible, it will create a copy.
python
a_tensor = torch.arange(12) # tensor([0, 1, 2, ..., 11])
print(a_tensor)

reshaped_tensor = a_tensor.reshape(3, 4)
print(reshaped_tensor)
# Output:
# tensor([[ 0,  1,  2,  3],
#         [ 4,  5,  6,  7],
#         [ 8,  9, 10, 11]])

A cool trick is to use -1 in one of the dimensions, and PyTorch will automatically infer the correct size.

python
flattened_tensor = reshaped_tensor.reshape(-1)
print(flattened_tensor)
# Output: tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

Hardware Acceleration: CPU vs. GPU (CUDA/MPS)

Definition and Problem:

One of the main reasons to use PyTorch is its ability to perform computations on a GPU. GPUs are designed for parallel processing, making them significantly faster than CPUs for the types of matrix operations that are common in deep learning.

CPU vs. GPU 🐌 vs. 🏎️

  • CPU (Central Processing Unit): The "brain" of the computer, great for sequential tasks.
  • GPU (Graphics Processing Unit): Specialized for handling many parallel computations at once. Think of it as having thousands of smaller cores.

For deep learning, which involves a lot of matrix multiplications, the parallel nature of GPUs can lead to massive speedups.

Moving Tensors to a Device

By default, tensors are created on the CPU. To move a tensor to the GPU, you can use the .to() method.

  • For NVIDIA GPUs: You'll use CUDA, a parallel computing platform from NVIDIA. The device is typically named 'cuda'.
  • For Apple Silicon (M1/M2/M3 chips): PyTorch uses the Metal Performance Shaders (MPS) backend. The device is named 'mps'.

Here's how you can check for and use a GPU:

python
import torch

# Check if a CUDA-enabled GPU is available
if torch.cuda.is_available():
    device = "cuda"
# Check for Apple Silicon GPU
elif torch.backends.mps.is_available():
    device = "mps"
else:
    device = "cpu"

print(f"Using {device} device")

# Create a tensor on the CPU
cpu_tensor = torch.rand(2, 2)
print(f"Tensor on CPU: {cpu_tensor}")

# Move the tensor to the selected device
gpu_tensor = cpu_tensor.to(device)
print(f"Tensor on GPU: {gpu_tensor}")

Important Note: For an operation between two tensors to work, they must be on the same device. If you try to perform an operation between a CPU tensor and a GPU tensor, you'll get an error.

This is like trying to have a conversation with someone in another room. You both need to be in the same room (the same device) to communicate.


References

For further reading and to dive deeper into the topics covered, here are some useful resources:

This is like trying to have a conversation with someone in another room. You both need to be in the same room (the same device) to communicate.


References

For further reading and to dive deeper into the topics covered, here are some useful resources:

Challenge

You are working on a deep learning project and need to perform some initial data preprocessing steps on a batch of images using PyTorch. Your task is to write a script that accomplishes the following, in order:

  1. Convert the provided Python list image_batch_list into a PyTorch tensor named image_tensor. Ensure its data type is torch.float32.
  2. "Normalize" the image_tensor by first subtracting a mean of 0.5 and then dividing by a standard deviation of 0.5. Store the result in a new tensor called normalized_tensor.
  3. The current shape of the tensor represents (batch_size, height, width). Reshape normalized_tensor to add a channel dimension, so its new shape is (batch_size, channels, height, width). The batch size is 2, there is 1 channel, and the height and width are 4. Use -1 to let PyTorch automatically infer one of the dimensions. Store the result in reshaped_tensor.
  4. Prepare for hardware acceleration. Create a variable device that holds the string 'cuda' if a CUDA-enabled GPU is available, and 'cpu' otherwise. Use torch.cuda.is_available() for the check.
  5. Move the reshaped_tensor to the device you just defined. Store this new tensor in a variable named tensor_on_device.
  6. Finally, create a tensor of random values named weights with the exact same shape as tensor_on_device and create it directly on the device.
  7. Perform an element-wise addition between tensor_on_device and weights, storing the result in a variable called final_output.

Expected result

Your final code should correctly implement all the specified steps. It must define the following variables in order:

  • image_tensor: A torch.Tensor created from image_batch_list with dtype set to torch.float32.
  • normalized_tensor: The result of subtracting 0.5 and then dividing by 0.5 from image_tensor.
  • reshaped_tensor: The normalized_tensor reshaped to the dimension (2, 1, 4, 4).
  • device: A string, either 'cuda' or 'cpu', based on GPU availability.
  • tensor_on_device: The reshaped_tensor moved to the target device using the .to() method.
  • weights: A random tensor created with the same shape as tensor_on_device and explicitly placed on the device during creation.
  • final_output: The result of adding tensor_on_device and weights.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.