Sub topic 3
Subword tokens and character offsets
This chapter covers how a transformer tokenizer splits text into pieces and how it records where each piece came from in the original string. The records are called offsets. Later chapters depend on them. The model predicts token positions, but a user wants the answer as text. Offsets connect the two.
You should already be comfortable with basic Python and with the idea that a tokenizer turns text into integer ids. The examples use the transformers library and the fast tokenizers it loads by default.
Why models use subwords
A model has a fixed vocabulary, usually 30,000 to 50,000 entries. Word-level vocabularies cannot cover every name, typo, or technical term. Character-level vocabularies cover everything but produce very long sequences. Subword tokenization sits between the two. Common words stay whole, and rare words are split into smaller pieces that are in the vocabulary.
The DistilBERT model used in this tutorial uses WordPiece. A piece that continues a word is marked with a ## prefix. A rare word such as "kilometres" may be split into a few pieces, while "river" stays whole. The exact split depends on the vocabulary, so run the tokenizer instead of guessing.
Other model families mark pieces differently. RoBERTa and GPT-2 use byte-level BPE, where a leading space is folded into the token and shown as Ġ. SentencePiece models mark word starts with ▁. The marking differs, but the consequence is the same: tokens do not line up one-to-one with words or with characters.
This matters for question answering because the answer is a span of text, and the model scores tokens. You need a reliable way to go from a token index back to a character range.
What the tokenizer returns
A fast tokenizer returns more than input_ids. Four pieces of information are useful here.
| Field | What it tells you |
|---|---|
| `input_ids` | The integer id of each token, which is what the model reads |
| `offset_mapping` | For each token, a `(start, end)` pair of character positions |
| `sequence_ids()` | For each token, 0 if it came from the question, 1 if it came from the context, or `None` for a special token |
| `word_ids()` | For each token, the index of the word it came from, or `None` for a special token |
Offsets are half-open ranges. A token with offsets (4, 9) covers text[4:9], so character 9 is not included. The positions are indexes into the Python string.
Run this to see all three together:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased-distilled-squad")
question = "What does the Amazon basin cover?"
context = "Its drainage basin covers about seven million square kilometres."
enc = tokenizer(question, context, return_offsets_mapping=True)
tokens = tokenizer.convert_ids_to_tokens(enc["input_ids"])
seq_ids = enc.sequence_ids()
for tok, (start, end), sid in zip(tokens, enc["offset_mapping"], seq_ids):
print(f"{tok:15} seq={sid!s:5} offsets=({start}, {end})")Read the output with these points in mind:
- The first token is
[CLS]and the separators are[SEP]. They haveseq=Noneand offsets(0, 0)because they do not come from either text. - Question tokens have
seq=0. Context tokens haveseq=1. - The offsets of context tokens restart at 0. They point into
context, not into the combined input. The offsets of question tokens point intoquestion. - Pieces that start with
##have offsets that begin where the previous piece ended.
The last two points cause most offset bugs. An offset pair means nothing until you know which string it belongs to, and sequence_ids() tells you that.
From tokens back to characters
Fast tokenizers have helper methods that convert in both directions. These are the two you will use most:
enc.char_to_token(char_index, sequence_index=1)returns the index of the token that contains a character of the context.enc.token_to_chars(token_index)returns the character span of a token as an object withstartandend.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased-distilled-squad")
question = "What does the Amazon basin cover?"
context = "Its drainage basin covers about seven million square kilometres."
enc = tokenizer(question, context)
char_pos = context.index("kilometres")
tok_idx = enc.char_to_token(char_pos, sequence_index=1)
print("token index:", tok_idx)
print("token text:", tokenizer.convert_ids_to_tokens(enc["input_ids"][tok_idx]))
span = enc.token_to_chars(tok_idx)
print("characters:", span.start, span.end, repr(context[span.start:span.end]))If "kilometres" is split into several pieces, char_to_token returns the first piece, because the first character belongs to it. token_to_chars on that piece returns only part of the word. A word-sized answer therefore needs the first and last pieces of the word. That is why the span decoding in a later chapter looks up the start offset of the first token and the end offset of the last token.
Why you should not use `decode` for answers
You could try to rebuild the answer with tokenizer.decode(input_ids[s:e+1]). This is lossy for three reasons:
- Normalization. Uncased models such as
bert-base-uncasedlowercase the text and strip accents before splitting. Decoding gives youcafe muller, notCafé Müller. - Whitespace. Decoding applies cleanup rules to spacing around punctuation. The result can differ from the source, for example in how spaces around hyphens or quotes are handled.
- Unknown tokens. A character outside the vocabulary becomes
[UNK]. Decoding gives you the literal[UNK], while the offsets still point to the real character.
Offsets avoid all three problems, because they slice the original string and never reconstruct it. The SQuAD metric compares your answer against reference text, so you want the exact original characters.
Special tokens and the question side
Every encoded pair has special tokens. For BERT-style models the layout is:
[CLS] question tokens [SEP] context tokens [SEP]Three rules follow from this layout:
- Special tokens have offsets
(0, 0). If you do not exclude them, a prediction that lands on[CLS]is read as "characters 0 to 0", which looks like an empty answer. - Question tokens can have valid-looking offsets. A start index inside the question would slice the question string, or worse, slice the context at the wrong place. The model should never predict an answer there, so the decoding code masks out every token whose
sequence_idis not 1. - Position 0 (
[CLS]) is not useless. Models trained on SQuAD 2.0 use it as the "no answer" position, which a later chapter covers.
The decoding example in this tutorial builds a mask from sequence_ids() for exactly this reason.
Edge cases
Leading spaces in byte-level BPE
In RoBERTa-style tokenizers a token such as Ġriver includes the space before the word. If offsets included that space, an answer slice could start with a blank character. The fast tokenizers have a trim_offsets setting, enabled by default for these models, that keeps the space out of the offset range. When you switch model families, print a few offsets and check that slices are clean. Don't assume the behavior carries over.
Text that changes length during normalization
Normalization can change the number of characters. An accented letter can be stored as one character or as a base letter plus a combining mark, and Unicode normalization may convert between the two. The tokenizer keeps track of this internally, so its offsets still point into the string you passed in. This is another reason to pass the raw context string to the tokenizer and slice that same string later. If you preprocess the context yourself after tokenizing, your offsets no longer match.
Truncated and overflowing inputs
When the context is longer than max_length, truncation cuts tokens from the end. The offsets of the remaining tokens are still correct, but characters after the cut have no token. A long-context chapter covers how overflowing windows solve this. For now, remember that a token index is only meaningful together with the specific encoding that produced it.
Multiple spaces and newlines
Whitespace between words is not a token for WordPiece. Two words separated by several spaces produce offsets with a gap between them. A slice from the first token's start to the last token's end includes that internal whitespace unchanged. This is usually what you want, because it returns the original text. It also means an answer can contain a newline if the source did.
A short checklist for working with offsets
- Load a fast tokenizer and pass
return_offsets_mapping=True. - Call
enc.sequence_ids()and only use offsets of tokens with id 1 when slicing the context. - Treat offsets as
[start, end)pairs into the original string. - Slice the original string and never decode tokens to get answer text.
- Remove
offset_mappingfrom the inputs before calling the model, because the model does not accept it. In the decoding example this is done withinputs.pop("offset_mapping").
Exercise
A colleague extracts answers with tokenizer.decode(input_ids[start_token:end_token + 1]) using bert-base-uncased. The context contains "Café Müller opened in 1998", and the model's span covers the first two words. What does the colleague's code return, and how would you fix it?
Show answer
The decode call returns the normalized text, something like "cafe muller", because the uncased tokenizer lowercases and strips accents. This does not match the original "Café Müller", so exact match against reference answers would fail. The fix is to request return_offsets_mapping=True, take offsets[start_token][0] as the start character and offsets[end_token][1] as the end character, and slice the original context string with context[start_char:end_char].
Exercise
You tokenize a question and context pair and find that the first context token has offsets (0, 3), and so does the first question token. Is this a bug? How do you tell the tokens apart?
Show answer
It is not a bug. Offsets are relative to the string each token came from, so the question and the context each start at character 0. Use enc.sequence_ids() to tell them apart: tokens with sequence id 0 belong to the question, and tokens with id 1 belong to the context. Only the context tokens should be used to slice the context string.