{"course":{"slug":"hugging-face","title":"Hugging Face, End to End","url":"https://addaly.com/learn/hugging-face","level":"intermediate","track":"create"},"lesson":{"slug":"tokenizers-in-practice","title":"Your text is integers, and the count is not the word count","url":"https://addaly.com/learn/hugging-face/tokenizers-in-practice","position":12,"of":75,"minutes":10,"answer":"The same message can use different numbers of tokens across languages and tokenizers. Measure the exact strings before drawing conclusions about context, and check price and quality separately.","keyIdea":"The same message can use different numbers of tokens across languages and tokenizers. Measure the exact strings before drawing conclusions about context, and check price and quality separately."},"body":{"format":"markdown","text":"## Count tokens before drawing a conclusion\n\nA tokenizer uses a vocabulary and splitting rules to turn text into integer IDs. One word can be one token or several. Spaces and punctuation can change the split, and another tokenizer can assign a different count or ID to the same text.\n\nCompare the two versions of one parcel question, in English and Hindi. Use the [GPT-2 tokenizer](https://huggingface.co/openai-community/gpt2/blob/607a30d783dfa663caf39e06633721c8d4cfcd7e/tokenizer.json) and the [XLM-R tokenizer](https://huggingface.co/FacebookAI/xlm-roberta-base/blob/e73636d4f797dec63c3081bb6ed5c7b0bb3f2089/tokenizer.json), which comes from a multilingual model [trained on text in 100 languages](https://arxiv.org/abs/1911.02116).\n\nIn a Python environment with `tokenizers==0.22.2` and `huggingface-hub==1.33.0`, run the example below. It downloads only the two revision-pinned tokenizer files, about 10.5 MB in total. No account, model weights or inference are needed.\n\n```python\nfrom huggingface_hub import hf_hub_download\nfrom tokenizers import Tokenizer\n\nmodels = (\n    (\"openai-community/gpt2\",\n     \"607a30d783dfa663caf39e06633721c8d4cfcd7e\"),\n    (\"FacebookAI/xlm-roberta-base\",\n     \"e73636d4f797dec63c3081bb6ed5c7b0bb3f2089\"),\n)\n\n> Figure: One question, two tokenizers. Bars (tokens per question): GPT-2, English 5; GPT-2, Hindi 30; XLM-R, English 5; XLM-R, Hindi 6. The exact English and Hindi parcel questions give different counts under these pinned vocabularies. Special tokens are excluded. A different sentence could give a different ratio.\n\ntexts = (\"Where is my parcel?\", \"मेरा पार्सल कहाँ है?\")\nfor repo, revision in models:\n    path = hf_hub_download(\n        repo, \"tokenizer.json\", revision=revision, token=False\n    )\n    tok = Tokenizer.from_file(path)\n    print(repo, [\n        len(tok.encode(text, add_special_tokens=False).ids)\n        for text in texts\n    ])\n```\n\nGPT-2 returns **5** for English and **30** for Hindi. XLM-R returns **5** and **6**. These counts are for the exact strings above, including the question marks and excluding special tokens.\n\n## What the counts tell you\n\n- **Context.** More tokens for the same message leave less room in a fixed token budget. For a chat system, count the whole formatted input, including instructions, roles and history.\n- **Cost.** If a provider bills input tokens at a fixed rate, a larger count increases that part of the bill. Neither these local files nor one sentence tell you what a hosted request will cost.\n- **Quality.** Token counts do not measure translation accuracy, useful answers or language coverage. Test those separately with representative examples and speakers of the language.\n\nThis is one measured comparison, without a universal ratio. Repeat it across several realistic messages before making a decision about a product or course.\n\n## Look at the pieces and their source spans\n\nThe variable `tok` holds XLM-R after the loop. Inspect the pieces and offsets for a short sentence, then try the same code with the GPT-2 file. Each offset tells you which slice of the original text contributed to that token.\n\n```python\ntext = \"Ravi lives in Pune.\"\nencoded = tok.encode(text, add_special_tokens=False)\nfor token, token_id, (start, end) in zip(\n    encoded.tokens, encoded.ids, encoded.offsets\n):\n    print(token, token_id, text[start:end])\n```\n\nOffsets make it possible to highlight the original span of a label in a reading tool. More than one token can refer to the same character, and a special token may have no source span.\n\n## Special tokens and truncation\n\nSpecial tokens tell a particular model about boundaries or roles. The raw count above leaves them out so it compares text segmentation. In a real pipeline keep the model's required tokens, but avoid adding them twice when the chat template has already inserted them.\n\nTruncation discards some of the input from the primary encoding when the input exceeds the configured limit. Choose which text to keep deliberately. For example, a classifier that only receives the beginning of a complaint may miss the event described at the end. Keep the important part, split long inputs into chunks, or choose a model with more room.\n\n## Do this now\n\nWrite three short requests in a language you use. Record the exact text, tokenizer revision and token counts. If you compare translations, make sure they mean the same thing. Decide what additional checks you need before making a claim about cost or teaching quality."},"check":{"question":"GPT-2 counts 5 tokens for the English parcel question and 30 for the Hindi translation. What does this experiment show?","options":[{"text":"Any hosted service charges six times as much for the full Hindi request.","correct":false,"tempting":"The experiment does not use a hosted service or count its output and overhead."},{"text":"The exact Hindi string uses more of a fixed token budget with this tokenizer.","correct":true},{"text":"The English answer will be six times more accurate.","correct":false,"tempting":"Input token counts do not measure answer quality."},{"text":"Every tokenizer will produce the same two counts.","correct":false,"tempting":"The second tokenizer returns 5 and 6 for the same strings."}]},"prev":{"slug":"the-auto-classes","title":"AutoModel gives you numbers, not answers","url":"https://addaly.com/learn/hugging-face/the-auto-classes"},"next":{"slug":"padding-and-attention-masks","title":"Padding on the wrong side ruins generation quietly","url":"https://addaly.com/learn/hugging-face/padding-and-attention-masks"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Your text is integers, and the count is not the word count', in Hugging Face, End to End. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/hugging-face/tokenizers-in-practice (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Your text is integers, and the count is not the word count","courseTitle":"Hugging Face, End to End","module":{"index":2,"slug":"transformers-from-text-to-text","title":"Transformers, from characters to output"},"answer":null,"keyIdea":"The same message can use different numbers of tokens across languages and tokenizers. Measure the exact strings before drawing conclusions about context, and check price and quality separately.","hero":{"kind":"figure","figure":{"t":"figure","label":"Figure","figure":{"type":"bars","title":"One question, two tokenizers","caption":"The exact English and Hindi parcel questions give different counts under these pinned vocabularies. Special tokens are excluded. A different sentence could give a different ratio.","unit":"tokens per question","series":[{"label":"GPT-2, English","value":5},{"label":"GPT-2, Hindi","value":30},{"label":"XLM-R, English","value":5},{"label":"XLM-R, Hindi","value":6,"highlight":true}]},"alt":"Figure: One question, two tokenizers. Bars (tokens per question): GPT-2, English 5; GPT-2, Hindi 30; XLM-R, English 5; XLM-R, Hindi 6. The exact English and Hindi parcel questions give different counts under these pinned vocabularies. Special tokens are excluded. A different sentence could give a different ratio."}},"blocks":[{"t":"h2","id":"count-tokens-before-drawing-a-conclusion","runs":[{"text":"Count tokens before drawing a conclusion"}]},{"t":"p","runs":[{"text":"A tokenizer uses a vocabulary and splitting rules to turn text into integer IDs. One word can be one token or several. Spaces and punctuation can change the split, and another tokenizer can assign a different count or ID to the same text."}]},{"t":"p","runs":[{"text":"Compare the two versions of one parcel question, in English and Hindi. Use the "},{"text":"GPT-2 tokenizer","href":"https://huggingface.co/openai-community/gpt2/blob/607a30d783dfa663caf39e06633721c8d4cfcd7e/tokenizer.json"},{"text":" and the "},{"text":"XLM-R tokenizer","href":"https://huggingface.co/FacebookAI/xlm-roberta-base/blob/e73636d4f797dec63c3081bb6ed5c7b0bb3f2089/tokenizer.json"},{"text":", which comes from a multilingual model "},{"text":"trained on text in 100 languages","href":"https://arxiv.org/abs/1911.02116"},{"text":"."}]},{"t":"p","runs":[{"text":"In a Python environment with "},{"text":"tokenizers==0.22.2","code":true},{"text":" and "},{"text":"huggingface-hub==1.33.0","code":true},{"text":", run the example below. It downloads only the two revision-pinned tokenizer files, about 10.5 MB in total. No account, model weights or inference are needed."}]},{"t":"code","lang":"python","label":"Python","text":"from huggingface_hub import hf_hub_download\nfrom tokenizers import Tokenizer\n\nmodels = (\n    (\"openai-community/gpt2\",\n     \"607a30d783dfa663caf39e06633721c8d4cfcd7e\"),\n    (\"FacebookAI/xlm-roberta-base\",\n     \"e73636d4f797dec63c3081bb6ed5c7b0bb3f2089\"),\n)\n\ntexts = (\"Where is my parcel?\", \"मेरा पार्सल कहाँ है?\")\nfor repo, revision in models:\n    path = hf_hub_download(\n        repo, \"tokenizer.json\", revision=revision, token=False\n    )\n    tok = Tokenizer.from_file(path)\n    print(repo, [\n        len(tok.encode(text, add_special_tokens=False).ids)\n        for text in texts\n    ])"},{"t":"p","runs":[{"text":"GPT-2 returns "},{"text":"5","b":true},{"text":" for English and "},{"text":"30","b":true},{"text":" for Hindi. XLM-R returns "},{"text":"5","b":true},{"text":" and "},{"text":"6","b":true},{"text":". These counts are for the exact strings above, including the question marks and excluding special tokens."}]},{"t":"h2","id":"what-the-counts-tell-you","runs":[{"text":"What the counts tell you"}]},{"t":"ul","items":[[{"text":"Context.","b":true},{"text":" More tokens for the same message leave less room in a fixed token budget. For a chat system, count the whole formatted input, including instructions, roles and history."}],[{"text":"Cost.","b":true},{"text":" If a provider bills input tokens at a fixed rate, a larger count increases that part of the bill. Neither these local files nor one sentence tell you what a hosted request will cost."}],[{"text":"Quality.","b":true},{"text":" Token counts do not measure translation accuracy, useful answers or language coverage. Test those separately with representative examples and speakers of the language."}]]},{"t":"p","runs":[{"text":"This is one measured comparison, without a universal ratio. Repeat it across several realistic messages before making a decision about a product or course."}]},{"t":"h2","id":"look-at-the-pieces-and-their-source-spans","runs":[{"text":"Look at the pieces and their source spans"}]},{"t":"p","runs":[{"text":"The variable "},{"text":"tok","code":true},{"text":" holds XLM-R after the loop. Inspect the pieces and offsets for a short sentence, then try the same code with the GPT-2 file. Each offset tells you which slice of the original text contributed to that token."}]},{"t":"code","lang":"python","label":"Python","text":"text = \"Ravi lives in Pune.\"\nencoded = tok.encode(text, add_special_tokens=False)\nfor token, token_id, (start, end) in zip(\n    encoded.tokens, encoded.ids, encoded.offsets\n):\n    print(token, token_id, text[start:end])"},{"t":"p","runs":[{"text":"Offsets make it possible to highlight the original span of a label in a reading tool. More than one token can refer to the same character, and a special token may have no source span."}]},{"t":"h2","id":"special-tokens-and-truncation","runs":[{"text":"Special tokens and truncation"}]},{"t":"p","runs":[{"text":"Special tokens tell a particular model about boundaries or roles. The raw count above leaves them out so it compares text segmentation. In a real pipeline keep the model’s required tokens, but avoid adding them twice when the chat template has already inserted them."}]},{"t":"p","runs":[{"text":"Truncation discards some of the input from the primary encoding when the input exceeds the configured limit. Choose which text to keep deliberately. For example, a classifier that only receives the beginning of a complaint may miss the event described at the end. Keep the important part, split long inputs into chunks, or choose a model with more room."}]},{"t":"h2","id":"do-this-now","runs":[{"text":"Do this now"}],"role":"try"},{"t":"p","runs":[{"text":"Write three short requests in a language you use. Record the exact text, tokenizer revision and token counts. If you compare translations, make sure they mean the same thing. Decide what additional checks you need before making a claim about cost or teaching quality."}]}],"check":{"question":[{"text":"GPT-2 counts 5 tokens for the English parcel question and 30 for the Hindi translation. What does this experiment show?"}],"options":[{"text":[{"text":"Any hosted service charges six times as much for the full Hindi request."}],"correct":false,"tempting":[{"text":"The experiment does not use a hosted service or count its output and overhead."}]},{"text":[{"text":"The exact Hindi string uses more of a fixed token budget with this tokenizer."}],"correct":true,"tempting":null},{"text":[{"text":"The English answer will be six times more accurate."}],"correct":false,"tempting":[{"text":"Input token counts do not measure answer quality."}]},{"text":[{"text":"Every tokenizer will produce the same two counts."}],"correct":false,"tempting":[{"text":"The second tokenizer returns 5 and 6 for the same strings."}]}],"order":[3,1,2,0],"why":null},"prev":{"slug":"the-auto-classes","title":"AutoModel gives you numbers, not answers","minutes":9},"next":{"slug":"padding-and-attention-masks","title":"Padding on the wrong side ruins generation quietly","minutes":9}}}