Account for variable-length padding in a batch

Check units and version numbers as you type. · 188 words

A batch groups several requests for faster AI processing. Because requests have different lengths, the service pads shorter sequences with special PAD tokens until every row has the same length. Padding is filler, not user input. An attention mask marks real positions, usually 1, and padding positions, usually 0; masked positions receive no attention weight. For example, a five-token sports prompt and a one-token prompt can share a five-token row with masks [1, 1, 1, 1, 1] and [1, 0, 0, 0, 0]. Training code may also give padded labels -100, meaning "do not score this position."

For a hand check, a museum guide request has three real tokens and is padded to five, giving mask [1, 1, 1, 0, 0]. If its three real token values are 2, 4, and 6, the masked average is (2 + 4 + 6) / 3 = 4. Including the two PAD values, both 0, would give 12 / 5 = 2.4. That is wrong because filler changed the result. The mask keeps PAD from acting like a word. Check both attention masks and label masks before trusting a batched score.

Check your recall

A five-token batch row contains three real tokens and two PAD tokens, with mask [1, 1, 1, 0, 0]. Which positions should affect the result?

Check your answer

Only the first three positions should affect the result. The two PAD positions must receive zero attention weight and be excluded from pooling and loss calculations.

Sources and credits

Original KeyTouch lesson. Background reading · Google · Rules of Machine Learning.