skip to content

Tokenizer code written for Transformers v4 passes use_fast=False, calls encode_plus and treats apply_chat_template's result as ids — what changes under v5, and what replaces each?

level: seniorimportance: should knowfreq 8%

answer

  1. no more slow and fast pair
  2. named backends chosen by AutoTokenizer
  3. use_fast is silently ignored
  4. backend='sentencepiece' to force one
  5. call the tokenizer; expect a BatchEncoding

basics

~10 s

Transformers v5 drops the slow/fast split: AutoTokenizer picks a named backend, ignores use_fast, and takes backend='sentencepiece' to force SentencePieceBackend. encode_plus gives way to calling the tokenizer, and apply_chat_template returns a BatchEncoding, not bare ids.

solid answer

~30 s

Transformers v5 keeps one tokenizer file per model, backed by `TokenizersBackend` (the Rust `tokenizers` library, preferred), `SentencePieceBackend`, `PythonBackend` (the old `PreTrainedTokenizer`) or `MistralCommonBackend`. `AutoTokenizer.from_pretrained` pops `use_fast` and ignores it, defaulting to `backend="tokenizers"`; pass `backend="sentencepiece"` to get the SentencePiece one. The migration guide replaces `encode_plus` with `__call__`, and at v5.18 the method is gone, so `tokenizer(text, ...)` is the call. `batch_decode` folds into `decode`, which now accepts a batch. `apply_chat_template` defaults to `return_dict=True` and returns a `BatchEncoding`, so code reading `.shape` on it breaks: use `out["input_ids"]`, `generate(**out)` or `return_dict=False`. Saving no longer writes `special_tokens_map.json`.

code

python · 16 lines
python
from transformers import AutoTokenizer

repo = "your-org/your-chat-model"

# v4: AutoTokenizer.from_pretrained(repo, use_fast=False)
tok = AutoTokenizer.from_pretrained(repo)  # v5: backend="tokenizers" by default

# v4: tok.encode_plus("Hello there", truncation=True, max_length=128)
enc = tok("Hello there", truncation=True, max_length=128)

messages = [{"role": "user", "content": "Hello!"}]
# v4 returned a tensor of ids here; v5 returns a BatchEncoding
inputs = tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
print(inputs.keys())  # input_ids, attention_mask

ids_only = tok.apply_chat_template(messages, add_generation_prompt=True, return_dict=False)

go deeper

for a junior

Know that Transformers v5 has one tokenizer per model on a named backend, and that you call the tokenizer directly instead of encode_plus.

for a middle

Explain that AutoTokenizer ignores use_fast and takes backend=, and that apply_chat_template now returns a BatchEncoding you unpack with generate(**inputs).

for a senior

Plan an upgrade: find silent changes (ignored use_fast, aliases that hide API removals, regenerated ids) as well as loud ones, and verify with fixture tests before reusing cached tokenized data.

for a principal

Weigh upgrading shared preprocessing in one step against pinning the old major: cached tokenized datasets, fixture drift and every consumer of the chat-template return value.

