Sub topic 10
Aligning Word Labels to Subword Tokens
This chapter assumes that you know basic Python, tokenization, and the idea of training a classifier. You should also understand BIO tags: B-ORG begins an organization entity, I-ORG continues it, and O means that a token is outside an entity.
Why alignment is necessary
A named entity recognition dataset often labels whole words:
| Word | Label |
|---|---|
| Microsoft | B-ORG |
| announced | O |
| Azure | B-PRODUCT |
Transformer tokenizers may split one word into several subword tokens. For example, an uncommon word might become ["micro", "##soft"]. The model predicts one label per subword token, but the dataset provides one label per original word.
You must therefore align each word label with the tokens created from that word. Incorrect alignment can train the model on the wrong targets.
Special tokens also need handling. Tokens such as [CLS] and [SEP] do not represent words, so they must not contribute to the loss. In Hugging Face training code, the label -100 tells the loss function to ignore a token.
Mapping tokens back to words
When you tokenize a pre-split sentence, pass is_split_into_words=True. The resulting encoding provides word_ids(). Each token receives the index of its original word. Special tokens receive None.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
example = {
"tokens": ["Microsoft", "announced", "Azure"],
"ner_tags": [1, 0, 2],
}
tokenized = tokenizer(
example["tokens"],
is_split_into_words=True,
truncation=True,
)
print(tokenized.tokens())
print(tokenized.word_ids())A typical output might include tokens such as [CLS], Microsoft, announced, Azure, and [SEP]. The word IDs identify which original word each token came from.
Choosing labels for split words
A common alignment policy assigns the original word's label to its first subword and assigns -100 to later subwords. This avoids counting one long word multiple times during training.
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 tokenizedThis policy works well with BIO data because the first subword receives the word's B- or I- label. Later subwords are ignored during loss calculation.
Another policy copies the label to every subword. That gives the model more supervised positions, but it can overweight words that split into many pieces. If you use this policy, do not accidentally turn an I-ORG label into another B-ORG label.
Truncation and dataset checks
Truncation can remove words from the end of a sentence. The word_ids() list still describes only the tokens that remain, so the alignment loop should iterate over tokenized word IDs rather than over the original words.
Check these conditions before training:
- Every non-
Noneword ID is a valid index in the original label list. - The labels and token sequence have the same length.
- Special tokens have label
-100. - BIO transitions remain valid after preprocessing.
- Examples that are too long are handled deliberately, such as by splitting them into windows.
Exercise
Exercise
Why should a later subword usually receive -100 instead of the original word's BIO label?
Show answer
It prevents one word from contributing multiple times to the loss and keeps the word-level annotation represented by its first subword.