Skip to content
wordpiece.org

Why decoding BERT ids cannot restore the original input

Compare decode output to raw offset slices for cased/uncased inputs; explain lowercasing, whitespace, and special tokens

Published 8 min read Verified

Decoding a BERT input_ids sequence does not reverse tokenization. It maps retained IDs to vocabulary strings and joins them with tokenizer-specific spacing conventions. Before those IDs existed, the encoder could already have normalized the text, divided it into WordPiece units, and inserted model-only tokens. That pipeline does not preserve every source character or its position. The useful engineering comparison is therefore not whether decoding looks readable, but whether each decoded token agrees with the raw slice recorded for it.

Scope and evidence

Verified: 2026-10-05. This procedure applies to google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 and google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8, loaded as fast tokenizers by transformers==4.56.2.

The evidence boundary is the pinned uncased tokenizer.json, the pinned multilingual cased tokenizer.json, and the versioned Transformers tokenizer API. The JSON files are authoritative for normalization and WordPiece settings; the API reference governs the fields used below.

Their lookup tables are not counts of content or model-input tokens. Verification identifies this source snapshot; it is not a claim that the sample below was executed. The script prints its local observations.

Keep content tokens separate from model-input tokens

A content token comes from source tokenization, whereas model-input tokens are the sequence actually submitted to the model. For one unpadded BERT sequence, the pinned postprocessor adds [CLS] and [SEP] around the content; batched padding can add [PAD]. attention_mask identifies non-padding positions, while special_tokens_mask identifies tokenizer-inserted special positions. Neither mask is encoded into the integer vocabulary entries.

Fast offset_mapping associates non-special positions with source spans. Special-token offsets must not be treated as source slices. A decode call receives IDs, not this mask or offset table. Omitting special tokens during display decoding cannot recover a suffix removed by truncation, and padding was never source text.

Why the round trip loses information

The uncased normalizer lowercases and strips accents before WordPiece selection. Uppercase distinctions and accented spellings therefore cannot generally be recovered from the surviving IDs. The multilingual cased normalizer does not lowercase or strip accents, but “cased” does not promise a byte-for-byte inverse: clean-text processing still controls control characters and whitespace, while WordPiece and unknown handling can still discard structure.

Whitespace is a separate issue. Tabs, newlines, and repeated spaces are not retained as literal separator IDs. Tokenization applies its spacing conventions, while offsets point to lexical spans. A decoder may insert one space between word pieces, remove an internal continuation marker, or place spaces around punctuation. Setting clean_up_tokenization_spaces=False disables an additional cleanup heuristic; it does not recover the original separator characters.

WordPiece also has two distinct outcomes. If a word is divided into known units, continuation pieces carry the internal ## marker. This is fragmentation, not an unknown character. If the algorithm cannot represent a character or a word exceeds its character limit, it emits the vocabulary’s unknown token. That ID says only “unknown”; it carries neither the offending characters nor their exact surrounding whitespace. One sequence can contain both known continuation pieces and an unknown position.

Run a source-to-offset comparison

After installing with python -m pip install transformers==4.56.2, the following self-contained diagnostic reveals results for both pinned tokenizers rather than embedding a claimed transcript.

from transformers import AutoTokenizer, __version__

assert __version__ == "4.56.2", __version__

PINNED = (
    (
        "google-bert/bert-base-uncased",
        "86b5e0934494bd15c9632b12f734a8a67f723594",
    ),
    (
        "google-bert/bert-base-multilingual-cased",
        "3f076fdb1ab68d5b2880cb87a0886f315b8146f8",
    ),
)

source = "Café  PLAY\tfoo\nunaffable 🚀"


def text_from_offsets(text, ranges):
    parts = []
    cursor = 0
    for start, end in ranges:
        if not (0 <= start <= end <= len(text)) or start < cursor:
            return None
        parts.extend((text[cursor:start], text[start:end]))
        cursor = end
    parts.append(text[cursor:])
    return "".join(parts)


