23/29
Part 4 of 5 · The loss and the length limitLearn and do

The length limit

The position table has block_size rows, and the mask is block_size by block_size. So the model can't read more than block_size tokens. Check the length first:

if T > self.block_size:
    raise ValueError(f"got {T} tokens, block_size is {self.block_size}")

Without the check, 17 tokens in a 16-position model still fail, but badly: the lookup asks for row 16 of a 16-row table and raises IndexError: index out of range in self from deep inside PyTorch. On a GPU the error can even be reported at a later line. Your check gives one clear message, at the line that caused it.

This matters most when the model generates text. Each step adds a token, so the text soon grows past block_size.

Predict

The text has grown past block_size. Which tokens go into the model for the next one?

Pick an answer above to see the rest