2 Working with text data

Language Models · v1.0.3

2026-11-03 01:40:25

Where we are

Where this fits

Unit 2 is step 1 of stage 1: the data sampling pipeline.

Builds on

  • unit 1: what an LLM is, and the three-stage roadmap
  • the transformer accepts a matrix of numbers

Supplies

  • the whole distance between a raw string and that matrix

Outline of key topics

  • why text has to become vectors
  • tokenization, vocabularies and byte pair encoding
  • sliding-window sampling of input-target pairs
  • token and positional embedding layers

Text as vectors

Embeddings, formally

Neural networks operate on continuous values; text is categorical. An embedding maps discrete tokens into a continuous vector space.

\[E : V \to \mathbb{R}^{d}, \qquad \mathbf{W} \in \mathbb{R}^{|V| \times d}\]

Since \(V\) is finite, \(E\) is fully described by a matrix with one row per token. GPT-2 uses \(d = 768\); the largest GPT-3 model uses \(d = 12{,}288\).

Higher dimensionality captures more nuance, at the cost of computation.

The embedding space

Two-dimensional word embeddings: related concepts cluster together.
  • Word2Vec predicts a word’s context, or the reverse
  • words appearing in similar contexts land close together
  • LLMs instead learn their own embeddings in the input layer, updated during training

Tokenization

Splitting text into tokens

Tokenization splits input text into words and individual punctuation marks.
  • a tokenizer is a function \(T : \Sigma^{*} \to V^{*}\)
  • splitting on whitespace alone glues punctuation to words
  • case is preserved — it distinguishes proper nouns and sentence structure
  • punctuation is its own token — it keeps the vocabulary small and stays a signal

Vocabulary and token IDs

A vocabulary sorts the unique tokens and numbers them.

\[V = \operatorname{sorted}(\operatorname{set}(T(\text{corpus})))\]

  • \(\mathrm{id}\) is a bijection, so one table supplies encode and decode
  • “The Verdict” gives 1,130 entries against 4,690 tokens — most words recur
  • decode must re-attach punctuation, so the round trip holds only up to whitespace

The closed-vocabulary failure

<|unk|> and <|endoftext|> appended as the two highest IDs.

Encoding a word absent from the corpus raises a lookup error — a property of a closed vocabulary, not a bug.

  • <|unk|> substitutes for an out-of-vocabulary word, so no lookup can miss
  • <|endoftext|> separates unrelated documents in the stream
  • [BOS], [EOS], [PAD] exist elsewhere; GPT uses none of them

Byte pair encoding

An invented word spelled from sub-words and characters the vocabulary already holds.

BPE trained GPT-2, GPT-3 and the original ChatGPT model.

  • admits sub-word units, so any string is spellable
  • no <|unk|> is ever required
  • vocabulary size 50,257; <|endoftext|> is ID 50256
  • used through an existing implementation, tiktoken

How the merges are learned

def train_bpe(corpus, num_merges):
    vocab = set(all_characters(corpus))
    for _ in range(num_merges):
        a, b = most_frequent_adjacent_pair(corpus, vocab)
        vocab.add(a + b)
        corpus = replace_pair(corpus, a, b)
    return vocab

Every character is present from the start, so encoding always terminates — in the worst case, character by character.

Data sampling

The sliding window

Each input block predicts the token following every position within it.

\[\mathbf{x}^{(i)} = (t_i, \dots, t_{i+n-1})\] \[\mathbf{y}^{(i)} = (t_{i+1}, \dots, t_{i+n})\]

  • the target is the token that actually followed
  • one window of length \(n\) carries \(n\) prediction tasks
  • batches are tensors of shape (batch \(\times\) context length)

Choosing the stride

Stride 1: windows overlap maximally.

Stride equal to the window: no overlap.
  • max_length fixes the context size \(n\); stride advances the window
  • stride 1 maximises the dataset and its redundancy
  • stride \(=n\) tiles the corpus, using each token once per epoch
  • the non-overlapping choice uses the data fully while limiting overfitting

Input embeddings

The token embedding layer

The embedding layer retrieves one weight-matrix row per token ID.

\[E(t) = \mathbf{W}_{t,:} = \mathbf{e}_t^{\top}\mathbf{W}\]

  • equivalent to one-hot encoding followed by a fully connected layer, at lower cost
  • being a linear layer, it trains by backpropagation
  • weights start random and are optimised with the rest of the model

Encoding word positions

The same token ID yields the same vector in any position.

Self-attention has no notion of order, so position is injected separately.

  • absolute — one embedding per position, conveying exact location
  • relative — encodes distance, generalising across lengths
  • GPT uses absolute positional embeddings, learned during training

Assembling the input embedding

\[\mathbf{Z}_{b,i,:} = E_{\text{tok}}(t_{b,i}) + E_{\text{pos}}(i)\]

token_emb = Embedding(vocab_size, d)      # 50257 x d
pos_emb   = Embedding(context_length, d)  #     n x d
Z = token_emb(batch) + pos_emb(arange(context_length))

The addition broadcasts: one \(n \times d\) positional matrix serves every example in the batch.

Summary

Summary

  • text becomes tokens, and tokens become IDs through a vocabulary that is a bijection
  • special tokens carry information about the text rather than from it
  • byte pair encoding removes the closed-vocabulary failure by admitting sub-words
  • a sliding window turns one token stream into supervised input-target pairs
  • embedding layers are lookup tables, optimised like any other layer
  • positional embeddings restore the order that self-attention lacks

The pipeline delivers a tensor of shape (batch \(\times\) context length \(\times\) embedding dimension) — the input to unit 3, Coding attention mechanisms.