A word count cannot tell you how many tokens a model will receive. Even an extra space can select a different vocabulary entry while leaving the token count unchanged. You will inspect the selected tokenizer's actual IDs, recover the supplied text and distinguish ordinary text from an explicit special marker.
Start after verifying the local model files. Use the same owned practice folder and pinned Linux/CPython CPU environment. All required inputs below are fictional strings or the verified tokenizer files. This exercise reads local files and prints observations; it downloads nothing, loads no model weights, generates no answer and writes no output file.
Count the right kind of unit
Python text is a sequence of Unicode code points, numerical identities for
characters and combining marks. len(text) counts those code points, not
necessarily the letters a reader perceives. UTF-8 encodes them as bytes for
storage: some code points need more than one byte. Neither count is a token
count. A tokenizer applies its own saved vocabulary and processing rules to
produce a list of numerical token IDs.
The selected tokenizer uses byte-level byte pair encoding (BPE). It can combine byte-based units using saved merge rules so a frequent chunk becomes one token while other text uses several. You are applying the saved tokenizer, not training its vocabulary. Other tokenizers use different rules and IDs; an ID is a vocabulary index, not a universal word number or an importance score.

Arrows trace this tokenizer's text-to-vocabulary mapping. The space-prefix notation is a display convention; EOS is a separate special token.
For this snapshot, library is one token, ID 23345. library, with one
leading space, is also one token but ID 4971. Its vocabulary-piece spelling
starts with the glyph represented by U+0120, followed by library.
That glyph makes a byte-level space prefix visible in the vocabulary display;
it is not an extra Unicode letter that you must insert into the input.
The arrows are not neural-network inference. The tokenizer maps text to IDs
before the model uses them.
The contrast is useful: counting tokens alone cannot reveal that the input
changed. Inspect actual IDs and decoded text too. For library\nbooks, where
\n denotes one newline, this tokenizer produces three IDs: 23345, 198 and
8981. The vocabulary display represents the newline with U+010A. Do not
assume every word, newline or character in arbitrary text has the same token
boundary as these examples.
Inspect four supplied strings
Save the complete file below as inspect_tokens.py in
~/genai-llm-practice, alongside .venv/ and the verified model/ folder.
The maintained course file is examples/tokenization/inspect_tokens.py;
its complete contents are supplied here.
Before running, predict which counts or IDs might change between the first two strings. Predict whether adding a newline creates a space or an actual new line on decoding. For the fourth string, you need not know the language: the task is to check encoding/decoding, not judge its meaning.
"""Save in the practice root; inspect the verified local tokenizer, not weights."""
import os
from pathlib import Path
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
from transformers import AutoTokenizer
MODEL_DIR = Path(__file__).resolve().parent / "model"
TEXTS = ["library", " library", "library\nbooks", "\u0928\u092e\u0938\u094d\u0924\u0947"]
def inspect(tokenizer, text):
ids = tokenizer.encode(text, add_special_tokens=False)
decoded = tokenizer.decode(ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)
print("text:", ascii(text))
print("code points/UTF-8 bytes/tokens:", len(text), len(text.encode("utf-8")), len(ids))
print("IDs:", ids)
print("vocabulary pieces:", ascii(tokenizer.convert_ids_to_tokens(ids)))
print("decoded:", ascii(decoded))
print("round trip:", decoded == text)
if decoded != text:
raise ValueError("This example did not round-trip; inspect the tokenizer and text")
return ids
def main():
tokenizer = AutoTokenizer.from_pretrained(
MODEL_DIR, local_files_only=True, trust_remote_code=False
)
for text in TEXTS:
inspect(tokenizer, text)
original = tokenizer.encode(TEXTS[0], add_special_tokens=False)
automatic = tokenizer.encode(TEXTS[0], add_special_tokens=True)
print("automatic special-token insertion changed IDs:", automatic != original)
print("EOS marker/ID:", ascii(tokenizer.eos_token), tokenizer.eos_token_id)
with_eos = original + [tokenizer.eos_token_id]
print("explicit EOS IDs/count:", with_eos, len(with_eos))
print("EOS kept:", ascii(tokenizer.decode(with_eos, skip_special_tokens=False, clean_up_tokenization_spaces=False)))
print("EOS hidden:", ascii(tokenizer.decode(with_eos, skip_special_tokens=True, clean_up_tokenization_spaces=False)))
repeated = original + original
print("deliberately repeated IDs/count:", repeated, len(repeated))
print("repeated text:", ascii(tokenizer.decode(repeated, clean_up_tokenization_spaces=False)))
if __name__ == "__main__":
main()
The fourth source string contains six \u escapes that Python turns into
Unicode code points: the Devanagari text commonly written as a greeting.
The tokenizer receives those six code points, not thirty-six literal backslash
characters. ascii() prints a quoted escaped representation so non-ASCII
characters, newlines and leading spaces remain inspectable in a plain terminal.
It changes how the result is displayed, not what is passed to encode().
encode(text, add_special_tokens=False) returns an ordinary Python list of
IDs with no request to insert automatic boundary markers. len(ids) is the
model-token count for that call. text.encode("utf-8") instead returns storage
bytes; its length answers a different question. convert_ids_to_tokens()
exposes vocabulary spellings, which can look unfamiliar because they show
byte-related display characters rather than normal words.
decode() converts the ID sequence back to text. We keep special markers
visible and set clean_up_tokenization_spaces=False so no optional display
cleanup obscures this inspection. The round-trip equality check is for these
supplied strings and this tokenizer. It does not establish that every tokenizer
preserves every input: another tokenizer may normalise text or have different
options. The function returns its IDs to a caller; the main loop uses its
printed trace to compare the four strings.
The script then compares add_special_tokens=True with the earlier call.
For this selected tokenizer and plain input, it changes nothing. That is an
observed condition, not a rule that special-token insertion never matters.
Later chat formatting has its own explicit markers and will be counted then.
Run from Bash in the practice root:
cd ~/genai-llm-practice
.venv/bin/python inspect_tokens.py
Illustrative observations for the four fixtures are:
| Input fixture | Code points / UTF-8 bytes / tokens |
|---|---|
library, without a leading space | 7 / 7 / 1 |
library, with one leading space | 8 / 8 / 1 |
Newline between library and books | 13 / 13 / 3 |
| The supplied six-code-point Devanagari string | 6 / 18 / 6 |
The fourth fixture's printed IDs are
[30658, 35090, 38770, 16525, 26293, 30581]. Compare them with the actual
list printed by your run; the English fixture IDs are traced above.
All four should report round trip: True. Inspect the returned text, not just
that boolean. For the fourth example, eighteen storage bytes becoming six
tokens is a measured result for this string; six tokens per six code points
is a coincidence here, not a Unicode tokenisation rule. Successful decoding
also says nothing about the English-focused model's ability to understand or
answer in that language. No model answer is produced by this exercise.
Markers can be hidden without being removed from the IDs
Special tokens are registered markers with model-specific roles. Here
<|im_end|> has ID 2 and serves as the end-of-sequence (EOS) marker.
The script explicitly appends that ID to the ordinary library IDs. This is
our constructed input, not a model choosing when to stop.
automatic special-token insertion changed IDs: False
EOS marker/ID: '<|im_end|>' 2
explicit EOS IDs/count: [23345, 2] 2
EOS kept: 'library<|im_end|>'
EOS hidden: 'library'
deliberately repeated IDs/count: [23345, 23345] 2
repeated text: 'librarylibrary'
original + [tokenizer.eos_token_id] concatenates two Python lists. Decoding
with skip_special_tokens=True hides the registered EOS marker from the
string. It does not delete an element from with_eos: the input still has
two IDs. This distinction matters when later budgets count the input that
actually reaches the model rather than the shortened display.
The deliberately broken fixture is original + original. Its repetition is
introduced by that line, not by the tokenizer automatically doubling the
prompt. The decoded string has no inserted separator. Changing a special-token
flag cannot repair an application that explicitly concatenates the same IDs
twice; fix the repeated construction. Keep this diagnosis separate from the
later lesson's conversation-template checks.
Try punctuation and an empty input
Save a copy as inspect_tokens_variant.py beside the original. In its TEXTS
list, change the first string from library to library?. Predict what can
remain the same and what must be remeasured, then run the copy with the same
interpreter. Explain why one extra visible character need not imply one extra
token for every tokenizer or string.
Then change only that first string to the empty string "" and rerun. Explain
whether there are ordinary IDs to repeat. Use the reported count and the
add_special_tokens comparison, without forcing an assumed word-count rule.
Hint
The vocabulary is unchanged; the input is different. Inspect len(ids), the
actual ID list and decoded string. The EOS example is appended explicitly even
if the ordinary input contains no IDs.
Answer and reasoning
For this tokenizer, library? becomes [23345, 47], two tokens, and decodes
back exactly. That observed extra token does not establish an always-one-token
punctuation rule. Other strings can have different saved pieces and boundaries.
The model vocabulary and package/model revisions stay unchanged.
The empty string has zero ordinary IDs here. Repeating an empty list yields
an empty list; explicitly appending EOS yields [2], one marker. The automatic
special-token flag still adds nothing for this tokenizer. A later generation
exercise requires a nonempty prompt, but tokenisation alone can represent an
empty input. The distinction is between the API's result and the caller's task
requirements.
Diagnose and resume the inspection
If local loading fails, return to file verification and confirm this script
is beside the intended model/. Do not substitute another checkpoint to obtain
a convenient count. If decoded text differs, inspect the exact input, tokenizer
revision, special-token options and cleanup setting; other normalisation can
change a round trip. A display such as \n or \u0120 in ascii() output
is an escaped representation to interpret, not necessarily a literal sequence
that was present in the input.
On a new terminal, return to the practice root and run the explicit
.venv/bin/python command. The original script and tokenizer files persist;
there is no saved model session or output file to restore. Keep verified
model/ and the original script. Inspect and delete only the optional variation
copy when finished. No model download, weight update or shared-cache cleanup
is part of this exercise.
Sources
Tokenisation algorithms (S09) provides subword/byte-level context. The Transformers 5.19.0 tokenizer source (S21) provides API conditions. The numerical IDs, marker behaviour and round trips above are observations of the course's fixed tokenizer files, not universal values copied from a tutorial.