Artificial Intelligence Fundamentals / Inside Generative AI

Tokens and text as numbers

Lesson 19 of 26. Open to read. No account needed.

Models Only Read Numbers

A large language model is a very large neural network, the kind of model from the previous module, trained on enormous amounts of text. Like every neural network, it calculates with numbers: weighted sums, activations, losses. So before a language model can do anything with a sentence, the sentence must be turned into numbers, and the model's numeric output must be turned back into text.

That conversion has two steps. The text is split into pieces called tokens, and each token is replaced by a number, its token ID. This lesson builds the simplest possible version of both steps and compares it with what real models use.

Tokens: Characters, Words or Pieces

There are three broad ways to split text:

  • Characters. Every letter, digit, space and punctuation mark is a token. The vocabulary is small, but sentences become long sequences.
  • Words. Short sequences, but the vocabulary must hold every word, and a word never seen before has no token.
  • Subwords. Pieces between characters and words. Common words stay whole; rarer words are built from smaller parts. A word such as "annoyingly" might become annoy, ing and ly, depending on the vocabulary. Unseen words can still be represented from known pieces.

Modern language models use subword tokenisers. One widely used kind, called byte pair encoding (BPE), builds its vocabulary from frequent combinations in its training text. The documentation of tiktoken, one BPE tokeniser, notes that its tokens are reversible, so the original text can always be recovered, that it works on any text, even text unlike its training data, and that on average one token corresponds to about 4 bytes of text. Tokens are therefore neither letters nor words; counting words does not tell you how many tokens a text has.

Token IDs

A vocabulary lists every token the tokeniser knows, and each token's position in that list is its ID. The model receives the sequence of IDs. The IDs are names, not quantities: token 13 is not "more" than token 7, just as grower 2 was not more than grower 1 in the wine data. Inside the model, each ID is replaced by a list of learned numbers that the network can calculate with.

The sentence "the cat sat" is split into tokens, here single characters: t, h, e, space, c, a, t and so on. A vocabulary table maps each token to an ID, for example t to 13 and a space to 0. The result is the sequence of IDs 13, 7, 5, 0, 3, 2, 13, 0, 12, 2, 13, which is what a model receives. Decoding reverses the mapping.

Read the diagram from top to bottom. The sentence is split into tokens, each token is looked up in the vocabulary, and the IDs form the sequence the model actually receives. The upward arrow on the side shows decoding: looking IDs up in reverse turns them back into text.

A Limited Context

A model can only take a limited number of tokens into account at once: its context. The configuration of GPT-2, an early openly published language model, fixes 1,024 token positions. Recent models allow far more, but every model has some limit. When a conversation or document exceeds it, older text has to be dropped or condensed, and the model can no longer use what it cannot see. A model that seems to "forget" the start of a very long conversation is often simply working without it.

Exercise: Text to IDs and Back

You will build a character-level vocabulary for a short course-written text, convert a sentence to IDs, and convert the IDs back to text.

Starting state: the course environment, active in your terminal. The script uses only plain Python.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/text-to-ids
    cd ~/ai-practice/text-to-ids
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\text-to-ids
    cd $HOME\ai-practice\text-to-ids
    

    Save this as text_to_ids.py in that folder:

    """Turn text into numbers and back with a tiny character vocabulary."""
    text = "the cat sat on the mat. the dog sat on the log."
    
    vocabulary = sorted(set(text))
    char_to_id = {char: number for number, char in enumerate(vocabulary)}
    id_to_char = {number: char for char, number in char_to_id.items()}
    
    print("Characters in the text:", len(text))
    print("Vocabulary size:", len(vocabulary))
    print("Vocabulary:", repr("".join(vocabulary)))
    
    sentence = "the cat sat"
    ids = [char_to_id[char] for char in sentence]
    print("IDs:", ids)
    decoded = "".join(id_to_char[number] for number in ids)
    print("Back to text:", decoded)
    print("Round trip matches:", decoded == sentence)
    
  2. Run it:

    python text_to_ids.py
    

    Output, which should match exactly:

    Characters in the text: 47
    Vocabulary size: 14
    Vocabulary: ' .acdeghlmnost'
    IDs: [13, 7, 5, 0, 3, 2, 13, 0, 12, 2, 13]
    Back to text: the cat sat
    Round trip matches: True
    

How the Script Works

The vocabulary. set(text) keeps one copy of each different character, and sorted puts them in a fixed order, with the space first and the full stop second. The text has 47 characters but only 14 different ones. repr prints the vocabulary in quotation marks so that the leading space is visible.

The two lookup tables. enumerate(vocabulary) pairs each character with its position, 0 to 13, and char_to_id stores those pairs: the space is 0, a is 2, t is 13. id_to_char is the same table reversed.

Encoding and decoding. The list comprehension looks up each character of "the cat sat" and gives 11 IDs, one per character, spaces included. "".join(...) looks each ID up in the reversed table and joins the characters back into a string, which matches the original exactly.

Real tokenisers work the same way in principle, with two differences: their tokens are subwords, so sentences need far fewer IDs, and their vocabularies hold tens of thousands of tokens, built from very large amounts of text.

Success: the output matches, and you can explain why 11 IDs are needed for an 11-character sentence and how decoding recovers the text.

If something differs:

What you seeLikely causeNext step
A different vocabulary or countThe text line was changed, perhaps with an extra spaceRestore the text exactly as shown
KeyError with a characterThe sentence uses a character that is not in the textUse only characters from the text, or see the independent task
Round trip matches: FalseOne of the lookup tables was typed differentlyCompare both lines with the listing
NameErrorA line was left out while pastingPaste the whole script again
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf text-to-ids
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse text-to-ids
    ls
    

    Check that the first ls shows text-to-ids before removing it. Do the independent task first.

Independent task: change sentence = "the cat sat" to sentence = "the cow" and predict what will happen before running the script. Then explain the result, and why real subword tokenisers do not have this problem.

Check Your Understanding

  1. A colleague says a model "understands" that token 13 is bigger than token 7. What is wrong with that?
  2. Why does a character vocabulary need very few IDs but produce long sequences, while a word vocabulary does the opposite?
  3. Why can a model lose track of the start of a very long conversation?

Answer and Reasoning

Independent task

The script stops with:

KeyError: 'w'

The vocabulary contains only the 14 characters that appear in the text, and w is not one of them, so char_to_id has no entry for it. A tokeniser that only knows the pieces of its training text fails on anything new. Subword tokenisers such as BPE avoid this: their smallest pieces cover every possible byte of text, so any text can be split into known tokens, and rare words simply need more of them.

Understanding check

  1. Token IDs are names, like positions in a list, not quantities. The model turns each ID into its own set of learned numbers; nothing in that treats 13 as larger than 7.
  2. A handful of characters is enough to write any text, so the vocabulary is tiny, but each character is a token, so texts become long. Words make short sequences, but a vocabulary would need every word, and new words would have no token.
  3. A model can only use a limited number of tokens at once, its context. When a conversation exceeds that limit, earlier parts are dropped or condensed, and the model cannot use what is no longer in its context.

References

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy