Skip to content
wordpiece.org

Reading token_type_ids in a BERT sentence pair

Print type ids aligned with actual tokens, including separator positions; describe segment roles and model-specific limits

Published 8 min read Verified

token_type_ids should be read as segment labels indexed by input_ids; the vector alone cannot prove that sentence B and its closing separator survived special-token handling. For the exact model used here, an ordinary, unpadded, untruncated pair has this alignment:

PositionVocabulary tokentoken_type_idSegment role
Opening[CLS]0Sequence boundary
Sentence AContent-position token0First sequence
Middle[SEP]0End of sequence A
Sentence BContent-position token1Second sequence
Closing[SEP]1End of sequence B

A content-position token is not necessarily a complete source word: it can be a WordPiece fragment or [UNK]. A model-input token is every entry in input_ids, including added special tokens and any padding.

Verified: 2026-10-05. The applicable artifact is google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594, loaded with transformers==4.56.2 and use_fast=True. The pinned tokenizer.json is the authority for vocabulary and normalization behavior.

Run the alignment check

In a clean Python 3 environment, install python -m pip install transformers==4.56.2, save the following as a script, and execute it. It requests the full commit explicitly, prints every index and field, and asserts the segment-role structure without claiming a precomputed output.

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
assert tokenizer.__class__.__name__ == "BertTokenizerFast"

# The Unicode character gives the local run a candidate unknown token.
sentence_a = "A clear sentence: 😀"
sentence_b = "The second segment stays aligned."

encoded = tokenizer(
    sentence_a,
    sentence_b,
    add_special_tokens=True,
    padding=False,
    truncation=False,
    return_attention_mask=True,
    return_token_type_ids=True,
    return_special_tokens_mask=True,
    return_offsets_mapping=True,
)

input_ids = encoded["input_ids"]
type_ids = encoded["token_type_ids"]
attention_mask = encoded["attention_mask"]
special_mask = encoded["special_tokens_mask"]
offsets = encoded["offset_mapping"]
tokens = tokenizer.convert_ids_to_tokens(input_ids)
input_length = len(input_ids)

assert all(len(value) == input_length for value in encoded.values())

separator_positions = [
    index for index, token in enumerate(tokens) if token == "[SEP]"
]
content_positions = [
    index for index, is_special in enumerate(special_mask) if not is_special
]
unknown_positions = [
    index
    for index in content_positions
    if input_ids[index] == tokenizer.unk_token_id
]
continuation_positions = [
    index
    for index in content_positions
    if tokens[index].startswith("##")
]

print(f"model={MODEL_ID}@{FULL_COMMIT}")
print(f"transformers={transformers.__version__}")
print(f"tokenizer={tokenizer.__class__.__name__}")
print()
print("idx  input_id  token       type  attn  special  offsets       role")

for index, (
    input_id,
    token,
    type_id,
    attention,
    is_special,
    offset,
) in enumerate(
    zip(
        input_ids,
        tokens,
        type_ids,
        attention_mask,
        special_mask,
        offsets,
    )
):
    if is_special:
        role = "added special"
    elif input_id == tokenizer.unk_token_id:
        role = "unknown"
    elif token.startswith("##"):
        role = "WordPiece continuation"
    else:
        role = "content"

    print(
        f"{index:>3}  {input_id:>8}  {token!r:<12} {type_id:>4}  "
        f"{attention:>4}  {is_special:>7}  {str(offset):<12}  {role}"
    )

print()
print("separator rows:", [
    (index, tokens[index], type_ids[index])
    for index in separator_positions
])
print("content-position count:", len(content_positions))
print("model-input count:", input_length)
print("unknown positions:", unknown_positions)
print("WordPiece continuation positions:", continuation_positions)

# Structural expectations for this nonempty, unpadded BERT pair.
assert input_ids[0] == tokenizer.cls_token_id
assert separator_positions == [1, input_length - 1]
assert [
    index for index, is_special in enumerate(special_mask) if is_special
] == [0] + separator_positions
assert attention_mask == [1] * input_length

first_separator = separator_positions[0]
assert all(value == 0 for value in type_ids[: first_separator + 1])
assert all(value == 1 for value in type_ids[first_separator + 1 :])

Read the result

The printed index is the join key. Do not align the type vector with a separately decoded string: decoding can hide control tokens, while convert_ids_to_tokens(input_ids) preserves one vocabulary item for every returned ID. The offset column is supplied by the fast tokenizer and helps trace content rows back to the source string. Offsets for sentence B refer to the second string, not to a concatenation of both inputs.

The two counts answer different questions. model-input count is len(input_ids). Because this call disables padding, content-position count identifies rows whose special_tokens_mask is zero. Those rows include recognized words, WordPiece continuations, and [UNK]; “content position” does not mean “known word.” The pinned model’s 30,522-entry WordPiece vocabulary is a lookup inventory, not this pair’s input length or unknown count.

An unknown and fragmentation are also different observations. A normalized unit for which WordPiece finds no accepted decomposition becomes one [UNK] ID. A unit decomposed into accepted pieces becomes several IDs, commonly with later pieces marked by the ## prefix. The emoji in the sample lets the local run expose that distinction. Neither case should be classified as an added [CLS] or [SEP]: under this wrapper, their positions have special_tokens_mask == 1.

The separator rows complete the segment diagnosis. The first [SEP] retains type 0 because it closes sequence A. The final [SEP] has type 1 because it belongs to the end of sequence B. A type vector without those positions cannot be interpreted safely.

Diagnose common mismatches

Use the output in this order:

  1. Confirm transformers, model ID, full revision, and fast-tokenizer class.
  2. Check that input_ids, token_type_ids, attention_mask, special_tokens_mask, and offsets all have the same length.
  3. Locate both [SEP] rows and the transition from 0 to 1.
  4. Check attention_mask before treating a zero type ID as sentence A.
  5. Reproduce the original add_special_tokens, padding, and truncation settings.

If the sentence-B IDs are all zero in this nonempty-pair example, first verify that the second value was actually passed as text_pair and that fields from separate calls were not combined. If the closing separator has type 0 while sentence B has type 1, inspect serialization, padding, truncation, or any manual array reconstruction after tokenization.

Padding also needs care. Under this BERT wrapper, padded token_type_ids are zero, while attention_mask is zero and input_ids contains the padding ID. A zero type ID alone therefore means neither “first segment” nor “real content.” Truncation can change which sequence survives, so do not retain a hard-coded final-row assertion after changing that option.

Limitations and re-check procedure

This procedure is limited to the exact English checkpoint and revision named above. It does not transfer token strings, counts, offsets, or unknown behavior to another checkpoint or revision. It also assumes the stock BertTokenizerFast path: token_type_ids identify segments, not attention, padding, special-token status, or token classes.

When the pinned tokenizer file, model revision, or dependency changes, treat the recorded tokens and counts as stale. Install the intended dependency set in a clean environment, rerun the script, and archive its output. Also retain a local hash of the resolved tokenizer.json; requesting a commit identifies the intended repository revision, while the archived hash makes the actual file comparison explicit. Re-check the versioned Tokenizer API and BertTokenizerFast source before updating a regression fixture. Preserve the segment-boundary assertions, but derive any expected token sequence from the newly reviewed pinned artifact rather than silently accepting changed output.

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