Mapping BERT subwords back to input words
Use fast BatchEncoding.word_ids for a pre-split fixture and test label alignment across continuation pieces
Use the fast tokenizer’s BatchEncoding.word_ids() as the join between model-input positions and words in a pre-split input. The precise engineering failure is assigning one word-level label to several WordPiece continuation tokens while accidentally placing labels on inserted tokens. A procedure that appears correct for single-piece words can then shift every label after the first fragmented word.
Verified: 2026-10-05 for google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2 and use_fast=True. This verification refers to the supplied tokenizer artifact and versioned Transformers API/source, not to an execution of the following script. The script prints its local observations rather than relying on output values quoted in this article.
Define the alignment contract
Suppose each element of words has exactly one label:
words = [word_0, word_1, ...]
word_labels = [label_0, label_1, ...]
Calling the tokenizer with is_split_into_words=True associates each encoded content token with the index of its source element. After encoding, batch.word_ids(batch_index=0) returns one entry per model-input position. Its value is a source-word index for a token produced from an input word, or None for an inserted token such as [CLS] or [SEP].
A model-input token means any position in input_ids, including inserted special tokens and any batch padding. A content token means a position whose word_id is not None. A single content word can produce several content tokens because BERT’s WordPiece tokenizer fragments it. Consequently:
len(batch["input_ids"]) != len(words)
in general.
For the diagnostic policy used below, every content token inherits its source word’s label, while every no-word position receives the IGNORE_LABEL sentinel. This is an inspection marker, not a model loss configuration. Before training, replace it with the ignored-label value required by the selected loss. That policy is explicit rather than inherent in word_ids(). If only the first piece of a word should train the model, continuations must instead receive the configured ignored-label value; if the task is sequence classification, word-level labels should not be expanded into token labels at all.
Runnable diagnostic
Run this in a Python 3 environment with exactly transformers==4.56.2. It uses one short, unpadded, untruncated sequence so that the first diagnostic failure is easy to interpret.
import tokenizers
import transformers
from transformers import AutoTokenizer
MODEL_ID = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
EXPECTED_TRANSFORMERS = "4.56.2"
if transformers.__version__ != EXPECTED_TRANSFORMERS:
raise RuntimeError(
f"Expected transformers=={EXPECTED_TRANSFORMERS}, "
f"found {transformers.__version__}"
)
tokenizer = AutoTokenizer.from_pretrained(
MODEL_ID,
revision=FULL_COMMIT,
use_fast=True,
)
assert tokenizer.is_fast
words = ["unaffable", "Paris", "tokenization"]
word_labels = [0, 1, 0]
IGNORE_LABEL = None
assert len(words) == len(word_labels)
batch = tokenizer(
words,
is_split_into_words=True,
add_special_tokens=True,
padding=False,
truncation=False,
)
token_ids = batch["input_ids"]
pieces = tokenizer.convert_ids_to_tokens(token_ids)
word_ids = batch.word_ids(batch_index=0)
# Diagnostic policy: repeat each word label on all of its content pieces.
aligned_labels = [
IGNORE_LABEL if word_id is None else word_labels[word_id]
for word_id in word_ids
]
roles = []
for position, word_id in enumerate(word_ids):
if word_id is None:
roles.append("no-word")
elif position > 0 and word_ids[position - 1] == word_id:
roles.append("continuation")
else:
roles.append("first")
positions_by_word = {index: [] for index in range(len(words))}
for position, word_id in enumerate(word_ids):
if word_id is not None:
positions_by_word[word_id].append(position)
observed_words = {word_id for word_id in word_ids if word_id is not None}
assert len(token_ids) == len(pieces) == len(word_ids)
assert len(token_ids) == len(aligned_labels)
assert observed_words == set(range(len(words)))
assert tokenizer.pad_token_id not in token_ids
unknown_positions = [
position for position, piece in enumerate(pieces)
if piece == tokenizer.unk_token
]
assert all(word_ids[position] is not None for position in unknown_positions)
fragmented_words = {
index: positions
for index, positions in positions_by_word.items()
if len(positions) > 1
}
assert fragmented_words, "Fixture did not exercise continuation pieces"
for word_id, positions in positions_by_word.items():
assert positions == list(range(positions[0], positions[-1] + 1))
for position in positions[1:]:
assert pieces[position].startswith("##")
assert aligned_labels[position] == word_labels[word_id]
assert any(role == "continuation" for role in roles)
assert all(
aligned_labels[position] == IGNORE_LABEL
for position, word_id in enumerate(word_ids)
if word_id is None
)
print("model:", MODEL_ID)
print("revision:", FULL_COMMIT)
print("transformers:", transformers.__version__)
print("tokenizers backend:", tokenizers.__version__)
print(f"input words: {len(words)}")
print(f"model-input positions: {len(token_ids)}")
print(f"content positions: {sum(word_id is not None for word_id in word_ids)}")
print(f"no-word positions: {sum(word_id is None for word_id in word_ids)}")
print(f"fragmented source-word indices: {sorted(fragmented_words)}")
print(f"unknown-token positions: {unknown_positions}")
print()
print(f"{'pos':>3} {'piece':>18} {'word_id':>7} {'role':>12} {'label':>5} source")
for position, (piece, word_id, role, label) in enumerate(
zip(pieces, word_ids, roles, aligned_labels)
):
source = "-" if word_id is None else words[word_id]
print(
f"{position:>3} {piece!r:>18} {str(word_id):>7} "
f"{role:>12} {label:>5} {source}"
)
print("aligned labels:", aligned_labels)
Interpret the diagnostic
A successful run establishes several invariants for this fixture. Every source-word index appears in word_ids; positions belonging to one word are contiguous; and every token after that word’s first token is a ## continuation. The generated label list has exactly one entry per model-input position. Continuation pieces therefore receive the same label as the first piece, while no-word positions receive the IGNORE_LABEL sentinel.
The distinction between [UNK] and fragmentation matters. An [UNK] position has a real source-word ID: it is a content position representing an input unit that the pinned tokenizer could not represent with known WordPiece tokens. Several content positions carrying the same non-None word ID demonstrate fragmentation. They are different observations and require different interpretations.
None does not universally mean “special token.” In this fixture there is no padding, so the no-word positions are the inserted [CLS] and [SEP]. In a padded batch, padding positions can also have None word IDs. Use special_tokens_mask or another explicit padding signal when the distinction matters. Do not assign a label merely because word_ids() returns an integer: a duplicate word string is still identified by source index, which is why the mapping should use indices rather than a dictionary keyed by text.
Boundaries of the mapping
is_split_into_words=True makes the supplied list the alignment boundary. The API does not decide whether punctuation, contractions, hyphens, whitespace, or scripts such as Chinese should form one “word” or several. A poor pre-split can attach one label to only part of the intended entity. Preserve a separate map from each supplied word index to character spans in the original text if exact source offsets are required; do not assume pretokenized offsets are offsets into one reconstructed string.
The diagnostic also assumes no truncation. With truncation enabled, a word may be absent or only partly retained. Check that every required source word remains represented rather than accepting partial coverage silently. Increasing the limit, filtering the example, or changing the token-label policy may be more appropriate than filling missing labels.
Re-check procedure
When the tokenizer revision or dependency changes, update the relevant pin deliberately and run the diagnostic again before updating expected project behavior. Record both transformers.__version__ and the installed tokenizers backend version printed by the script. The latter is a dependency of the fast implementation and is not fixed merely by naming transformers==4.56.2.
For a model-file change, replace FULL_COMMIT, review the new tokenizer.json, and compare token IDs, pieces, word IDs, and aligned labels against the previous revision. Keep a reviewed snapshot of the downloaded tokenizer file in the project’s artifact controls. For a Transformers or backend change, repeat the run in a clean environment and investigate any difference as a possible API, serialization, normalization, vocabulary, or alignment change. Also rerun padded and truncated cases; this short fixture is a mapping regression test, not a throughput or model-quality benchmark.
The evidence boundary is the pinned tokenizer.json, the Transformers v4.56.2 tokenizer API, and the v4.56.2 BertTokenizerFast source.
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.