for model_id, revision in PINNED:
    tok = AutoTokenizer.from_pretrained(
        model_id,
        revision=revision,
        use_fast=True,
    )
    assert tok.is_fast, type(tok).__name__

    encoded = tok(
        source,
        add_special_tokens=True,
        padding=False,
        truncation=False,
        return_offsets_mapping=True,
        return_special_tokens_mask=True,
        return_attention_mask=True,
    )

    ids = encoded["input_ids"]
    offsets = encoded["offset_mapping"]
    special_mask = encoded["special_tokens_mask"]
    attention_mask = encoded["attention_mask"]

    fields = (ids, offsets, special_mask, attention_mask)
    assert len({len(field) for field in fields}) == 1

    content_positions = [
        i for i, is_special in enumerate(special_mask) if not is_special
    ]
    content_ids = [ids[i] for i in content_positions]
    content_offsets = [offsets[i] for i in content_positions]
    content_tokens = tok.convert_ids_to_tokens(content_ids)

    raw_concatenated = "".join(
        source[start:end] for start, end in content_offsets
    )
    offset_text = text_from_offsets(source, content_offsets)
    decoded_content = tok.decode(
        content_ids,
        skip_special_tokens=False,
        clean_up_tokenization_spaces=False,
    )
    decoded_input = tok.decode(
        ids,
        skip_special_tokens=False,
        clean_up_tokenization_spaces=False,
    )

    unknowns = [
        i for i, token_id in enumerate(content_ids)
        if token_id == tok.unk_token_id
    ]
    continuations = [
        i for i, token in enumerate(content_tokens)
        if token.startswith("##")
    ]
    mismatches = [
        (content_tokens[i], source[start:end])
        for i, (start, end) in enumerate(content_offsets)
        if content_tokens[i] != source[start:end]
    ]

    print(f"\n{model_id}@{revision}")
    print("tokenizer:", type(tok).__name__)
    print("source:", repr(source))
    print("model-input/content counts:", len(ids), len(content_ids))
    print("input_ids:", ids)
    print("attention_mask:", attention_mask)
    print("special_tokens_mask:", special_mask)

    for i, token_id in enumerate(ids):
        is_special = bool(special_mask[i])
        token = tok.convert_ids_to_tokens(token_id)
        start, end = offsets[i]
        raw = None if is_special else source[start:end]
        print(
            f"{i:2d} id={token_id:5d} special={int(is_special)} "
            f"token={token!r} raw={raw!r}"
        )

    print("unknown content positions:", unknowns)
    print("continuation-subword positions:", continuations)
    print("token/raw mismatches:", mismatches)
    print("raw slices concatenated:", repr(raw_concatenated))
    print("decoded content:", repr(decoded_content))
    print("decoded model input:", repr(decoded_input))
    print("decoded content == raw concatenation:",
          decoded_content == raw_concatenated)
    print("offset slices plus gaps == source:",
          offset_text == source)

Interpret the observations

Start with the count and mask lines. They separate content from the sequence passed to the model. Rows marked as special have no meaningful raw slice. In this unpadded request, the attention mask distinguishes retained positions from padding, while the special mask distinguishes inserted BERT symbols from content positions.

Next, compare each token with its raw value. For the uncased tokenizer, lowercase and accent-removal operations can produce a token spelling different from its source slice. For the cased tokenizer, case and accents need not differ; a mismatch may instead be an internal WordPiece marker. The printed mismatches distinguish these cases without assuming a particular output in advance.

A false comparison between decoded content and concatenated raw slices is not by itself evidence of corruption. Concatenation omits the original whitespace gaps, while decoding applies spacing conventions. By contrast, if the offset-based reconstruction equals the source, the original string and returned spans still contain enough positional information for that sample. That information is not present merely because a readable decode was produced.

The unknown and continuation lists diagnose different losses. An unknown position cannot reveal the characters that the WordPiece algorithm failed to represent. A continuation position represents a known subword and can be related back to its source through the offset. Also avoid using blanket skip_special_tokens=True as a mask-aware content extractor: an unknown input position may carry the [UNK] ID even though its special_tokens_mask value is zero. The example therefore filters by the mask first and decodes those content IDs with special-token skipping disabled.

Limitations and re-check procedure

This diagnostic is limited to one mixed source sample and the two named tokenizer snapshots. It does not establish behavior for every Unicode input, custom added tokens, production batching, truncation strategies, or other tokenizer families. It also depends on retaining the original string: IDs alone cannot supply offsets, and a discarded source suffix cannot be diagnosed from the remaining sequence.

When a pinned file or dependency changes, do not weaken the version assertion and reuse the old conclusion. Replace the revision with the new full commit hash, inspect the new tokenizer.json normalization, pre-tokenization, post-processing, and WordPiece settings, and rerun the unchanged sample against both models. Compare IDs, masks, offsets, token/raw mismatches, unknown positions, continuation positions, and decoded strings. Record the new full revisions, exact Transformers version, and verification date; if an assertion fails, treat the change as a new tokenizer contract requiring separate evidence.

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