← All notes

Tokenizer padding, truncation, and special tokens

Answer: A tokenizer converts text into tensors; to batch varying-length sequences, use padding (shorter sequences gain pad tokens) and truncation (long sequences lose trailing tokens).

Call, encode, decode

Padding

In the attention mask, padding positions are 0, so the model ignores them. padding=True pads to the longest sequence; max_length pads to a fixed size.

Truncation

Set truncation=True and specify max_length to clip tokens so a sequence fits within a maximum length.

Left padding for generation

Large language models pad on the left side because generation predicts the next token from the right side, and LLMs aren't trained to continue generation from padding tokens.

Artifacts

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Hugging Face docs (huggingface/transformers, huggingface/huggingface_hub, huggingface/diffusers on GitHub), Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0). Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Hugging Face docs, Tokenizers, Apache-2.0 (huggingface docs repos); Hugging Face docs, Text generation, Apache-2.0 (huggingface docs repos).

Cite this

Permanent ID: iil:note:v9w0ww7y

iinventedlight. 2026. "Tokenizer padding, truncation, and special tokens." iinventedlight Library, iil:note:v9w0ww7y, version of 2026-11-09. https://iinventedlight.com/library/notes/hf-tokenizers-padding-truncation/. License: CC-BY-4.0.

@misc{iil_note_v9w0ww7y,
  author = {{iinventedlight}},
  title = {{Tokenizer padding, truncation, and special tokens}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-09},
  url = {https://iinventedlight.com/library/notes/hf-tokenizers-padding-truncation/},
  note = {Permanent ID iil:note:v9w0ww7y. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/hf-tokenizers-padding-truncation.md.