Sub topic 10
Aligning word labels to subword tokens
This chapter assumes you know BIO tagging, can run a Hugging Face tokenizer, and have a rough idea of how a token classifier is trained. Word-level NER datasets give one label per word. A transformer sees subword tokens, so the two sequences have different lengths. Alignment is the step that reconciles them. Mistakes here rarely raise errors. They quietly lower your scores.
Why the lengths differ
NER datasets such as CoNLL-2003 store text as a list of words with one tag per word. A subword tokenizer such as BERT's WordPiece splits rare or long words into pieces and adds special tokens like [CLS] and [SEP].
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
words = ["Hugging", "Face", "is", "in", "Brooklyn", "."]
enc = tokenizer(words, is_split_into_words=True)
print(tokenizer.convert_ids_to_tokens(enc["input_ids"]))
print(enc.word_ids())The word count is 6, but the token list is longer, and it includes [CLS] and [SEP]. The word_ids() method returns one entry per token. Each entry is the index of the source word, or None for special tokens. For example, a word split into three pieces shows the same index three times in a row. This list is the key to alignment.
Two requirements follow:
- Every token position needs a label value, because the model emits one prediction per token and the loss compares them position by position.
- Positions that should not count must hold a value the loss ignores.
print(len(words), len(enc["input_ids"]))word_ids() is available only on fast tokenizers, which are backed by the Rust tokenizers library. AutoTokenizer returns a fast tokenizer by default when one exists. If you get a NotImplementedError about word_ids, you have a slow tokenizer.
Pass is_split_into_words=True when the input is already a list of words. Without it, the tokenizer treats the list as a batch of separate texts. With it, the tokenizer keeps your word boundaries, which is what makes the word-to-token mapping reliable.
The ignore index -100
PyTorch's CrossEntropyLoss skips any target equal to -100 by default (the ignore_index parameter). Transformers models use this convention in their token-classification heads. Setting a label to -100 removes that position from both the loss and the gradient.
You use -100 for:
- Special tokens such as
[CLS]and[SEP], which have no word. - Padding added later by a data collator.
- Optionally, continuation subwords.
Do not use 0 as a filler. In most label schemes 0 is O, so you would teach the model that special tokens are outside any entity.
First-subword labeling
The most common strategy labels only the first subword of each word and masks the rest. This is the function from the chapter plan.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
def tokenize_and_align_labels(example):
tokenized = tokenizer(example["tokens"], is_split_into_words=True, truncation=True)
labels = []
previous_word_id = None
for word_id in tokenized.word_ids():
if word_id is None:
labels.append(-100)
elif word_id != previous_word_id:
labels.append(example["ner_tags"][word_id])
else:
labels.append(-100)
previous_word_id = word_id
tokenized["labels"] = labels
return tokenizedThe loop tracks previous_word_id. A token is the first subword of its word when its word_id differs from the previous token's. Here is a worked example for the word "Brooklyn" split into Brook, ##lyn:
| Token | word_id | Label written |
|---|---|---|
| `[CLS]` | None | -100 |
| `Hugging` | 0 | B-ORG id |
| `Face` | 1 | I-ORG id |
| `Brook` | 4 | B-LOC id |
| `##lyn` | 4 | -100 |
| `[SEP]` | None | -100 |
The label values in ner_tags are integers, not strings. Check how your dataset encodes them before you write the function. With the datasets library, dataset.features["ner_tags"].feature.names gives the mapping.
You can test the function without downloading a dataset:
example = {
"tokens": ["Hugging", "Face", "is", "in", "Brooklyn", "."],
"ner_tags": [3, 4, 0, 0, 5, 0],
}
out = tokenize_and_align_labels(example)
for token, label in zip(tokenizer.convert_ids_to_tokens(out["input_ids"]), out["labels"]):
print(f"{token:12} {label}")The integer tags here are arbitrary stand-ins. Check that each non--100 label appears exactly once per word, and that no label is attached to a special token.
Alternative: label every subword
You can instead give every subword a label. Continuation pieces of a B-X word receive I-X, and continuation pieces of an I-X or O word keep the same label.
def align_all_subwords(word_labels, word_ids, label_names):
aligned = []
previous = None
for word_id in word_ids:
if word_id is None:
aligned.append(-100)
elif word_id != previous:
aligned.append(word_labels[word_id])
else:
name = label_names[word_labels[word_id]]
if name.startswith("B-"):
name = "I-" + name[2:]
aligned.append(label_names.index(name))
previous = word_id
return aligned
label_names = ["O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
print(align_all_subwords([0, 5], [None, 0, 1, 1, None], label_names))This prints [-100, 0, 5, 6, -100]. The second word is B-LOC (5), so its continuation piece becomes I-LOC (6).
| Strategy | Training signal | Inference handling | Main risk |
|---|---|---|---|
| First subword only | One label per word | Read predictions at first subwords | Wasted signal on long words |
| All subwords | One label per token | Aggregate predictions per word | Inconsistent tags inside one word |
First-subword labeling is simpler and matches the usual evaluation, which is per word. Labeling all subwords gives more training signal. It also lets the model learn that I- follows B- inside a word. The cost is that you must decide how to combine disagreeing predictions at inference time.
Reading predictions back
Alignment applies at inference too. If you trained with first-subword labels, you take each word's prediction from its first token. Any other token's output is meaningless, because the model never received a target for it.
def predictions_to_word_tags(pred_ids, word_ids, id2label):
tags = {}
for pred, word_id in zip(pred_ids, word_ids):
if word_id is not None and word_id not in tags:
tags[word_id] = id2label[pred]
return [tags[i] for i in sorted(tags)]
id2label = {0: "O", 1: "B-ORG", 2: "I-ORG", 3: "B-LOC"}
print(predictions_to_word_tags([0, 1, 2, 0, 3, 3, 0], [None, 0, 1, 2, 3, 3, None], id2label))This prints ['B-ORG', 'I-ORG', 'O', 'B-LOC']. The extra 3 on the second piece of word 3 is skipped because that word already has a tag.
The aggregation_strategy option in the Hugging Face pipeline does this work for you at the entity level. The pipeline's "simple" strategy merges consecutive tokens that belong to the same entity group. The "first" strategy takes the first subword's label for each word. Use "first" when you trained with first-subword labels.
Diagram of the alignment flow
Edge cases and gotchas
Truncation
Long inputs are cut at the model's maximum length when truncation=True. Words past the cut have no tokens, so they get no labels. That is correct, because word_ids() only lists words that survived. Do not index ner_tags by token position. Always index it by word_id.
When documents are long, truncating loses entities. Split the text into windows before tokenizing, or use return_overflowing_tokens=True with a stride, and be careful to align labels for each window.
Words that produce no tokens
Some tokenizers drop characters such as stray control characters or certain whitespace. A word made only of such characters can yield zero tokens. Alignment by word_ids() handles this without error, because the word never appears. Your predictions then have fewer words than your gold labels, so evaluation code that zips them together will misalign. Compare by word index, not by position in a list.
Padding
Do not pad in the mapping function. Let DataCollatorForTokenClassification pad each batch dynamically. It pads labels with -100, so padding stays out of the loss.
from transformers import DataCollatorForTokenClassification
data_collator = DataCollatorForTokenClassification(tokenizer)If you pad labels yourself with 0, padding becomes O supervision and can bias the model toward predicting O.
Tokenizers that need a space prefix
RoBERTa-style byte-level BPE tokenizers treat a word differently depending on whether a space precedes it. With is_split_into_words=True, you must also pass add_prefix_space=True when loading the tokenizer. Otherwise, the tokenizer raises an error for pretokenized input.
roberta_tok = AutoTokenizer.from_pretrained("roberta-base", add_prefix_space=True)Splitting problems from custom tokenization
If your words come from spaCy and your model uses its own tokenizer, the word boundaries are spaCy's. That is fine, as long as you feed the same word list to the model tokenizer and the label array. Do not rejoin words with spaces and retokenize, since the boundaries may then change and your labels will no longer line up.
Dataset with character offsets
Some datasets store entities as character spans rather than per-word tags. Convert them to per-word BIO tags first, or use return_offsets_mapping=True and assign a label to each token whose offsets fall inside an entity span. Either route requires the tokenizer's offsets to match the original string exactly, so keep the original text unchanged.
Verifying alignment
Always inspect a few examples before training. Three quick checks catch most bugs:
- The count of non-
-100labels equals the number of words, when truncation does not occur and you use first-subword labeling. - No special token carries a real label.
- Decoding the tokens at labeled positions gives back the first piece of each word.
def check_alignment(example):
out = tokenize_and_align_labels(example)
n_labeled = sum(1 for label in out["labels"] if label != -100)
return n_labeled == len(example["tokens"]), len(out["labels"]) == len(out["input_ids"])
print(check_alignment(example))The expected output is (True, True). Run the function over a sample of the training set and assert both values hold. Truncated examples will legitimately fail the first check, so filter them out or count words by word_ids().
Applying the function to a dataset
Once the function is correct, map it over the whole dataset in batches. When batched=True, the function receives lists, so a batched version loops over each example and uses batch.word_ids(batch_index=i).
def tokenize_and_align_batch(batch):
tokenized = tokenizer(batch["tokens"], is_split_into_words=True, truncation=True)
all_labels = []
for i, tags in enumerate(batch["ner_tags"]):
previous = None
labels = []
for word_id in tokenized.word_ids(batch_index=i):
if word_id is None:
labels.append(-100)
elif word_id != previous:
labels.append(tags[word_id])
else:
labels.append(-100)
previous = word_id
all_labels.append(labels)
tokenized["labels"] = all_labels
return tokenized
# dataset = dataset.map(tokenize_and_align_batch, batched=True)The single-example function from earlier works with map when batched=False, but it is slower. The batched version calls the Rust tokenizer once per batch.
Summary of decisions
- Use a fast tokenizer and
is_split_into_words=True. - Map labels by
word_id, never by token position. - Use
-100for special tokens, padding and ignored subwords. - Pick first-subword or all-subword labeling, and use the same choice when reading predictions.
- Let the data collator pad, and inspect several examples before training.
Exercise
A word "Zurich-based" is tokenized into Zur, ##ich, -, based with word_id 2 for all four tokens, and its gold tag is B-ORG (id 3). Using the first-subword strategy, what labels do the four tokens receive? What would they receive if you labeled all subwords instead, and why might the second choice cause trouble at inference?
Show answer
With first-subword labeling the labels are [3, -100, -100, -100]. With all-subword labeling they are [3, I-ORG id, I-ORG id, I-ORG id], because continuation pieces of a B- word become I- of the same type. At inference the model may predict different tags on the pieces of one word, for example B-ORG on Zur and O on based, so you must choose a rule such as taking the first piece or using the pipeline's aggregation strategy to get one tag per word.
Exercise
Your training loss falls normally, but entity F1 is near zero for entities in long sentences. You pad labels with 0 inside your mapping function and index ner_tags with the token position. Name two bugs and the fix for each.
Show answer
First, indexing ner_tags by token position is wrong once any word splits into multiple subwords, because positions drift away from word indices. Index by word_id from word_ids(). Second, padding labels with 0 trains the model to predict O on padding, since 0 is usually the O tag. Pad with -100, for example by using DataCollatorForTokenClassification, so padding is ignored by the loss.