Skip to content
Module 3 ยท Training and Generation
Chapter 12 of 17
Run it in your browser

Chapter 12: Dataset and DataLoader

The map with Training highlighted Figure 12.1: We begin the training module by preparing our data pipeline.

We have our model, and we know from Chapter 11 that our goal is to predict the next token. Now we need to feed data into the engine. Instead of pushing one character at a time, we will feed the model thousands of examples simultaneously. In this chapter, we build a pipeline to prepare and batch our Shakespeare dataset.

In this chapter you will:

  • Use a sliding window to generate training examples.
  • Understand how batches process multiple sequences in parallel.
  • Build a PyTorch Dataset and DataLoader.

Words to Know

  • Block Size: The maximum number of tokens the model can look at at one time (its context window).
  • Batching: Grouping multiple training examples together and processing them at the same time.
  • Dataset: A PyTorch tool that defines how to fetch one training example from the text.
  • DataLoader: A PyTorch tool that automatically groups single examples into batches and shuffles them.

Theory

The Sliding Window

In the last chapter, we saw how a single sequence provides multiple training examples. But how do we extract these sequences from a large text file like our selection of Shakespeare's plays?

We use a sliding window (Figure 12.2).

A sliding window over text Figure 12.2: A sliding window creates multiple, overlapping examples from one long text.

So basically you have a window that can only see so many characters. We will call this our block_size (the maximum length our model can use as context). Once we place our window at the start of our text we can extract our first sequence. Then we move the window over by 1 character and extract the next sequence. We do this until we get to the end of our text.

Processing in Parallel: Batches

If we fed each sequence to the model one by one, training would crawl. Modern computers, especially those with graphics chips (GPUs), are very good at doing the same math on many pieces of data at once, and they are wasted on one sequence at a time.

To see how much batching matters, we can time it:

Terminal
$ python src/examples/ch12_batch_speed.py
32 sequences, one at a time : 2.191 s
the same 32 as one batch    : 0.245 s
batching is 9.0x faster on this machine

This is 9x faster. This is without using a GPU on your average computer. As seen from the log, the model in Chapter 13 trained for around 8 minutes on the computer that logged it. It would have taken more than an hour if we fed in one sequence at a time. With a GPU there is even more difference because there are thousands of processors available.

Combining examples into a batch Figure 12.3: A batch stacks multiple independent examples into a single block.

We group multiple sequences together into a batch (Figure 12.3). If our batch size is 32, we pass 32 independent sequences through the model in one go. The model processes them in parallel, calculates the loss for all 32, and averages it out.

Why 32 and Not 1, or 1,000

There are two reasons why you want to batch. Speed is one. The other is how accurate your steps will be.

When we take our loss we get a step to adjust our weights. If our batch size were 1, we would be stepping in the direction that one snippet of Shakespeare tells us to. That could be a stage note or a long sequence of talk or maybe just blank space. We would jump in each direction and try to correct ourselves heavily each time. If we average 32 random chunks of Shakespeare together we get a more accurate step in the direction that the text wants to go as a whole.

A batch size of 1,000 would have two drawbacks. One being that all those sequences need to fit in memory. On a laptop, memory is the limit you hit first. You also wouldn't get much more accurate directions if you averaged 1000 snippets instead of 32 but your step would take 30x longer. There's nothing magic about a batch size of 32, and you'll see other books use 16 or 64. It's big enough to be accurate and small enough to fit.

Once we get to our "Training" step on our map we can begin to plug our batched data into our model and start the training loop.

Code

To handle this efficiently, we use two built-in PyTorch tools: Dataset and DataLoader (Figure 12.4).

Code flow: raw data into dataset and dataloader Figure 12.4: The Dataset handles the sliding window, and the DataLoader stacks the examples into a batch.

src/ch11_dataloader.py (excerpt)
class TextDataset(Dataset):
    def __init__(self, data, block_size):
        self.data = data
        self.block_size = block_size

    def __len__(self):
        # We need block_size + 1 tokens to form one (input, target) pair
        return len(self.data) - self.block_size

    def __getitem__(self, idx):
        # Input is a block of text
        x = self.data[idx     : idx + self.block_size]
        # Target is the same text, shifted one character to the right
        y = self.data[idx + 1 : idx + self.block_size + 1]
        return x, y

train_dataset = TextDataset(train_data, gpt_cfg.block_size)
val_dataset   = TextDataset(val_data,   gpt_cfg.block_size)

# DataLoader automatically batches the data for us
train_loader = DataLoader(
    train_dataset, batch_size=train_cfg.batch_size, shuffle=True
)

Run the full script to see the pipeline produce one batch:

Terminal
$ python src/ch11_dataloader.py
Data loaded: 1,115,394 total tokens
  Train : 1,003,854 tokens
  Val   : 111,540 tokens

Dataset sizes:
  Train examples: 1,003,726
  Val   examples: 111,412

DataLoader config:
  Batch size  : 32
  Train batches per epoch: 31,367

--- Inspecting one batch ---
x_batch shape: torch.Size([32, 128])  (batch_size, block_size)
y_batch shape: torch.Size([32, 128])  (batch_size, block_size)

