Chapter 12: Dataset and DataLoader¶
Figure 12.1: We begin the training module by preparing our data pipeline.
So we have our model. From Chapter 11 we know we want to predict the next token. Time to input data into our model. We are not going to enter individual characters into our model but instead input thousands of examples at once. This chapter will be used to create a pipeline to 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 previous chapter, we learned how one sequence can generate many training examples. But where do we get those sequences from? For instance, how do we get sequences from our large text file of Shakespeare plays?
We use a sliding window (Figure 12.2).
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¶
Training each sequence separately would take too long. Our current technology allows for computations on sequences at a large scale. So if we only trained one at a time, we would not be taking full advantage of our computer's graphics processor (GPU).
To see how much batching matters, we can time it:
$ 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.
Figure 12.3: A batch stacks multiple independent examples into a single block.
We bundle many sequences together into a batch (Figure 12.3). Say our batch size is 32. We feed the model 32 independent sequences at once. The model runs them in parallel. It computes the loss across all 32 sequences and averages the loss.
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).
Figure 12.4: The Dataset handles the sliding window, and the DataLoader stacks the examples into a batch.
Run the full script to see the pipeline produce one batch:
$ 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:
- We loaded our text file and converted it to token IDs.
- Lines 12 and 14 form the sliding window for
TextDataset. Line 12 slices the text starting at positionidx. Line 14 slices the same text shifted one character to the right, which is its target. - Lines 21-23 create a
DataLoader. It will automatically batch and shuffle our training data for us. When we go through all of the batches once, that is called an epoch, the term in the output above. - We grabbed one batch and inspected it to confirm the target
yis the inputxshifted 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.
Lines 12 and 13 slice the array to create overlapping sequences for the input and target.
$ 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
Imagine wanting your company's house-style assistant to learn from a library of documents. Say we had 100,000 company documents that we wanted to teach our assistant on. Obviously we're not teaching it one word at a time. When learning, you can teach your assistant in groups of 32 at a time. These could be emails or articles or even whole books. That is what makes it so efficient to teach your assistant on these large data sets.
Watch Out
Watch your dataset's __len__. If you have 100 characters and your block_size is 10, you only have 90 starting spots. Why? Because we need 11 characters to create a single example, 10 characters to input and 1 more to predict. That's why there's len(self.data) - self.block_size in the code.
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
Datasetdefines how to grab a single example. - PyTorch's
DataLoaderhandles the tedious work of grouping examples into batches and shuffling them.
Check Your Understanding¶
- If you have a sequence of 1000 tokens and a block size of 100, how many examples can a sliding window extract?
- Why is batching important for training speed?
- 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.
- Run it. Run
src/examples/ch12_batching_demo.pyas it is. Copy the four examples it prints, each with its Input and its Target. - 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 the40in the middle to any whole number that is not already in the list, and run the script again. - 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?
- 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. Prior to this work, choices of model size, text volume to train on, and compute budget had been guesswork. This paper measured all three variables and discovered error decreases smoothly and predictably across an extremely wide range of model sizes. Turning model building into a cost/budget exercise explained why the industry then scaled up for the next few years. It also shows why there is a limit to how well the model you train yourself will do, because roughly 825,000 parameters and about a million characters of Shakespeare buy you a certain quality of text, 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