Skip to content
wordpiece.org

Building an offset-safe WordPiece highlighting UI

Use raw offsets for display spans, treat [UNK] and special tokens explicitly, and avoid reconstructing display text from token strings

Published 8 min read Verified

An offset-safe WordPiece highlighting UI does not rebuild display text from token strings. It keeps the original input string and uses tokenizer offsets to place highlights over the exact character ranges the model actually consumed. For google-bert/bert-base-uncased at revision 86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2, the fast tokenizer returns offset_mapping and special_tokens_mask when you ask for them. Those two fields are the difference between a UI that shows Héllo and one that shows hello, between a highlight on 🤗 and a stray [UNK] label, and between subword highlighting that matches the original word and one that prints ##ization as if it were real text.

The failure mode: tokens are model strings, not display strings

The tempting shortcut is to call tokenizer.convert_ids_to_tokens(ids) and join the results. That produces the model’s view: lowercased and accent-stripped for the uncased BERT tokenizer, with ## prefixes on WordPiece continuations, and with special tokens such as [CLS] and [SEP] inserted. If you render that joined string, you have replaced the user’s text with a normalized approximation. You cannot recover the original casing, spacing, punctuation, or accents from the token strings alone. You also cannot tell from the joined string which characters produced an unknown token or which subword fragments belong together. The fast tokenizer’s offset_mapping avoids that loss: each content token points back to a (start, end) slice in the original string. The UI’s job is to render the original text and apply highlights at those offsets.

Run the diagnostic before you build the overlay

The following self-contained Python 3 script uses AutoTokenizer.from_pretrained(..., revision=FULL_COMMIT, use_fast=True) for the pinned uncased model. It tokenizes a string with casing, accent, repeated spaces, a long word that may fragment, and an emoji that may become [UNK]. It prints the token id, token string, offset, and whether the token is special. It then builds UI-safe spans only from non-special tokens with non-empty, in-bounds offsets. The exact output depends on the pinned files and your environment; the script does not assume or hardcode any token count.

# transformers==4.56.2
from transformers import AutoTokenizer

MODEL = "google-bert/bert-base-uncased"
REVISION = "86b5e0934494bd15c9632b12f734a8a67f723594"

tokenizer = AutoTokenizer.from_pretrained(
    MODEL,
    revision=REVISION,
    use_fast=True,
)

text = "Héllo,   tokenization! 🤗"

enc = tokenizer(
    text,
    add_special_tokens=True,
    return_offsets_mapping=True,
    return_special_tokens_mask=True,
)

ids = enc["input_ids"]
tokens = tokenizer.convert_ids_to_tokens(ids)
offsets = enc["offset_mapping"]
special = enc["special_tokens_mask"]

print("tokenizer:", type(tokenizer).__name__)
print("vocab_size:", tokenizer.vocab_size)
print("input:", repr(text))
print()
print("idx  id      token           offset        kind")
for i, (tid, tok, off, sp) in enumerate(zip(ids, tokens, offsets, special)):
    kind = "SPECIAL" if sp else "CONTENT"
    print(f"{i:>3}  {tid:>6}  {tok!r:15} {str(off):>12}  {kind}")

# UI-safe spans: only non-special tokens with a non-empty, in-bounds offset.
ui_spans = []
for i, (tok, off, sp) in enumerate(zip(tokens, offsets, special)):
    if sp:
        continue
    if off is None:
        continue
    start, end = off
    if start == end:
        # Zero-length offsets are not useful for highlighting.
        continue
    assert 0 <= start < end <= len(text), (i, tok, off, text)
    ui_spans.append((i, tok, start, end, text[start:end]))

print()
print("ui_spans (model token -> original text slice):")
for i, tok, start, end, piece in ui_spans:
    print(f"{i:>3}  {tok!r:15} offsets=({start},{end})  original={piece!r}")

print()
print("offset bounds check passed for all non-special, non-empty spans")

Reading the diagnostic

In the table, SPECIAL rows are model-input tokens. They may have offsets such as (0,0) because they are inserted by the tokenizer rather than copied from the input. Do not draw those as highlights over the source text. If you want to show them, render them as separate labels. CONTENT rows are the tokens that correspond to input. These include [UNK], which is not a special token; it is a content token that represents an unrecognized piece. Its offset should point to the original characters that caused the unknown. Fragmentation is different: a known word such as tokenization may become multiple content tokens, often one base token and one or more ## continuation tokens. The offsets for those content tokens should cover the corresponding original substrings. The continuation token string may start with ##, but the UI should display text[start:end], not the token string. You will also see gaps: whitespace between tokens is not necessarily covered by any offset. That is normal. The UI must preserve the full original string and leave uncovered characters as ordinary text.

A safe UI algorithm

Tokenize the original string once with return_offsets_mapping=True and return_special_tokens_mask=True. Keep the original string as the rendering source. Iterate over input_ids, offset_mapping, and special_tokens_mask together. Skip special tokens. For each content token, if the offset is None or (0,0), skip highlighting for that token rather than guessing. Otherwise, take start, end = offset, validate 0 <= start < end <= len(text), and record a span with text[start:end]. Do not derive the span from convert_ids_to_tokens. Do not call decode to create the displayed text. When rendering, sort spans by start; for BERT WordPiece on ordinary text they should be non-overlapping and ordered, but your renderer should still guard against zero-length or out-of-order spans. If you want to group subwords into a single word highlight, use the offsets to check contiguity and the ## prefix only as a grouping hint. The label inside the highlight should still be the original slice. For [UNK], you can add a visual class such as unknown and show the original characters with a tooltip explaining that the model saw [UNK]. That keeps the UI truthful: the user sees their text, and the model’s tokenization is exposed through spans, classes, and metadata rather than through a rewritten string.

Limitations and the re-check procedure

Verified: 2026-10-05. This guide applies to google-bert/bert-base-uncased at revision 86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2. If you use google-bert/bert-base-multilingual-cased, verify against revision 3f076fdb1ab68d5b2880cb87a0886f315b8146f8; the pinned vocabulary sizes are 30,522 for the uncased model and 119,547 for the multilingual cased model. Those numbers describe the vocabulary files, not how many tokens a particular string will produce. A limitation of the offset approach is that offsets are an implementation detail of the fast tokenizer and the pinned tokenizer.json. They are not guaranteed to remain identical across arbitrary revisions or dependency versions. Special-token offsets may be (0,0) or None; whitespace and some control characters may not be covered by any token; and Unicode normalization can change which characters a token maps to. The diagnostic above checks a concrete string and asserts bounds, but it does not prove behavior for every possible input.

To re-check, rerun the diagnostic whenever the pinned revision or transformers changes. Compare the special-token mask, the offsets for [CLS] and [SEP], the offset for an unknown character such as an emoji, and the offsets for a long word that fragments. Also run the tokenizer with add_special_tokens=False if your UI manages special tokens separately, because the mask and offsets differ. If any of those observations change, revisit your skip rules, grouping logic, and rendering assumptions. The invariant that should not change is the one this article started with: use the original string and the returned offsets for display, and treat token strings as model metadata rather than display text.

Sources

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.

Check it yourself

Open the tokenizer

Every count in this guide comes from a vocabulary pinned by checksum. Paste the same text into the tool and you will get the same output.

Related guides