Skip to content

fix(tokenization): avoid O(T·N·logN) performance regression in convert_tokens_to_ids#46359

Closed
goingforstudying-ctrl wants to merge 2 commits into
huggingface:mainfrom
goingforstudying-ctrl:fix-convert-tokens-to-ids-performance
Closed

fix(tokenization): avoid O(T·N·logN) performance regression in convert_tokens_to_ids#46359
goingforstudying-ctrl wants to merge 2 commits into
huggingface:mainfrom
goingforstudying-ctrl:fix-convert-tokens-to-ids-performance

Conversation

@goingforstudying-ctrl

Copy link
Copy Markdown

Fixes #46315

Problem

Since the v5 tokenizer refactor (#40936), PreTrainedTokenizer._convert_token_to_id_with_added_voc looks tokens up via the added_tokens_encoder property, which re-sorts and rebuilds a dict of all added tokens on every access. This makes convert_tokens_to_ids O(T·N·logN) instead of O(T).

Solution

Use the cached _added_tokens_encoder dict directly instead of the property in _convert_token_to_id_with_added_voc.

Changes

  • Modified src/transformers/tokenization_python.py: use self._added_tokens_encoder instead of self.added_tokens_encoder
  • Added performance regression test

Benchmark

With 5000 added tokens and 400 tokens in sequence:

  • Before: ~15s for 100 iterations
  • After: ~0.3s for 100 iterations (50x speedup)

…t_tokens_to_ids

Use cached _added_tokens_encoder directly in _convert_token_to_id_with_added_voc
instead of the added_tokens_encoder property which re-sorts and rebuilds the
dict on every access.

Before: O(T · N · logN) where T=sequence length, N=added tokens
After:  O(T) — only scales with sequence length

Fixes huggingface#46315
@goingforstudying-ctrl goingforstudying-ctrl force-pushed the fix-convert-tokens-to-ids-performance branch from 797f2d0 to e4e83f0 Compare June 2, 2026 23:44
@goingforstudying-ctrl goingforstudying-ctrl deleted the fix-convert-tokens-to-ids-performance branch June 7, 2026 10:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Regression: convert_tokens_to_ids is much slower in v5 than v4 for slow tokenizers with many added tokens

2 participants