When would you need the offset_mapping feature that HuggingFace fast tokenizers provide?
Same topic, related formats. Practice these next.
Same topic, related formats. Practice these next.
Describe what offset_mapping returns from a HuggingFace fast tokenizer. Give two concrete use cases where offset_mapping is required, and explain what problem arises if you try to implement the same functionality without it using a slow tokenizer.
offset_mapping returns per-token (start, end) character spans, letting you map model predictions back onto the original text for NER, extractive QA, and highlighting.
Imagine highlighting a sentence in a book with sticky tabs, where each tab covers a few letters. Later someone tells you 'the answer is on tab 3 through tab 5', but you need to point at the actual words on the page. You need a little map that says 'tab 3 starts at letter 12 and ends at letter 17'. That map is offset_mapping. The fast tokenizer hands it to you for free; without it you would have to count letters by hand and you would miscount whenever spaces, accents, or emoji get involved.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example. Click to expand.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example.
Everything important, quickly.
3 min: what offsets are + NER mapping + QA span extraction + why decoded-token reconstruction fails + the Unicode/byte trap + special-token (0,0) handling.
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("bert-base-cased") # fast by default
text = "Ada Lovelace wrote the first algorithm."
enc = tok(text, return_offsets_mapping=True)
# Suppose the NER model tagged tokens 1..2 as B-PER, I-PER.
span_tokens = [1, 2]
start = enc["offset_mapping"][span_tokens[0]][0]
end = enc["offset_mapping"][span_tokens[-1]][1]
print(text[start:end]) # 'Ada Lovelace'
# Special tokens like [CLS]/[SEP] carry (0, 0) -- mask before mapping.
for tok_id, (s, e) in zip(enc["input_ids"], enc["offset_mapping"]):
if (s, e) == (0, 0):
continue # skip specialsReal products, models, and research that use this idea.
What an interviewer would ask next. Try answering before peeking at the approach.
Red flags and common mistakes that signal junior thinking. Click to expand.
Trying to rebuild character spans by string-matching detokenized pieces, which silently breaks on the WordPiece ## prefix and any multi-byte Unicode character.
The night-before-the-interview bullets. Scan these on the way to the call.
Primary sources. Skim if you want the original framing.