With a Hugging Face Transformers tokenizer, how do you map each token back to its character span in the original text, for example to highlight entities?
answer
- ask the tokenizer for spans
- a start and end per token
- return_offsets_mapping=True
- special tokens get an empty span
- needs the Rust-backed backend
basics
~10 sPass return_offsets_mapping=True: the BatchEncoding gains offset_mapping, one (start, end) character pair per token, with (0, 0) for added special tokens. It comes from the Rust-backed TokenizersBackend; word_ids() and char_to_token() add word and character lookups.
solid answer
~40 sCall the tokenizer with `return_offsets_mapping=True`. The `BatchEncoding` gains an `offset_mapping` key holding, for every token, a `(start, end)` pair of character positions in the original string, so `text[start:end]` recovers the token's source text; special tokens the tokenizer added, such as `[CLS]`, get `(0, 0)`. To highlight a predicted entity, take its tokens' first start and last end. `word_ids()` maps each token to the index of the word it came from (`None` for special tokens), and `char_to_token()` goes the other way, from a character to its token. These alignment features come from the Rust-backed `TokenizersBackend` in Transformers v5; a Python-based backend raises a `ValueError` for `word_ids()`.
go deeper
Recall that return_offsets_mapping=True gives a (start, end) character span for each token, and that added special tokens get (0, 0).
Explain word_ids() and char_to_token() alongside offsets, and how to turn a run of predicted tokens into one highlighted character span.
Handle long documents with stride and return_overflowing_tokens, merge windows through overflow_to_sample_mapping, and confirm the loaded backend supports alignment.
Decide where alignment lives in a labelling or extraction pipeline so annotations, model output and the displayed text always share one source of character positions.
## Why you need offsets A tokenizer splits text into subword **tokens**, and models predict per token. People, though, read characters and words. To underline an entity a model found, or to turn a character-level annotation into token labels, you need a map between token positions and character positions in the original string. Rebuilding it by decoding tokens is fragile: decoding can change spacing, case or Unicode normalisation, so the decoded text does not line up with the input. ## return_offsets_mapping Pass **`return_offsets_mapping=True`** when you call the tokenizer. The returned `BatchEncoding` gains an **`offset_mapping`** entry: for each token, a pair `(start, end)` of character indices into the string you passed, so `text[start:end]` is the slice that produced the token. - Special tokens the tokenizer **added**, such as `[CLS]` and `[SEP]`, get **`(0, 0)`**, an empty span. - Several tokens from one word have adjacent spans, so the first token's start and the last token's end cover the word. - With `return_tensors="pt"` the offsets become a tensor of shape `(batch, seq_len, 2)`; without it, a list of pairs per row. ```python enc = tokenizer(text, return_offsets_mapping=True) start = enc["offset_mapping"][first_tok][0] end = enc["offset_mapping"][last_tok][1] highlight = text[start:end] ``` ## Highlighting a predicted entity, step by step 1. Tokenize the text once with `return_offsets_mapping=True` and keep the result. 2. Run the model on the same encoding and read a label per token. 3. Group consecutive tokens that share an entity label into a run. 4. Take the first token's `start` and the last token's `end` from `offset_mapping`. 5. Slice the original string with those two numbers, or wrap that range in markup for display. Skip tokens whose span is `(0, 0)` when grouping, so special tokens never extend a run to the start of the text. Because the offsets index the string you passed, the highlight lands exactly on the source characters, whatever the tokenizer did to case or spacing internally. ## word_ids and char_to_token The `BatchEncoding` also carries alignment helpers: | Helper | Maps | Typical use | |---|---|---| | `offset_mapping` | token to `(start, end)` characters | highlighting, character-level labels | | `word_ids(batch_index)` | token to word index (`None` for special tokens) | labelling only the first subword of each word | | `char_to_token(batch_index, char_index)` | character to token index | finding the token that covers an annotated character | | `token_to_chars(batch_index, token_index)` | token to its character span | one-off lookups | | `sequence_ids(batch_index)` | token to sequence 0 or 1 of a pair (`None` for special tokens) | telling question tokens from passage tokens | For token classification, a common recipe uses `word_ids()` to give each word's first token the word's label and to mark special tokens and continuation tokens so the loss ignores them. `is_split_into_words=True` tells the tokenizer the input is already split into words, which keeps `word_ids()` aligned with your word list. ## Long documents: windows and their source Texts longer than `max_length` can be cut into overlapping windows: 1. Call the tokenizer with `truncation=True`, `max_length`, a `stride` (the number of overlapping tokens) and `return_overflowing_tokens=True`. 2. Each window becomes its own row, and `overflow_to_sample_mapping` tells you which input text each row came from. 3. The `offset_mapping` of every window still points into that original text, so predictions from all windows can be merged back into one character-level result. ## The backend requirement Offsets come from the Rust `tokenizers` library, which tracks the source span of every token as it encodes. In Transformers v5 that is **`TokenizersBackend`**, which `AutoTokenizer` loads by default; in v4 terms it was the fast tokenizer. Python-based backends, `PythonBackend` and `SentencePieceBackend`, do not track spans the same way: calling `word_ids()` on their output raises a `ValueError` saying it is not available for Python-based tokenizers. If alignment matters, check `type(tokenizer)` before you build a labelling pipeline on it. ## Pitfalls - Using decoded token text to search for spans instead of offsets. - Forgetting that added special tokens have `(0, 0)` spans, then highlighting the start of the text. - Normalising or lower-casing the text yourself before tokenizing, then applying offsets to the original string. - Merging overlapping windows without `overflow_to_sample_mapping`, which mixes documents.
- How do you align word-level NER labels to subword tokens using the tokenizer's output?Tokenize the words with `is_split_into_words=True`, then walk `word_ids()`: give the first token of each word that word's label, and give special tokens (`None`) and later subwords a value the loss ignores. The word index keeps every label attached to the right token however the words were split.
- Decoding each token and searching for it in the text is as reliable as offsets.
- Special tokens get offsets pointing at the end of the text.
- Every tokenizer backend returns offsets, including the pure-Python one.
- Offsets are token indices, not character positions.
Assumes Transformers v5 (5.18), where offsets come from the Rust-backed TokenizersBackend, the class v4 called the fast tokenizer.