Text data exercises
Extended practice, worked solutions, and transfer
← Back to the exercise catalogue
Text data
Starting points: text and data and embedding space are enough to begin the first exercises; each exercise below lists any additional preparation. In particular, the training-windows exercise uses training examples and input-target shifting, the BPE-merges exercise uses the tokenization lesson, and the data-leakage exercise uses corpus preparation.
Current scope: six bilingual formative exercises cover the text → representations pipeline, windows and input-target shifting, BPE merge counting, and finally split-leakage diagnosis and tokenizer fitting. Each exercise has a descriptive, stable anchor independent of its title and position in the collection. Prerequisites on each exercise guide the suggested order.
Reconstruct the representation pipeline
Preparation: a first pass through text and data and embedding space is enough.
Place these items in causal order, then write one sentence describing what each arrow does:
- token IDs
- contextualized hidden states
- source text
- token strings/fragments
- initial token embeddings
Do not insert a universal “position vector added at lookup” step. State where position handling belongs at this level of abstraction.
Show hints
- Which component defines the token vocabulary?
- An ID is used to retrieve a row; it is not itself a vector.
- Contextualization happens after the initial lookup.
Show the worked solution
Source text → tokenizer output (tokens/fragments) → integer token IDs → embedding-table lookup → initial token embeddings → architecture-dependent position handling and network processing → contextualized hidden states.
The tokenizer maps text to discrete vocabulary entries. The IDs index the embedding table. The lookup selects vectors but does not mix information across sequence positions. Subsequent model computation produces context-dependent states. Position handling is architecture-dependent: learned absolute position embeddings may be added to token embeddings, while RoPE acts on query/key vectors inside attention.
Common errors:
- “The tokenizer produces embeddings”: it produces token units and IDs; the model’s embedding table supplies the vectors.
- “The ID is a coordinate”: it is a discrete vocabulary index; arithmetic distance between IDs has no general semantic interpretation.
- “Every model adds a position vector immediately after lookup”: positional mechanisms differ across architectures.
Success criterion: all stages are ordered correctly; token, ID, initial vector and contextualized state are distinguished; positional handling is not presented as universal.
Calculate lookup and trace tensor shapes
Preparation: embedding space for the matrix and the lookup; tensors is an optional notation reference. The exercise progresses in three stages: calculate, complete, generalize.
Stage 1 — Perform an embedding lookup. Use the synthetic matrix from the canonical lesson:
\[ E = \begin{bmatrix} 0.1 & 0.0 \\ 0.0 & 0.2 \\ 0.8 & -0.1 \\ -0.2 & 0.5 \\ 0.3 & 0.7 \end{bmatrix} \in \mathbb{R}^{5\times 2}. \]
For token IDs \([2,0,3]\):
- Which rows are selected, in order?
- Write the resulting matrix \(X\).
- Give its shape.
- Would changing ID 3 to ID 4 mean “moving one unit” in embedding space?
Show hints
- IDs are zero-based row indices in this example.
- Copy the selected rows without adding or averaging them.
- The sequence length is the number of selected IDs; the embedding dimension is the number of columns.
Show the worked solution
The selected rows are \(E_2\), \(E_0\) and \(E_3\), so
\[ X = \begin{bmatrix} 0.8 & -0.1 \\ 0.1 & 0.0 \\ -0.2 & 0.5 \end{bmatrix} \in \mathbb{R}^{3\times 2}. \]
The shape is \((L,d)=(3,2)\): three token positions and two features per token. Replacing ID 3 by ID 4 selects a different row; the integer difference is not a distance or displacement in the learned vector space.
Common errors:
- Selecting columns instead of rows confuses the embedding dimension with the vocabulary index.
- Adding or averaging the selected rows changes the operation: a lookup returns one row per ID.
- “ID 4 is one unit from ID 3” confuses discrete labels with geometric coordinates.
Stage 2 — Complete a shape trace. A batch contains two sequences of three token IDs each. The embedding table has vocabulary size \(V=5\) and embedding dimension \(d=2\). Complete the missing entries:
| Object | Shape | Meaning |
|---|---|---|
| Embedding table \(E\) | \((5,2)\) | vocabulary entries × features |
| Token IDs | \((2,3)\) | batch × sequence |
| Lookup result | ? | batch × sequence × features |
| One sequence after lookup | ? | sequence × features |
Then explain why the vocabulary size \(V\) does not appear as an axis in the lookup result.
Show hints
- Each of the six IDs selects one row of \(E\).
- The selected row has length \(d=2\).
- The lookup output contains one vector for each batch-position pair, not the entire vocabulary table.
Show the worked solution
The lookup result has shape \((2,3,2)\); one sequence has shape \((3,2)\). The vocabulary axis indexes the source table. After row selection, the output axes describe the batch, sequence positions and features. The vocabulary dimension is therefore not retained as an output axis.
Notation note: this activity uses \(d\) for the embedding width. The tensor reference uses \(D\) for the model feature width and \(d_h\) for a per-head width. Here, \(d\) and \(D\) denote the same feature-axis role; they are local notation choices, not universally interchangeable symbols.
Common errors:
- \((2,3,5,2)\) would incorrectly retain the whole vocabulary table as an extra output axis.
- \((2,3,5)\) confuses vocabulary size with embedding width.
- \((2,2,3)\) swaps the sequence and feature axes.
Stage 3 — Generalize to the batch. A batch contains \(B=2\) sequences, each with \(L=3\) token IDs. The embedding dimension is \(d=2\).
- Give the shape of the ID tensor.
- Give its shape after the embedding lookup.
- Does the lookup combine information between the three positions?
- If a later width-preserving Transformer block returns hidden states, what is their common shape?
Show hints
- Count examples, then positions.
- Each ID is replaced by a vector of length \(d\).
- Lookup is an indexed selection, not a contextual mixing operation.
Show the worked solution
\[ \text{IDs}: (B,L)=(2,3), \qquad \text{embeddings}: (B,L,d)=(2,3,2). \]
Lookup preserves the batch and sequence-position axes and adds the feature axis. It does not mix information across positions. A width-preserving block commonly returns hidden states of shape \((2,3,2)\), although exact conventions depend on the architecture and implementation.
Common errors:
- \((2,2,3)\) swaps the position and feature axes.
- \((2,3)\) omits the vector dimension after the lookup.
- Claiming that the lookup contextualizes tokens assigns the Transformer’s later computation to the embedding table.
Optional practical trace — from text to vectors
This trace complements the lookup exercise with a real tokenizer and a synthetic embedding table. It follows the successive objects without claiming to reproduce the internal weights of a pretrained GPT-2.
Install the pinned version with python -m pip install tiktoken==0.14.0. NumPy is already a project dependency.
import numpy as np
import tiktoken
text = "hello world"
utf8_bytes = text.encode("utf-8")
encoding = tiktoken.get_encoding("gpt2")
token_ids = encoding.encode(text)
token_bytes = [encoding.decode_single_token_bytes(i) for i in token_ids]
token_strings = [part.decode("utf-8") for part in token_bytes]
assert utf8_bytes == b"hello world"
assert token_ids == [31373, 995]
assert token_strings == ["hello", " world"]
assert encoding.decode(token_ids) == text
# Last token in the English and French lesson prefixes.
prefix_cases = (
("What have the Romans ever done for us?", 9, 30, b"?"),
("C'est une bonne situation, ça, scribe ?", 15, 5633, b" ?"),
)
for prefix, expected_count, expected_id, expected_bytes in prefix_cases:
prefix_ids = encoding.encode(prefix)
assert len(prefix_ids) == expected_count
assert encoding.decode(prefix_ids) == prefix
assert prefix_ids[-1] == expected_id
assert encoding.decode_single_token_bytes(prefix_ids[-1]) == expected_bytes
# Full decomposition of the French prefix, to compare with the lesson table.
fr_prefix_ids = encoding.encode("C'est une bonne situation, ça, scribe ?")
fr_fragments = [encoding.decode_single_token_bytes(i) for i in fr_prefix_ids]
assert encoding.decode(fr_prefix_ids) == "C'est une bonne situation, ça, scribe ?"
assert len(fr_prefix_ids) == 15
assert fr_fragments[-1] == b" ?"
print("French prefix:")
for fragment, fragment_id in zip(fr_fragments, fr_prefix_ids):
print(f" {fragment!r} -> {fragment_id}")
# Comparison with fixed input: some tokens here contain only a space.
fixed_text = "2 + 2 = 4"
comparisons = (
("gpt2", [17, 1343, 362, 796, 604], [b"2", b" +", b" 2", b" =", b" 4"]),
(
"cl100k_base",
[17, 489, 220, 17, 284, 220, 19],
[b"2", b" +", b" ", b"2", b" =", b" ", b"4"],
),
)
for name, expected_ids, expected_fragments in comparisons:
tokenizer = tiktoken.get_encoding(name)
ids = tokenizer.encode(fixed_text)
assert ids == expected_ids
assert [tokenizer.decode_single_token_bytes(i) for i in ids] == expected_fragments
assert tokenizer.decode(ids) == fixed_text
# Synthetic table: real GPT-2 uses different dimensions and learned weights.
vocab_size, d = 50_257, 2
E = np.zeros((vocab_size, d), dtype=np.float32)
E[31373] = [0.1, 0.2]
E[995] = [-0.3, 0.4]
X = E[token_ids]
assert X.shape == (2, 2)
assert np.allclose(X, [[0.1, 0.2], [-0.3, 0.4]])
# Illustrative positional vectors, not GPT-2's actual parameters.
P = np.array([[0.01, 0.02], [0.03, 0.04]], dtype=np.float32)
Z = X + P
assert Z.shape == (2, 2)
assert np.allclose(Z, [[0.11, 0.22], [-0.27, 0.44]])Interpret this carefully: IDs depend on the tokenizer; the vectors in E and P are invented. The script checks the path text → IDs → lookup → positional addition, but runs no Transformer block and therefore computes no contextualized states. For byte-level details and BPE merges, see the BPE-merges exercise.
Inspect a Hugging Face tokenizer
The example below inspects a specific Hugging Face tokenizer. The first load may require network access; for a reproducible experiment, record library versions and pin a model revision rather than relying on a moving default branch.
from importlib.metadata import version
from transformers import AutoTokenizer
model_id = "gpt2"
revision = "YOUR_COMMIT_SHA" # Replace with the exact model commit SHA
tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision)
text = " Hello world — café"
ids = tokenizer.encode(text, add_special_tokens=False)
tokens = tokenizer.convert_ids_to_tokens(ids)
print("transformers:", version("transformers"))
print("tokenizer:", model_id)
print("tokens:", tokens)
print("IDs:", ids)
print("count:", len(ids))
print("decoded:", tokenizer.decode(ids))The displayed IDs and fragments belong to the loaded tokenizer. To compare two tokenizers, run the same protocol on the same text, record their revision/version identifiers, and compare fragments and token counts—not numeric ID values across vocabularies. Decoding can also depend on cleanup conventions and special tokens.
Diagnose identity, position and context
Preparation: contextualized representations and position and RoPE, after the representation-pipeline exercise and the lookup exercise. For the mathematical framing of Stage 3, the deep dive on dependencies across positions and layers is an optional reference. The exercise progresses in three stages: diagnose claims, predict under controlled changes, then calculate a toy numerical example.
Stage 1 — Classify claims. For a fixed tokenizer and fixed embedding matrix, classify each statement as valid, invalid, or architecture-dependent, and justify your choice. No specific model configuration is supplied: when a statement refers to “this model”, decide whether the information given is sufficient to determine its behavior.
A. The same token ID selects the same initial embedding row on every occurrence. B. Two token IDs with consecutive integer values must have similar embeddings. C. The same token ID must have the same contextualized hidden state in every sentence. D. This model adds a learned absolute position vector to each token embedding before its first Transformer block. E. RoPE is applied to query/key representations inside attention, rather than being a vector universally added by the embedding lookup.
Show hints
- Hold the tokenizer and matrix fixed.
- Separate the lookup result from later network states.
- Distinguish a common architecture family from a universal rule.
Show the worked solution
- A — Valid, under the stated fixed-matrix condition: lookup selects the same row.
- B — Invalid: row indices are labels, not coordinates.
- C — Invalid: context and position can change later hidden states even when the initial lookup is identical.
- D — Architecture-dependent / not decidable from the information given: learned absolute position embeddings are one possible design, but the exercise does not specify which positional mechanism this model uses. A possible design must not become a universal claim.
- E — Valid as a description of RoPE: it acts on query/key vectors within attention; other positional mechanisms exist.
Common error: the decisive distinction separates a property of the tokenizer, a property of a fixed lookup table, and a property of the complete network computation. The third does not follow from the first two.
Stage 2 — Predict what changes, and what stays invariant. Assume a deterministic tokenizer and a fixed model checkpoint. Consider the same token ID \(t\) in three situations:
- It occurs twice in the same input sequence.
- It occurs at the same sequence position in two different input sequences with different preceding (visible) context; in a decoder-only causal model, tokens to the right are masked and cannot affect this position.
- It is replaced by a different ID \(u\), while all other positions remain unchanged.
For each situation, predict whether the initial embedding selected by lookup, the position-dependent operation or representation (whether position information is added to the token stream before the first block or applied inside attention), and the contextualized hidden state can change. State any architectural qualification needed; do not assume that a change at one position leaves all later states unchanged.
Show hints
- A fixed embedding table maps an ID to a fixed row.
- Some architectures add position information to the token stream before the first block; RoPE instead transforms query/key vectors inside attention. Do not assume every model has a distinct position-aware input embedding.
- Contextualized states depend on the network computation and surrounding input.
Show the worked solution
- The same ID selects the same initial embedding row. If the architecture adds learned absolute position embeddings before the first block, the resulting input representation can differ by position. With a mechanism such as RoPE, the token embedding itself is not changed by a position vector; positional effects enter later inside attention. Contextualized states may differ because position and surrounding context matter.
- The initial lookup row remains the same for the same ID and fixed table. Because the token is held at the same position, the position index and position-dependent operation are fixed: an absolute position vector is identical, and RoPE applies the same position-indexed rotation, although the query/key content being rotated can differ. The resulting position-aware query/key representations can therefore differ because their content differs. Contextualized states can differ because the preceding (visible) context differs; in a causal decoder, tokens to the right cannot affect this position.
- A different ID generally selects a different row. If its position is unchanged, the positional operation itself need not change: an absolute scheme adds the same position vector, while RoPE applies the same position-dependent rotation to the newly computed query/key vectors. The resulting position-aware representations can nevertheless change because their content inputs changed. Contextualized states may change at that position and at other positions that depend on it.
These are qualitative predictions, not guarantees about the magnitude of a numerical change. Exact effects depend on architecture, masking, position mechanism and model parameters.
Common errors:
- “Same ID means same hidden state”: only the initial lookup row is invariant under a fixed table; later computation is context-sensitive.
- “Changing one ID affects only one output position”: contextual mixing can propagate the change to other positions, subject to the architecture and attention mask.
- “Different IDs must produce very different vectors”: distinct rows need not be far apart geometrically.
Stage 3 — Controlled numerical calculation (toy aggregation, not an attention layer).
Use two short phrases with the same target and different preceding context: A = [good, situation] and B = [bad, situation]. These are simplified pedagogical units, not a tokenization claimed for any real tokenizer. The synthetic embedding table contains: \[ E[\text{good}]=(0.1,0.2),\quad E[\text{bad}]=(0.9,-0.4),\quad E[\text{situation}]=(0.5,0.5). \] The shared target “situation” is at position 1 in both windows. Add the same positional vector \(P_1=(0.02,0.05)\); the preceding context words are at position 0 and use \(P_0=(0.01,0.00)\). To isolate the effect of the preceding context, define a fixed illustrative aggregation: \[ h_{\text{target}}=0.4\,z_{\text{prefix}}+0.6\,z_{\text{target}},\qquad z=x+P. \] 1. Verify that the lookup and positional term for “situation” are identical in A and B. 2. Compute the position-adjusted prefix vectors, then compute \(z_{\text{target}}\). 3. Compute \(h_A\), \(h_B\), and their Euclidean distance. 4. Explain what the example demonstrates and what it does not demonstrate.
Show the worked solution and NumPy code
The lookup for “situation” is \((0.5,0.5)\) in both windows; \(z_{\text{target}}=(0.52,0.55)\). The prefixes give \(z_{\text{good}}=(0.11,0.20)\) and \(z_{\text{bad}}=(0.91,-0.40)\). \[ h_A=(0.356,0.410),\qquad h_B=(0.676,0.170). \] The distance is \(\sqrt{0.320^2+0.240^2}=0.400\).
import numpy as np
E = {"good": np.array([0.1, 0.2]),
"bad": np.array([0.9, -0.4]),
"situation": np.array([0.5, 0.5])}
P0, P1 = np.array([0.01, 0.00]), np.array([0.02, 0.05])
z_target = E["situation"] + P1
z_good, z_bad = E["good"] + P0, E["bad"] + P0
h_A = 0.4 * z_good + 0.6 * z_target
h_B = 0.4 * z_bad + 0.6 * z_target
assert np.allclose(h_A, [0.356, 0.410])
assert np.allclose(h_B, [0.676, 0.170])
print("distance:", np.linalg.norm(h_A - h_B))Limitation: this fixed-weight average is not a Transformer’s self-attention. It computes no Q/K/V projections, content-dependent scores, softmax, residual connections, normalization, or MLP. This is an exercise in isolating a dependency, not a faithful simulation of a block.
Build windows and align targets
Preparation: the “sliding windows and stride” section of from tokenized corpus to training examples, after the representation-pipeline exercise and the lookup exercise. This exercise focuses on the input-target contract; it does not ask you to implement a tokenizer or data loader.
Consider the token-ID stream:
\[ s = [11, 4, 4, 9, 2, 7, 5] \]
with context length \(L=3\) and stride \(S=2\).
Stage 1 — Construct the examples.
- Write the retained input windows.
- For each one, write the target shifted one position in the source stream.
- Give the shapes of the input and target arrays.
Show hints
- A window starting at position \(a\) uses \(s[a:a+L]\) as input.
- Its target is \(s[a+1:a+L+1]\).
- Stride gives the successive starts: \(0, 2, 4, \ldots\); a window is retained only when its target is complete.
Show the worked solution
The valid starts are \(a=0\) and \(a=2\):
\[ X = \begin{bmatrix} 11 & 4 & 4 \\ 4 & 9 & 2 \end{bmatrix}, \qquad Y = \begin{bmatrix} 4 & 4 & 9 \\ 9 & 2 & 7 \end{bmatrix}. \]
Both arrays have shape \((2,3)\): two examples and three positions per example. At every position, the target is the token immediately following the corresponding input token in the source stream.
Stage 2 — Diagnose the corpus tail.
The next start after \(a=2\) would be \(a=4\).
- Why is this window not retained?
- How many windows would be obtained with stride 1, then with stride 3?
- For \(N\) tokens, context length \(L\), and stride \(S\), explain the role of \(N-L-1\) in the formula \[ n_{\text{windows}} = 1 + \left\lfloor\frac{N-L-1}{S}\right\rfloor, \] when \(N\geq L+1\).
Show hints
- An input of length \(L\) consumes \(L\) tokens, but its shifted target also needs the successor of the final input token.
- At least \(L+1\) source tokens are therefore required for one complete example.
- Valid starts are multiples of \(S\) that do not exceed \(N-L-1\).
Show the worked solution
At \(a=4\), the input would be \([2,7,5]\), but its target would have to be \([7,5,\,?]\): the final successor does not exist in the supplied stream. The reference implementation drops this window; it invents neither an end token nor padding.
For \(N=7\) and \(L=3\):
- \(S=1\): starts \(0,1,2,3\), so 4 windows.
- \(S=2\): starts \(0,2\), so 2 windows.
- \(S=3\): starts \(0,3\), so 2 windows.
The term \(N-L-1\) is the final valid start: after the \(L\) input tokens, one target token must remain. The formula counts multiples of \(S\) from zero through this inclusive bound.
Stage 3 — Detect an alignment bug.
A faulty implementation builds targets by copying inputs exactly. Explain why the shapes can be correct while the next-token prediction objective is not. Give a simple test that would detect this error.
Show the worked solution
The shape \((n_{\text{windows}},L)\) checks array structure, not semantic alignment. If targets equal inputs, the model is trained to reproduce the token already present at each position instead of predicting its successor.
A direct test checks, for every window, that the target at position \((k,i)\) equals the source token immediately following the corresponding input. For internal positions, one can also check the invariant that all target columns except the last equal the input columns starting from the second; the final position must be compared with the next token in the source stream. The existing sliding_input_target_pairs tests already cover these invariants.
Common errors:
- Forgetting the extra token required by the final target and counting an incomplete window.
- Confusing input length \(L\) with the \(L+1\) source segment needed for a complete pair.
- Assuming equal shapes guarantee correct shifting.
- Treating stride as a change to the shift: stride changes window starts, not the relationship between each input and its target.
Stage 4 — Distinguish teacher forcing from free-running generation.
Consider the reference sequence \([A,B,C,D]\). With input length 3, the shifted examples are \(x=[A,B,C]\) and \(y=[B,C,D]\).
- Which prefix is available at each position to predict \(B\), \(C\), and \(D\), respectively?
- Suppose the model predicts \(X\) rather than \(B\) at the first position. Which token is still supplied as input at the second position under teacher forcing?
- During free-running generation from prompt \([A]\), if the model selects \(X\), which context is used for the next prediction?
- Why does teacher forcing not feed the model’s own predictions back as inputs?
Show the worked solution
The observed prefixes are \([A]\), then \([A,B]\), then \([A,B,C]\); they predict \(B\), \(C\), and \(D\), respectively. The causal mask lets each position use its prefix but not future positions.
Even if the model predicts \(X\) at the first position, the input at the second position remains \(B\), because teacher forcing uses the reference prefix supplied by the data. The prediction \(X\) is not fed back into this forward pass. During free-running generation, by contrast, the selected token is appended to the context: after selecting \(X\) from \([A]\), the next context is \([A,X]\).
Teacher forcing therefore allows predictions conditioned on reference prefixes to be computed in parallel and compared with shifted targets. Free-running generation constructs its own trajectory, one selection at a time. Prefill/decode is yet another distinction: it names inference execution phases, not the source of the input tokens.
Success criterion: the pairs are exact, the corpus tail is handled without an invented token, the window count is justified, the input-target copy bug is detected by a checkable invariant, and the difference between a reference prefix and feedback of model predictions is explained correctly.
Further work: partition leakage remains for a separate exercise. Batching and loss masks are distinct topics; they are not implemented by the reference function used here.
Count BPE merges and encode a new word
Preparation: the “Worked example: BPE merges on a tiny corpus” section in Tokenization strategies. We reuse its word-level teaching convention: initial characters plus an end-of-word marker </w>. This is not a specification of a production byte-level tokenizer.
The training corpus contains these occurrences:
| Word | Number of occurrences |
|---|---|
low |
2 |
lower |
1 |
owl |
1 |
Stage 1 — Count pairs.
- Write the initial units for each word.
- Count adjacent pairs across all corpus occurrences.
- Which pair is merged first? Justify your choice.
Show hints
- A pair is counted once for each occurrence in which it appears; repeated copies of a word therefore contribute multiple times.
- The
</w>marker is a unit and can form a pair with the final character. - Do not count only distinct pairs: count their occurrences.
Show the worked solution
The initial units are:
low(two occurrences):l · o · w · </w>lower:l · o · w · e · r · </w>owl:o · w · l · </w>
The frequencies are:
| Pair | Count |
|---|---|
o + w |
4 |
l + o |
3 |
w + </w> |
2 |
w + e, e + r, r + </w>, w + l, l + </w> |
1 each |
The first merge is therefore o + w → ow, with four occurrences. It is strictly more frequent than l + o (three occurrences), so no tie-breaker is needed.
Stage 2 — Apply the merge and recount.
Replace every non-overlapping occurrence of o · w with ow, then recount the pairs. What is the next merge?
Show hints
After the first merge, the sequences are:
- twice
l · ow · </w> - once
l · ow · e · r · </w> - once
ow · l · </w>
Recount the boundaries between adjacent units; the old frequencies do not automatically remain valid.
Show the worked solution
After o + w → ow, the pair l + ow occurs three times: twice in low and once in lower. The next most frequent pair is ow + </w> (twice), followed by pairs with count 1. The second merge is therefore l + ow → low.
The corpus becomes:
| Word | Sequence after two merges |
|---|---|
low (×2) |
low · </w> |
lower |
low · e · r · </w> |
owl |
ow · l · </w> |
Stage 3 — Transfer the rules to unseen text.
The word lowest does not occur in the training corpus. Starting from the characters l · o · w · e · s · t · </w>, apply the two learned merges in order. Give the final segmentation and explain why frequencies should not be recounted on this new word.
Show the worked solution
First apply o + w → ow, then l + ow → low. The resulting segmentation is:
low · e · s · t · </w>
At encoding time, the tokenizer reuses the merge order learned from the corpus. It does not retrain its vocabulary or recalculate frequencies from the text being encoded. This is the distinction between tokenizer training and encoding new text.
Common errors:
- Counting a pair only once per distinct word and ignoring repeated occurrences.
- Counting non-adjacent pairs or continuing to use frequencies from before a merge.
- Merging only one occurrence when all non-overlapping occurrences of the selected pair must be replaced under the stated convention.
- Recounting frequencies on
lowestat encoding time, as if the tokenizer were retrained for every request. - Presenting this character-level example as a description of every byte-level BPE tokenizer.
Success criterion: initial frequencies are exact, sequences are updated before the second count, merge order is respected on the unseen word, and training/encoding are distinguished.
Diagnose split leakage
Preparation: Preparing a corpus for pretraining, especially its sections on deduplication, split design, and tokenizer fitting; windows and stride. This exercise distinguishes evaluation leakage from an explicitly chosen temporal-continuation protocol.
We want to measure a model’s ability to predict tokens in data that did not influence its fitting. For each protocol below, identify possible dependencies between training and validation, then propose the minimal correction.
Stage 1 — Diagnose three protocols.
A. Split after windowing. A tokenized document is converted into windows of length 4 and stride 2. The windows are then randomly assigned to train and validation.
B. Split by document without deduplication. Documents are assigned to train and validation, but a near-identical copy of a training document appears in validation under a different identifier.
C. Temporal split within one document. To simulate predicting the continuation of a known stream, tokens before a cutoff are used for training and tokens after it for validation. Validation windows may use the earlier prefix as context, but no validation target participates in training.
For each protocol:
- Does the split guarantee the intended independence?
- What information may be shared or reused across partitions?
- What change is needed, or which assumption must be made explicit?
Show hints
- A window contains both inputs and targets: inspect source tokens, not only dataset rows.
- Different document identifiers do not guarantee independent content.
- Temporal-continuation evaluation does not measure the same kind of generalization as evaluation on entirely unseen documents.
Show the worked solution
- A — Likely leakage. Neighboring windows share context tokens and may reuse tokens as targets in one partition and inputs in another. Randomly splitting windows therefore does not separate the source units. First define and split independent units (documents, groups, or time periods), then construct windows within each partition. If the protocol explicitly permits continuation from a known prefix, treat it as case C, with a clearly defined cutoff and targets.
- B — Likely leakage. Splitting by identifier does not detect near-duplicates. Group sufficiently similar copies and variants before or after splitting, using a documented method, then audit cross-partition overlap. The threshold and deduplication unit must fit the corpus; removing every repetition is not automatically desirable.
- C — Not necessarily leakage. This is a valid continuation-prediction protocol if the operational objective is to predict the continuation of a stream whose prefix is available. Earlier context may be supplied to validation, but post-cutoff targets must remain excluded from training, and no training window may consume post-cutoff tokens. This protocol does not support a claim of generalization to independent documents.
Stage 2 — Check tokenizer fitting.
In a conventional held-out experiment, a BPE tokenizer is fitted on train + validation, then the model is trained only on train tokens. Validation is never used to compute training loss.
- Did validation influence the fitting protocol?
- What correction is expected if the goal is to measure generalization to unseen data?
- Why should the tokenizer revision be frozen before encoding validation and test?
Show the worked solution
Yes: the BPE vocabulary and merge order were fitted using validation text. For a conventional held-out experiment, fit the tokenizer on train only, freeze it, then encode train, validation, and test with that same revision. This prevents statistics or lexical units from held-out text influencing tokenizer fitting. Validation remains excluded from model-weight optimization. Other conventions exist in large-scale pretraining pipelines; in that case, describe the data-construction protocol precisely and do not claim the same held-out setup.
Success criterion: distinguish window overlap, document duplicates, and temporal continuation; identify the relevant split unit; explain why tokenizer fitting can also contaminate a held-out evaluation.