Aligning NER labels to BERT WordPiece pieces
Use word_ids to assign labels to the first piece and ignore later pieces; document alternate labeling choices
Aligning NER labels to BERT WordPiece pieces is a preprocessing contract, not a post-processing trick. Your gold data labels words: Barack is B-PER, Obama is I-PER, Hawaii is B-LOC. BERT reads WordPiece pieces. It may split one word into several model-input tokens, replace a whole word with [UNK], and always add special tokens such as [CLS] and [SEP]. The token-classification head returns one prediction per model-input token, so your training labels must have the same length as input_ids. The practical rule for the pinned English uncased BERT tokenizer is: use word_ids() to find the first piece of each original word, assign that word’s NER label to the first piece, assign IGNORE_INDEX to later pieces, and assign IGNORE_INDEX to special tokens.
Verified: 2026-10-05. The tokenizer claims in this article are scoped to google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2. If you use google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8, the same word_ids() contract applies, but fragmentation and unknown-token behavior must be re-checked; do not transfer counts or piece boundaries between models.
The exact problem: three token counts, one label vector
For NER, you have three related but distinct quantities. The first is your original word count: the number of items in words and ner_tags. The second is the number of content tokens: the non-special model-input tokens that represent those words, after WordPiece splitting and unknown replacement. The third is the number of model-input tokens: len(input_ids), which includes content tokens plus special tokens and any padding. Your labels vector must match this third count. Confusing content tokens with model-input tokens is a common source of shape errors.
word_ids() returns one entry per model-input token. For a special token, it returns None. For a content token, it returns the index of the original word. If one word becomes several pieces, the same word index repeats. That repetition is fragmentation. If a word becomes [UNK], the token is still a content token with that word’s index; it is not a continuation piece. In the pinned BERT WordPiece path, an unknown word is represented by a single [UNK] token for the whole word, not by a sequence of partial unknown pieces. This distinction matters when you build labels and when you inspect error patterns.
Diagnostic procedure with word_ids
The following self-contained script uses the pinned revision and prints the alignment table. It asserts structural invariants rather than particular token texts. Run it locally; the exact tokens you see depend on the pinned tokenizer and your input.
# Requires transformers==4.56.2
from collections import Counter
from transformers import AutoTokenizer
MODEL = "google-bert/bert-base-uncased"
REVISION = "86b5e0934494bd15c9632b12f734a8a67f723594"
tokenizer = AutoTokenizer.from_pretrained(
MODEL,
revision=REVISION,
use_fast=True,
)
words = ["Barack", "Obama", "was", "tokenization", "in", "Hawaii", "🤖"]
ner_tags = ["B-PER", "I-PER", "O", "O", "O", "B-LOC", "O"]
enc = tokenizer(
words,
is_split_into_words=True,
return_offsets_mapping=True,
return_special_tokens_mask=True,
)
input_ids = enc["input_ids"]
word_ids = enc.word_ids()
special = enc["special_tokens_mask"]
offsets = enc["offset_mapping"]
IGNORE_INDEX = None # diagnostic marker; use your loss's ignore index in training
aligned = []
seen = set()
for i, wid in enumerate(word_ids):
if wid is None or special[i] == 1:
aligned.append(IGNORE_INDEX)
elif wid not in seen:
aligned.append(ner_tags[wid])
seen.add(wid)
else:
aligned.append(IGNORE_INDEX)
tokens = tokenizer.convert_ids_to_tokens(input_ids)
print("tokens:", tokens)
print("word_ids:", word_ids)
print("special_tokens_mask:", special)
print("offset_mapping:", offsets)
print("gold word labels:", ner_tags)
print("aligned token labels:", aligned)
first_piece_labels = {}
for wid, label in zip(word_ids, aligned):
if wid is not None and label != IGNORE_INDEX:
assert wid not in first_piece_labels, (wid, first_piece_labels)
first_piece_labels[wid] = label
assert len(aligned) == len(input_ids), (len(aligned), len(input_ids))
assert len(first_piece_labels) == len(words), (len(first_piece_labels), len(words))
assert set(first_piece_labels) == set(range(len(words)))
per_word = Counter(wid for wid in word_ids if wid is not None)
unk_id = tokenizer.unk_token_id
print("model-input tokens:", len(input_ids))
print("content/non-special tokens:", sum(wid is not None for wid in word_ids))
print("pieces per original word:", {i: per_word.get(i, 0) for i in range(len(words))})
print("unknown-token positions:", [i for i, tid in enumerate(input_ids) if tid == unk_id])
print("first-piece labels:", first_piece_labels)
The printed table is the diagnosis. tokens, word_ids, and aligned token labels should line up by position. Special positions should show word_id=None and label IGNORE_INDEX. A fragmented word should show the same word index on consecutive positions, with the entity label only on the first of those positions. An unknown replacement should appear as one [UNK] position with a real word index and one label, not as a run of continuation pieces.
Interpreting the observations
If pieces per original word shows a value greater than 1, that word fragmented. The first piece received the word label; the continuation pieces received IGNORE_INDEX. That is the intended first-piece contract. If a value is 1 but the corresponding token is [UNK], the word was replaced by an unknown token. That is not fragmentation. The whole word is represented by one model-input token, and under the first-piece rule it receives the word’s NER label. If you prefer not to train on unknown replacements, you can override that position to IGNORE_INDEX, but document the choice because it changes the supervision.
model-input tokens is larger than content/non-special tokens because of [CLS], [SEP], and any padding. The script counts these rather than assuming a number. The offset_mapping is included as a cross-check; depending on how you call the tokenizer, offsets may be relative to the joined input or to individual pre-split words, so verify the frame before using offsets to project character-span labels.
Alternate labeling choices
The first-piece rule is not the only valid policy. You can assign the same entity label to every piece of a word. That increases the number of positive labels and changes class balance; post-processing must avoid counting the same entity several times. You can assign B- to the first piece and I- to later pieces for words that split, but then truncation can leave an I- tag without its B- context unless you repair it. You can label only the last piece; this is less common and complicates word-level reconstruction. You can also mask [UNK] positions to IGNORE_INDEX instead of labeling them. Each choice is defensible, but the training labels, loss mask, and decoding logic must agree. The first-piece approach is simple because every original word contributes exactly one non-ignore label to the loss.
Special tokens should normally be IGNORE_INDEX for token classification. Assigning O to [CLS] and [SEP] teaches the model to predict O at positions that are not words and can distort metrics. Padding positions must also be IGNORE_INDEX. If your framework requires integer labels for all positions, use an ignore index that the loss function respects.
Limitations and re-check procedure
This alignment depends on is_split_into_words=True or on a pre-tokenization that matches your gold word boundaries. If you tokenize raw text and project span labels through character offsets, word_ids() may not correspond to your NER words. The diagnostic also assumes the fast tokenizer. With use_fast=False, word_ids() is not available in the same form. The pinned revision and transformers version matter: WordPiece vocabularies and normalization behavior can change between revisions. The English uncased model and the multilingual cased model are not interchangeable; the pinned English uncased tokenizer vocabulary has 30,522 entries, while the pinned multilingual cased vocabulary has 119,547. Those are vocabulary sizes, not token counts for any sentence.
When the pinned tokenizer.json or the Transformers dependency changes, re-run the script with the new revision and a probe set that includes a multi-piece word, punctuation, an unknown-prone token, and the special-token boundaries. Check four invariants: len(aligned) == len(input_ids); every original word has exactly one non-ignore label; continuation pieces are IGNORE_INDEX; special and padding positions are IGNORE_INDEX. If any invariant fails, inspect tokens, word_ids, and aligned token labels together before training. If you switch models, change both the model id and the full commit revision, then run the same check. Do not copy fragmentation patterns or counts from one checkpoint to another.
Verified: 2026-10-05. This note’s tokenizer-specific claims are limited to the pinned revisions and transformers==4.56.2; the code above is the local check that keeps your NER label alignment honest when those pins move.
Sources
- google-bert/bert-base-uncased tokenizer.json at 86b5e093
Pinned WordPiece vocabulary and normalization settings for the English uncased model.
- Hugging Face Transformers v4.56.2 tokenizer API
Versioned reference for encoding options, output fields, and fast-tokenizer alignment methods.
- Transformers v4.56.2 BertTokenizerFast source
Versioned implementation of the BERT fast-tokenizer wrapper.
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.