## The slow/fast split is gone Up to v4, many models had two tokenizer implementations: a **slow** Python one (often built on the `sentencepiece` library) and a **fast** Rust one from the Hugging Face `tokenizers` library, with `use_fast` choosing between them. **Transformers v5** consolidates to one tokenizer file per model, built on a named **backend**: | Backend | What it is | Notes | |---|---|---| | `TokenizersBackend` | Rust `tokenizers` library | Preferred; offsets, parallel batch encoding, training | | `SentencePieceBackend` | the `sentencepiece` library | Inherits from `PythonBackend` | | `PythonBackend` | pure-Python implementation | Previously `PreTrainedTokenizer` | | `MistralCommonBackend` | the `mistral-common` library | Previously `MistralCommonTokenizer` | The old names survive as aliases (`PreTrainedTokenizerFast` is `TokenizersBackend`, `PreTrainedTokenizer` is `PythonBackend`), so imports keep working while the behaviour underneath is the v5 one. ## Why the change, and what else moved The goal of the refactor is that tokenizers behave like models: a tokenizer class defines its full pipeline, and an instance is either trained or empty. In v5 you can create an empty `LlamaTokenizer()` and train it, or initialise one directly from a `vocab` and `merges`. Two related behaviour changes matter when upgrading: - **Backend synchronisation is gone.** v4 copied settings such as `add_prefix_space` or `do_lower_case` into the backend after initialisation; v5 takes behaviour from `tokenizer.json` or the class definition at load time only. - **`prepare_seq2seq_batch()` is deprecated**; encode source and target in one call, `tokenizer(src_texts, text_target=tgt_texts, max_length=128)`, and the target ids come back under `labels`. ## use_fast and the backend argument `AutoTokenizer.from_pretrained` selects the class from the checkpoint's configuration, as before. In v5 it **pops `use_fast` and discards it** without a warning, and takes **`backend=`** instead, defaulting to `"tokenizers"`: - `backend="tokenizers"` loads the Rust-backed tokenizer. - `backend="sentencepiece"` loads the SentencePiece one, which needs the repo's SentencePiece model file. So `use_fast=False` code that relied on slow-tokenizer quirks now silently runs the Rust tokenizer. That is usually what you want, but a pipeline that compared ids against fixtures produced by a slow tokenizer may see differences. Backend-only features follow the backend: offset mappings, `word_ids()` and `train_new_from_iterator` (retraining a tokenizer's vocabulary on a new corpus with the same pipeline) come from `TokenizersBackend`. ## Encoding and decoding calls - **`encode_plus`**: the v5 migration guide replaces it with `__call__`, and at v5.18 the method is no longer defined, so old calls fail with an `AttributeError`. Write `tokenizer(text, truncation=True, max_length=128)`. - **`encode`** still exists and returns a plain list of ids, without an attention mask. - **`batch_decode`** is folded into **`decode`**, which now accepts a single sequence or a batch and returns a string or a list of strings. `batch_decode` remains as a backward-compatible wrapper. - **`as_target_tokenizer()`** is removed; pass `text_target=` to the call. ## apply_chat_template's return value In v4, `apply_chat_template(..., tokenize=True)` returned bare `input_ids` unless you passed `return_dict=True`. In v5 `return_dict` defaults to **`True`** and the method returns a **`BatchEncoding`** with `input_ids` and `attention_mask`, like a normal tokenizer call. What breaks: 1. Reading `.shape` on the result raises an `AttributeError`, because it is a dictionary-like object. 2. With the Rust backend, indexing it with an integer returns the backend `Encoding` object for that row, not a row of ids. 3. Code that built its own attention mask from the ids is now redundant. Fixes: read `out["input_ids"]`, unpack it with `model.generate(**out)`, or pass `return_dict=False` for the old shape. ## What saving writes - `special_tokens_map.json` and `added_tokens.json` are no longer written; special tokens live in `tokenizer_config.json` and added tokens in `tokenizer.json`. Old files are still read on load. - `additional_special_tokens` becomes **`extra_special_tokens`**, and `additional_special_tokens_ids` is replaced by `extra_special_tokens_ids`. ## A migration checklist 1. Remove `use_fast`; add `backend="sentencepiece"` only where you truly need it. 2. Replace every `encode_plus` call with the tokenizer call. 3. Search for `apply_chat_template` and fix every consumer of its return value. 4. Re-run a tokenization fixture test against v5 ids before trusting cached datasets. 5. Rename `additional_special_tokens` usages. 6. Save the tokenizer once under v5 and diff the output folder, so downstream tooling that read `special_tokens_map.json` is updated before it breaks. For a checkpoint you already loaded through its `tokenizer.json` under v4, ids for ordinary text normally carry over; checkpoints you loaded with `use_fast=False` are where ids can shift. Most of the risk sits in the code around the tokenizer, which is why a fixture test of real inputs, with expected ids and expected keys, is the cheapest guard.

  • Your v4 code imports PreTrainedTokenizerFast directly. Does it still work in v5?
    The import still resolves, because v5 keeps `PreTrainedTokenizerFast` as an alias of `TokenizersBackend`, and `PreTrainedTokenizer` as an alias of `PythonBackend`. The behaviour is the v5 one, including the new `apply_chat_template` return and the removed methods, so the alias hides the rename, not the API changes.
  • Why might ids from a v5 tokenizer differ from fixtures generated with a v4 slow tokenizer?
    v5 ignores `use_fast=False` and loads the Rust-backed tokenizer by default, and it no longer syncs settings such as `add_prefix_space` into the backend after init; behaviour comes from `tokenizer.json` or the class definition. Regenerate fixtures under v5, or pin `backend="sentencepiece"` where the SentencePiece path is what you validated.

  • use_fast=False still loads the Python slow tokenizer in v5.
  • v5 raises an error on use_fast, so you notice the change immediately.
  • apply_chat_template still returns a tensor of ids by default in v5.
  • batch_decode was deleted in v5, so every call to it crashes.
  • encode() is the drop-in replacement for encode_plus.

Assumes Transformers v5 (5.18): named tokenizer backends replace the slow/fast pair, use_fast is ignored, encode_plus is gone and apply_chat_template returns a BatchEncoding.