Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 3: Transformers and Language Models

Week 03 / Lesson 1

Turning text into model inputs

Trace text through tokenization, embedding lookup, and position information.

Section 1.1 1 of 7

Overview

Focus

Trace text through tokenization, embedding lookup, and position information.

Your route through the lesson

  • 1.2 Bytes, subword tokens, and token counts
  • 1.3 Embedding lookup and vocabulary dimensions
  • 1.4 Position and word order
  • 1.5 Put it into practice
  • 1.6 Guided comparison
  • 1.7 A tokenizer on unfamiliar identifiers

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 1.2 2 of 7

Bytes, subword tokens, and token counts

Focus

Trace text through a tokenizer and distinguish token count from word count.

A language model operates on integer token identifiers rather than raw words. A tokenizer maps text into a sequence of units. Whether decoding reconstructs the exact original text is a property to test: normalization or discarded formatting can make a round trip lossy. Units may be characters, bytes, or learned pieces of words. A vocabulary assigns each allowed unit an integer. The integer is an address, not a meaningful numerical ranking of words.

With a character vocabulary {a:0,b:1,space:2}, text “a b” becomes [0,2,1]. A whitespace tokenizer could instead make two tokens, a and b, while omitting the separator unless its representation preserves it. Different schemes therefore produce different counts and can have different round-trip properties. Subword tokenizers can represent a long word using several tokens; punctuation and whitespace also affect segmentation.

Use the tokenizer that belongs to the model. A token identifier 42 from one vocabulary need not mean the same text in another. A model's context limit counts its tokens, not displayed words. Before comparing costs or context usage, measure the actual encoded sequence, including instructions and output reservation.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A character vocabulary encodes a=0,b=1,space=2. What encodes “a b”?
2. Two tokenizers assign different identifiers to the same word. Which identifiers should a model receive?
3. A sentence has ten displayed words. Can its token count be assumed to be ten?

Section 1.3 3 of 7

Embedding lookup and vocabulary dimensions

Focus

Interpret an embedding table as learned vectors indexed by tokens.

An embedding table is a learned matrix with one row per vocabulary entry. If vocabulary size is 100 and hidden width is 16, the table has shape (100,16). Looking up token identifiers [2,5,2] returns three vectors shaped (3,16), with the same row reused for both appearances of token 2.

The hidden width describes how many learned numerical features represent each token. It is different from vocabulary size and sequence length. For a batch of B sequences of length T, embedding output has shape (B,T,hidden_width). PyTorch's Embedding module performs this indexed lookup and trains its table through gradients.

Initial vectors can be random. They become useful through the training objective, not because a vector happens to contain decimal values. A token's identifier is not itself a similarity score, and an embedding coordinate does not necessarily have a simple human interpretation. This language-model embedding is learned for the model's task; later document-search embeddings are evaluated specifically for retrieval.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A vocabulary has 100 entries and each embedding has width 16. What shape has the embedding table?
2. Identifiers [2,5,2] are looked up in one unchanged embedding table. What is true?
3. A model uses random embedding initialization before training. What makes the vectors task-useful?

Section 1.4 4 of 7

Position and word order

Focus

Explain why token order needs an order-sensitive representation.

An embedding lookup by itself gives a token the same vector wherever it occurs. Attention that only compares those token vectors has no independent knowledge of which position came first. A model needs order-sensitive information to distinguish “dog bites person” from “person bites dog.”

A simple decoder adds a learned position vector to each token embedding. Position 0,1,2 has its own vector, so the same token at two locations receives different combined inputs. Other model designs introduce position through sinusoidal functions or rotations in attention. Their implementation differs, but the purpose is to represent relative or absolute order.

