Sub topic 7
Subword tokenization and its effect on NER
Transformer NER models do not read words. They read pieces of words called subword tokens, and every prediction they make is attached to one of those pieces. This chapter explains how the pieces are made and what that does to entity spans, offsets, sequence length and casing. The next chapters build on it to run and fine-tune models.
This chapter assumes you know basic Python, what a token is, and what BIO tags are (see the chapter on entity spans and BIO tags). You should also have transformers installed. Models and tokenizers download on first use.
Why subwords exist
A word-level vocabulary has two problems. It gets very large, and it fails on words it has never seen, such as new names, typos and product codes. A character-level vocabulary never fails, but sequences become very long.
Subword tokenization sits between the two. The tokenizer keeps whole words that are common and splits rare words into smaller known pieces. A name like Reykjavik may come out as several pieces, while the stays whole. Any string can be represented, because the pieces fall back to single characters or bytes if needed.
Three algorithms are common:
| Algorithm | Typical models | How pieces are marked |
|---|---|---|
| WordPiece | BERT, DistilBERT, ELECTRA | Continuation pieces start with `##` |
| Byte-level BPE | RoBERTa, GPT-2 | A leading space is part of the piece, shown as `Ġ` |
| SentencePiece (Unigram or BPE) | XLM-R, T5, DeBERTa-v3 | A word-start marker, shown as `▁` |
The marker conventions differ, but the NER consequences are the same for all three.
Looking at the pieces
Pass a list of words with is_split_into_words=True and ask the encoding which word each token came from. The word_ids() method returns one entry per token. Special tokens such as [CLS] and [SEP] get None.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
words = ["Satya", "Nadella", "visited", "Reykjavik", "."]
enc = tokenizer(words, is_split_into_words=True)
for token, word_id in zip(enc.tokens(), enc.word_ids()):
print(f"{token:12} {word_id}")The output starts with [CLS] and ends with [SEP], both with word id None. In between, a rare word like Reykjavik is usually split into several tokens that all share the same word id. The exact split depends on the model's vocabulary, so run it yourself instead of relying on any example.
word_ids() and tokens() only work with fast tokenizers, the Rust-backed implementations that AutoTokenizer loads by default. A slow tokenizer raises an error when you call them.
From text to tokens to labels
The path from raw text to a prediction on a span has several steps. Each one can shift or lose information.
The model produces one label for each token. You almost never want those labels. You want character spans in the original string, so you keep word_ids or offsets from the tokenizer to go back.
Offsets: the reliable way back to the text
Rather than rebuilding text from ## pieces, ask for character offsets. Each token gets a (start, end) pair that indexes into the original string.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
text = "Satya Nadella visited Reykjavik."
enc = tokenizer(text, return_offsets_mapping=True)
for token, (start, end) in zip(enc.tokens(), enc["offset_mapping"]):
print(f"{token:12} {start:3} {end:3} {text[start:end]!r}")Special tokens have the offset (0, 0), so they slice to an empty string. Real tokens slice to the exact characters they cover. This is how the Hugging Face pipeline reports start and end for each entity, and how you can convert predictions into spaCy-style character spans.
Do not reconstruct an entity by joining token strings and removing ##. That approach breaks on whitespace, punctuation spacing, accents and lowercasing, because the tokenizer may normalize text. Offsets always point at what the user actually wrote.
How subwords affect NER
One word becomes several predictions
NER labels belong to words or spans, but the model predicts per token. If Reykjavik becomes four tokens, the model emits four labels for it. Something must decide what the word's label is. There are two common conventions:
- Use the first subword's prediction for the whole word. This is the standard approach in training and evaluation.
- Predict every subword and merge afterward. This is what aggregation does at inference time.
Training-side handling is covered in the chapter on aligning word labels to subword tokens. Inference-side merging is covered in the chapter on the Hugging Face pipeline.
Inconsistent labels inside a word
When every piece is predicted independently, the pieces of one word can disagree. For example, the first piece might get B-LOC and the second O. The result is a fragment of the word marked as an entity. Merging strategies exist to repair this, and they make different trade-offs:
- Taking the first piece's label is simple, but it trusts the least informed token.
- Averaging scores or taking the highest-scoring label uses all pieces.
- Filtering out
Opieces can extend an entity past where the word ends.
Entity boundaries and punctuation
A model tokenizer may split a string differently from spaCy. Take U.K. or Dr. Smith's. spaCy applies its own exception rules, so its tokens will not match the pieces a transformer sees. Entity spans must therefore be exchanged in character offsets, not token indexes. A span (24, 30) means the same thing to both libraries, while "token 5" does not.
Longer sequences
Subword splitting increases length. A sentence of 20 words may become 30 or more tokens. Names, rare domain terms, and text in languages that the vocabulary covers poorly are split the most. Counting pieces per word shows how heavily your data is fragmented. This ratio is sometimes called fertility.
from collections import Counter
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
words = ["Dr.", "Oluwaseun", "Adebayo", "joined", "Novartis", "in", "Basel", "."]
enc = tokenizer(words, is_split_into_words=True)
counts = Counter(i for i in enc.word_ids() if i is not None)
for i, word in enumerate(words):
print(f"{word:10} {counts[i]} piece(s)")
print("fertility:", sum(counts.values()) / len(words))A fertility close to 1.0 means most words stay whole. Values well above 1.5 on your own data suggest the vocabulary does not suit your domain. Rare identifiers, chemical names and non-English names are typical causes.
Truncation silently drops entities
Transformers have a maximum input length, often 512 tokens including special tokens. With truncation=True, everything after that limit is discarded without an error. Any entity in the discarded part is never predicted, and during training its labels never count.
A sliding window avoids the loss. Windows overlap by stride tokens, so entities near a boundary appear whole in at least one window.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
sentence = "The report was written in Paris by Ada Lovelace and reviewed in London ."
words = sentence.split() * 40
enc = tokenizer(
words,
is_split_into_words=True,
truncation=True,
max_length=64,
stride=16,
return_overflowing_tokens=True,
)
print("windows:", len(enc["input_ids"]))
for i in range(len(enc["input_ids"])):
ids = [w for w in enc.word_ids(i) if w is not None]
print(i, "tokens:", len(enc["input_ids"][i]), "words:", min(ids), "to", max(ids))Word ids in each window refer to the original word list, so you can map predictions back. Overlapping windows produce duplicate predictions for the same words. You must deduplicate them, for example by preferring the window where the word is farthest from an edge.
Casing and normalization
bert-base-cased keeps capitalization, and bert-base-uncased lowercases the input. Capitalization is one of the strongest signals for names in English, so uncased models usually do worse on NER. Prefer a cased model unless your text is all lowercase or all uppercase.
Differences between tokenizer families
SentencePiece models treat a leading space as part of the first piece. Byte-level BPE models such as RoBERTa also include the space. This matters in two ways:
- With RoBERTa,
is_split_into_words=Truerequires the tokenizer to be created withadd_prefix_space=True. Without it, the library raises an error. - Offsets from byte-level models may include the leading space, depending on the tokenizer settings. Check with the offset printout above before you trust spans.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("roberta-base", add_prefix_space=True)
enc = tokenizer(["Satya", "Nadella", "visited", "Reykjavik"], is_split_into_words=True)
print(list(zip(enc.tokens(), enc.word_ids())))Common mistakes
- Treating token indexes as word indexes. The 5th token is not the 5th word.
- Rebuilding entity text from pieces instead of slicing the original string with offsets.
- Forgetting that
[CLS]and[SEP]take positions, so labels must be shifted or masked for them. - Using a slow tokenizer and then calling
word_ids(). - Truncating long documents without a stride and never noticing the loss.
- Comparing spaCy and transformer outputs by token index instead of character span.
Exercise
A model predicts B-LOC for the first piece of the word "Reykjavik" and O for its three later pieces. The pipeline uses the "first subword" rule to label whole words. What entity label does the word get, and what would a method that keeps only the non-O pieces report as the entity's character span?
Show answer
With the first-subword rule the word gets B-LOC, so the whole of "Reykjavik" is one location entity. A method that keeps only non-O pieces sees just the first piece, so it reports a span covering only that piece's characters, a fragment of the word such as "Rey". This is why merging by word, using word_ids or offsets, is needed to get complete spans.
Exercise
You tokenize a 1,200-token document with truncation=True and max_length=512 and no stride. Your gold data has entities at tokens 700 to 703. What happens to them, and which two tokenizer arguments change this?
Show answer
They are cut off and never seen by the model, with no error raised. For training, their labels are lost. For inference, they are never predicted. Adding returnoverflowingtokens=True and a stride value produces overlapping windows that cover the whole document, and the predictions from the windows must then be merged and deduplicated.