AI Hints
Fine-Tuning LLMs · Lesson 12 of 120

Padding, Truncation, Attention Masks

Many texts at once.

⏱ 2 min read▶ Video at 18:32🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

Models work fastest on a batch, which is a group of texts, processed together. But texts have different lengths, and a batch must be a neat rectangle of numbers. Here's how we fix that.

  • A batch = a group of texts
  • Different lengths
  • Must be a neat rectangle

Three words

Padding means adding pad tokens to short texts, until every text is the same length. Truncation means cutting long texts, down to a maximum length. And the attention mask is a list of ones and zeros. One means a real token. Zero means padding, so the model should ignore it.

keyvalue
Paddingfill short texts
Truncationcut long texts
Attention mask1 = real, 0 = padding
Resulta neat rectangle

See it in action

We tokenize two messages together. Padding equals true pads the shorter one. Return tensors PT gives us PyTorch tensors. Then we truncate a long message to five tokens. Run it. The short message got four padding tokens, the number two. Its attention mask ends in four zeros. And truncation cut the message after five tokens.

app.pypython
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
batch = tok(["Is Dune in stock?", "How much is The Hobbit in hardback?"],
            padding=True, return_tensors="pt")
print(batch["input_ids"])
print(batch["attention_mask"])
short = tok("How much is The Hobbit in hardback?", truncation=True, max_length=5)
print(tok.decode(short["input_ids"]))
Output
tensor([[ 4182,   422,  1935,   281,  6132,    47,     2,     2,     2,     2],
        [ 2020,  1083,   314,   378, 20625,  3333,   281,  1759,  2676,    47]])
tensor([[1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
How much is The Hob

Quick check

Let's check. In an attention mask, what does a zero mean? Pause, and think about it. The answer is C. Zero marks a padding token, which the model ignores.

Quick check
In an attention mask, a 0 means...

Summary

Let's recap. Padding makes texts the same length. Truncation cuts long texts. And the attention mask tells the model which tokens are real. Next, loading a model, and looking at what it outputs.

Key takeaways
  • padding=True
  • truncation=True, max_length
  • attention_mask
Next up: Loading a Model — AutoModelForCausalLM