Skip to content
wordpiece.org

Mapping extractive-QA answer spans through BERT offsets

Build safe raw-answer-span to token-span logic for a pair encoding, checking sequence ids and special tokens

Published 8 min read Verified

Mapping an extractive-QA answer span to BERT token indices is a coordinate transformation between two coordinate systems: character offsets in the raw context and token indices in the model input. The raw span is [answer_start, answer_start + len(answer_text)). The model input for a pair is [CLS] question [SEP] context [SEP]. You need the contiguous range of context token indices that covers that character span, excluding question tokens and special tokens. Fast tokenizers expose both offset_mapping and sequence_ids, which are sufficient if you filter correctly.

The precise problem

When you call a fast tokenizer on a question-context pair with return_offsets_mapping=True, each model-input token gets an offset pair (start, end). For tokens from the question, offsets index the question string; for tokens from the context, offsets index the context string; for special tokens, offsets are (0, 0). sequence_ids() tells you which sequence a token belongs to: 0 for the question, 1 for the context, and None for special tokens such as [CLS] and [SEP]. token_type_ids is a model feature, not an alignment tool: it also uses 0 and 1, but it is shaped for BERT’s segment embeddings and can be ambiguous if you forget that special tokens receive a type id. Use sequence_ids() for alignment, and treat token_type_ids as a separate model input.

The naive approach — take the first and last token whose offsets overlap the answer — fails if you do not filter by sequence_id. A question token can have the same offset range as a context token, and special tokens always have (0, 0), which can overlap an answer that starts at character zero. The safe rule is: select token indices i such that sequence_ids()[i] == 1 and the half-open intervals [offset_start, offset_end) and [answer_start, answer_end) intersect. Because context tokens appear in order, the selected indices form a contiguous span; use first_index to last_index + 1 for Python slicing.

Diagnostic procedure

Pin the tokenizer before you measure anything. This article uses google-bert/bert-base-uncased at revision 86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2. The pinned WordPiece vocabulary has size 30,522 for this model. The following self-contained script checks the alignment assumptions directly. It prints each token, its sequence id, its offset, and whether it overlaps the answer span, then asserts that the selected span is non-empty, that every selected token belongs to sequence 1, and that every special token has offset (0, 0).

import transformers
from transformers import AutoTokenizer

assert transformers.__version__ == "4.56.2"

MODEL = "google-bert/bert-base-uncased"
REVISION = "86b5e0934494bd15c9632b12f734a8a67f723594"

tokenizer = AutoTokenizer.from_pretrained(
    MODEL,
    revision=REVISION,
    use_fast=True,
)
assert tokenizer.is_fast

question = "Who wrote the declaration?"
context = "The Declaration of Independence was written by Thomas Jefferson."
answer_text = "Thomas Jefferson"
answer_start = context.index(answer_text)
answer_end = answer_start + len(answer_text)

enc = tokenizer(
    question,
    context,
    add_special_tokens=True,
    return_offsets_mapping=True,
    return_token_type_ids=True,
)

input_ids = enc["input_ids"]
offsets = enc["offset_mapping"]
seq_ids = enc.sequence_ids()
tokens = tokenizer.convert_ids_to_tokens(input_ids)

print(f"model={MODEL} revision={REVISION}")
print(f"answer_span=({answer_start}, {answer_end}) text={answer_text!r}")
print("idx | token | seq_id | offset | overlaps_answer")
overlap_indices = []
for i, (tok, sid, off) in enumerate(zip(tokens, seq_ids, offsets)):
    overlaps = sid == 1 and off[0] < answer_end and off[1] > answer_start
    if overlaps:
        overlap_indices.append(i)
    print(f"{i:3d} | {tok!r:20s} | {str(sid):>6s} | {off} | {overlaps}")

assert overlap_indices, "no context tokens overlap the answer span"
token_span = (overlap_indices[0], overlap_indices[-1] + 1)

for i in overlap_indices:
    assert seq_ids[i] == 1, f"token {i} is not in the context sequence"

for i, sid in enumerate(seq_ids):
    if sid is None:
        assert offsets[i] == (0, 0), f"special token {i} has offset {offsets[i]}"

print(f"token_span={token_span}")
print("span_tokens=", tokens[token_span[0]:token_span[1]])
print("span_ids=", input_ids[token_span[0]:token_span[1]])

When you run this locally, the printed rows should show [CLS] and both [SEP] tokens with seq_id=None and offset (0, 0). The question tokens should show seq_id=0 and offsets into the question string. The context tokens should show seq_id=1 and offsets into the context string. The overlapping rows should be exactly the tokens covering Thomas Jefferson. If the assertion fails, do not patch around it; inspect the pinned revision and the tokenizer version first.

Interpreting the observations

Subword fragmentation and unknown tokens are different conditions, and both matter for span mapping. If Thomas Jefferson were split into thomas and jefferson or into pieces such as jeff and ##erson, the overlapping rule still selects every piece that intersects the answer span. That is what you want for a token-level span: the model’s prediction is over these pieces, not over raw words. If a word is not in the pinned vocabulary, the fast tokenizer emits [UNK] and gives that token an offset covering the whole unknown word. The [UNK] token is a model-input token, not a content token that decodes back to the original string. For alignment, it still belongs to the context sequence and still overlaps the answer span if the answer includes that word. Do not treat [UNK] as a fragmentation; it is a vocabulary fallback.

The token span may cover more characters than the answer. If the answer starts or ends inside a WordPiece, the selected subword token necessarily includes the rest of that piece. This is a limitation of token-level QA: the model’s output is a token span, and the decoded string can include extra characters at the boundaries. If your downstream evaluation compares decoded spans to character-level gold spans, you must use the tokenizer’s decode and accept that the decoded span may differ from answer_text when the answer is not token-aligned. For SQuAD-style data, answers are often word-aligned, but that is a dataset property, not a tokenizer guarantee.

Limitations and boundary conditions

The mapping above assumes no truncation and no overflowing windows. If you pass truncation=True, the context may be cut off, and an answer outside the retained window will produce an empty overlap set. If you use return_overflowing_tokens=True with stride, you must map the answer to the correct overflow window before computing the token span. Padding also adds tokens, but their sequence_id is None and their offset is (0, 0), so the seq_id == 1 filter excludes them. The same logic applies to google-bert/bert-base-multilingual-cased at revision 3f076fdb1ab68d5b2880cb87a0886f315b8146f8, whose pinned vocabulary size is 119,547; the sequence-id and offset semantics are the same, but the vocabulary and fragmentation behavior differ.

Verified: 2026-10-05; this diagnostic was checked against google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2. The limitation is that offset mapping describes the tokenizer’s view of the original strings; it does not enforce that an answer span is a single word or that decoded text equals the raw answer. When the pinned tokenizer.json or the Transformers version changes, re-run the script and check three things: sequence_ids() still returns 0, 1, and None in the expected positions; context-token offsets remain relative to the context string; and the overlapping set is non-empty for a known answer. Also confirm the vocabulary size and special-token ids against the new pinned file. If any of those checks change, update your span-mapping code before trusting old token spans.

Sources

Token counts in this article were produced by the tokenizers pinned on the sources page and are checked by the site's test suite. If a count ever stops matching the pinned vocabulary, the build fails.

Check it yourself

Open the tokenizer

Every count in this guide comes from a vocabulary pinned by checksum. Paste the same text into the tool and you will get the same output.

Related guides