Skip to content
wordpiece.org

Testing BERT WordPiece on log lines and stack traces

Use synthetic timestamps and paths; show per-field diagnostics and unknown coverage instead of a blanket efficiency claim

Published 8 min read Verified

Testing BERT WordPiece on log lines and stack traces starts with a narrow question: how does your pinned tokenizer split each field, and where does the model input stop being the same as the content you logged? A single total token count hides the useful details. Timestamps, paths, UUIDs, exception names, and file frames fragment differently. Unknown tokens are a separate failure mode from fragmentation. This guide uses per-field diagnostics and offset checks so you can see both.

Freeze the tokenizer before comparing anything

The version authority is the pinned tokenizer.json, not a model card summary or a different revision. This guide is scoped to google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2. The multilingual cased alternative is google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8; do not merge its token counts with the English uncased model. The pinned English uncased vocabulary is 30,522 entries, and the pinned multilingual cased vocabulary is 119,547 entries. Those are vocabulary sizes, not token counts for a particular log line. Verified: 2026-10-05.

Use revision=FULL_COMMIT and use_fast=True. The fast tokenizer is what gives you offset_mapping and alignment helpers in Transformers v4.56.2, which is the versioned API reference for encoding options such as add_special_tokens, truncation, special_tokens_mask, and offsets. If you compare runs across revisions or across tokenizer implementations, token strings and offsets may change even when the text does not.

Run the per-field diagnostic

The snippet below builds synthetic log and stack-trace text. It tokenizes each field with add_special_tokens=False, prints content token counts, counts [UNK], shows the first pieces and offsets, then compares content tokens with model-input tokens for a single BERT sequence. It also asserts that the single-sequence model input adds exactly [CLS] and [SEP] beyond the content tokens when no truncation is applied. Run it locally; do not treat any printed token list as universal until you run it against your own pinned files.

# Requires: pip install "transformers==4.56.2"
from transformers import AutoTokenizer

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

tok = AutoTokenizer.from_pretrained(MODEL, revision=FULL_COMMIT, use_fast=True)

log_line = (
    "2026-10-05T14:03:11Z ERROR [worker-17] "
    "c.s.a.PaymentService - Failed to POST /v1/charge "
    "id=01J8Z6Q9K2 path=/srv/app/var/log/payment.log code=ECONNRESET"
)
stack_trace = (
    'Traceback (most recent call last):\n'
    '  File "/app/worker.py", line 88, in process_order\n'
    '    raise TimeoutError("upstream timed out")\n'
    'TimeoutError: upstream timed out'
)

fields = {
    "timestamp": "2026-10-05T14:03:11Z",
    "level": "ERROR",
    "thread": "worker-17",
    "logger": "c.s.a.PaymentService",
    "path": "/srv/app/var/log/payment.log",
    "id": "01J8Z6Q9K2",
    "code": "ECONNRESET",
    "stack_file": "/app/worker.py",
    "stack_symbol": "process_order",
    "stack_exception": "TimeoutError",
}

def tokenize_no_special(text):
    return tok(text, add_special_tokens=False, return_offsets_mapping=True)

print("tokenizer:", MODEL, FULL_COMMIT)
print("vocab_size:", tok.vocab_size)
print("unk_token:", tok.unk_token, "id:", tok.unk_token_id)

print("\nfield diagnostics (content tokens; add_special_tokens=False)")
print(f"{'field':16} {'content':>7} {'unknown':>7}  first tokens")
for name, value in fields.items():
    enc = tokenize_no_special(value)
    pieces = tok.convert_ids_to_tokens(enc["input_ids"])
    unknown = sum(1 for t in pieces if t == tok.unk_token)
    print(f"{name:16} {len(pieces):>7} {unknown:>7}  {pieces[:5]}")

for name, text in [("log_line", log_line), ("stack_trace", stack_trace)]:
    enc = tokenize_no_special(text)
    pieces = tok.convert_ids_to_tokens(enc["input_ids"])
    unknown = sum(1 for t in pieces if t == tok.unk_token)
    print(f"\n{name}: content_tokens={len(pieces)} unknown={unknown}")
    print("first offsets:", list(zip(pieces[:8], enc["offset_mapping"][:8])))
    if unknown:
        print(
            "unknown offsets:",
            [
                (pieces[i], enc["offset_mapping"][i])
                for i, t in enumerate(pieces)
                if t == tok.unk_token
            ][:10],
        )

enc_no_special = tokenize_no_special(log_line)
enc_with_special = tok(
    log_line,
    add_special_tokens=True,
    return_offsets_mapping=True,
    return_special_tokens_mask=True,
)
assert len(enc_with_special["input_ids"]) == len(enc_no_special["input_ids"]) + 2, (
    "BERT single-sequence model input should add exactly [CLS] and [SEP]"
)
print("\nmodel-input check:")
print("content_tokens:", len(enc_no_special["input_ids"]))
print("model_input_tokens:", len(enc_with_special["input_ids"]))
print("special_tokens_mask:", enc_with_special["special_tokens_mask"])

Reading the output

Content tokens are what the tokenizer produces for a field with add_special_tokens=False. Model-input tokens are what the model actually consumes after [CLS], [SEP], padding, and truncation are applied. For a single BERT sequence, the model input length is normally content length plus two, unless truncation removes content. The assertion in the snippet checks that relationship for the synthetic line. If it fails, check truncation settings, special-token configuration, or whether you accidentally passed a pair of sequences.

Unknown tokens and fragmentation are different. A fragmented field is split into several WordPiece pieces that are still known to the vocabulary. An unknown token is [UNK]: the tokenizer could not represent some character or substring using the pinned vocabulary. The diagnostic prints both len(pieces) and unknown. A long file path may produce many pieces and zero unknowns. A stray control character may produce one unknown inside an otherwise ordinary path. The offset list tells you which substring produced the unknown, so you can decide whether to sanitize, escape, or preserve it.

For bert-base-uncased, normalization lowercases and removes accent marks according to the pinned tokenizer files. ERROR and error can therefore collapse to the same pieces, and mixed-case paths may lose distinctions. The multilingual cased revision preserves case but uses a different vocabulary and different token strings. Do not compare its per-field counts with the English uncased counts as though they were interchangeable. Also remember that a high token count for a timestamp or UUID is not a performance claim; it is a local tokenizer observation about that pinned model and revision.

Limitations and re-check procedure

The diagnostic measures synthetic strings only. Real logs may contain Unicode, ANSI color escapes, binary fragments, very long hashes, or repeated separators. Those can change fragmentation and unknown counts. The fast tokenizer behavior also depends on the tokenizers implementation bundled with Transformers v4.56.2, so upgrading the library can change offsets or tokenization details even if you keep the same tokenizer.json revision. Token counts from this procedure do not predict model accuracy, latency, or cost for an unrelated LLM.

When the pinned tokenizer.json or transformers dependency changes, re-run the snippet and diff the printed vocab_size, unk_token_id, per-field token lists, unknown counts, offsets, and model-input length. If you switch to the multilingual cased model, replace both MODEL and FULL_COMMIT, then re-run rather than reusing English uncased observations. Keep the revision pinned to the full commit hash. If a diff appears, inspect the changed token strings and offsets before changing any log preprocessing. The check is complete when the content-token count, unknown count, and model-input relationship are understood for your own log fields under the exact pinned revision.

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