Skip to content
wordpiece.org

Using token_to_chars for precise BERT highlighting

Compare token_to_chars with offset_mapping and handle special-token None spans when building a highlighter

Published 8 min read Verified

Use token_to_chars when a highlight must remain anchored to the original text rather than being reconstructed from token labels. The engineering problem is that one source string becomes a mixture of content tokens, WordPiece fragments, unknown tokens, and added special tokens. Only some of those tokens represent source characters. A fast BERT encoding exposes both compact spans through offset_mapping and per-character positions through token_to_chars, but they express special or unknown content differently.

This guide is pinned to google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8 with transformers==4.56.2. Do not transfer token observations from another checkpoint, tokenizer revision, normalization configuration, or library release.

Comparing the two alignment views

offset_mapping returns one half-open (start, end) tuple per model-input token. It is compact and usually sufficient when the highlighter needs the complete source span of each content token.

token_to_chars(token_index) returns the tokenizer encoding’s individual source-character positions for that same token. A content token can therefore be rendered from its aligned positions and checked against its offset. Added tokens such as [CLS] and [SEP] have no source characters: their position list contains None. That does not mean the text contains an unknown word; it means the token was added by the tokenizer.

Use special_tokens_mask to distinguish added special tokens from content. Do not classify them by looking for a zero-width offset, and do not inspect the literal source text for strings such as [CLS]: text with those characters can still be encoded as ordinary content. In a padded production call, also exclude positions whose attention-mask value is zero.

An unknown token is different. If its ID equals tokenizer.unk_token_id, the model received source material that its WordPiece procedure could not represent as known vocabulary pieces. Nevertheless, the fast alignment can retain the source characters covered by [UNK]. The highlighter must keep the original string because the unknown token’s ID or displayed label cannot reconstruct that text exactly.

Fragmentation is different again. It means several known tokens cover one source word or expression. A BERT continuation piece commonly starts with ##, but that marker is tokenizer notation, not literal source text, and the first piece of a fragmented word has no such marker. A continuation count is therefore evidence of fragmentation, not a complete count of fragments.

Runnable alignment diagnostic

The following Python 3 program retrieves the exact tokenizer revision, checks the installed Transformers version, prints both alignment representations, and asserts their agreement for content tokens in the selected diagnostic. It does not contain a precomputed transcript. Run it with network access or a populated Hugging Face cache.

# Install first: python -m pip install transformers==4.56.2
from html import escape

import tokenizers
import transformers
from transformers import AutoTokenizer

MODEL_ID = "google-bert/bert-base-multilingual-cased"
FULL_COMMIT = "3f076fdb1ab68d5b2880cb87a0886f315b8146f8"
TRANSFORMERS_VERSION = "4.56.2"

assert transformers.__version__ == TRANSFORMERS_VERSION

tokenizer = AutoTokenizer.from_pretrained(
    MODEL_ID,
    revision=FULL_COMMIT,
    use_fast=True,
)
assert tokenizer.is_fast
assert tokenizer.__class__.__name__ == "BertTokenizerFast"
assert tokenizer.init_kwargs.get("_commit_hash") == FULL_COMMIT

text = "Ada's café tokenizer 🧪 is wonderfully fragmentary."
encoded = tokenizer(
    text,
    add_special_tokens=True,
    padding=False,
    truncation=False,
    return_offsets_mapping=True,
    return_special_tokens_mask=True,
)

input_ids = encoded["input_ids"]
tokens = tokenizer.convert_ids_to_tokens(input_ids)
offsets = encoded["offset_mapping"]
special_mask = encoded["special_tokens_mask"]
fast_encoding = encoded.encodings[0]

assert len(input_ids) == len(tokens) == len(offsets) == len(special_mask)

rows = []
content_intervals = []

for index, (token_id, token, offset, special) in enumerate(
    zip(input_ids, tokens, offsets, special_mask)
):
    chars = fast_encoding.token_to_chars(index)

    if special:
        assert chars and all(position is None for position in chars)
        kind = "special"
    else:
        assert chars and all(position is not None for position in chars)
        assert all(0 <= position < len(text) for position in chars)

        # Diagnostic invariant for this pinned BERT WordPiece tokenizer
        # and this source string, not a universal tokenizer guarantee.
        span_from_chars = (min(chars), max(chars) + 1)
        assert span_from_chars == tuple(offset)
        assert offset[0] < offset[1]

        if token_id == tokenizer.unk_token_id:
            kind = "unknown"
        elif token.startswith("##"):
            kind = "wordpiece-continuation"
        else:
            kind = "content"

        content_intervals.extend((position, position + 1) for position in chars)

    rows.append(
        {
            "index": index,
            "id": token_id,
            "token": token,
            "special": special,
            "offset": tuple(offset),
            "chars": chars,
            "kind": kind,
        }
    )

