Skip to content
wordpiece.org

Comparing raw offsets after BERT accent normalization

Use a cased/uncased pair with accented input; inspect raw slices versus normalized token strings

Published 8 min read Verified

Verified: 2026-10-05 against the pinned tokenizer files and versioned API documentation. This guide is scoped to google-bert/bert-base-uncased at 86b5e0934494bd15c9632b12f734a8a67f723594 and google-bert/bert-base-multilingual-cased at 3f076fdb1ab68d5b2880cb87a0886f315b8146f8, using transformers==4.56.2. For these pinned fast WordPiece tokenizers, an offset identifies a span in the original string passed to the tokenizer; it is not an index into a separately normalized copy of that string. The displayed token may therefore differ from the raw source slice. That distinction is the alignment contract to test.

The uncased tokenizer.json enables lowercasing and accent stripping. The multilingual cased file disables lowercasing and does not enable accent stripping. Neither behavior should be inferred from token text alone: WordPiece can split a word, and failure to represent a normalized word can produce [UNK]. Compare the same accented literal through both tokenizers, retain all returned fields, and reconstruct each raw slice with text[start:end].

Reproduce the comparison

Run the following in a clean Python 3 environment after installing transformers==4.56.2. It passes each full commit as revision, requires a fast tokenizer, disables padding and truncation, and prints the model-input count, content count, unknown count, and continuation-piece count. It also prints every token’s offset, raw slice, token form, and classification. The version assertion prevents an accidental comparison with another Transformers release.

from importlib.metadata import version
import unicodedata

from transformers import AutoTokenizer

assert version("transformers") == "4.56.2", (
    f"Expected transformers==4.56.2, got {version('transformers')}"
)

TEXT = "Café déjà vu."
FULL_COMMIT = {
    "uncased": "86b5e0934494bd15c9632b12f734a8a67f723594",
    "multilingual-cased": "3f076fdb1ab68d5b2880cb87a0886f315b8146f8",
}
MODELS = {
    "uncased": "google-bert/bert-base-uncased",
    "multilingual-cased": "google-bert/bert-base-multilingual-cased",
}


def simple_fold(value):
    decomposed = unicodedata.normalize("NFKD", value.casefold())
    return "".join(ch for ch in decomposed if not unicodedata.combining(ch))


def has_accent_form(value):
    return value is not None and unicodedata.normalize("NFKD", value) != value


observations = {}

for label, model_id in MODELS.items():
    tokenizer = AutoTokenizer.from_pretrained(
        model_id,
        revision=FULL_COMMIT[label],
        use_fast=True,
    )
    assert tokenizer.is_fast

    encoded = tokenizer(
        TEXT,
        add_special_tokens=True,
        padding=False,
        truncation=False,
        return_attention_mask=True,
        return_offsets_mapping=True,
        return_special_tokens_mask=True,
    )

    ids = encoded["input_ids"]
    offsets = encoded["offset_mapping"]
    special_masks = encoded["special_tokens_mask"]
    tokens = tokenizer.convert_ids_to_tokens(ids)
    unk_id = tokenizer.unk_token_id

    assert encoded["attention_mask"] == [1] * len(ids)

    rows = []
    print(f"\n{label}: {model_id}@{FULL_COMMIT[label]}")
    print("idx  offset    content  unk   ##    raw          token       fold")

    for index, (token_id, span, special_mask) in enumerate(
        zip(ids, offsets, special_masks)
    ):
        start, end = span
        token = tokens[index]
        special = bool(special_mask)
        unknown = token_id == unk_id

        # An input-derived [UNK] is content, not an added boundary token.
        content = (not special) or unknown
        raw = TEXT[start:end] if content else None

        assert 0 <= start <= end <= len(TEXT)
        if content:
            assert start < end
        else:
            assert span == (0, 0)

        row = {
            "content": content,
            "unknown": unknown,
            "continuation": content and token.startswith("##"),
            "raw": raw,
            "token": token,
            "accent_source": has_accent_form(raw),
            "fold_match": raw is not None and token == simple_fold(raw),
        }
        rows.append(row)

        print(
            f"{index:03d}  {span!s:>7}  "
            f"{str(content):>7}  {str(unknown):>5} "
            f"{str(row['continuation']):>5}  "
            f"{raw!r:<12} {token!r:<11} "
            f"{row['fold_match']}"
        )

    observations[label] = rows
    print("model_input_count =", len(ids))
    print("content_count =", sum(row["content"] for row in rows))
    print("unknown_count =", sum(row["unknown"] and row["content"] for row in rows))
    print(
        "continuation_piece_count =",
        sum(row["continuation"] for row in rows),
    )

