Skip to content
Module 1 · Foundations
Chapter 3 of 17
Run it in your browser

Chapter 3: Tensors and PyTorch

The map with Module 1 highlighted Figure 3.1: Tensors are the containers that carry data through every stage.

Like we learned in the last chapter we know what our language model needs to do. So we can begin creating (Figure 3.1). We need to convert text to numerical values but first we need something to store and manipulate these numerical values efficiently. Tensors are used to hold data and PyTorch allows us to perform calculations on these tensors. Your numbers may vary slightly depending on your computer or version of PyTorch.

In this chapter you will:

  • Learn what a tensor is and how it stores data.
  • See how tensor shapes represent different dimensions.
  • Understand how matrix multiplication transforms data.
  • Turn raw scores into probabilities using Softmax.

Words to Know

  • PyTorch: a Python library (ready-made code) that does math on large sets of numbers very quickly.
  • Tensor: a container of numbers, arranged as a list, a table, or a stack of tables.
  • Shape: how big a tensor is in each direction, such as how many rows and how many columns.
  • Matrix Multiplication: a way of multiplying two tensors that turns data from one shape into another.
  • Softmax: a function that turns any numbers into probabilities that sum to 1.

Theory: The Data Containers

PyTorch is a Python library used to perform math on big arrays of numbers. We could do these calculations in plain Python, but it would take us weeks to train something. PyTorch can handle millions of calculations in minutes.

A 1D vector, a 2D matrix, and a 3D tensor shown as shapes Figure 3.2: Tensors can be 1D (a list), 2D (a table), or 3D (a stack of tables).

A tensor holds numbers: a list, a table, or a stack of tables (Figure 3.2). Programmers refer to a tensor as a multi-dimensional array. If you've ever worked with a spreadsheet, you already understand 2D tensors, and a 3D tensor is just a stack of spreadsheets.

In this book, we work mostly with 3D tensors. Their dimensions, or shape, represent:

  • B = Batch size (how many sequences we process at once)
  • T = Time (how many tokens in each sequence)
  • C = Channel size (how many numbers we use to represent each token)

We write shapes like (B, T, C). For example, (32, 128, 128) means "32 sequences, each 128 tokens long, each token described by 128 numbers."

Matrix Multiplication as Data Transformation

A data tensor and a transformation tensor combine to make a result tensor Figure 3.3: Matrix multiplication transforms data from one shape to another.

You can use the matrix multiplication operation @ on tensors to make your neural network transform data. This is shown in Figure 3.3. If the inner dimensions match then you can multiply the tensors. For example (3, 4) @ (4, 5) = (3, 5).

If we say that (3, 4) means we have 3 students each with 4 test scores. And (4, 5) means 4 test scores each mapped to 5 skill ratings. We get (3, 5). So now we have 3 students each with 5 skill ratings.

Softmax: Turning Scores into Probabilities

Softmax is a mathematical function that converts any list of numbers (known as logits) to probabilities (Figure 3.4). The values produced are guaranteed to all be positive and sum to exactly 1.0. Softmax does this by taking the exponential of each number, which grows very rapidly and thus exaggerates the difference between numbers even more.

Raw scores 1.0, 2.0, 3.0 turning into probabilities 0.09, 0.24, 0.67 Figure 3.4: Softmax forces numbers into a 0-to-1 range where they total exactly 1.0.

Code: Basic Operations

The code below shows the basic PyTorch operations we will use.

src/ch02_tensors.py (excerpt)
1
2
3
4
5
6
7
8
9
    # A 1D tensor is simply a list of numbers
    a = torch.tensor([1.0, 2.0, 3.0, 4.0])

    # A 2D tensor represents a table or matrix of numbers
    b = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])

    x = torch.randn(2, 5, 8)
    W = torch.randn(8, 4)
    y = x @ W

Run the file to see how PyTorch handles these:

Terminal
$ python src/ch02_tensors.py
--- 1. Creating tensors ---
1D tensor: tensor([1., 2., 3., 4.])
  shape: torch.Size([4])

2D tensor:
tensor([[1., 2., 3.],
        [4., 5., 6.]])
  shape: torch.Size([2, 3])
