# Attention Masks and Padding

> Why a batch needs padding, how an attention mask keeps the filler out of the model's reading, and the convention bugs that hide in it, for your AI interview.

**In short:** An attention mask tells the model which positions are real text and which are padding filler, so the filler gets no attention. Padding makes every prompt in a batch the same length, so they fit in one rectangle of numbers.

AI and LLM interview question Q066, Transformer architecture. Intermediate, occasional (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/attention-masks-and-padding

## Say it in 30 seconds

A batch of prompts has to be the same length to fit in one rectangle of numbers, so I pad the short ones with filler. An attention mask marks the filler, so the model gives it zero attention. The mask also has to reach the averaging step (pooling) and the training loss (the error score the model learns from), or the filler leaks in. Most bugs come from mixing up which value means real and which means padding, so I check that first.

## Say it in 2 minutes

When a model runs a batch of prompts, the batch has to be a neat rectangle. So the shorter prompts get padding tokens added until they match the longest one. Padding is filler, not meaning, so the model must not treat it as real words. That is the job of the attention mask. It is a row of ones and zeros, one per position: a one means real text, a zero means filler.

Inside each attention layer, the mask goes onto the scores before softmax, the step that turns raw scores into weights that add up to 1.Blocked positions are set to minus infinity, and softmax turns minus infinity into a weight of zero. Decoder models also need a causal mask, so a token cannot look at later tokens, and the two masks are combined. Pooling and the loss need the same care. An average over a padded row must skip the filler, and padding labels are set to -100 so the loss ignores them.

The convention is where bugs hide. The BERT tokenizer in Hugging Face uses one for real tokens and zero for padding. PyTorch, a deep-learning library, uses True for padding in its attention layer, the opposite. Pass a Hugging Face mask straight into PyTorch's layer and the model ignores the real words and attends to the filler. For decoder models, pad on the left, because generation continues from the last token. Padding also wastes compute, so pad to the longest prompt in a batch and group similar lengths together.

I test it with two prompts of different lengths, and compare the pooled result with and without the mask. If the answer changes when the batch gets more padding, the mask is wrong.

## What is an attention mask, in plain words?

Models need every input in a batch to be the same length, so the batch can be stacked into one rectangle of numbers. Short prompts get padding added until they match the longest prompt in the batch. Padding is filler. It has no meaning, so the model has to be told to ignore it.

The attention mask is that instruction. It is a list of ones and zeros, one for each position. A one says this position is real text. A zero says it is padding, so attention must not look at it. The tokenizer builds the mask, and you pass it to the model with the inputs.

Picture a claims clerk handed a tray of forms. Some forms are short, so the clerk slips blank sheets under them to make the stack even. When adding up the claim amounts, the clerk skips the blank sheets. The mask is the note that says which sheets are blank. A made-up case has the same shape:a support bot reads a 12-token ticket next to a 90-token one, and the mask keeps the 78 filler slots out of its reading.

- **Padding:** Filler tokens added to a short input so it matches the batch length.
- **Attention mask:** Ones and zeros that mark real tokens and padding, so attention skips the padding.
- **Embedding:** A list of numbers that stands for one token.
- **Pooling:** Averaging many token vectors into one vector.
- **Causal mask:** A rule that stops a decoder token from looking at later tokens.

## What do the 1s and 0s mean, and do libraries agree?

Not every library uses the same convention, so the meaning of the numbers has to be checked each time. Hugging Face, an open-source library for loading ready-made AI models, has its own glossary. Its example is BERT, an early text model. The glossary defines the mask like this:

> "The attention mask is a binary tensor indicating the position of the padded indices so that the model does not attend to them." (Hugging Face, Transformers glossary)
>
> "For the BertTokenizer, 1 indicates a value that should be attended to, while 0 indicates a padded value." (Hugging Face, Transformers glossary)

- **Hugging Face (BERT tokenizer): 1 means real, 0 means padding.** The BERT tokenizer returns attention_mask with this meaning.
- **PyTorch MultiheadAttention: True means ignore.** Its key_padding_mask marks padding with True, so a Hugging Face mask must be inverted before it goes in.

> "For a binary mask, a True value indicates that the corresponding key value will be ignored for the purpose of attention." (PyTorch, MultiheadAttention)
>
> "The boolean mask semantics for attn_mask are the inverse of MultiheadAttention's key_padding_mask." (PyTorch, scaled_dot_product_attention)

> **Tip:** Asked how a padding mask works, name the convention before the code. Say which value means real and which means padding, and that the two PyTorch APIs disagree.

## Where does the mask go inside attention?

The mask is applied to the attention scores, before softmax. The original Transformer paper masks by setting to minus infinity "all values in the input of the softmax which correspond to illegal connections". Softmax turns minus infinity into a weight of zero, so the blocked positions contribute nothing.

*Diagram, Two masks, one attention step: A padded batch feeds a padding mask, and a decoder also feeds a causal mask. Both mark spots in the same scores, and softmax gives every marked spot a weight of zero.*
1. The batch feeds the padding mask, which marks the filler spots.
2. A decoder model also feeds the causal rule, so no token sees later tokens.
3. The padding mask marks the filler spots in the scores.
4. The causal mask marks the later spots in the same scores.
5. Marked spots become minus infinity, so softmax gives them zero weight.

Doing it after softmax is the wrong place. Zeroing weights after softmax leaves the rest no longer adding up to 1, so the mix of values is wrong.

## How does padding leak into the average?

Sentence embeddings, one list of numbers for a whole sentence, are often a mean (average) of the token vectors.If the mean includes the padding positions, the answer depends on how much padding the batch happened to have. The padding positions still hold numbers, because the pad token has its own embedding and passes through the layers.

*Diagram, Mean pooling with and without the mask: Without a mask, the same prompt gives a different vector depending on how much padding its batch adds. With the mask, only the real tokens are averaged, so the vector stays the same however much padding the batch has.*
1. The padded row goes into a plain average, filler included.
2. The same row goes into a masked average, which skips the filler.
3. So the no-mask average shifts when the padding changes.
4. The masked average stays the same however much padding the batch has.

Here is the same problem in plain Python, with made-up numbers. The mask decides which positions count, and the softmax line shows the blocked spots getting zero weight.

```python
# Made-up embeddings for one support ticket: 3 real tokens, padded to 5 positions.
# The mask uses 1 for a real token and 0 for padding (the Hugging Face convention).
import math

vectors = [[0.9, 0.1], [0.7, 0.3], [0.5, 0.5], [0.3, 0.3], [0.3, 0.3]]
mask = [1, 1, 1, 0, 0]

def mean_pool(rows, keep):
    # Average only the positions the mask keeps.
    kept = [r for r, k in zip(rows, keep) if k == 1]
    return [round(sum(r[d] for r in kept) / len(kept), 2) for d in range(2)]

print("no mask:  ", mean_pool(vectors, [1, 1, 1, 1, 1]))
print("with mask:", mean_pool(vectors, mask))

# One query token scores all 5 positions. Blocked spots become -inf, so softmax gives them 0.
scores = [2.0, 1.0, 0.5, 1.5, 1.5]
blocked = [s if k == 1 else float("-inf") for s, k in zip(scores, mask)]
exps = [math.exp(s) for s in blocked]
weights = [round(e / sum(exps), 2) for e in exps]
print("weights:  ", weights)
```

Output:

```text
no mask:   [0.54, 0.3]
with mask: [0.7, 0.3]
weights:   [0.63, 0.23, 0.14, 0.0, 0.0]
```

## What else must the mask touch: loss, padding side and cost?

The loss must also ignore padding. The loss is the error score the model learns from. Set the label of each filler position to -100, the default ignore_index in PyTorch's CrossEntropyLoss, so no error is counted for filler.

For decoder-only chat and generation models, the padding goes on the left. Generation continues from the last token, so filler on the right puts the model's next word after the padding. Hugging Face's LLM tutorial says it plainly: LLMs aren't trained to continue generation from padding tokens.

Padding also costs compute. A padded position is still computed. PyTorch's attention note says that on its optimized inference fastpath, a NestedTensor (a format that stores only the real tokens) represents padding more efficiently, with an extra speedup proportional to the fraction of the input that is padding.Hugging Face's guidance is to pad to the longest sequence in a batch and truncate to the model's maximum length, which works well in most cases. For big jobs, sort prompts by length so each batch has similar lengths.

> **Tip:** When the job is slow and the batch is mostly filler, say that padding is wasted compute and group similar lengths before buying a bigger GPU.

### How would you batch 10,000 tickets for a classifier?

1. **Sort by length:** Group tickets of similar length, so each batch needs little padding.
2. **Pad to the batch, not the model maximum:** Pad each batch to its own longest ticket. Padding every ticket to the model maximum wastes compute.
3. **Pass the mask with the inputs:** Send input_ids and attention_mask together, and keep the padding side the one the model was trained with.
4. **Pool with the mask:** Average only the real token vectors, so the same ticket gets the same vector in any batch.
5. **Test the convention:** Run one ticket alone and inside a batch. Same answer means the mask works.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Padding makes a batch a rectangle, and the mask says which positions are real.
- [ ] The mask goes onto the scores before softmax, blocked spots get zero weight.
- [ ] Decoders combine the padding mask with the causal mask.
- [ ] The conventions differ: 1 for real in Hugging Face, True for padding in PyTorch.
- [ ] The mask must also reach the pooling step and the loss.
- [ ] Padding wastes compute, so batch by length.

**Common traps**

- Trap: "Padding is harmless, the model learns to ignore it." Better: Not reliably. Without the mask, the filler changes attention and the averages. Pass the mask every time.
- Trap: "Multiply the weights by the mask after softmax." Better: Mask the scores before softmax, so blocked spots get zero weight and the rest still add up to 1.
- Trap: "Use the same mask in every library." Better: Check the convention. The BERT tokenizer in Hugging Face uses 1 for real tokens, and PyTorch's key_padding_mask uses True for padding.

## Can you spot the bug?

**Spot the bug:** A team passes a Hugging Face attention_mask straight into PyTorch MultiheadAttention as key_padding_mask. What happens?

A. Training runs a little slower, with no change to results.
B. Real tokens are ignored and the filler is attended to, because the convention is inverted.
C. The model stops producing an output.
D. Padding is added to the tokens a second time.

**Answer:** B. PyTorch marks padding with True, but the Hugging Face mask uses 1 for real tokens. Inverting the mask first fixes it.

**Quick check:** A decoder-only chat model answers well alone but gives junk for some prompts in a batch. Which cause fits best?

A. The temperature is set too high.
B. The padding sits on the right, so generation starts after the filler.
C. The attention mask is too large for the model.
D. The tokenizer lowercases the input.

**Answer:** B. Decoder-only models continue from the last token, so padding should be on the left. Temperature and tokenizer casing do not move the padding.

## Can you answer these from memory?

**Flash cards**

- **Why pad a batch?** So every prompt has the same length and fits in one tensor.
- **What does a 1 mean in a Hugging Face mask?** A real token that attention may look at. A 0 marks padding.
- **Where is the mask applied?** To the scores, before softmax. Blocked spots get zero weight.
- **What does PyTorch use for padding?** True in key_padding_mask. It is the inverse of Hugging Face.
- **Why left padding for chat models?** Generation continues from the last token, so the filler must not sit after it.
- **Does padding affect the loss?** Yes, unless padding labels are set to -100 so the loss ignores them.

## Likely follow-up questions

- Q050 What is causal (masked) attention? https://designervenkat.online/interview/ai/what-is-causal-masked-attention
- Q063 Masked vs causal language modelling? https://designervenkat.online/interview/ai/masked-vs-causal-language-modelling
- Q056 Why is attention quadratic in sequence length? https://designervenkat.online/interview/ai/why-is-attention-quadratic-in-sequence-length
- Q055 What is the KV cache, and why does it speed up generation? https://designervenkat.online/interview/ai/what-is-the-kv-cache
- Q314 Static vs continuous batching? https://designervenkat.online/interview/ai/static-vs-continuous-batching
- Q065 Prefill vs decode phases? https://designervenkat.online/interview/ai/prefill-vs-decode-phases
