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.
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.
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 AutoTokenizertok = 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"]))
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.
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.