5 Pretraining on unlabeled data

Language Models · v1.0.5

2026-11-03 01:40:26

Where we are

Where this fits

The three stages of building an LLM. This unit is stage 2.

Built already

  • a complete GPTModel and a greedy generation loop
  • every weight random, so the output is noise

Still missing

  • a measure of error
  • an optimization loop
  • decoding beyond argmax
  • persistence of trained weights

Outline of key topics

  1. Cross entropy loss and perplexity — turning gibberish into a number.
  2. Training and validation loss — measuring a corpus, not a sentence.
  3. The pretraining loop — ordinary deep learning with AdamW, and the overfitting it exposes.
  4. Temperature and top-\(k\) sampling — decoding as a separate design choice.
  5. Checkpoints and OpenAI’s GPT-2 weights — borrowing a pretrained model.

Training runs on a 5,145-token public-domain story, so every experiment finishes on a laptop.

Measuring the error

From logits to a loss

Probabilities at the target positions are logged, averaged, and negated.
  • Each target is the input shifted one position forward.
  • The quantity of interest is the probability the model assigns to the true next token.
  • Before training that probability is about \(1/|V|\).
  • Training is precisely the process of pushing those probabilities up.

Cross entropy and perplexity

\[\mathcal{L} = -\frac{1}{N}\sum_{i=1}^{N} \log p(y_i \mid x_i)\]

\[\text{perplexity} = e^{\mathcal{L}}\]

  • One call to PyTorch’s cross_entropy computes \(\mathcal{L}\) from raw logits and target IDs.
  • Perplexity reads as the effective number of tokens the model is undecided among.
  • An untrained model over 50,257 tokens sits near \(\log|V| \approx 10.98\).

Loss per token falls steeply as the true token gains probability.

Training on a corpus

Split and loaders

The text is split, tokenized, chunked to the context length, shuffled, and batched.
  • Corpus: The Verdict, Edith Wharton — about 5,145 tokens.
  • Split 90/10 into training and validation text.
  • Sliding window with stride equal to the context length, shortened to 256 tokens.
  • Loss is averaged over a loader, optionally over a few batches for a cheap estimate.

The pretraining loop

Each epoch iterates the training batches: loss, gradients, weight update.
for inputs, targets in train_loader:
    loss = batch_loss(model, x, y)
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()
  • Standard deep learning practice; nothing is LLM-specific.
  • AdamW decouples weight decay, penalising large weights without distorting the adaptive step.
  • Both losses are evaluated periodically with dropout disabled.

Overfitting, read from the curves

Past epoch 2 the training loss keeps falling while the validation loss stagnates.
  • Ten epochs, about five minutes; training loss falls from \(9.8\) to \(0.4\).
  • A falling training loss beside a flat validation loss is the signature of memorization.
  • Generated sentences appear verbatim in the source text.
  • This follows from corpus size, not from a defect: in practice, a far larger corpus is traversed once.

Decoding

Temperature scaling

Temperature 0.1 sharpens the distribution; temperature 5 flattens it.

\[p_i = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}\]

  • Greedy argmax decoding is deterministic: one prompt, one continuation, often a memorised passage.
  • Sampling in proportion to probability restores variety.
  • \(T<1\) sharpens toward argmax; \(T>1\) flattens toward nonsense.

Creativity and coherence pull in opposite directions, and the temperature is the dial between them.

Top-\(k\) sampling

With \(k=3\) the three largest logits survive; the rest are masked to \(-\infty\).
  • Since \(e^{-\infty}=0\), masked tokens receive probability exactly zero after the softmax.
  • The same masking device used by causal attention.
  • Top-\(k\) decides which tokens are candidates; temperature decides how evenly to sample among them.
  • Together they make high temperatures usable.

One generate function

def generate(model, idx, n_new,
             temperature=0.0,
             top_k=None, eos_id=None):
    for _ in range(max_new_tokens):
        logits = last_position_logits(model, idx)
        if top_k is not None:
            logits = mask_below_top_k(logits, top_k)
        next_id = (sample(softmax(logits / T))
                   if T > 0.0
                   else argmax(logits))
        if next_id == eos_id:
            break
        idx = append(idx, next_id)
    return idx

Greedy decoding is the special case \(T = 0\) — the earlier behaviour is subsumed, not discarded.

Persisting and borrowing weights

Checkpoints

  • A checkpoint stores the parameter dictionary: a mapping from each layer to its weight tensors.
  • Reloading constructs a fresh architecture, then assigns the saved parameters into it by name.
  • The reloaded model is switched to evaluation mode so dropout no longer discards learned information.
  • Adaptive optimizers hold per-parameter statistics; a checkpoint meant for resuming training must carry the optimizer state as well, or convergence suffers.

Construct an architecture, then assign parameters into it by name — the same mechanism serves for weights trained elsewhere.

OpenAI’s GPT-2 weights

Four sizes, 124M to 1,558M parameters; one architecture, differing embedding size and repetition counts.
  • Openly released weights remove the need to spend tens to hundreds of thousands of dollars.
  • The configuration must match: context length back to 1,024, and query/key/value bias vectors enabled.
  • Loading walks every tensor with a shape check at each assignment.

Three details in the mapping

def load_weights_into_gpt(gpt, params):
    assign(gpt.pos_emb, p.wpe)
    assign(gpt.tok_emb, p.wte)
    for blk, bp in zip(gpt.blocks, p.blocks):
        # split the combined QKV tensor
        assign_attention(blk.att, bp.attn)
    assign(gpt.out_head, p.wte)  # tied
  • Split. Query, key and value weights were stored as one combined tensor.
  • Transpose. TensorFlow’s layout is the transpose of PyTorch’s.
  • Weight tying. The output head reuses the token embedding matrix.

Coherent English from the loaded model is itself the proof that architecture and assignment agree.

Summary

Summary

  • Cross entropy loss and perplexity quantify the quality of next-token predictions.
  • The LLM training loop is ordinary deep learning with cross entropy and AdamW.
  • A falling training loss beside a flat validation loss means memorization, not learning.
  • Temperature and top-\(k\) sampling govern diversity and coherence at decoding time, independently of the weights.
  • A checkpoint for resuming training holds the optimizer state as well as the weights.
  • Pretraining at scale is prohibitive, so openly released GPT-2 weights are poured into the same architecture.

Where next

A pretrained GPT-2 is a general next-token predictor: it completes text, but it answers no question and labels nothing. Stage 3 is adapting it.

In 6 Fine-tuning for classification:

  • the 50,257-unit vocabulary head is replaced with a small class-sized linear layer
  • most of the backbone is frozen
  • classification logits are read from the last token position

The loss function, training loop and checkpointing carry over unchanged; only the head and the targets differ.