Lesson 2 · Unit 02
Batches
Collate, pad to the longest, bucket by length, accumulate
What you practise
- The collate function, padding to the longest in the batch, bucketing by length, shuffling, gradient accumulation and the effective batch size
Try a question from this lesson
Pick one
Three examples have 3, 5 and 40 tokens. They must go through the model as one rectangular batch. Which choice wastes the least compute?
Hint
The model runs on every position of the rectangle, padding included. Which rectangle is smallest without losing data?
Correct answer
Pad every row to the longest in this batch, 40
Why
The model computes on every cell of the rectangle. Padding to 40 makes 120 cells; padding to 512 makes 1,536, almost all of them wasted. Cutting to 3 tokens throws the data away. Pad to the longest row of the batch, no further.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The collate function
A DataLoader picks the samples for a batch and hands them, as a list, to its collate_fn. That function returns the batch tensor.
Padding there, to the longest sample in the list, is called dynamic padding: each batch is only as wide as it needs to be. pad_sequence does the padding, with 0 unless told otherwise.
def collate(batch):
return pad_sequence(
batch, batch_first=True)Concept
Gradient accumulation
Suppose a batch of 32 will not fit in memory but a batch of 8 will. Run four batches of 8, calling backward() on each, and step once.
Gradients add up until they are zeroed, so the four small gradients sum. Dividing each loss by 4 turns that sum into the average, the same gradient the batch of 32 would have given.
10 more exercises in the app
- 3× multiple choice
- 3× type the answer
- 1× fill the blanks
- 1× order the lines
- 1× match the pairs
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.