print(f"model: {MODEL_ID}@{FULL_COMMIT}")
print(f"transformers: {transformers.__version__}")
print(f"tokenizers dependency: {tokenizers.__version__}")
print(
    {
        "source_code_points": len(text),
        "model_input_tokens": len(input_ids),
        "content_tokens": sum(not row["special"] for row in rows),
        "special_tokens": sum(row["special"] for row in rows),
        "unknown_content_tokens": sum(row["kind"] == "unknown" for row in rows),
        "wordpiece_continuation_tokens": sum(
            row["kind"] == "wordpiece-continuation" for row in rows
        ),
    }
)

for row in rows:
    chars = ",".join("None" if value is None else str(value) for value in row["chars"])
    print(
        f'{row["index"]:>2}  {row["kind"]:<23} '
        f'{row["token"]!r:<24} {row["offset"]!s:<12} [{chars}]'
    )

def merge_intervals(intervals):
    merged = []
    for start, end in sorted(intervals):
        if merged and start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return merged

def render_highlight(source, intervals):
    output = []
    cursor = 0
    for start, end in merge_intervals(intervals):
        output.append(escape(source[cursor:start]))
        output.append(f"<mark>{escape(source[start:end])}</mark>")
        cursor = end
    output.append(escape(source[cursor:]))
    return "".join(output)

print("highlight:", render_highlight(text, content_intervals))

Interpreting the diagnostic

The first count is a source-code-point count; it is not a BERT token count. The model-input count includes added special tokens. The content count excludes positions identified by special_tokens_mask, and the final two classifications describe potentially different phenomena.

For every content row, the assertion derives a half-open span from token_to_chars and compares it with offset_mapping. A failure is actionable: retain the source string, token ID, token label, special-token mask, offset, and character-position list, then inspect that exact row. Do not silently prefer one result or clamp an invalid interval. First determine whether normalization, Unicode handling, a tokenizer-file change, or the installed tokenizers dependency produced the mismatch.

For added tokens, the printed None positions are expected alignment information, not missing diagnostics. Exclude those rows before building intervals. For an unknown content token, keep its character positions and mark its source span if the highlighter should cover all represented input. For continuation pieces, merge their adjacent or overlapping intervals so that a word is not rendered with unnecessary internal markup.

This makes token_to_chars particularly useful when the rendering layer wants per-character coverage or wants to verify that compact offsets did not conceal unusual alignment. If the application only needs one contiguous span per content token and its corpus checks consistently pass, offset_mapping remains the simpler representation. The important point is not that one API is universally superior; it is that their agreement is testable and their None and unknown cases have different meanings.

Limitations and change detection

The sample is a diagnostic, not proof for every multilingual input. Python strings index code points, while a user may consider a combining sequence or emoji sequence one displayed grapheme. A technically correct character interval can still cut a user-perceived grapheme. Test the exact scripts, punctuation, whitespace, control characters, and normalization patterns that the application accepts. Also note that pinning Transformers does not independently pin every version-sensitive behavior of its tokenizers dependency; the program prints that installed version for this reason.

Verified: 2026-10-05. The applicable model is google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8, and the applicable Transformers version is 4.56.2. This is a source- and API-level verification, not a claim that the displayed runtime counts are universal.

When the pinned tokenizer file, model revision, Transformers version, or tokenizers dependency changes, rerun the program over a checked-in corpus and compare IDs, token labels, masks, offsets, character positions, and rendered intervals. Review the new pinned tokenizer.json, versioned tokenizer API, and BertTokenizerFast implementation before accepting changed behavior. Record an approved digest of the tokenizer artifact used by your build, investigate every alignment diff, and update the verification date only after the new snapshots and limitations have been reviewed.

The evidence boundary is the pinned tokenizer.json, the Transformers 4.56.2 tokenizer documentation, and the versioned BertTokenizerFast source.

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