Bitpath

Lesson 2 · Unit 02

Batches

Collate, pad to the longest, bucket by length, accumulate

13 exercisesabout 3 min

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?

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.

Python
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.

One email when Bitpath is ready to try. Nothing else. Privacy