uncased_evidence = [
    row for row in observations["uncased"]
    if row["content"]
    and row["accent_source"]
    and row["raw"] != row["token"]
    and row["fold_match"]
]
assert uncased_evidence, (
    "No accented uncased row matched the simple case/accent fold; "
    "inspect the pinned normalizer and dependency."
)
assert any(row["accent_source"] for row in observations["multilingual-cased"]), (
    "The cased run did not expose an accented source row; inspect the test input."
)
print("\nPASS: inspect [UNK] and ## rows separately from raw/token differences.")

The script does not print a precomputed result. Its uncased guard requires at least one accented source row whose token matches the script’s simple case-and-accent fold; if that guard fails, inspect the normalization settings or dependency rather than editing the expected row. The cased side deliberately has no corresponding equality assertion. A cased result can be a whole token, a ## fragment sequence, or [UNK], and those outcomes answer different questions.

Interpret the rows

model_input_count is the length of input_ids, so it includes the tokens added by BERT, including its sequence-boundary tokens. content_count excludes those added boundary tokens but includes an input-derived [UNK]. In this no-padding example, attention should cover every model-input position. The code uses the offset span and unknown-token identity when classifying rows, so [UNK] is not silently folded into either the special-token or fragmentation category.

When carrying this procedure into batched or annotated data, keep the original sequence string beside each encoding. Padding introduces zero-length positions that are neither source content nor evidence of tokenization; truncation means some source characters have no returned token. Compare attention and special-token masks with the offsets, but do not count padding as content. If words are pre-split, rerun the test in that mode because supplied word boundaries are then part of tokenizer input semantics.

For each content token, treat (start, end) as Python string indices for this character-based BERT diagnostic and verify 0 <= start < end <= len(text). The raw slice is read from the exact source string, including its case and diacritics. convert_ids_to_tokens exposes the vocabulary symbol after normalization and WordPiece segmentation. The fold_match column says only that a token matches a deliberately simple Unicode case/accent fold of the raw slice. It is not a reimplementation of BERT normalization and must not be used to predict token IDs.

In the uncased rows, a mismatch involving Café or another accented source is evidence of the configured normalization path, provided the offsets still delimit the intended source word. It is not evidence that the fast tokenizer moved the token into normalized-string coordinates. In the cased rows, equality between the raw slice and token is consistent with preserving Latin accents, but inequality alone does not prove accent removal: inspect the ## and unknown flags and the pinned strip_accents setting. This is why the paired output is more informative than decoding either model and comparing strings.

[UNK] means that WordPiece could not build a representable sequence for the normalized word under its vocabulary and length rules. An accent-normalized form can be unrepresentable, but [UNK] alone does not reveal why. Fragmentation instead appears when a representable word is emitted as a first piece plus one or more continuation pieces beginning with ##; each piece is a separate content and model-input token. Repeated or overlapping spans are not automatically errors, because subword alignment can divide or share source coverage. The narrow invariant worth automating is that every content row has a valid nonempty span and every added boundary row has (0, 0). Semantic correctness still requires reviewing the intended word boundaries.

Limitation

This procedure deliberately uses one accented string, scalar inputs, no padding or truncation, no is_split_into_words, and the fast-tokenizer offset mapping available in Transformers 4.56.2. It does not claim that every tokenizer family, pretokenized input mode, language, or Unicode edge case has identical offset behavior. Most importantly, offsets refer to the exact string given to the tokenizer. If an application normalizes, repairs, decodes, or slices text before tokenization, that earlier string is the coordinate system; preserving offsets back to bytes or a database field requires a separate source map.

Re-check after a change

When the pinned file or dependency changes, do not carry old row expectations forward. Keep the full model revision in the loading call, assert transformers==4.56.2 or explicitly repeat the diagnostic in the new version, and run against the new complete commit rather than a branch name. In a fresh cache, record the package version, both full commit IDs, the input, and the printed rows.

Download the two tokenizer.json files at those commits and compare their normalizer, pre_tokenizer, post_processor, and WordPiece model sections; also record local file hashes. Re-run the offset-boundary and content/unknown assertions. A changed vocabulary can alter [UNK] decisions without changing offsets, while changed normalization or alignment code can change token strings and their grouping. Treat the pinned tokenizer.json as the authority for normalization and vocabulary behavior, and update the verification date only after reviewing the new output.

The evidence boundary is the pinned uncased tokenizer.json, the pinned multilingual cased tokenizer.json, and the Transformers v4.56.2 tokenizer API. The script reveals observations locally; this article does not claim that its output was precomputed or benchmarked.

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