esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
Let’s talk

I’ll build the agent for it.

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.

12 min readIntermediateOccasional · estimateFacts checked 27 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

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.

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.

Key words

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.

Two masks, one attention step

Batch of 2 prompts

the short one gets padding

Masks

Padding mask

marks the filler positions

Causal mask

decoder models only, set by model type

Attention scores

blocked spots become minus infinity

Softmax weights

blocked spots get weight 0

  1. 1The batch feeds the padding mask, which marks the filler spots.
  2. 2A decoder model also feeds the causal rule, so no token sees later tokens.
  3. 3The padding mask marks the filler spots in the scores.
  4. 4The causal mask marks the later spots in the same scores.
  5. 5Marked spots become minus infinity, so softmax gives them zero weight.
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.

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.

Mean pooling with and without the mask

Row: 3 real, 2 padding

the padding positions still hold numbers

No mask

Average all 5

padding counts toward the mean

Mask on

Average the 3 real

padding is skipped

Changes with padding

same text, a different vector

Same vector each time

same text, same vector

  1. 1The padded row goes into a plain average, filler included.
  2. 2The same row goes into a masked average, which skips the filler.
  3. 3So the no-mask average shifts when the padding changes.
  4. 4The masked average stays the same however much padding the batch has.
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.

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

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

    Sort by length

    Group tickets of similar length, so each batch needs little padding.

  2. 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. 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. 4

    Pool with the mask

    Average only the real token vectors, so the same ticket gets the same vector in any batch.

  5. 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."

    BetterNot 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."

    BetterMask 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."

    BetterCheck 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?

Quick check

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

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q050What is causal (masked) attention?10 min
  2. Q063Masked vs causal language modelling?11 min
  3. Q056Why is attention quadratic in sequence length?11 min
  4. Q055What is the KV cache, and why does it speed up generation?12 min
  5. Q314Static vs continuous batching?12 min
  6. Q065Prefill vs decode phases?10 min

Last updated on 27 November 2026

Is your AI feature giving different answers in a batch?

I design and build AI products and agents, the screens and the system behind them. Book a short call and tell me what your batch job does.