...
--- 2. Shapes and dimensions ---
x shape: torch.Size([2, 5, 8])  - (batch=2, time=5, channels=8)
...
3D matmul: torch.Size([2, 5, 8]) @ torch.Size([8, 4]) = torch.Size([2, 5, 4])
...
Softmax([1.0, 2.0, 3.0]) = [0.0900, 0.2447, 0.6652]
  Sum = 1.0000

What just happened:

  1. Lines 2 and 5 created 1D and 2D tensors, printing their shapes.
  2. Line 7 looked at a 3D tensor with a shape of (2, 5, 8), representing (Batch, Time, Channels).
  3. Line 9 multiplied a 3D tensor by a 2D matrix. PyTorch automatically did that matrix multiplication for every sequence in the batch at the same time. We call that batched matrix multiplication. It allows us to write less repetitive code instead of doing this step one sequence at a time (which would be slow in Python).

Shape Check

Table 3.1 shows the tensor shapes before and after matrix multiplication.

Table 3.1: Tensor shapes before and after matrix multiplication.

Tensor Shape Meaning
x (2, 5, 8) 2 sequences, 5 tokens each, 8 numbers per token
W (8, 4) Transformation weights: 8 inputs to 4 outputs
y (2, 5, 4) 2 sequences, 5 tokens each, now 4 numbers per token

Try It

Open src/ch02_tensors.py, change logits = torch.tensor([1.0, 2.0, 3.0]) to [1.0, 2.0, 10.0], and run it. Notice how the highest number takes almost 100% of the probability after Softmax.

In Business

During your house-style email writer training, you'll start to save that data as tensors. Think of tensors as multi-dimensional arrays. With these tensors we can start to apply the math described above to learn your company's writing style from big datasets.

Watch Out

Dimension mismatch is by far the most common error message you will encounter in PyTorch. Multiplying (3, 4) by (5, 6) won't work in PyTorch because the inner dimensions 4 and 5 do not match. Check your shapes twice.

Key Takeaways

  • A tensor contains numbers, and programmers refer to tensors as "multi-dimensional arrays."
  • Shape (B, T, C) = batch × time × channels, the convention we'll use throughout this book.
  • @ denotes matrix multiplication. The inner dimensions must match.
  • Softmax converts any values into probabilities that add up to 1.
  • PyTorch automatically manages batches for us by using batched matrix multiplication, so we write no code that iterates over each sequence.
  • We've created tensors ready to hold our data. The next stage in our map will convert text to tokens.

Check Your Understanding

  1. If an output has shape (32, 128, 128), what does that mean in our (B, T, C) notation?
  2. Why should the inner dimensions match when doing matrix multiplication?
  3. What's the difference between logits and probabilities?

Assignment

Assignment 3: One number, new shape

About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.

  1. Run it. Run src/ch02_tensors.py without changing anything. Copy the line of output that begins 3D matmul:.
  2. Change one number. Locate the line W = torch.randn(8, 4). W stores the transformation's weights. It takes in 8 numbers for each token and outputs 4. Replace the 4 with a 6 and run the script again.
  3. Compare. Which numbers on the 3D matmul: line were different? Which were the same? How many numbers are used to describe each token now?
  4. Explain it. In two or three sentences understandable by a manager, describe what the multiplication changed about the data and what it didn't change.

Hand in: both 3D matmul: lines, your answers to step 3, and your sentences.

Further Reading

The library you are typing into. This paper argues for how the tool we will be using in this book was designed. You are able to write Python code that runs line by line and can print a tensor or step through your debugger, all while having the benefit of compiled speed under the hood. This allows the code we will write in this book to be followed line by line and still train a fairly realistic model.

Paszke, A., Gross, S., Massa, F., Lerer, A., Bradbury, J., Chanan, G., Killeen, T., Lin, Z., Gimelshein, N., Antiga, L., Desmaison, A., Köpf, A., Yang, E., DeVito, Z., Raison, M., Tejani, A., Chilamkurthy, S., Steiner, B., Fang, L., ... Chintala, S. (2019). PyTorch: An imperative style, high-performance deep learning library (arXiv:1912.01703). arXiv. https://doi.org/10.48550/arXiv.1912.01703

Next up: Chapter 4: Tokenization