First example in batch:
  x (input)  : 'ness! serious vanity!\nMis-shapen chaos of well-seeming for...
  y (target) : 'ess! serious vanity!\nMis-shapen chaos of well-seeming form...
  (y is x shifted by 1 character)

DataLoader ready! Ready for Chapter 13.

What just happened:

  1. We loaded our text file and converted it to token IDs.
  2. Lines 12 and 14 comprise the sliding window in TextDataset. Line 12 cuts the slice of text beginning at position idx. Line 14 cuts the same slice shifted one character to the right, its target.
  3. Lines 21-23 instantiate a DataLoader which batches and shuffles our training data automatically. One pass through all of the batches is known as an epoch, the term in the output above.
  4. We grabbed one batch and inspected it to confirm the target y is the input x shifted by one character.

Shape Check:

Table 12.1 lists the shapes of the batched input and target.

Table 12.1: Tensor shapes for the batched input and target sequences.

Variable Shape Meaning
x_batch [32, 128] 32 sequences, each containing 128 input characters.
y_batch [32, 128] 32 sequences, each containing 128 target characters.

Try It

We can see the sliding window in action with a tiny dataset.

src/examples/ch12_batching_demo.py
"""Show how a sliding window creates multiple overlapping examples."""
import torch

data = torch.tensor([10, 20, 30, 40, 50, 60, 70])
block_size = 3

print(f"Data: {data.tolist()}")
print(f"Block size: {block_size}\n")

# A simple loop to show the sliding window
for i in range(len(data) - block_size):
    x = data[i : i + block_size]
    y = data[i + 1 : i + block_size + 1]
    print(f"Example {i+1}:")
    print(f"  Input  : {x.tolist()}")
    print(f"  Target : {y.tolist()}")

Lines 12 and 13 slice the array to create overlapping sequences for the input and target.

Terminal
$ python src/examples/ch12_batching_demo.py
Data: [10, 20, 30, 40, 50, 60, 70]
Block size: 3

Example 1:
  Input  : [10, 20, 30]
  Target : [20, 30, 40]
Example 2:
  Input  : [20, 30, 40]
  Target : [30, 40, 50]
Example 3:
  Input  : [30, 40, 50]
  Target : [40, 50, 60]
Example 4:
  Input  : [40, 50, 60]
  Target : [50, 60, 70]

Try It

Open src/examples/ch12_batching_demo.py. Change block_size to 4, run it again, and notice how the number of available examples decreases.

In Business

Say you want to train your company's house-style assistant from an archive of 100,000 corporate documents. You're not going to point to one word at a time and make it learn. Processing information in batches allows the assistant to read through 32 documents (emails, papers, books) at once and learn from them all. That's how training remains fast when it needs to happen at scale.

Watch Out

Be careful about your dataset's __len__. If you have 100 characters, with block_size 10, you can only have 90 starting positions. Why? Because you need 11 characters to provide a single example, 10 for the input and 1 more for the target. That's why the code uses len(self.data) - self.block_size.

Key Takeaways

  • A sliding window extracts overlapping sequences from a continuous block of text.
  • Batching processes multiple independent sequences in parallel, which speeds up training.
  • PyTorch's Dataset defines how to grab a single example.
  • PyTorch's DataLoader handles the tedious work of grouping examples into batches and shuffling them.

Check Your Understanding

  1. If you have a sequence of 1000 tokens and a block size of 100, how many examples can a sliding window extract?
  2. Why is batching important for training speed?
  3. Why do we shuffle the training data?

Assignment

Assignment 12: Follow one number

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/examples/ch12_batching_demo.py as it is. Copy the four examples it prints, each with its Input and its Target.
  2. Change one number. Find the line data = torch.tensor([10, 20, 30, 40, 50, 60, 70]). These seven numbers stand in for a text of seven characters. Change the 40 in the middle to any whole number that is not already in the list, and run the script again.
  3. Compare. In how many examples is your number part of the Input? In how many is it part of the Target? How many examples does the script print now, and did that count change?
  4. Explain it. In two or three sentences a manager could follow, say how a sliding window turns one text into many training examples, and why one character can appear in several of them.

Hand in: both sets of four examples, your answers to step 3, and your sentences.

Further Reading

Why the field started building bigger. Before this, deciding how large to make a model, how much text to train it on, and how much compute to spend was guesswork. The paper measured all three and found the error falls along smooth, predictable curves across a very wide range of sizes. Model building became a budgeting exercise, which is why the industry spent the following years scaling up. The same curves also explain the ceiling on the model you train here, because about 825,000 parameters and about a million characters of Shakespeare buy a certain quality of text, and no more.

Kaplan, J., McCandlish, S., Henighan, T., Brown, T. B., Chess, B., Child, R., Gray, S., Radford, A., Wu, J., & Amodei, D. (2020). Scaling laws for neural language models (arXiv:2001.08361). arXiv. https://doi.org/10.48550/arXiv.2001.08361

Next up: Chapter 13: The Training Loop