Sub topic 3
Subword Tokens and Character Offsets
Prerequisites
This chapter assumes basic Python, familiarity with tokenization, and a general idea of how transformer models process token IDs. You should also know that a string is a sequence of characters, while a token is a model-specific unit.
Extractive question answering needs both representations. The model predicts token positions, but datasets such as SQuAD usually describe answers with character positions in the original context.
Why subword tokens matter
A tokenizer converts text into tokens that a transformer can process. Words are not always kept as whole tokens. A tokenizer may split an uncommon word into several subword tokens:
| Text | Possible tokens |
|---|---|
| `unbreakable` | `un`, `##break`, `##able` |
| `playing` | `play`, `##ing` |
| `river` | `river` |
The exact representation depends on the tokenizer. The ## notation is common for WordPiece tokenizers, but other tokenizers use different markers.
Subword tokenization keeps the vocabulary manageable. The model can reuse pieces from many words instead of storing every complete word. However, splitting creates an alignment problem: one answer may cover several tokens, and token boundaries may not match character boundaries.
Character offsets and token offsets
A character offset is a pair (start, end) that identifies a slice of text. The start is included and the end is excluded, so the answer is:
answer = context[start:end]For example, in this context:
context = "The Amazon River is in South America."
answer = context[4:17]
print(answer) # Amazon RiverA fast Hugging Face tokenizer can return an offset mapping. Each mapping entry gives the character range represented by one token.
Special tokens such as [CLS] and [SEP] do not represent normal characters. Their offsets are commonly (0, 0). Do not use them as answer positions.
Inspecting a question and context pair
For question answering, encode the question and context together. Use sequence_ids() to tell which encoded tokens came from each input:
0identifies question tokens.1identifies context tokens.Noneidentifies special tokens.
from transformers import AutoTokenizer
name = "distilbert-base-cased-distilled-squad"
tokenizer = AutoTokenizer.from_pretrained(name)
question = "What is the capital?"
context = "The capital of France is Paris."
encoded = tokenizer(
question,
context,
return_offsets_mapping=True,
return_tensors="pt",
)
tokens = tokenizer.convert_ids_to_tokens(encoded["input_ids"][0])
offsets = encoded["offset_mapping"][0].tolist()
sequence_ids = encoded.sequence_ids(0)
for token, offset, sequence_id in zip(tokens, offsets, sequence_ids):
print(f"{token:>12} offset={offset} sequence={sequence_id}")The offset for a question token refers to the question string. The offset for a context token refers to the context string. Therefore, only offsets whose sequence ID is 1 should be used to extract an answer from context.
Aligning an answer with tokens
Suppose a dataset says that the answer begins at answer_start and has length len(answer_text). Compute the exclusive end position first:
answer_end = answer_start + len(answer_text)Find the first context token whose range contains the answer start, and the last context token whose range contains the answer end. The resulting token pair becomes the model's start and end label.
Be careful with whitespace and punctuation. The annotated answer must match the context exactly. If the dataset includes a leading space but the annotation starts after that space, a direct comparison can shift the labels by one character.
Exercise
Why should a question-answering decoder ignore tokens with sequence ID 0 or None?
Show answer
Sequence ID 0 marks question tokens and None marks special tokens. Neither token belongs to the context string from which the extractive answer must be copied.