Keep position indices separate from token identifiers. A six-token sequence uses positions 0 through 5 regardless of vocabulary size. A learned position table also has a supported maximum length; exceeding it cannot be repaired by pretending the next position is zero without changing the model's behavior. Padding and batching need explicit masks so artificial padding does not become meaningful evidence.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Why add position information to repeated token embeddings?
2. A sequence contains six tokens. Which are its zero-based position indices?
3. A learned position table supports length 32. A request has 40 tokens. What is needed?

Section 1.5 5 of 7

Put it into practice

Focus

Compare two text encodings and inspect an embedding lookup.

Download week03.py and run python week03.py --lesson 1 using the PyTorch environment. The lab compares a reversible character encoding with a whitespace-based segmentation on short supplied text. It records the original text, identifiers or units, decoded text where defined, and token counts.

Read the vocabulary construction: sorted(set(text)) collects distinct characters and fixes a reproducible order. enumerate assigns each character an integer. A dictionary maps characters to identifiers; a reverse dictionary supports decoding. These Python operations expose the encoding contract rather than hiding it behind a downloaded tokenizer.

The lab then performs an embedding lookup and adds position vectors. Check the output shape and verify that repeated identifiers reuse the same token vector before position addition. A whitespace split does not preserve repeated spaces by itself, so its reconstruction limitation is reported. This is a comparison of toy encoding choices, not a claim that a character vocabulary is compatible with an arbitrary pretrained model.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Python builds a vocabulary from sorted distinct characters. Why preserve that exact mapping with a checkpoint?
2. A whitespace split discards repeated spaces. What does a failed exact text round trip reveal?
3. A batch of two sequences, each four tokens long, uses embedding width eight. What output shape is expected?

Section 1.6 6 of 7

Guided comparison

Focus

Separate vocabulary size, sequence length, and hidden width in a complete example.

Take vocabulary {a:0,b:1,space:2}. Its size is three even if a text repeats a hundred times. Encoding “a b” produces three identifiers. If each identifier looks up a four-value vector, the result is shaped (3,4). Adding a batch axis gives (1,3,4).

Suppose the token embedding for a is [1,0,0,0] and the first position vector is [0,0.1,0,0]. Their sum is [1,0.1,0,0]. The same token at another position receives another positional contribution. The model still knows which vocabulary row supplied the token component.

When the lab prints a shape, label every axis aloud or in optional notes: examples, tokens, hidden features. A common error swaps vocabulary size with sequence length because both happen to equal three in this toy case. Repeat with a longer repeated string; sequence length changes while the vocabulary table can stay the same. That changed case tests the distinction rather than the coincidence.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A vocabulary has three entries; a text repeats one entry twenty times with width four. What is the unbatched lookup shape?
2. Token vector [1,0,0,0] and position vector [0,0.1,0,0] are added. What is their sum?
3. Vocabulary size and input sequence length both equal three in a token-embedding example. How can their different roles be checked?

Section 1.7 7 of 7

A tokenizer on unfamiliar identifiers

Focus

Apply tokenizer and context reasoning to unfamiliar identifiers and Unicode text.

A troubleshooting assistant receives an equipment identifier such as ZX-900A. A word-oriented segmentation may split it into several pieces. A byte-oriented encoding represents the underlying bytes and can use more than one byte for a non-ASCII character. The visible number of characters therefore need not match bytes or model tokens.

Consider “café”. Depending on representation, the accented letter can occupy multiple bytes; a character vocabulary may treat the displayed accented character as one unit. A pretrained subword vocabulary may use a different decomposition again. Measure with the deployed tokenizer before deciding whether a long diagnostic log fits.

Keep exact source text when identifiers matter. Normalizing case, removing hyphens, or reconstructing text with different whitespace can change an equipment code or command. A tokenizer comparison should report both count and reconstruction behavior. A small count is useful only if the representation still preserves what the application needs.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. An equipment code has seven displayed characters. Why measure its deployed tokenization?
2. Why can the UTF-8 byte count of “café” differ from its visible character count?
3. A diagnostic application needs exact device identifiers. What should a tokenizer comparison check besides count?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Calculating causal attention →